aboutsummaryrefslogtreecommitdiffstats
path: root/src/declarative
diff options
context:
space:
mode:
Diffstat (limited to 'src/declarative')
-rw-r--r--src/declarative/debugger/qdeclarativeenginedebugservice_p.h2
-rw-r--r--src/declarative/declarative.pro7
-rw-r--r--src/declarative/designer/designer.pri2
-rw-r--r--src/declarative/designer/designersupport.cpp408
-rw-r--r--src/declarative/designer/designersupport.h153
-rwxr-xr-xsrc/declarative/items/checksync.pl108
-rw-r--r--src/declarative/items/context2d/context2d.pri16
-rw-r--r--src/declarative/items/context2d/qquickcanvasitem.cpp714
-rw-r--r--src/declarative/items/context2d/qquickcanvasitem_p.h149
-rw-r--r--src/declarative/items/context2d/qquickcontext2d.cpp3540
-rw-r--r--src/declarative/items/context2d/qquickcontext2d_p.h211
-rw-r--r--src/declarative/items/context2d/qquickcontext2dcommandbuffer.cpp469
-rw-r--r--src/declarative/items/context2d/qquickcontext2dcommandbuffer_p.h268
-rw-r--r--src/declarative/items/context2d/qquickcontext2dnode.cpp124
-rw-r--r--src/declarative/items/context2d/qquickcontext2dnode_p.h86
-rw-r--r--src/declarative/items/context2d/qquickcontext2dtexture.cpp778
-rw-r--r--src/declarative/items/context2d/qquickcontext2dtexture_p.h205
-rw-r--r--src/declarative/items/context2d/qquickcontext2dtile.cpp165
-rw-r--r--src/declarative/items/context2d/qquickcontext2dtile_p.h112
-rw-r--r--src/declarative/items/items.pri131
-rw-r--r--src/declarative/items/qquickanchors.cpp1180
-rw-r--r--src/declarative/items/qquickanchors_p.h201
-rw-r--r--src/declarative/items/qquickanchors_p_p.h176
-rw-r--r--src/declarative/items/qquickanimatedimage.cpp397
-rw-r--r--src/declarative/items/qquickanimatedimage_p.h117
-rw-r--r--src/declarative/items/qquickanimatedimage_p_p.h88
-rw-r--r--src/declarative/items/qquickanimation.cpp792
-rw-r--r--src/declarative/items/qquickanimation_p.h209
-rw-r--r--src/declarative/items/qquickanimation_p_p.h153
-rw-r--r--src/declarative/items/qquickborderimage.cpp600
-rw-r--r--src/declarative/items/qquickborderimage_p.h110
-rw-r--r--src/declarative/items/qquickborderimage_p_p.h103
-rw-r--r--src/declarative/items/qquickcanvas.cpp2644
-rw-r--r--src/declarative/items/qquickcanvas.h164
-rw-r--r--src/declarative/items/qquickcanvas_p.h323
-rw-r--r--src/declarative/items/qquickclipnode.cpp120
-rw-r--r--src/declarative/items/qquickclipnode_p.h71
-rw-r--r--src/declarative/items/qquickdrag.cpp462
-rw-r--r--src/declarative/items/qquickdrag_p.h208
-rw-r--r--src/declarative/items/qquickdroparea.cpp428
-rw-r--r--src/declarative/items/qquickdroparea_p.h167
-rw-r--r--src/declarative/items/qquickevents.cpp239
-rw-r--r--src/declarative/items/qquickevents_p_p.h144
-rw-r--r--src/declarative/items/qquickflickable.cpp2003
-rw-r--r--src/declarative/items/qquickflickable_p.h277
-rw-r--r--src/declarative/items/qquickflickable_p_p.h262
-rw-r--r--src/declarative/items/qquickflipable.cpp308
-rw-r--r--src/declarative/items/qquickflipable_p.h104
-rw-r--r--src/declarative/items/qquickfocusscope.cpp70
-rw-r--r--src/declarative/items/qquickfocusscope_p.h68
-rw-r--r--src/declarative/items/qquickgridview.cpp1958
-rw-r--r--src/declarative/items/qquickgridview_p.h146
-rw-r--r--src/declarative/items/qquickimage.cpp746
-rw-r--r--src/declarative/items/qquickimage_p.h122
-rw-r--r--src/declarative/items/qquickimage_p_p.h85
-rw-r--r--src/declarative/items/qquickimagebase.cpp290
-rw-r--r--src/declarative/items/qquickimagebase_p.h119
-rw-r--r--src/declarative/items/qquickimagebase_p_p.h93
-rw-r--r--src/declarative/items/qquickimplicitsizeitem.cpp64
-rw-r--r--src/declarative/items/qquickimplicitsizeitem_p.h75
-rw-r--r--src/declarative/items/qquickimplicitsizeitem_p_p.h78
-rw-r--r--src/declarative/items/qquickitem.cpp5236
-rw-r--r--src/declarative/items/qquickitem.h421
-rw-r--r--src/declarative/items/qquickitem_p.h752
-rw-r--r--src/declarative/items/qquickitemchangelistener_p.h82
-rw-r--r--src/declarative/items/qquickitemsmodule.cpp241
-rw-r--r--src/declarative/items/qquickitemsmodule_p.h65
-rw-r--r--src/declarative/items/qquickitemview.cpp1732
-rw-r--r--src/declarative/items/qquickitemview_p.h296
-rw-r--r--src/declarative/items/qquickitemview_p_p.h260
-rw-r--r--src/declarative/items/qquicklistview.cpp2533
-rw-r--r--src/declarative/items/qquicklistview_p.h215
-rw-r--r--src/declarative/items/qquickloader.cpp858
-rw-r--r--src/declarative/items/qquickloader_p.h123
-rw-r--r--src/declarative/items/qquickloader_p_p.h121
-rw-r--r--src/declarative/items/qquickmousearea.cpp1168
-rw-r--r--src/declarative/items/qquickmousearea_p.h231
-rw-r--r--src/declarative/items/qquickmousearea_p_p.h112
-rw-r--r--src/declarative/items/qquickmultipointtoucharea.cpp729
-rw-r--r--src/declarative/items/qquickmultipointtoucharea_p.h267
-rw-r--r--src/declarative/items/qquickninepatchnode.cpp302
-rw-r--r--src/declarative/items/qquickninepatchnode_p.h98
-rw-r--r--src/declarative/items/qquickpainteditem.cpp528
-rw-r--r--src/declarative/items/qquickpainteditem.h130
-rw-r--r--src/declarative/items/qquickpainteditem_p.h71
-rw-r--r--src/declarative/items/qquickpathview.cpp1781
-rw-r--r--src/declarative/items/qquickpathview_p.h259
-rw-r--r--src/declarative/items/qquickpathview_p_p.h199
-rw-r--r--src/declarative/items/qquickpincharea.cpp600
-rw-r--r--src/declarative/items/qquickpincharea_p.h315
-rw-r--r--src/declarative/items/qquickpincharea_p_p.h116
-rw-r--r--src/declarative/items/qquickpositioners.cpp1532
-rw-r--r--src/declarative/items/qquickpositioners_p.h295
-rw-r--r--src/declarative/items/qquickpositioners_p_p.h164
-rw-r--r--src/declarative/items/qquickrectangle.cpp556
-rw-r--r--src/declarative/items/qquickrectangle_p.h189
-rw-r--r--src/declarative/items/qquickrectangle_p_p.h103
-rw-r--r--src/declarative/items/qquickrepeater.cpp476
-rw-r--r--src/declarative/items/qquickrepeater_p.h112
-rw-r--r--src/declarative/items/qquickrepeater_p_p.h89
-rw-r--r--src/declarative/items/qquickscalegrid.cpp214
-rw-r--r--src/declarative/items/qquickscalegrid_p_p.h134
-rw-r--r--src/declarative/items/qquickshadereffect.cpp763
-rw-r--r--src/declarative/items/qquickshadereffect_p.h158
-rw-r--r--src/declarative/items/qquickshadereffectmesh.cpp216
-rw-r--r--src/declarative/items/qquickshadereffectmesh_p.h103
-rw-r--r--src/declarative/items/qquickshadereffectnode.cpp317
-rw-r--r--src/declarative/items/qquickshadereffectnode_p.h151
-rw-r--r--src/declarative/items/qquickshadereffectsource.cpp921
-rw-r--r--src/declarative/items/qquickshadereffectsource_p.h259
-rw-r--r--src/declarative/items/qquicksprite.cpp130
-rw-r--r--src/declarative/items/qquicksprite_p.h136
-rw-r--r--src/declarative/items/qquickspriteengine.cpp501
-rw-r--r--src/declarative/items/qquickspriteengine_p.h323
-rw-r--r--src/declarative/items/qquickspriteimage.cpp455
-rw-r--r--src/declarative/items/qquickspriteimage_p.h140
-rw-r--r--src/declarative/items/qquickstateoperations.cpp1346
-rw-r--r--src/declarative/items/qquickstateoperations_p.h275
-rw-r--r--src/declarative/items/qquicktext.cpp1950
-rw-r--r--src/declarative/items/qquicktext_p.h252
-rw-r--r--src/declarative/items/qquicktext_p_p.h169
-rw-r--r--src/declarative/items/qquicktextedit.cpp2091
-rw-r--r--src/declarative/items/qquicktextedit_p.h314
-rw-r--r--src/declarative/items/qquicktextedit_p_p.h144
-rw-r--r--src/declarative/items/qquicktextinput.cpp2007
-rw-r--r--src/declarative/items/qquicktextinput_p.h302
-rw-r--r--src/declarative/items/qquicktextinput_p_p.h172
-rw-r--r--src/declarative/items/qquicktextnode.cpp1344
-rw-r--r--src/declarative/items/qquicktextnode_p.h110
-rw-r--r--src/declarative/items/qquicktranslate.cpp319
-rw-r--r--src/declarative/items/qquicktranslate_p.h162
-rw-r--r--src/declarative/items/qquickview.cpp539
-rw-r--r--src/declarative/items/qquickview.h120
-rw-r--r--src/declarative/items/qquickview_p.h105
-rw-r--r--src/declarative/items/qquickvisualadaptormodel.cpp889
-rw-r--r--src/declarative/items/qquickvisualadaptormodel_p.h129
-rw-r--r--src/declarative/items/qquickvisualdatamodel.cpp2668
-rw-r--r--src/declarative/items/qquickvisualdatamodel_p.h242
-rw-r--r--src/declarative/items/qquickvisualitemmodel.cpp235
-rw-r--r--src/declarative/items/qquickvisualitemmodel_p.h175
-rw-r--r--src/declarative/items/qquickwindowmodule.cpp55
-rw-r--r--src/declarative/items/qquickwindowmodule_p.h63
-rw-r--r--src/declarative/items/syncexcludes11
-rw-r--r--src/declarative/particles/particleresources/noise.pngbin19477 -> 0 bytes
-rw-r--r--src/declarative/particles/particles.pri69
-rw-r--r--src/declarative/particles/particles.qrc5
-rw-r--r--src/declarative/particles/qquickage.cpp112
-rw-r--r--src/declarative/particles/qquickage_p.h102
-rw-r--r--src/declarative/particles/qquickangledirection.cpp116
-rw-r--r--src/declarative/particles/qquickangledirection_p.h133
-rw-r--r--src/declarative/particles/qquickcumulativedirection.cpp70
-rw-r--r--src/declarative/particles/qquickcumulativedirection_p.h69
-rw-r--r--src/declarative/particles/qquickcustomaffector.cpp211
-rw-r--r--src/declarative/particles/qquickcustomaffector_p.h164
-rw-r--r--src/declarative/particles/qquickcustomparticle.cpp596
-rw-r--r--src/declarative/particles/qquickcustomparticle_p.h121
-rw-r--r--src/declarative/particles/qquickdirection.cpp64
-rw-r--r--src/declarative/particles/qquickdirection_p.h71
-rw-r--r--src/declarative/particles/qquickellipseextruder.cpp80
-rw-r--r--src/declarative/particles/qquickellipseextruder_p.h86
-rw-r--r--src/declarative/particles/qquickfriction.cpp111
-rw-r--r--src/declarative/particles/qquickfriction_p.h104
-rw-r--r--src/declarative/particles/qquickgravity.cpp97
-rw-r--r--src/declarative/particles/qquickgravity_p.h118
-rw-r--r--src/declarative/particles/qquickgroupgoal.cpp112
-rw-r--r--src/declarative/particles/qquickgroupgoal_p.h102
-rw-r--r--src/declarative/particles/qquickimageparticle.cpp1803
-rw-r--r--src/declarative/particles/qquickimageparticle_p.h429
-rw-r--r--src/declarative/particles/qquickitemparticle.cpp269
-rw-r--r--src/declarative/particles/qquickitemparticle_p.h138
-rw-r--r--src/declarative/particles/qquicklineextruder.cpp84
-rw-r--r--src/declarative/particles/qquicklineextruder_p.h77
-rw-r--r--src/declarative/particles/qquickmaskextruder.cpp113
-rw-r--r--src/declarative/particles/qquickmaskextruder_p.h97
-rw-r--r--src/declarative/particles/qquickparticleaffector.cpp279
-rw-r--r--src/declarative/particles/qquickparticleaffector_p.h201
-rw-r--r--src/declarative/particles/qquickparticleemitter.cpp501
-rw-r--r--src/declarative/particles/qquickparticleemitter_p.h351
-rw-r--r--src/declarative/particles/qquickparticleextruder.cpp70
-rw-r--r--src/declarative/particles/qquickparticleextruder_p.h73
-rw-r--r--src/declarative/particles/qquickparticlegroup.cpp143
-rw-r--r--src/declarative/particles/qquickparticlegroup_p.h112
-rw-r--r--src/declarative/particles/qquickparticlepainter.cpp150
-rw-r--r--src/declarative/particles/qquickparticlepainter_p.h132
-rw-r--r--src/declarative/particles/qquickparticlesmodule.cpp120
-rw-r--r--src/declarative/particles/qquickparticlesmodule_p.h63
-rw-r--r--src/declarative/particles/qquickparticlesystem.cpp1106
-rw-r--r--src/declarative/particles/qquickparticlesystem_p.h380
-rw-r--r--src/declarative/particles/qquickpointattractor.cpp162
-rw-r--r--src/declarative/particles/qquickpointattractor_p.h169
-rw-r--r--src/declarative/particles/qquickpointdirection.cpp85
-rw-r--r--src/declarative/particles/qquickpointdirection_p.h135
-rw-r--r--src/declarative/particles/qquickrectangleextruder.cpp86
-rw-r--r--src/declarative/particles/qquickrectangleextruder_p.h88
-rw-r--r--src/declarative/particles/qquickspritegoal.cpp153
-rw-r--r--src/declarative/particles/qquickspritegoal_p.h125
-rw-r--r--src/declarative/particles/qquicktargetdirection.cpp131
-rw-r--r--src/declarative/particles/qquicktargetdirection_p.h191
-rw-r--r--src/declarative/particles/qquicktrailemitter.cpp285
-rw-r--r--src/declarative/particles/qquicktrailemitter_p.h171
-rw-r--r--src/declarative/particles/qquickturbulence.cpp205
-rw-r--r--src/declarative/particles/qquickturbulence_p.h119
-rw-r--r--src/declarative/particles/qquickv8particledata.cpp503
-rw-r--r--src/declarative/particles/qquickv8particledata_p.h69
-rw-r--r--src/declarative/particles/qquickwander.cpp180
-rw-r--r--src/declarative/particles/qquickwander_p.h161
-rw-r--r--src/declarative/qml/qdeclarativecomponent_p.h2
-rw-r--r--src/declarative/qml/qdeclarativeengine.cpp6
-rw-r--r--src/declarative/qml/qdeclarativeexpression_p.h2
-rw-r--r--src/declarative/qml/qdeclarativemetatype.cpp1
-rw-r--r--src/declarative/qtquick2.cpp193
-rw-r--r--src/declarative/qtquick2_p.h63
-rw-r--r--src/declarative/scenegraph/coreapi/qsgdefaultrenderer.cpp527
-rw-r--r--src/declarative/scenegraph/coreapi/qsgdefaultrenderer_p.h123
-rw-r--r--src/declarative/scenegraph/coreapi/qsggeometry.cpp466
-rw-r--r--src/declarative/scenegraph/coreapi/qsggeometry.h295
-rw-r--r--src/declarative/scenegraph/coreapi/qsggeometry_p.h73
-rw-r--r--src/declarative/scenegraph/coreapi/qsgmaterial.cpp535
-rw-r--r--src/declarative/scenegraph/coreapi/qsgmaterial.h144
-rw-r--r--src/declarative/scenegraph/coreapi/qsgnode.cpp1264
-rw-r--r--src/declarative/scenegraph/coreapi/qsgnode.h348
-rw-r--r--src/declarative/scenegraph/coreapi/qsgnodeupdater.cpp287
-rw-r--r--src/declarative/scenegraph/coreapi/qsgnodeupdater_p.h86
-rw-r--r--src/declarative/scenegraph/coreapi/qsgrenderer.cpp743
-rw-r--r--src/declarative/scenegraph/coreapi/qsgrenderer_p.h234
-rw-r--r--src/declarative/scenegraph/qsgadaptationlayer.cpp315
-rw-r--r--src/declarative/scenegraph/qsgadaptationlayer_p.h257
-rw-r--r--src/declarative/scenegraph/qsgcontext.cpp512
-rw-r--r--src/declarative/scenegraph/qsgcontext_p.h144
-rw-r--r--src/declarative/scenegraph/qsgcontextplugin.cpp104
-rw-r--r--src/declarative/scenegraph/qsgcontextplugin_p.h81
-rw-r--r--src/declarative/scenegraph/qsgdefaultdistancefieldglyphcache.cpp324
-rw-r--r--src/declarative/scenegraph/qsgdefaultdistancefieldglyphcache_p.h165
-rw-r--r--src/declarative/scenegraph/qsgdefaultglyphnode.cpp95
-rw-r--r--src/declarative/scenegraph/qsgdefaultglyphnode_p.cpp306
-rw-r--r--src/declarative/scenegraph/qsgdefaultglyphnode_p.h87
-rw-r--r--src/declarative/scenegraph/qsgdefaultglyphnode_p_p.h96
-rw-r--r--src/declarative/scenegraph/qsgdefaultimagenode.cpp293
-rw-r--r--src/declarative/scenegraph/qsgdefaultimagenode_p.h90
-rw-r--r--src/declarative/scenegraph/qsgdefaultrectanglenode.cpp548
-rw-r--r--src/declarative/scenegraph/qsgdefaultrectanglenode_p.h108
-rw-r--r--src/declarative/scenegraph/qsgdistancefieldglyphnode.cpp316
-rw-r--r--src/declarative/scenegraph/qsgdistancefieldglyphnode_p.cpp725
-rw-r--r--src/declarative/scenegraph/qsgdistancefieldglyphnode_p.h107
-rw-r--r--src/declarative/scenegraph/qsgdistancefieldglyphnode_p_p.h140
-rw-r--r--src/declarative/scenegraph/qsgflashnode.cpp62
-rw-r--r--src/declarative/scenegraph/qsgflashnode_p.h69
-rw-r--r--src/declarative/scenegraph/qsgpathsimplifier.cpp1673
-rw-r--r--src/declarative/scenegraph/qsgpathsimplifier_p.h68
-rw-r--r--src/declarative/scenegraph/scenegraph.pri86
-rw-r--r--src/declarative/scenegraph/util/qsgareaallocator.cpp290
-rw-r--r--src/declarative/scenegraph/util/qsgareaallocator_p.h73
-rw-r--r--src/declarative/scenegraph/util/qsgdistancefieldutil.cpp805
-rw-r--r--src/declarative/scenegraph/util/qsgdistancefieldutil_p.h111
-rw-r--r--src/declarative/scenegraph/util/qsgengine.cpp115
-rw-r--r--src/declarative/scenegraph/util/qsgengine.h102
-rw-r--r--src/declarative/scenegraph/util/qsgflatcolormaterial.cpp202
-rw-r--r--src/declarative/scenegraph/util/qsgflatcolormaterial.h74
-rw-r--r--src/declarative/scenegraph/util/qsgpainternode.cpp464
-rw-r--r--src/declarative/scenegraph/util/qsgpainternode_p.h160
-rw-r--r--src/declarative/scenegraph/util/qsgsimplematerial.h222
-rw-r--r--src/declarative/scenegraph/util/qsgsimplerectnode.cpp132
-rw-r--r--src/declarative/scenegraph/util/qsgsimplerectnode.h77
-rw-r--r--src/declarative/scenegraph/util/qsgsimpletexturenode.cpp154
-rw-r--r--src/declarative/scenegraph/util/qsgsimpletexturenode.h82
-rw-r--r--src/declarative/scenegraph/util/qsgtexture.cpp541
-rw-r--r--src/declarative/scenegraph/util/qsgtexture.h133
-rw-r--r--src/declarative/scenegraph/util/qsgtexture_p.h118
-rw-r--r--src/declarative/scenegraph/util/qsgtexturematerial.cpp410
-rw-r--r--src/declarative/scenegraph/util/qsgtexturematerial.h102
-rw-r--r--src/declarative/scenegraph/util/qsgtexturematerial_p.h73
-rw-r--r--src/declarative/scenegraph/util/qsgtextureprovider.cpp59
-rw-r--r--src/declarative/scenegraph/util/qsgtextureprovider_p.h68
-rw-r--r--src/declarative/scenegraph/util/qsgvertexcolormaterial.cpp173
-rw-r--r--src/declarative/scenegraph/util/qsgvertexcolormaterial.h69
-rw-r--r--src/declarative/util/qdeclarativeanimation.cpp2441
-rw-r--r--src/declarative/util/qdeclarativeanimation_p.h458
-rw-r--r--src/declarative/util/qdeclarativeanimation_p_p.h366
-rw-r--r--src/declarative/util/qdeclarativebehavior.cpp228
-rw-r--r--src/declarative/util/qdeclarativebehavior_p.h97
-rw-r--r--src/declarative/util/qdeclarativebind.cpp309
-rw-r--r--src/declarative/util/qdeclarativebind_p.h98
-rw-r--r--src/declarative/util/qdeclarativechangeset.cpp479
-rw-r--r--src/declarative/util/qdeclarativechangeset_p.h166
-rw-r--r--src/declarative/util/qdeclarativeconnections.cpp302
-rw-r--r--src/declarative/util/qdeclarativeconnections_p.h102
-rw-r--r--src/declarative/util/qdeclarativefontloader.cpp335
-rw-r--r--src/declarative/util/qdeclarativefontloader_p.h97
-rw-r--r--src/declarative/util/qdeclarativelistaccessor.cpp138
-rw-r--r--src/declarative/util/qdeclarativelistaccessor_p.h80
-rw-r--r--src/declarative/util/qdeclarativelistcompositor.cpp1203
-rw-r--r--src/declarative/util/qdeclarativelistcompositor_p.h371
-rw-r--r--src/declarative/util/qdeclarativepackage.cpp202
-rw-r--r--src/declarative/util/qdeclarativepackage_p.h98
-rw-r--r--src/declarative/util/qdeclarativepath.cpp1484
-rw-r--r--src/declarative/util/qdeclarativepath_p.h452
-rw-r--r--src/declarative/util/qdeclarativepath_p_p.h88
-rw-r--r--src/declarative/util/qdeclarativepathinterpolator.cpp122
-rw-r--r--src/declarative/util/qdeclarativepathinterpolator_p.h100
-rw-r--r--src/declarative/util/qdeclarativepixmapcache.cpp1241
-rw-r--r--src/declarative/util/qdeclarativepixmapcache_p.h143
-rw-r--r--src/declarative/util/qdeclarativepropertychanges.cpp796
-rw-r--r--src/declarative/util/qdeclarativepropertychanges_p.h112
-rw-r--r--src/declarative/util/qdeclarativesmoothedanimation.cpp503
-rw-r--r--src/declarative/util/qdeclarativesmoothedanimation_p.h103
-rw-r--r--src/declarative/util/qdeclarativesmoothedanimation_p_p.h136
-rw-r--r--src/declarative/util/qdeclarativespringanimation.cpp462
-rw-r--r--src/declarative/util/qdeclarativespringanimation_p.h111
-rw-r--r--src/declarative/util/qdeclarativestate.cpp734
-rw-r--r--src/declarative/util/qdeclarativestate_p.h210
-rw-r--r--src/declarative/util/qdeclarativestate_p_p.h264
-rw-r--r--src/declarative/util/qdeclarativestategroup.cpp516
-rw-r--r--src/declarative/util/qdeclarativestategroup_p.h97
-rw-r--r--src/declarative/util/qdeclarativestateoperations.cpp158
-rw-r--r--src/declarative/util/qdeclarativestateoperations_p.h88
-rw-r--r--src/declarative/util/qdeclarativestyledtext.cpp624
-rw-r--r--src/declarative/util/qdeclarativestyledtext_p.h69
-rw-r--r--src/declarative/util/qdeclarativesvgparser.cpp614
-rw-r--r--src/declarative/util/qdeclarativesvgparser_p.h60
-rw-r--r--src/declarative/util/qdeclarativesystempalette.cpp312
-rw-r--r--src/declarative/util/qdeclarativesystempalette_p.h122
-rw-r--r--src/declarative/util/qdeclarativetimeline.cpp947
-rw-r--r--src/declarative/util/qdeclarativetimeline_p_p.h200
-rw-r--r--src/declarative/util/qdeclarativetimer.cpp324
-rw-r--r--src/declarative/util/qdeclarativetimer_p.h115
-rw-r--r--src/declarative/util/qdeclarativetransition.cpp392
-rw-r--r--src/declarative/util/qdeclarativetransition_p.h111
-rw-r--r--src/declarative/util/qdeclarativetransitionmanager.cpp282
-rw-r--r--src/declarative/util/qdeclarativetransitionmanager_p_p.h85
-rw-r--r--src/declarative/util/qdeclarativeutilmodule.cpp98
-rw-r--r--src/declarative/util/qdeclarativeutilmodule_p.h63
-rw-r--r--src/declarative/util/util.pri60
332 files changed, 5 insertions, 117435 deletions
diff --git a/src/declarative/debugger/qdeclarativeenginedebugservice_p.h b/src/declarative/debugger/qdeclarativeenginedebugservice_p.h
index 7c74c63801..c2ee93b665 100644
--- a/src/declarative/debugger/qdeclarativeenginedebugservice_p.h
+++ b/src/declarative/debugger/qdeclarativeenginedebugservice_p.h
@@ -66,7 +66,7 @@ class QDeclarativeWatcher;
class QDataStream;
class QDeclarativeDebugStatesDelegate;
-class QDeclarativeEngineDebugService : public QDeclarativeDebugService
+class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativeEngineDebugService : public QDeclarativeDebugService
{
Q_OBJECT
public:
diff --git a/src/declarative/declarative.pro b/src/declarative/declarative.pro
index 265e4eba33..ca81a4a3d3 100644
--- a/src/declarative/declarative.pro
+++ b/src/declarative/declarative.pro
@@ -31,10 +31,3 @@ HEADERS += qtdeclarativeversion.h
include(util/util.pri)
include(qml/qml.pri)
include(debugger/debugger.pri)
-include(scenegraph/scenegraph.pri)
-include(items/items.pri)
-include(particles/particles.pri)
-include(designer/designer.pri)
-
-HEADERS += qtquick2_p.h
-SOURCES += qtquick2.cpp
diff --git a/src/declarative/designer/designer.pri b/src/declarative/designer/designer.pri
deleted file mode 100644
index c523525977..0000000000
--- a/src/declarative/designer/designer.pri
+++ /dev/null
@@ -1,2 +0,0 @@
-HEADERS += designer/designersupport.h
-SOURCES += designer/designersupport.cpp
diff --git a/src/declarative/designer/designersupport.cpp b/src/declarative/designer/designersupport.cpp
deleted file mode 100644
index 9c565c138c..0000000000
--- a/src/declarative/designer/designersupport.cpp
+++ /dev/null
@@ -1,408 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "designersupport.h"
-#include <private/qquickitem_p.h>
-
-#include <private/qquickshadereffectsource_p.h>
-#include <private/qquickrectangle_p.h>
-#include <private/qdeclarativeengine_p.h>
-#include <private/qquickview_p.h>
-#include <private/qdeclarativestategroup_p.h>
-#include <QtGui/QImage>
-
-QT_BEGIN_NAMESPACE
-
-DesignerSupport::DesignerSupport()
-{
-}
-
-DesignerSupport::~DesignerSupport()
-{
- QHash<QQuickItem*, QQuickShaderEffectTexture*>::iterator iterator;
-
- for (iterator = m_itemTextureHash.begin(); iterator != m_itemTextureHash.end(); ++iterator) {
- QQuickShaderEffectTexture *texture = iterator.value();
- QQuickItem *item = iterator.key();
- QQuickItemPrivate::get(item)->derefFromEffectItem(true);
- delete texture;
- }
-}
-
-void DesignerSupport::refFromEffectItem(QQuickItem *referencedItem, bool hide)
-{
- if (referencedItem == 0)
- return;
-
- QQuickItemPrivate::get(referencedItem)->refFromEffectItem(hide);
- QQuickCanvasPrivate::get(referencedItem->canvas())->updateDirtyNode(referencedItem);
-
- Q_ASSERT(QQuickItemPrivate::get(referencedItem)->rootNode);
-
- if (!m_itemTextureHash.contains(referencedItem)) {
- QQuickShaderEffectTexture *texture = new QQuickShaderEffectTexture(referencedItem);
-
- texture->setLive(true);
- texture->setItem(QQuickItemPrivate::get(referencedItem)->rootNode);
- texture->setRect(referencedItem->boundingRect());
- texture->setSize(referencedItem->boundingRect().size().toSize());
- texture->setRecursive(true);
-#ifndef QT_OPENGL_ES
- texture->setFormat(GL_RGBA8);
-#else
- texture->setFormat(GL_RGBA);
-#endif
- texture->setHasMipmaps(false);
-
- m_itemTextureHash.insert(referencedItem, texture);
- }
-}
-
-void DesignerSupport::derefFromEffectItem(QQuickItem *referencedItem, bool unhide)
-{
- if (referencedItem == 0)
- return;
-
- delete m_itemTextureHash.take(referencedItem);
- QQuickItemPrivate::get(referencedItem)->derefFromEffectItem(unhide);
-}
-
-QImage DesignerSupport::renderImageForItem(QQuickItem *referencedItem, const QRectF &boundingRect, const QSize &imageSize)
-{
- if (referencedItem == 0 || referencedItem->parentItem() == 0) {
- qDebug() << __FILE__ << __LINE__ << "Warning: Item can be rendered.";
- return QImage();
- }
-
- QQuickShaderEffectTexture *renderTexture = m_itemTextureHash.value(referencedItem);
-
- Q_ASSERT(renderTexture);
- if (renderTexture == 0)
- return QImage();
- renderTexture->setRect(boundingRect);
- renderTexture->setSize(imageSize);
- renderTexture->updateTexture();
-
- QImage renderImage = renderTexture->toImage();
- renderImage = renderImage.mirrored(false, true);
-
- if (renderImage.size().isEmpty())
- qDebug() << __FILE__ << __LINE__ << "Warning: Image is empty.";
-
- return renderImage;
-}
-
-bool DesignerSupport::isDirty(QQuickItem *referencedItem, DirtyType dirtyType)
-{
- if (referencedItem == 0)
- return false;
-
- return QQuickItemPrivate::get(referencedItem)->dirtyAttributes & dirtyType;
-}
-
-void DesignerSupport::resetDirty(QQuickItem *referencedItem)
-{
- if (referencedItem == 0)
- return;
-
- QQuickItemPrivate::get(referencedItem)->dirtyAttributes = 0x0;
- QQuickItemPrivate::get(referencedItem)->removeFromDirtyList();
-}
-
-QTransform DesignerSupport::canvasTransform(QQuickItem *referencedItem)
-{
- if (referencedItem == 0)
- return QTransform();
-
- return QQuickItemPrivate::get(referencedItem)->itemToCanvasTransform();
-}
-
-QTransform DesignerSupport::parentTransform(QQuickItem *referencedItem)
-{
- if (referencedItem == 0)
- return QTransform();
-
- QTransform parentTransform;
-
- QQuickItemPrivate::get(referencedItem)->itemToParentTransform(parentTransform);
-
- return parentTransform;
-}
-
-QString propertyNameForAnchorLine(const QQuickAnchorLine::AnchorLine &anchorLine)
-{
- switch (anchorLine) {
- case QQuickAnchorLine::Left: return QLatin1String("left");
- case QQuickAnchorLine::Right: return QLatin1String("right");
- case QQuickAnchorLine::Top: return QLatin1String("top");
- case QQuickAnchorLine::Bottom: return QLatin1String("bottom");
- case QQuickAnchorLine::HCenter: return QLatin1String("horizontalCenter");
- case QQuickAnchorLine::VCenter: return QLatin1String("verticalCenter");
- case QQuickAnchorLine::Baseline: return QLatin1String("baseline");
- case QQuickAnchorLine::Invalid:
- default: return QString();
- }
-}
-
-bool isValidAnchorName(const QString &name)
-{
- static QStringList anchorNameList(QStringList() << QLatin1String("anchors.top")
- << QLatin1String("anchors.left")
- << QLatin1String("anchors.right")
- << QLatin1String("anchors.bottom")
- << QLatin1String("anchors.verticalCenter")
- << QLatin1String("anchors.horizontalCenter")
- << QLatin1String("anchors.fill")
- << QLatin1String("anchors.centerIn")
- << QLatin1String("anchors.baseline"));
-
- return anchorNameList.contains(name);
-}
-
-bool DesignerSupport::isAnchoredTo(QQuickItem *fromItem, QQuickItem *toItem)
-{
- Q_ASSERT(dynamic_cast<QQuickItemPrivate*>(QQuickItemPrivate::get(fromItem)));
- QQuickItemPrivate *fromItemPrivate = static_cast<QQuickItemPrivate*>(QQuickItemPrivate::get(fromItem));
- QQuickAnchors *anchors = fromItemPrivate->anchors();
- return anchors->fill() == toItem
- || anchors->centerIn() == toItem
- || anchors->bottom().item == toItem
- || anchors->top().item == toItem
- || anchors->left().item == toItem
- || anchors->right().item == toItem
- || anchors->verticalCenter().item == toItem
- || anchors->horizontalCenter().item == toItem
- || anchors->baseline().item == toItem;
-}
-
-bool DesignerSupport::areChildrenAnchoredTo(QQuickItem *fromItem, QQuickItem *toItem)
-{
- foreach (QQuickItem *childItem, fromItem->childItems()) {
- if (childItem) {
- if (isAnchoredTo(childItem, toItem))
- return true;
-
- if (areChildrenAnchoredTo(childItem, toItem))
- return true;
- }
- }
-
- return false;
-}
-
-QQuickAnchors *anchors(QQuickItem *item)
-{
- QQuickItemPrivate *itemPrivate = static_cast<QQuickItemPrivate*>(QQuickItemPrivate::get(item));
- return itemPrivate->anchors();
-}
-
-QQuickAnchors::Anchor anchorLineFlagForName(const QString &name)
-{
- if (name == QLatin1String("anchors.top"))
- return QQuickAnchors::TopAnchor;
-
- if (name == QLatin1String("anchors.left"))
- return QQuickAnchors::LeftAnchor;
-
- if (name == QLatin1String("anchors.bottom"))
- return QQuickAnchors::BottomAnchor;
-
- if (name == QLatin1String("anchors.right"))
- return QQuickAnchors::RightAnchor;
-
- if (name == QLatin1String("anchors.horizontalCenter"))
- return QQuickAnchors::HCenterAnchor;
-
- if (name == QLatin1String("anchors.verticalCenter"))
- return QQuickAnchors::VCenterAnchor;
-
- if (name == QLatin1String("anchors.baseline"))
- return QQuickAnchors::BaselineAnchor;
-
-
- Q_ASSERT_X(false, Q_FUNC_INFO, "wrong anchor name - this should never happen");
- return QQuickAnchors::LeftAnchor;
-}
-
-bool DesignerSupport::hasAnchor(QQuickItem *item, const QString &name)
-{
- if (!isValidAnchorName(name))
- return false;
-
- if (name == QLatin1String("anchors.fill"))
- return anchors(item)->fill() != 0;
-
- if (name == QLatin1String("anchors.centerIn"))
- return anchors(item)->centerIn() != 0;
-
- if (name == QLatin1String("anchors.right"))
- return anchors(item)->right().item != 0;
-
- if (name == QLatin1String("anchors.top"))
- return anchors(item)->top().item != 0;
-
- if (name == QLatin1String("anchors.left"))
- return anchors(item)->left().item != 0;
-
- if (name == QLatin1String("anchors.bottom"))
- return anchors(item)->bottom().item != 0;
-
- if (name == QLatin1String("anchors.horizontalCenter"))
- return anchors(item)->horizontalCenter().item != 0;
-
- if (name == QLatin1String("anchors.verticalCenter"))
- return anchors(item)->verticalCenter().item != 0;
-
- if (name == QLatin1String("anchors.baseline"))
- return anchors(item)->baseline().item != 0;
-
- return anchors(item)->usedAnchors().testFlag(anchorLineFlagForName(name));
-}
-
-QQuickItem *DesignerSupport::anchorFillTargetItem(QQuickItem *item)
-{
- return anchors(item)->fill();
-}
-
-QQuickItem *DesignerSupport::anchorCenterInTargetItem(QQuickItem *item)
-{
- return anchors(item)->centerIn();
-}
-
-
-
-QPair<QString, QObject*> DesignerSupport::anchorLineTarget(QQuickItem *item, const QString &name, QDeclarativeContext *context)
-{
- QObject *targetObject = 0;
- QString targetName;
-
- if (name == QLatin1String("anchors.fill")) {
- targetObject = anchors(item)->fill();
- } else if (name == QLatin1String("anchors.centerIn")) {
- targetObject = anchors(item)->centerIn();
- } else {
- QDeclarativeProperty metaProperty(item, name, context);
- if (!metaProperty.isValid())
- return QPair<QString, QObject*>();
-
- QQuickAnchorLine anchorLine = metaProperty.read().value<QQuickAnchorLine>();
- if (anchorLine.anchorLine != QQuickAnchorLine::Invalid) {
- targetObject = anchorLine.item;
- targetName = propertyNameForAnchorLine(anchorLine.anchorLine);
- }
-
- }
-
- return QPair<QString, QObject*>(targetName, targetObject);
-}
-
-void DesignerSupport::resetAnchor(QQuickItem *item, const QString &name)
-{
- if (name == QLatin1String("anchors.fill")) {
- anchors(item)->resetFill();
- } else if (name == QLatin1String("anchors.centerIn")) {
- anchors(item)->resetCenterIn();
- } else if (name == QLatin1String("anchors.top")) {
- anchors(item)->resetTop();
- } else if (name == QLatin1String("anchors.left")) {
- anchors(item)->resetLeft();
- } else if (name == QLatin1String("anchors.right")) {
- anchors(item)->resetRight();
- } else if (name == QLatin1String("anchors.bottom")) {
- anchors(item)->resetBottom();
- } else if (name == QLatin1String("anchors.horizontalCenter")) {
- anchors(item)->resetHorizontalCenter();
- } else if (name == QLatin1String("anchors.verticalCenter")) {
- anchors(item)->resetVerticalCenter();
- } else if (name == QLatin1String("anchors.baseline")) {
- anchors(item)->resetBaseline();
- }
-}
-
-QList<QObject*> DesignerSupport::statesForItem(QQuickItem *item)
-{
- QList<QObject*> objectList;
- QList<QDeclarativeState *> stateList = QQuickItemPrivate::get(item)->_states()->states();
- qCopy(stateList.begin(), stateList.end(), objectList.begin());
-
- return objectList;
-}
-
-bool DesignerSupport::isComponentComplete(QQuickItem *item)
-{
- return static_cast<QQuickItemPrivate*>(QQuickItemPrivate::get(item))->componentComplete;
-}
-
-int DesignerSupport::borderWidth(QQuickItem *item)
-{
- QQuickRectangle *rectangle = qobject_cast<QQuickRectangle*>(item);
- if (rectangle)
- return rectangle->border()->width();
-
- return 0;
-}
-
-void DesignerSupport::refreshExpressions(QDeclarativeContext *context)
-{
- QDeclarativeContextPrivate::get(context)->data->refreshExpressions();
-}
-
-void DesignerSupport::setRootItem(QQuickView *view, QQuickItem *item)
-{
- QQuickViewPrivate::get(view)->setRootObject(item);
-}
-
-bool DesignerSupport::isValidWidth(QQuickItem *item)
-{
- return QQuickItemPrivate::get(item)->heightValid;
-}
-
-bool DesignerSupport::isValidHeight(QQuickItem *item)
-{
- return QQuickItemPrivate::get(item)->widthValid;
-}
-
-void DesignerSupport::updateDirtyNode(QQuickItem *item)
-{
- QQuickCanvasPrivate::get(item->canvas())->updateDirtyNode(item);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/designer/designersupport.h b/src/declarative/designer/designersupport.h
deleted file mode 100644
index 7654363276..0000000000
--- a/src/declarative/designer/designersupport.h
+++ /dev/null
@@ -1,153 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DESIGNERSUPPORT_H
-#define DESIGNERSUPPORT_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 <QtCore/QtGlobal>
-#include <QtCore/QHash>
-#include <QtCore/QRectF>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickItem;
-class QQuickShaderEffectTexture;
-class QImage;
-class QTransform;
-class QDeclarativeContext;
-class QQuickView;
-
-
-class Q_DECLARATIVE_EXPORT DesignerSupport
-{
-public:
- enum DirtyType {
- TransformOrigin = 0x00000001,
- Transform = 0x00000002,
- BasicTransform = 0x00000004,
- Position = 0x00000008,
- Size = 0x00000010,
-
- ZValue = 0x00000020,
- Content = 0x00000040,
- Smooth = 0x00000080,
- OpacityValue = 0x00000100,
- ChildrenChanged = 0x00000200,
- ChildrenStackingChanged = 0x00000400,
- ParentChanged = 0x00000800,
-
- Clip = 0x00001000,
- Canvas = 0x00002000,
-
- EffectReference = 0x00008000,
- Visible = 0x00010000,
- HideReference = 0x00020000,
-
- TransformUpdateMask = TransformOrigin | Transform | BasicTransform | Position | Size | Canvas,
- ComplexTransformUpdateMask = Transform | Canvas,
- ContentUpdateMask = Size | Content | Smooth | Canvas,
- ChildrenUpdateMask = ChildrenChanged | ChildrenStackingChanged | EffectReference | Canvas
- };
-
-
- DesignerSupport();
- ~DesignerSupport();
-
- void refFromEffectItem(QQuickItem *referencedItem, bool hide = true);
- void derefFromEffectItem(QQuickItem *referencedItem, bool unhide = true);
-
- QImage renderImageForItem(QQuickItem *referencedItem, const QRectF &boundingRect, const QSize &imageSize);
-
- static bool isDirty(QQuickItem *referencedItem, DirtyType dirtyType);
- static void resetDirty(QQuickItem *referencedItem);
-
- static QTransform canvasTransform(QQuickItem *referencedItem);
- static QTransform parentTransform(QQuickItem *referencedItem);
-
- static bool isAnchoredTo(QQuickItem *fromItem, QQuickItem *toItem);
- static bool areChildrenAnchoredTo(QQuickItem *fromItem, QQuickItem *toItem);
- static bool hasAnchor(QQuickItem *item, const QString &name);
- static QQuickItem *anchorFillTargetItem(QQuickItem *item);
- static QQuickItem *anchorCenterInTargetItem(QQuickItem *item);
- static QPair<QString, QObject*> anchorLineTarget(QQuickItem *item, const QString &name, QDeclarativeContext *context);
- static void resetAnchor(QQuickItem *item, const QString &name);
-
-
- static QList<QObject*> statesForItem(QQuickItem *item);
-
- static bool isComponentComplete(QQuickItem *item);
-
- static int borderWidth(QQuickItem *item);
-
- static void refreshExpressions(QDeclarativeContext *context);
-
- static void setRootItem(QQuickView *view, QQuickItem *item);
-
- static bool isValidWidth(QQuickItem *item);
- static bool isValidHeight(QQuickItem *item);
-
- static void updateDirtyNode(QQuickItem *item);
-
-private:
- QHash<QQuickItem*, QQuickShaderEffectTexture*> m_itemTextureHash;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // DESIGNERSUPPORT_H
diff --git a/src/declarative/items/checksync.pl b/src/declarative/items/checksync.pl
deleted file mode 100755
index 7dffa72e88..0000000000
--- a/src/declarative/items/checksync.pl
+++ /dev/null
@@ -1,108 +0,0 @@
-#!/usr/bin/perl
-#############################################################################
-##
-## Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-## All rights reserved.
-## Contact: Nokia Corporation (qt-info@nokia.com)
-##
-## This file is part of the Declarative module of the Qt Toolkit.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## GNU Lesser General Public License Usage
-## This file may be used under the terms of the GNU Lesser General Public
-## License version 2.1 as published by the Free Software Foundation and
-## appearing in the file LICENSE.LGPL included in the packaging of this
-## file. Please review the following information to ensure the GNU Lesser
-## General Public License version 2.1 requirements will be met:
-## http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-##
-## In addition, as a special exception, Nokia gives you certain additional
-## rights. These rights are described in the Nokia Qt LGPL Exception
-## version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU General
-## Public License version 3.0 as published by the Free Software Foundation
-## and appearing in the file LICENSE.GPL included in the packaging of this
-## file. Please review the following information to ensure the GNU General
-## Public License version 3.0 requirements will be met:
-## http://www.gnu.org/copyleft/gpl.html.
-##
-## Other Usage
-## Alternatively, this file may be used in accordance with the terms and
-## conditions contained in a signed written agreement between you and Nokia.
-##
-##
-##
-##
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-use strict;
-use warnings;
-
-die "Usage: $0 <QML directory>" if (@ARGV != 1);
-
-my @excludes;
-open (SYNCEXCLUDES, "<", "syncexcludes");
-while (<SYNCEXCLUDES>) {
- if (/^([a-zA-Z0-9\._]+)/) {
- my $exclude = $1;
- push (@excludes, $exclude);
- }
-}
-
-my $portdir = ".";
-my $qmldir = $ARGV[0];
-
-opendir (PORTDIR, $portdir) or die "Cannot open port directory";
-opendir (QMLDIR, $qmldir) or die "Cannot open QML directory";
-
-my @portfiles = readdir(PORTDIR);
-my @qmlfiles = readdir(QMLDIR);
-
-closedir(PORTDIR);
-closedir(QMLDIR);
-
-foreach my $qmlfile (@qmlfiles) {
- if ($qmlfile =~ /^qdeclarative.*\.cpp$/ or $qmlfile =~ /qdeclarative.*\.h$/) {
-
- if (grep { $_ eq $qmlfile} @excludes) {
- next;
- }
-
- my $portfile = $qmlfile;
- $portfile =~ s/^qdeclarative/qsg/;
-
- if (grep { $_ eq $portfile} @portfiles) {
-
- open (PORTFILE, "<", "$portdir/$portfile") or die("Cannot open $portdir/$portfile for reading");
-
- my $firstline = <PORTFILE>;
-
- close (PORTFILE);
-
- if ($firstline and $firstline =~ /^\/\/ Commit: ([a-z0-9]+)/) {
- my $sha1 = $1;
- my $commitSha1 = "";
-
- my $output = `cd $qmldir; git log $qmlfile | head -n 1`;
- if ($output =~ /commit ([a-z0-9]+)/) {
- $commitSha1 = $1;
- }
-
- if ($commitSha1 eq $sha1) {
- print ("$portfile: OK\n");
- } else {
- print ("$portfile: OUT OF DATE\n");
- }
- } else {
- print ("$portfile: OUT OF DATE\n");
- }
- } else {
- print ("$portfile: MISSING\n");
- }
- }
-}
diff --git a/src/declarative/items/context2d/context2d.pri b/src/declarative/items/context2d/context2d.pri
deleted file mode 100644
index 60b3e4b0c1..0000000000
--- a/src/declarative/items/context2d/context2d.pri
+++ /dev/null
@@ -1,16 +0,0 @@
-SOURCES += \
- $$PWD/qquickcanvasitem.cpp \
- $$PWD/qquickcontext2d.cpp \
- $$PWD/qquickcontext2dnode.cpp \
- $$PWD/qquickcontext2dtile.cpp \
- $$PWD/qquickcontext2dtexture.cpp \
- $$PWD/qquickcontext2dcommandbuffer.cpp \
-
-HEADERS += \
- $$PWD/qquickcanvasitem_p.h \
- $$PWD/qquickcontext2d_p.h \
- $$PWD/qquickcontext2dnode_p.h \
- $$PWD/qquickcontext2dtile_p.h \
- $$PWD/qquickcontext2dtexture_p.h \
- $$PWD/qquickcontext2dcommandbuffer_p.h \
-
diff --git a/src/declarative/items/context2d/qquickcanvasitem.cpp b/src/declarative/items/context2d/qquickcanvasitem.cpp
deleted file mode 100644
index 81b7a49722..0000000000
--- a/src/declarative/items/context2d/qquickcanvasitem.cpp
+++ /dev/null
@@ -1,714 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <private/qsgadaptationlayer_p.h>
-#include "qquickcanvasitem_p.h"
-#include <private/qquickitem_p.h>
-#include "qquickcontext2d_p.h"
-#include "qquickcontext2dnode_p.h"
-#include "qquickcontext2dtexture_p.h"
-#include <private/qdeclarativepixmapcache_p.h>
-
-#include <qdeclarativeinfo.h>
-#include <private/qdeclarativeengine_p.h>
-#include <QtCore/QBuffer>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickCanvasItemPrivate : public QQuickItemPrivate
-{
-public:
- QQuickCanvasItemPrivate();
- ~QQuickCanvasItemPrivate();
- QQuickContext2D* context;
- QQuickContext2DTexture* texture;
- QSizeF canvasSize;
- QSize tileSize;
- QRectF canvasWindow;
- QRectF dirtyRect;
- uint renderInThread : 1;
- uint hasCanvasSize :1;
- uint hasTileSize :1;
- uint hasCanvasWindow :1;
- uint componentCompleted :1;
- QQuickCanvasItem::RenderTarget renderTarget;
- QHash<QUrl, QDeclarativePixmap*> images;
- QUrl baseUrl;
-};
-
-QQuickCanvasItemPrivate::QQuickCanvasItemPrivate()
- : QQuickItemPrivate()
- , context(0)
- , texture(0)
- , canvasSize(1, 1)
- , tileSize(1, 1)
- , renderInThread(false)
- , hasCanvasSize(false)
- , hasTileSize(false)
- , hasCanvasWindow(false)
- , componentCompleted(false)
- , renderTarget(QQuickCanvasItem::FramebufferObject)
-{
-}
-
-QQuickCanvasItemPrivate::~QQuickCanvasItemPrivate()
-{
- qDeleteAll(images);
-}
-
-/*!
- \qmlclass Canvas QQuickCanvasItem
- \inqmlmodule QtQuick 2
- \since QtQuick 2.0
- \brief The Canvas item provides a 2D canvas element which enables drawing via Javascript.
- \inherits Item
- \ingroup qml-basic-visual-elements
-
- The Canvas item allows drawing of straight and curved lines, simple and
- complex shapes, graphs, and referenced graphic images. It can also add text, colors,
- shadows, gradients, and patterns, and do low level pixel operations. The Canvas
- output may be saved as an image file or serialized to a url.
-
- To define a drawing area in the Canvas item set the \c width and \c height properties.
- For example, the following code creates a Canvas item which has a drawing area with a height of 100
- pixels and width of 200 pixels:
- \qml
- import QtQuick 2.0
- Canvas {
- id:mycanvas
- width:100
- height:200
- }
- \endqml
-
- Currently the Canvas item only supports the two-dimensional rendering context.
-
- \section1 Threaded Rendering and Render Target
-
- The Canvas item supports two render targets: \c Canvas.Image and \c Canvas.FramebufferObject.
-
- The \c Canvas.Image render target is a \a QImage object. This render target supports background
- thread rendering, allowing complex or long running painting to be executed without blocking the UI.
-
- The Canvas.FramebufferObject render target utilizes OpenGL hardware accelaration rather than rendering into
- system memory, which in many cases results in faster rendering.
-
- The default render target is Canvas.Image and the default renderInThread property is
- false.
-
- \section1 Tiled Canvas
- The Canvas item supports tiled rendering by setting \l canvasSize, \l tileSize
- and \l canvasWindow properties.
-
- Tiling allows efficient display of a very large virtual via a smaller canvas
- window. The actual memory consumption is in relatation to the canvas window size. The painting
- code can draw within the virtual canvas without handling coordinate system transformations.
-
- The tiles overlapping with the canvas window may be cached eliminating the need to redraw,
- which can lead to significantly improved performance in some situations.
-
- \section1 Pixel Operations
- All HTML5 2D context pixel operations are supported. In order to ensure improved
- pixel reading/writing performance the \a Canvas.Image render target should be chosen. The
- \a Canvas.FramebufferObject render target requires the pixel data to be exchanged between
- the system memory and the graphic card, which is significantly more expensive. Rendering
- may also be synchronized with the V-sync signal (to avoid {en.wikipedia.org/wiki/Screen_tearing}{screen tearing})
- which will futher impact pixel operations with \c Canvas.FrambufferObject render target.
-
- \section1 Tips for Porting Existing HTML5 Canvas applications
-
- Although the Canvas item is provides a HTML5 like API, HTML5 canvas applications
- need to be modified to run in the Canvas item:
- \list
- \o Replace all DOM API calls with QML property bindings or Canvas item methods.
- \o Replace all HTML event handlers with the \a MouseArea item.
- \o Change setInterval/setTimeout function calls with the \a Timer item.
- \o Place painting code into the \a QtQuick2::Canvas::onPaint handler and trigger
- painting by calling the \c markDirty or \c requestPaint methods.
- \o To draw images, load them by calling the Canvas's loadImage method and then request to paint
- them in the onImageLoaded handler.
- \endlist
-
- \sa QtQuick2::Context2D
-*/
-
-QQuickCanvasItem::QQuickCanvasItem(QQuickItem *parent)
- : QQuickItem(*(new QQuickCanvasItemPrivate), parent)
-{
- setFlag(ItemHasContents);
-}
-
-QQuickCanvasItem::~QQuickCanvasItem()
-{
- Q_D(QQuickCanvasItem);
- delete d->context;
-}
-
-/*!
- \qmlproperty size QtQuick2::Canvas::canvasSize
- Holds the logical canvas size that the context paints on.
-
- By default, the canvas size is the same size as the current canvas item size.
- By setting the canvasSize, tileSize and canvasWindow, the Canvas
- item can act as a large virtual canvas with many seperately rendered tile rectangles
- Only those tiles within the current canvas window are painted by
- the Canvas render engine.
-
- \sa QtQuick2::Canvas::tileSize QtQuick2::Canvas::canvasWindow
-*/
-QSizeF QQuickCanvasItem::canvasSize() const
-{
- Q_D(const QQuickCanvasItem);
- return d->canvasSize;
-}
-
-void QQuickCanvasItem::setCanvasSize(const QSizeF & size)
-{
- Q_D(QQuickCanvasItem);
- if (d->canvasSize != size) {
- d->hasCanvasSize = true;
- d->canvasSize = size;
- emit canvasSizeChanged();
- polish();
- update();
- }
-}
-
-/*!
- \qmlproperty size QtQuick2::Canvas::tileSize
- Holds the canvas rendering tile size.
-
- The Canvas item enters tiled mode by setting canvasSize, tileSize and
- the canvasWindow. This can improve rendering performance
- by rendering and caching tiles instead of rendering the whole canvas every time.
-
- Memory will be consumed only by those tiles within the current visible region.
-
- By default the tileSize is the same as the canvasSize.
-
- \sa QtQuick2::Canvas::canvaasSize QtQuick2::Canvas::canvasWindow
-*/
-QSize QQuickCanvasItem::tileSize() const
-{
- Q_D(const QQuickCanvasItem);
- return d->tileSize;
-}
-
-void QQuickCanvasItem::setTileSize(const QSize & size)
-{
- Q_D(QQuickCanvasItem);
- if (d->tileSize != size) {
- d->hasTileSize = true;
- d->tileSize = size;
-
- emit tileSizeChanged();
- polish();
- update();
- }
-}
-
-/*!
- \qmlproperty rect QtQuick2::Canvas::canvasWindow
- Holds the current canvas visible window.
-
- By default the canvasWindow size is the same as the Canvas item
- size with the topleft point as (0, 0).
-
- If the canvasSize is different to the Canvas item size, the Canvas
- item can display different visible areas by changing the canvas windowSize
- and/or position.
-
- \sa QtQuick2::Canvas::canvasSize QtQuick2::Canvas::tileSize
-*/
-QRectF QQuickCanvasItem::canvasWindow() const
-{
- Q_D(const QQuickCanvasItem);
- return d->canvasWindow;
-}
-
-void QQuickCanvasItem::setCanvasWindow(const QRectF& rect)
-{
- Q_D(QQuickCanvasItem);
- if (d->canvasWindow != rect) {
- d->canvasWindow = rect;
-
- d->hasCanvasWindow = true;
- emit canvasWindowChanged();
- polish();
- update();
- }
-}
-
-
-QQuickContext2D* QQuickCanvasItem::context() const
-{
- Q_D(const QQuickCanvasItem);
- return d->context;
-}
-/*!
- \qmlproperty bool QtQuick2::Canvas::renderInThread
- Holds the current canvas rendering mode.
-
- Set renderInThread to true to render complex and long
- running painting in a dedicated background
- thread, avoiding blocking the main UI.
-
- \note: Not all renderTargets support background rendering. If background rendering
- is not supported by the current renderTarget, the renderInThread
- property is ignored.
-
- The default value is false.
- \sa QtQuick2::Canvas::renderTarget
-*/
-bool QQuickCanvasItem::renderInThread() const
-{
- Q_D(const QQuickCanvasItem);
- return d->renderInThread;
-}
-/*!
- \qmlproperty bool QtQuick2::Canvas::renderTarget
- Holds the current canvas render target.
-
- \list
- \o Canvas.Image - render to an in memory image buffer, the render
- target supports background rendering.
- \o Canvas.FramebufferObject - render to an OpenGL frame buffer,
- this render target will ignore the
- renderInThread property. The actual
- rendering happens in the main QML rendering
- process, which may be in a seperate render thread
- or in the main GUI thread depending upon the platform.
- \endlist
-
- The default render target is \c Canvas.Image.
- \sa QtQuick2::Canvas::renderInThread
-*/
-QQuickCanvasItem::RenderTarget QQuickCanvasItem::renderTarget() const
-{
- Q_D(const QQuickCanvasItem);
- return d->renderTarget;
-}
-
-void QQuickCanvasItem::setRenderTarget(RenderTarget target)
-{
- Q_D(QQuickCanvasItem);
- if (d->renderTarget != target) {
- d->renderTarget = target;
-
- if (d->componentCompleted)
- createTexture();
- emit renderTargetChanged();
- }
-}
-
-void QQuickCanvasItem::_doPainting(const QRectF& region)
-{
- Q_D(QQuickCanvasItem);
- emit paint(QDeclarativeV8Handle::fromHandle(d->context->v8value())
- , QQuickContext2DTexture::tiledRect(region, d->tileSize));
- if (d->texture)
- d->texture->wake();
-}
-
-void QQuickCanvasItem::setRenderInThread(bool renderInThread)
-{
- Q_D(QQuickCanvasItem);
- if (d->renderInThread != renderInThread) {
- d->renderInThread = renderInThread;
-
- if (d->componentCompleted)
- createTexture();
-
- if (d->renderInThread)
- connect(this, SIGNAL(painted()), SLOT(update()));
- else
- disconnect(this, SIGNAL(painted()), this, SLOT(update()));
- emit renderInThreadChanged();
- polish();
- update();
- }
-}
-
-void QQuickCanvasItem::geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry)
-{
- Q_D(QQuickCanvasItem);
- QQuickItem::geometryChanged(newGeometry, oldGeometry);
-
- const qreal w = newGeometry.width();
- const qreal h = newGeometry.height();
-
- if (!d->hasCanvasSize) {
- d->canvasSize = QSizeF(w, h);
- emit canvasSizeChanged();
- }
-
- if (!d->hasTileSize) {
- d->tileSize = d->canvasSize.toSize();
- emit tileSizeChanged();
- }
-
- if (!d->hasCanvasWindow) {
- d->canvasWindow = newGeometry;
- emit canvasWindowChanged();
- }
-
- polish();
- update();
-}
-
-void QQuickCanvasItem::componentComplete()
-{
- Q_D(QQuickCanvasItem);
- QQuickItem::componentComplete();
-
- if (!d->context)
- createContext();
- createTexture();
-
- d->baseUrl = qmlEngine(this)->contextForObject(this)->baseUrl();
- requestPaint();
- updatePolish(); //force update the canvas sizes to texture for the first time
- update();
- d->componentCompleted = true;
-}
-
-void QQuickCanvasItem::updatePolish()
-{
- Q_D(QQuickCanvasItem);
- QQuickItem::updatePolish();
- if (d->texture) {
- if (!d->renderInThread && d->dirtyRect.isValid())
- _doPainting(d->dirtyRect);
-
- d->texture->canvasChanged(d->canvasSize.toSize()
- , d->tileSize
- , d->canvasWindow.toAlignedRect()
- , d->dirtyRect.toAlignedRect()
- , d->smooth);
- d->dirtyRect = QRectF();
- }
-}
-
-QSGNode *QQuickCanvasItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
-{
- Q_D(QQuickCanvasItem);
- QQuickContext2DNode *node = static_cast<QQuickContext2DNode *>(oldNode);
- if (!node)
- node = new QQuickContext2DNode(this);
-
- node->setTexture(d->texture);
- node->setSize(d->canvasWindow.size());
- node->update();
- return node;
-}
-
-void QQuickCanvasItem::createTexture()
-{
- Q_D(QQuickCanvasItem);
-
- if (!d->texture
- || d->texture->threadRendering() != d->renderInThread
- || d->texture->renderTarget() != d->renderTarget) {
- if (d->texture) {
- d->texture->deleteLater();
- d->texture = 0;
- }
-
- if (d->renderTarget == QQuickCanvasItem::Image) {
- d->texture = new QQuickContext2DImageTexture(d->renderInThread);
- } else if (d->renderTarget == QQuickCanvasItem::FramebufferObject) {
- d->texture = new QQuickContext2DFBOTexture();
- }
-
- if (d->renderInThread && !d->texture->supportThreadRendering()) {
- qWarning("Canvas: render target does not support thread rendering, force to non-thread rendering mode.");
- d->renderInThread = false;
- emit renderInThreadChanged();
- }
-
- if (d->renderInThread)
- connect(d->texture, SIGNAL(textureChanged()), this, SLOT(update()));
-
- d->texture->setItem(this);
- }
-}
-
-void QQuickCanvasItem::createContext()
-{
- Q_D(QQuickCanvasItem);
-
- delete d->context;
-
- d->context = new QQuickContext2D(this);
-
- QV8Engine *e = QDeclarativeEnginePrivate::getV8Engine(qmlEngine(this));
- d->context->setV8Engine(e);
-}
-
-/*!
- \qmlmethod object QtQuick2::Canvas::getContext(string contextId)
-
- Currently, the canvas item only supports the 2D context. If the \a contextId
- parameter isn't provided or is "2d", then the QtQuick2::Context2D object is
- returned, otherwise returns an invalid value.
- */
-QDeclarativeV8Handle QQuickCanvasItem::getContext(const QString &contextId)
-{
- Q_D(QQuickCanvasItem);
-
- if (contextId.toLower() != QLatin1String("2d"))
- return QDeclarativeV8Handle::fromHandle(v8::Undefined());
-
- if (!d->context)
- createContext();
- return QDeclarativeV8Handle::fromHandle(d->context->v8value());
-}
-
-/*!
- \qmlmethod void QtQuick2::Canvas::markDirty(rect region)
-
- Mark the given \a region as dirty, so that when this region is visible
- the canvas renderer will redraw it. This will trigger the "onPaint" signal
- handler function.
-
- \sa QtQuick2::Canvas::paint QtQuick2::Canvas::requestPaint
- */
-void QQuickCanvasItem::markDirty(const QRectF& region)
-{
- Q_D(QQuickCanvasItem);
- d->dirtyRect |= region;
- if (d->componentCompleted)
- polish();
- update();
-}
-
-
-/*!
- \qmlmethod bool QtQuick2::Canvas::save(string filename)
-
- Save the current canvas content into an image file \a filename.
- The saved image format is automatically decided by the \a filename's
- suffix.
-
- Note: calling this method will force painting the whole canvas, not just the
- current canvas visible window.
-
- \sa canvasWindow canvasSize toDataURL
- */
-bool QQuickCanvasItem::save(const QString &filename) const
-{
- Q_D(const QQuickCanvasItem);
- QUrl url = d->baseUrl.resolved(QUrl::fromLocalFile(filename));
- return toImage().save(url.toLocalFile());
-}
-
-QImage QQuickCanvasItem::loadedImage(const QUrl& url)
-{
- Q_D(QQuickCanvasItem);
- QUrl fullPathUrl = d->baseUrl.resolved(url);
- if (!d->images.contains(fullPathUrl)) {
- loadImage(url);
- }
- QDeclarativePixmap* pix = d->images.value(fullPathUrl);
- if (pix->isLoading() || pix->isError()) {
- return QImage();
- }
- return pix->image();
-}
-
-/*!
- \qmlmethod void QtQuick2::Canvas::loadImage(url image)
- Loads the given \c image asynchronously.
-
- When the image is ready, onImageLoaded will be emitted.
- The loaded image can be unloaded by the \a QtQuick2::Canvas::unloadImage method.
-
- Note: Only loaded images can be painted on the Canvas item.
- \sa QtQuick2::Canvas::unloadImage QtQuick2::Canvas::imageLoaded QtQuick2::Canvas::isImageLoaded
- \sa QtQuick2::Context2D::createImageData QtQuick2::Context2D::drawImage
- */
-void QQuickCanvasItem::loadImage(const QUrl& url)
-{
- Q_D(QQuickCanvasItem);
- QUrl fullPathUrl = d->baseUrl.resolved(url);
- if (!d->images.contains(fullPathUrl)) {
- QDeclarativePixmap* pix = new QDeclarativePixmap();
- d->images.insert(fullPathUrl, pix);
-
- pix->load(qmlEngine(this)
- , fullPathUrl
- , QDeclarativePixmap::Cache | QDeclarativePixmap::Asynchronous);
- pix->connectFinished(this, SIGNAL(imageLoaded()));
- }
-}
-/*!
- \qmlmethod void QtQuick2::Canvas::unloadImage(url image)
- Unloads the \c image.
-
- Once an image is unloaded it cannot be painted by the canvas context
- unless it is loaded again.
-
- \sa QtQuick2::Canvas::loadImage QtQuick2::Canvas::imageLoaded QtQuick2::Canvas::isImageLoaded
- \sa QtQuick2::Context2D::createImageData QtQuick2::Context2D::drawImage
- */
-void QQuickCanvasItem::unloadImage(const QUrl& url)
-{
- Q_D(QQuickCanvasItem);
- QUrl removeThis = d->baseUrl.resolved(url);
- if (d->images.contains(removeThis)) {
- delete d->images.value(removeThis);
- d->images.remove(removeThis);
- }
-}
-
-/*!
- \qmlmethod void QtQuick2::Canvas::isImageError(url image)
- Returns true if the \a image failed to load.
-
- \sa QtQuick2::Canvas::loadImage
- */
-bool QQuickCanvasItem::isImageError(const QUrl& url) const
-{
- Q_D(const QQuickCanvasItem);
- QUrl fullPathUrl = d->baseUrl.resolved(url);
- return d->images.contains(fullPathUrl)
- && d->images.value(fullPathUrl)->isError();
-}
-
-/*!
- \qmlmethod void QtQuick2::Canvas::isImageLoading(url image)
- Returns true if the \a image is currently loading.
-
- \sa QtQuick2::Canvas::loadImage
- */
-bool QQuickCanvasItem::isImageLoading(const QUrl& url) const
-{
- Q_D(const QQuickCanvasItem);
- QUrl fullPathUrl = d->baseUrl.resolved(url);
- return d->images.contains(fullPathUrl)
- && d->images.value(fullPathUrl)->isLoading();
-}
-/*!
- \qmlmethod void QtQuick2::Canvas::isImageLoaded(url image)
- Returns true if the \a image is sucessfully loaded and ready to use.
-
- \sa QtQuick2::Canvas::loadImage
- */
-bool QQuickCanvasItem::isImageLoaded(const QUrl& url) const
-{
- Q_D(const QQuickCanvasItem);
- QUrl fullPathUrl = d->baseUrl.resolved(url);
- return d->images.contains(fullPathUrl)
- && d->images.value(fullPathUrl)->isReady();
-}
-
-QImage QQuickCanvasItem::toImage(const QRectF& region) const
-{
- Q_D(const QQuickCanvasItem);
- if (d->texture) {
- if (region.isEmpty())
- return d->texture->toImage(canvasWindow());
- else
- return d->texture->toImage(region);
- }
- return QImage();
-}
-
-/*!
- \qmlmethod string QtQuick2::Canvas::toDataURL(string mimeType)
-
- Returns a data URL for the image in the canvas.
-
- The default \a mimeType is "image/png".
-
- \sa QtQuick2::Canvas::save
- */
-QString QQuickCanvasItem::toDataURL(const QString& mimeType) const
-{
- QImage image = toImage();
-
- if (!image.isNull()) {
- QByteArray ba;
- QBuffer buffer(&ba);
- buffer.open(QIODevice::WriteOnly);
- QString mime = mimeType.toLower();
- QString type;
- if (mime == QLatin1Literal("image/png")) {
- type = QLatin1Literal("PNG");
- } else if (mime == QLatin1Literal("image/bmp"))
- type = QLatin1Literal("BMP");
- else if (mime == QLatin1Literal("image/jpeg"))
- type = QLatin1Literal("JPEG");
- else if (mime == QLatin1Literal("image/x-portable-pixmap"))
- type = QLatin1Literal("PPM");
- else if (mime == QLatin1Literal("image/tiff"))
- type = QLatin1Literal("TIFF");
- else if (mime == QLatin1Literal("image/xpm"))
- type = QLatin1Literal("XPM");
- else
- return QLatin1Literal("data:,");
-
- image.save(&buffer, type.toAscii());
- buffer.close();
- QString dataUrl = QLatin1Literal("data:%1;base64,%2");
- return dataUrl.arg(mime).arg(QLatin1String(ba.toBase64().constData()));
- }
- return QLatin1Literal("data:,");
-}
-
-/*!
- \qmlsignal QtQuick2::Canvas::onPaint(QtQuick2::Context2D context, rect region)
-
- This handler is called to render the \a region.
-
- This signal can be triggered by QtQuick2::Canvas::markdirty, QtQuick2::Canvas::requestPaint
- or by changing the current canvas window.
-*/
-
-/*!
- \qmlsignal QtQuick2::Canvas::onPainted()
-
- This handler is called after all context painting commands are executed and
- the Canvas has been rendered.
-*/
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/context2d/qquickcanvasitem_p.h b/src/declarative/items/context2d/qquickcanvasitem_p.h
deleted file mode 100644
index 293434209a..0000000000
--- a/src/declarative/items/context2d/qquickcanvasitem_p.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKCANVASITEM_P_H
-#define QQUICKCANVASITEM_P_H
-
-#include <qquickitem.h>
-#include <private/qv8engine_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-class QQuickContext2D;
-class QQuickCanvasItemPrivate;
-class Q_DECLARATIVE_EXPORT QQuickCanvasItem : public QQuickItem
-{
- Q_OBJECT
- Q_ENUMS(RenderTarget)
- Q_ENUMS(ImageFilterMode)
-
- Q_PROPERTY(QSizeF canvasSize READ canvasSize WRITE setCanvasSize NOTIFY canvasSizeChanged)
- Q_PROPERTY(QSize tileSize READ tileSize WRITE setTileSize NOTIFY tileSizeChanged)
- Q_PROPERTY(QRectF canvasWindow READ canvasWindow WRITE setCanvasWindow NOTIFY canvasWindowChanged)
- Q_PROPERTY(bool renderInThread READ renderInThread WRITE setRenderInThread NOTIFY renderInThreadChanged)
- Q_PROPERTY(RenderTarget renderTarget READ renderTarget WRITE setRenderTarget NOTIFY renderTargetChanged)
-public:
- enum RenderTarget {
- Image,
- FramebufferObject
- };
-
- enum ImageFilterMode {
- Threshold,
- Mono,
- GrayScale,
- Brightness,
- Invert,
- Blur,
- Opaque,
- Convolute
- };
-
- QQuickCanvasItem(QQuickItem *parent = 0);
- ~QQuickCanvasItem();
-
- QSizeF canvasSize() const;
- void setCanvasSize(const QSizeF &);
-
- QSize tileSize() const;
- void setTileSize(const QSize &);
-
- QRectF canvasWindow() const;
- void setCanvasWindow(const QRectF& rect);
-
- bool renderInThread() const;
- void setRenderInThread(bool renderInThread);
-
- RenderTarget renderTarget() const;
- void setRenderTarget(RenderTarget target);
-
- QQuickContext2D* context() const;
- QImage toImage(const QRectF& region = QRectF()) const;
-
- QImage loadedImage(const QUrl& url);
-
-Q_SIGNALS:
- void paint(QDeclarativeV8Handle context, const QRect &region);
- void painted();
- void canvasSizeChanged();
- void tileSizeChanged();
- void renderInThreadChanged();
- void textureChanged();
- void canvasWindowChanged();
- void renderTargetChanged();
- void imageLoaded();
-public Q_SLOTS:
- QString toDataURL(const QString& type = QLatin1String("image/png")) const;
- QDeclarativeV8Handle getContext(const QString & = QLatin1String("2d"));
- void markDirty(const QRectF& region);
- void requestPaint() {markDirty(canvasWindow());}
- // Save current canvas to disk
- bool save(const QString& filename) const;
- void loadImage(const QUrl& url);
- void unloadImage(const QUrl& url);
- bool isImageLoaded(const QUrl& url) const;
- bool isImageLoading(const QUrl& url) const;
- bool isImageError(const QUrl& url) const;
-private Q_SLOTS:
- void _doPainting(const QRectF& region);
-protected:
- virtual void componentComplete();
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
- virtual void geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry);
- virtual void updatePolish();
-private:
- void createContext();
- void createTexture();
- Q_DECLARE_PRIVATE(QQuickCanvasItem)
- friend class QQuickContext2D;
- friend class QQuickContext2DTexture;
-};
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickCanvasItem)
-
-QT_END_HEADER
-
-#endif //QQUICKCANVASITEM_P_H
diff --git a/src/declarative/items/context2d/qquickcontext2d.cpp b/src/declarative/items/context2d/qquickcontext2d.cpp
deleted file mode 100644
index 1f7a84baa6..0000000000
--- a/src/declarative/items/context2d/qquickcontext2d.cpp
+++ /dev/null
@@ -1,3540 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickcontext2d_p.h"
-#include "qquickcontext2dcommandbuffer_p.h"
-#include "qquickcanvasitem_p.h"
-#include <private/qquickitem_p.h>
-#include <private/qquickshadereffectsource_p.h>
-#include <QtGui/qopenglframebufferobject.h>
-
-#include <QtCore/qdebug.h>
-#include <private/qsgcontext_p.h>
-#include <private/qdeclarativesvgparser_p.h>
-#include <private/qdeclarativepath_p.h>
-
-#include <private/qquickimage_p_p.h>
-
-#include <QtGui/qguiapplication.h>
-#include <qdeclarativeinfo.h>
-#include <QtCore/qmath.h>
-#include <private/qv8engine_p.h>
-
-#include <qdeclarativeengine.h>
-#include <private/qv8domerrors_p.h>
-#include <QtCore/qnumeric.h>
-
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass Context2D QQuickContext2D
- \inqmlmodule QtQuick 2
- \since QtQuick 2.0
- \brief The Context2D API allows you to draw 2d graphic shapes on the \c Canvas item.
-
- The Context2D object can be created by \c Canvas item's \c getContext() method:
- \code
- Canvas {
- id:canvas
- onPaint:{
- var ctx = canvas.getContext('2d');
- //...
- }
- }
- \endcode
- The Context2D API implements the same \l {http://www.w3.org/TR/2dcontext}{W3C Canvas 2D Context API standard}
- with some enhanced features.
-
- The Context2D API provides the rendering \bold{context} which defines the methods and attributes needed to draw
- on the \c Canvas item. The following assigns the canvas rendering context to a \c{context}
- variable:
- \code
- var context = mycanvas.getContext("2d")
- \endcode
-
- The Context2D API renders the canvas as a coordinate system whose origin (0,0) is
- at the top left corner, as shown in the figure below. Coordinates increase along
- the \c{x} axis from left to right and along the \c{y} axis from top to bottom of
- the canvas.
- \image qml-item-canvas-context.gif
-*/
-
-Q_CORE_EXPORT double qstrtod(const char *s00, char const **se, bool *ok);
-
-static const double Q_PI = 3.14159265358979323846; // pi
-
-#define DEGREES(t) ((t) * 180.0 / Q_PI)
-
-#define CHECK_CONTEXT(r) if (!r || !r->context || !r->context->buffer()) \
- V8THROW_ERROR("Not a Context2D object");
-
-#define CHECK_CONTEXT_SETTER(r) if (!r || !r->context || !r->context->buffer()) \
- V8THROW_ERROR_SETTER("Not a Context2D object");
-#define qClamp(val, min, max) qMin(qMax(val, min), max)
-#define CHECK_RGBA(c) (c == '-' || c == '.' || (c >=0 && c <= 9))
-QColor qt_color_from_string(v8::Local<v8::Value> name)
-{
- v8::String::AsciiValue str(name);
-
- char *p = *str;
- int len = str.length();
- //rgb/hsl color string has at least 7 characters
- if (!p || len > 255 || len <= 7)
- return QColor(p);
- else {
- bool isRgb(false), isHsl(false), hasAlpha(false);
- Q_UNUSED(isHsl)
-
- while (isspace(*p)) p++;
- if (strncmp(p, "rgb", 3) == 0)
- isRgb = true;
- else if (strncmp(p, "hsl", 3) == 0)
- isHsl = true;
- else
- return QColor(p);
-
- p+=3; //skip "rgb" or "hsl"
- hasAlpha = (*p == 'a') ? true : false;
-
- ++p; //skip "("
-
- if (hasAlpha) ++p; //skip "a"
-
- int rh, gs, bl, alpha = 255;
-
- //red
- while (isspace(*p)) p++;
- rh = strtol(p, &p, 10);
- if (*p == '%') {
- rh = qRound(rh/100.0 * 255);
- ++p;
- }
- if (*p++ != ',') return QColor();
-
- //green
- while (isspace(*p)) p++;
- gs = strtol(p, &p, 10);
- if (*p == '%') {
- gs = qRound(gs/100.0 * 255);
- ++p;
- }
- if (*p++ != ',') return QColor();
-
- //blue
- while (isspace(*p)) p++;
- bl = strtol(p, &p, 10);
- if (*p == '%') {
- bl = qRound(bl/100.0 * 255);
- ++p;
- }
-
- if (hasAlpha) {
- if (*p++!= ',') return QColor();
- while (isspace(*p)) p++;
- bool ok = false;
- alpha = qRound(qstrtod(p, const_cast<const char **>(&p), &ok) * 255);
- }
-
- if (*p != ')') return QColor();
- if (isRgb)
- return QColor::fromRgba(qRgba(qClamp(rh, 0, 255), qClamp(gs, 0, 255), qClamp(bl, 0, 255), qClamp(alpha, 0, 255)));
- else
- return QColor::fromHsl(qClamp(rh, 0, 255), qClamp(gs, 0, 255), qClamp(bl, 0, 255), qClamp(alpha, 0, 255));
- }
- return QColor();
-}
-
-QFont qt_font_from_string(const QString& fontString) {
- QFont font;
- // ### this is simplified and incomplete
- // ### TODO:get code from Qt webkit
- QStringList tokens = fontString.split(QLatin1String(" "));
- foreach (const QString &token, tokens) {
- if (token == QLatin1String("italic"))
- font.setItalic(true);
- else if (token == QLatin1String("bold"))
- font.setBold(true);
- else if (token.endsWith(QLatin1String("px"))) {
- QString number = token;
- number.remove(QLatin1String("px"));
- //font.setPointSizeF(number.trimmed().toFloat());
- font.setPixelSize(number.trimmed().toInt());
- } else
- font.setFamily(token);
- }
-
- return font;
-}
-
-
-
-class QQuickContext2DEngineData : public QV8Engine::Deletable
-{
-public:
- QQuickContext2DEngineData(QV8Engine *engine);
- ~QQuickContext2DEngineData();
-
- v8::Persistent<v8::Function> constructorContext;
- v8::Persistent<v8::Function> constructorGradient;
- v8::Persistent<v8::Function> constructorPattern;
- v8::Persistent<v8::Function> constructorPixelArray;
- v8::Persistent<v8::Function> constructorImageData;
-};
-
-V8_DEFINE_EXTENSION(QQuickContext2DEngineData, engineData)
-
-class QV8Context2DResource : public QV8ObjectResource
-{
- V8_RESOURCE_TYPE(Context2DType)
-public:
- QV8Context2DResource(QV8Engine *e) : QV8ObjectResource(e) {}
- QQuickContext2D* context;
-};
-
-class QV8Context2DStyleResource : public QV8ObjectResource
-{
- V8_RESOURCE_TYPE(Context2DStyleType)
-public:
- QV8Context2DStyleResource(QV8Engine *e)
- : QV8ObjectResource(e)
- , patternRepeatX(false)
- , patternRepeatY(false)
- {}
- QBrush brush;
- bool patternRepeatX:1;
- bool patternRepeatY:1;
-};
-
-class QV8Context2DPixelArrayResource : public QV8ObjectResource
-{
- V8_RESOURCE_TYPE(Context2DPixelArrayType)
-public:
- QV8Context2DPixelArrayResource(QV8Engine *e) : QV8ObjectResource(e) {}
-
- QImage image;
-};
-
-QImage qt_image_convolute_filter(const QImage& src, const QVector<qreal>& weights, int radius = 0)
-{
- int sides = radius ? radius : qRound(qSqrt(weights.size()));
- int half = qFloor(sides/2);
-
- QImage dst = QImage(src.size(), src.format());
- int w = src.width();
- int h = src.height();
- for (int y = 0; y < dst.height(); ++y) {
- QRgb *dr = (QRgb*)dst.scanLine(y);
- for (int x = 0; x < dst.width(); ++x) {
- unsigned char* dRgb = ((unsigned char*)&dr[x]);
- unsigned char red=0, green=0, blue=0, alpha=0;
- int sy = y;
- int sx = x;
-
- for (int cy=0; cy<sides; cy++) {
- for (int cx=0; cx<sides; cx++) {
- int scy = sy + cy - half;
- int scx = sx + cx - half;
- if (scy >= 0 && scy < w && scx >= 0 && scx < h) {
- const QRgb *sr = (const QRgb*)(src.constScanLine(scy));
- const unsigned char* sRgb = ((const unsigned char*)&sr[scx]);
- qreal wt = radius ? weights[0] : weights[cy*sides+cx];
- red += sRgb[0] * wt;
- green += sRgb[1] * wt;
- blue += sRgb[2] * wt;
- alpha += sRgb[3] * wt;
- }
- }
- }
- dRgb[0] = red;
- dRgb[1] = green;
- dRgb[2] = blue;
- dRgb[3] = alpha;
- }
- }
- return dst;
-}
-
-void qt_image_boxblur(QImage& image, int radius, bool quality)
-{
- int passes = quality? 3: 1;
- for (int i=0; i < passes; i++) {
- image = qt_image_convolute_filter(image, QVector<qreal>() << 1.0/(radius * radius * 1.0), radius);
- }
-}
-
-static QPainter::CompositionMode qt_composite_mode_from_string(const QString &compositeOperator)
-{
- if (compositeOperator == QLatin1String("source-over")) {
- return QPainter::CompositionMode_SourceOver;
- } else if (compositeOperator == QLatin1String("source-out")) {
- return QPainter::CompositionMode_SourceOut;
- } else if (compositeOperator == QLatin1String("source-in")) {
- return QPainter::CompositionMode_SourceIn;
- } else if (compositeOperator == QLatin1String("source-atop")) {
- return QPainter::CompositionMode_SourceAtop;
- } else if (compositeOperator == QLatin1String("destination-atop")) {
- return QPainter::CompositionMode_DestinationAtop;
- } else if (compositeOperator == QLatin1String("destination-in")) {
- return QPainter::CompositionMode_DestinationIn;
- } else if (compositeOperator == QLatin1String("destination-out")) {
- return QPainter::CompositionMode_DestinationOut;
- } else if (compositeOperator == QLatin1String("destination-over")) {
- return QPainter::CompositionMode_DestinationOver;
- } else if (compositeOperator == QLatin1String("lighter")) {
- return QPainter::CompositionMode_Lighten;
- } else if (compositeOperator == QLatin1String("copy")) {
- return QPainter::CompositionMode_Source;
- } else if (compositeOperator == QLatin1String("xor")) {
- return QPainter::CompositionMode_Xor;
- } else if (compositeOperator == QLatin1String("qt-clear")) {
- return QPainter::CompositionMode_Clear;
- } else if (compositeOperator == QLatin1String("qt-destination")) {
- return QPainter::CompositionMode_Destination;
- } else if (compositeOperator == QLatin1String("qt-multiply")) {
- return QPainter::CompositionMode_Multiply;
- } else if (compositeOperator == QLatin1String("qt-screen")) {
- return QPainter::CompositionMode_Screen;
- } else if (compositeOperator == QLatin1String("qt-overlay")) {
- return QPainter::CompositionMode_Overlay;
- } else if (compositeOperator == QLatin1String("qt-darken")) {
- return QPainter::CompositionMode_Darken;
- } else if (compositeOperator == QLatin1String("qt-lighten")) {
- return QPainter::CompositionMode_Lighten;
- } else if (compositeOperator == QLatin1String("qt-color-dodge")) {
- return QPainter::CompositionMode_ColorDodge;
- } else if (compositeOperator == QLatin1String("qt-color-burn")) {
- return QPainter::CompositionMode_ColorBurn;
- } else if (compositeOperator == QLatin1String("qt-hard-light")) {
- return QPainter::CompositionMode_HardLight;
- } else if (compositeOperator == QLatin1String("qt-soft-light")) {
- return QPainter::CompositionMode_SoftLight;
- } else if (compositeOperator == QLatin1String("qt-difference")) {
- return QPainter::CompositionMode_Difference;
- } else if (compositeOperator == QLatin1String("qt-exclusion")) {
- return QPainter::CompositionMode_Exclusion;
- }
- return QPainter::CompositionMode_SourceOver;
-}
-
-static QString qt_composite_mode_to_string(QPainter::CompositionMode op)
-{
- switch (op) {
- case QPainter::CompositionMode_SourceOver:
- return QLatin1String("source-over");
- case QPainter::CompositionMode_DestinationOver:
- return QLatin1String("destination-over");
- case QPainter::CompositionMode_Clear:
- return QLatin1String("qt-clear");
- case QPainter::CompositionMode_Source:
- return QLatin1String("copy");
- case QPainter::CompositionMode_Destination:
- return QLatin1String("qt-destination");
- case QPainter::CompositionMode_SourceIn:
- return QLatin1String("source-in");
- case QPainter::CompositionMode_DestinationIn:
- return QLatin1String("destination-in");
- case QPainter::CompositionMode_SourceOut:
- return QLatin1String("source-out");
- case QPainter::CompositionMode_DestinationOut:
- return QLatin1String("destination-out");
- case QPainter::CompositionMode_SourceAtop:
- return QLatin1String("source-atop");
- case QPainter::CompositionMode_DestinationAtop:
- return QLatin1String("destination-atop");
- case QPainter::CompositionMode_Xor:
- return QLatin1String("xor");
- case QPainter::CompositionMode_Plus:
- return QLatin1String("plus");
- case QPainter::CompositionMode_Multiply:
- return QLatin1String("qt-multiply");
- case QPainter::CompositionMode_Screen:
- return QLatin1String("qt-screen");
- case QPainter::CompositionMode_Overlay:
- return QLatin1String("qt-overlay");
- case QPainter::CompositionMode_Darken:
- return QLatin1String("qt-darken");
- case QPainter::CompositionMode_Lighten:
- return QLatin1String("lighter");
- case QPainter::CompositionMode_ColorDodge:
- return QLatin1String("qt-color-dodge");
- case QPainter::CompositionMode_ColorBurn:
- return QLatin1String("qt-color-burn");
- case QPainter::CompositionMode_HardLight:
- return QLatin1String("qt-hard-light");
- case QPainter::CompositionMode_SoftLight:
- return QLatin1String("qt-soft-light");
- case QPainter::CompositionMode_Difference:
- return QLatin1String("qt-difference");
- case QPainter::CompositionMode_Exclusion:
- return QLatin1String("qt-exclusion");
- default:
- break;
- }
- return QString();
-}
-
-
-static v8::Local<v8::Object> qt_create_image_data(qreal w, qreal h, QV8Engine* engine, const QImage& image)
-{
- QQuickContext2DEngineData *ed = engineData(engine);
- v8::Local<v8::Object> imageData = ed->constructorImageData->NewInstance();
- QV8Context2DPixelArrayResource *r = new QV8Context2DPixelArrayResource(engine);
- if (image.isNull()) {
- r->image = QImage(w, h, QImage::Format_ARGB32);
- r->image.fill(0x00000000);
- } else {
- Q_ASSERT(image.width() == w && image.height() == h);
- r->image = image.format() == QImage::Format_ARGB32 ? image : image.convertToFormat(QImage::Format_ARGB32);
- }
- v8::Local<v8::Object> pixelData = ed->constructorPixelArray->NewInstance();
- pixelData->SetExternalResource(r);
-
- imageData->SetInternalField(0, pixelData);
- return imageData;
-}
-
-//static script functions
-
-/*!
- \qmlproperty QtQuick2::Canvas QtQuick2::Context2D::canvas
- Holds the canvas item that the context paints on.
-
- This property is read only.
-*/
-static v8::Handle<v8::Value> ctx2d_canvas(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- return engine->newQObject(r->context->canvas());
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::restore()
- Pops the top state on the stack, restoring the context to that state.
-
- \sa QtQuick2::Context2D::save()
-*/
-static v8::Handle<v8::Value> ctx2d_restore(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- r->context->popState();
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::reset()
- Resets the context state and properties to the default values.
-*/
-static v8::Handle<v8::Value> ctx2d_reset(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- r->context->reset();
- r->context->m_path = QPainterPath();
- r->context->m_path.setFillRule(Qt::WindingFill);
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::save()
- Pushes the current state onto the state stack.
-
- Before changing any state attributes, you should save the current state
- for future reference. The context maintains a stack of drawing states.
- Each state consists of the current transformation matrix, clipping region,
- and values of the following attributes:
- \list
- \o\a QtQuick2::Context2D::strokeStyle
- \o\a QtQuick2::Context2D::fillStyle
- \o\a QtQuick2::Context2D::fillRule
- \o\a QtQuick2::Context2D::globalAlpha
- \o\a QtQuick2::Context2D::lineWidth
- \o\a QtQuick2::Context2D::lineCap
- \o\a QtQuick2::Context2D::lineJoin
- \o\a QtQuick2::Context2D::miterLimit
- \o\a QtQuick2::Context2D::shadowOffsetX
- \o\a QtQuick2::Context2D::shadowOffsetY
- \o\a QtQuick2::Context2D::shadowBlur
- \o\a QtQuick2::Context2D::shadowColor
- \o\a QtQuick2::Context2D::globalCompositeOperation
- \o\a QtQuick2::Context2D::font
- \o\a QtQuick2::Context2D::textAlign
- \o\a QtQuick2::Context2D::textBaseline
- \endlist
-
- The current path is NOT part of the drawing state. The path can be reset by
- invoking the \a QtQuick2::Context2D::beginPath() method.
-*/
-static v8::Handle<v8::Value> ctx2d_save(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- r->context->pushState();
-
- return args.This();
-}
-
-// transformations
-/*!
- \qmlmethod object QtQuick2::Context2D::rotate(real angle)
- Rotate the canvas around the current origin by \c angle in radians and clockwise direction.
- \code
- ctx.rotate(Math.PI/2);
- \endcode
- \image qml-item-canvas-rotate.png
-
- The rotation transformation matrix is as follows:
-
- \image qml-item-canvas-math-rotate.png
-
- where the \c angle of rotation is in radians.
-
-*/
-static v8::Handle<v8::Value> ctx2d_rotate(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- if (args.Length() == 1) {
- qreal angle = args[0]->NumberValue();
- if (!qIsFinite(angle))
- return args.This();
-
- r->context->state.matrix.rotate(DEGREES(angle));
- r->context->buffer()->updateMatrix(r->context->state.matrix);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::scale(real x, real y)
- Increases or decreases the size of each unit in the canvas grid by multiplying the scale factors
- to the current tranform matrix.
- Where \c x is the scale factor in the horizontal direction and \c y is the scale factor in the
- vertical direction.
- The following code doubles the horizontal size of an object drawn on the canvas and half its
- vertical size:
- \code
- ctx.scale(2.0, 0.5);
- \endcode
- \image qml-item-canvas-scale.png
-
-*/
-static v8::Handle<v8::Value> ctx2d_scale(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- if (args.Length() == 2) {
- qreal x, y;
- x = args[0]->NumberValue();
- y = args[1]->NumberValue();
- if (!qIsFinite(x) || !qIsFinite(y))
- return args.This();
-
- r->context->state.matrix.scale(x, y);
- r->context->buffer()->updateMatrix(r->context->state.matrix);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::setTransform(real a, real b, real c, real d, real e, real f)
- Changes the transformation matrix to the matrix given by the arguments as described below.
-
- Modifying the transformation matrix directly enables you to perform scaling,
- rotating, and translating transformations in a single step.
-
- Each point on the canvas is multiplied by the matrix before anything is
- drawn. The \l{HTML5 Canvas API} defines the transformation matrix as:
-
- \image qml-item-canvas-math.png
- where:
- \list
- \o \c{a} is the scale factor in the horizontal (x) direction
- \image qml-item-canvas-scalex.png
- \o \c{c} is the skew factor in the x direction
- \image qml-item-canvas-canvas-skewx.png
- \o \c{e} is the translation in the x direction
- \image qml-item-canvas-canvas-translate.png
- \o \c{b} is the skew factor in the y (vertical) direction
- \image qml-item-canvas-canvas-skewy.png
- \o \c{d} is the scale factor in the y direction
- \image qml-item-canvas-canvas-scaley.png
- \o \c{f} is the translation in the y direction
- \image qml-item-canvas-canvas-translatey.png
- \o the last row remains constant
- \endlist
- The scale factors and skew factors are multiples; \c{e} and \c{f} are
- coordinate space units, just like the units in the \a QtQuick2::Context2D::translate(x,y)
- method.
-
- \sa QtQuick2::Context2D::transform()
-*/
-static v8::Handle<v8::Value> ctx2d_setTransform(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- if (args.Length() == 6) {
- qreal a = args[0]->NumberValue();
- qreal b = args[1]->NumberValue();
- qreal c = args[2]->NumberValue();
- qreal d = args[3]->NumberValue();
- qreal e = args[4]->NumberValue();
- qreal f = args[5]->NumberValue();
-
- if (!qIsFinite(a)
- || !qIsFinite(b)
- || !qIsFinite(c)
- || !qIsFinite(d)
- || !qIsFinite(e)
- || !qIsFinite(f))
- return args.This();
-
- r->context->state.matrix = QTransform(a, b, c, d, e, f);
- r->context->buffer()->updateMatrix(r->context->state.matrix);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::transform(real a, real b, real c, real d, real e, real f)
- This method is very similar to \a QtQuick2::Context2D::setTransform(), but instead of replacing the old
- tranform matrix, this method applies the given tranform matrix to the current matrix by mulitplying to it.
-
- The \a setTransform(a, b, c, d, e, f) method actually resets the current transform to the identity matrix,
- and then invokes the transform(a, b, c, d, e, f) method with the same arguments.
-
- \sa QtQuick2::Context2D::setTransform()
-*/
-static v8::Handle<v8::Value> ctx2d_transform(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- if (args.Length() == 6) {
- qreal a = args[0]->NumberValue();
- qreal b = args[1]->NumberValue();
- qreal c = args[2]->NumberValue();
- qreal d = args[3]->NumberValue();
- qreal e = args[4]->NumberValue();
- qreal f = args[5]->NumberValue();
-
- if (!qIsFinite(a)
- || !qIsFinite(b)
- || !qIsFinite(c)
- || !qIsFinite(d)
- || !qIsFinite(e)
- || !qIsFinite(f))
- return args.This();
-
- r->context->state.matrix *= QTransform(a, b, c, d, e, f);
- r->context->buffer()->updateMatrix(r->context->state.matrix);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::translate(real x, real y)
- Translates the origin of the canvas to point (\c x, \c y).
-
- \c x is the horizontal distance that the origin is translated, in coordinate space units,
- \c y is the vertical distance that the origin is translated, in coordinate space units.
- Translating the origin enables you to draw patterns of different objects on the canvas
- without having to measure the coordinates manually for each shape.
-*/
-static v8::Handle<v8::Value> ctx2d_translate(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- if (args.Length() == 2) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y))
- return args.This();
-
- r->context->state.matrix.translate(x, y);
- r->context->buffer()->updateMatrix(r->context->state.matrix);
- }
-
- return args.This();
-}
-
-
-/*!
- \qmlmethod object QtQuick2::Context2D::resetTransform()
- Reset the transformation matrix to default value.
-
- \sa QtQuick2::Context2D::transform(), QtQuick2::Context2D::setTransform(), QtQuick2::Context2D::reset()
-*/
-static v8::Handle<v8::Value> ctx2d_resetTransform(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- r->context->state.matrix = QTransform();
- r->context->buffer()->updateMatrix(r->context->state.matrix);
-
- return args.This();
-}
-
-
-/*!
- \qmlmethod object QtQuick2::Context2D::shear(real sh, real sv )
- Shear the transformation matrix with \a sh in horizontal direction and \a sv in vertical direction.
-*/
-static v8::Handle<v8::Value> ctx2d_shear(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- if (args.Length() == 2) {
- qreal sh = args[0]->NumberValue();
- qreal sv = args[1]->NumberValue();
-
- if (!qIsFinite(sh) || !qIsFinite(sv))
- return args.This();
-
- r->context->state.matrix.shear(sh, sv);
- r->context->buffer()->updateMatrix(r->context->state.matrix);
- }
- return args.This();
-}
-// compositing
-
-/*!
- \qmlproperty real QtQuick2::Context2D::globalAlpha
- Holds the the current alpha value applied to rendering operations.
- The value must be in the range from 0.0 (fully transparent) to 1.0 (fully opque).
- The default value is 1.0.
-*/
-static v8::Handle<v8::Value> ctx2d_globalAlpha(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
- return v8::Number::New(r->context->state.globalAlpha);
-}
-
-static void ctx2d_globalAlpha_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- qreal globalAlpha = value->NumberValue();
-
- if (!qIsFinite(globalAlpha))
- return;
-
- if (globalAlpha >= 0.0 && globalAlpha <= 1.0 && r->context->state.globalAlpha != globalAlpha) {
- r->context->state.globalAlpha = globalAlpha;
- r->context->buffer()->setGlobalAlpha(r->context->state.globalAlpha);
- }
-}
-
-/*!
- \qmlproperty string QtQuick2::Context2D::globalCompositeOperation
- Holds the the current the current composition operation, from the list below:
- \list
- \o source-atop - A atop B. Display the source image wherever both images are opaque.
- Display the destination image wherever the destination image is opaque but the source image is transparent.
- Display transparency elsewhere.
- \o source-in - A in B. Display the source image wherever both the source image and destination image are opaque.
- Display transparency elsewhere.
- \o source-out - A out B. Display the source image wherever the source image is opaque and the destination image is transparent.
- Display transparency elsewhere.
- \o source-over - (default) A over B. Display the source image wherever the source image is opaque.
- Display the destination image elsewhere.
- \o destination-atop - B atop A. Same as source-atop but using the destination image instead of the source image and vice versa.
- \o destination-in - B in A. Same as source-in but using the destination image instead of the source image and vice versa.
- \o destination-out - B out A. Same as source-out but using the destination image instead of the source image and vice versa.
- \o destination-over - B over A. Same as source-over but using the destination image instead of the source image and vice versa.
- \o lighter - A plus B. Display the sum of the source image and destination image, with color values approaching 255 (100%) as a limit.
- \o copy - A (B is ignored). Display the source image instead of the destination image.
- \o xor - A xor B. Exclusive OR of the source image and destination image.
- \endlist
-
- Additionally, this property also accepts the compositon modes listed in \a {QPainter::CompositionMode}. According to the W3C standard, these
- extension composition modes are provided as "vendorName-operationName" syntax, for example: \c {QPainter::CompositionMode_Exclusion} is porvided as
- "qt-exclusion".
-*/
-static v8::Handle<v8::Value> ctx2d_globalCompositeOperation(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- return engine->toString(qt_composite_mode_to_string(r->context->state.globalCompositeOperation));
-}
-
-static void ctx2d_globalCompositeOperation_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
-
- QString mode = engine->toString(value);
- QPainter::CompositionMode cm = qt_composite_mode_from_string(mode);
- if (cm == QPainter::CompositionMode_SourceOver && mode != QStringLiteral("source-over"))
- return;
-
- if (cm != r->context->state.globalCompositeOperation) {
- r->context->state.globalCompositeOperation = cm;
- r->context->buffer()->setGlobalCompositeOperation(cm);
- }
-}
-
-// colors and styles
-/*!
- \qmlproperty variant QtQuick2::Context2D::fillStyle
- Holds the current style used for filling shapes.
- The style can be either a string containing a CSS color, a CanvasGradient or CanvasPattern object. Invalid values are ignored.
- This property accepts several color syntaxes:
- \list
- \o 'rgb(red, green, blue)' - for example: 'rgb(255, 100, 55)' or 'rgb(100%, 70%, 30%)'
- \o 'rgba(red, green, blue, alpha)' - for example: 'rgb(255, 100, 55, 1.0)' or 'rgb(100%, 70%, 30%, 0.5)'
- \o 'hsl(hue, saturation, lightness)'
- \o 'hsla(hue, saturation, lightness, alpha)'
- \o '#RRGGBB' - for example: '#00FFCC'
- \o Qt.rgba(red, green, blue, alpha) - for example: Qt.rgba(0.3, 0.7, 1, 1.0)
- \endlist
- If the \a fillStyle or \a strokeStyle is assigned many times in a loop, the last Qt.rgba() syntax should be chosen, as it has the
- best performance, because it's already a valid QColor value, does not need to be parsed everytime.
-
- The default value is '#000000'.
- \sa QtQuick2::Context2D::createLinearGradient
- \sa QtQuick2::Context2D::createRadialGradient
- \sa QtQuick2::Context2D::createPattern
- \sa QtQuick2::Context2D::strokeStyle
- */
-static v8::Handle<v8::Value> ctx2d_fillStyle(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- QColor color = r->context->state.fillStyle.color();
- if (color.isValid()) {
- if (color.alpha() == 255)
- return engine->toString(color.name());
- QString alphaString = QString::number(color.alphaF(), 'f');
- while (alphaString.endsWith(QLatin1Char('0')))
- alphaString.chop(1);
- if (alphaString.endsWith(QLatin1Char('.')))
- alphaString += QLatin1Char('0');
- return engine->toString(QString::fromLatin1("rgba(%1, %2, %3, %4)").arg(color.red()).arg(color.green()).arg(color.blue()).arg(alphaString));
- }
- return r->context->m_fillStyle;
-}
-
-static void ctx2d_fillStyle_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- if (value->IsObject()) {
- QColor color = engine->toVariant(value, qMetaTypeId<QColor>()).value<QColor>();
- if (color.isValid()) {
- r->context->state.fillStyle = color;
- r->context->buffer()->setFillStyle(color);
- r->context->m_fillStyle = value;
- } else {
- QV8Context2DStyleResource *style = v8_resource_cast<QV8Context2DStyleResource>(value->ToObject());
- if (style && style->brush != r->context->state.fillStyle) {
- r->context->state.fillStyle = style->brush;
- r->context->buffer()->setFillStyle(style->brush, style->patternRepeatX, style->patternRepeatY);
- r->context->m_fillStyle = value;
- r->context->state.fillPatternRepeatX = style->patternRepeatX;
- r->context->state.fillPatternRepeatY = style->patternRepeatY;
- }
- }
- } else if (value->IsString()) {
- QColor color = qt_color_from_string(value);
- if (color.isValid() && r->context->state.fillStyle != QBrush(color)) {
- r->context->state.fillStyle = QBrush(color);
- r->context->buffer()->setFillStyle(r->context->state.fillStyle);
- r->context->m_fillStyle = value;
- }
- }
-}
-/*!
- \qmlproperty enumeration QtQuick2::Context2D::fillRule
- Holds the current fill rule used for filling shapes. The following fill rules supported:
- \list
- \o Qt.OddEvenFill
- \o Qt.WindingFill
- \endlist
- Note: Unlike the \a QPainterPath, the Canvas API uses the winding fill as the default fill rule.
- The fillRule property is part of the context rendering state.
-
- \sa QtQuick2::Context2D::fillStyle
- */
-static v8::Handle<v8::Value> ctx2d_fillRule(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- return engine->fromVariant(r->context->state.fillRule);
-}
-
-static void ctx2d_fillRule_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- if ((value->IsString() && engine->toString(value) == QStringLiteral("WindingFill"))
- ||(value->IsNumber() && value->NumberValue() == Qt::WindingFill)) {
- r->context->state.fillRule = Qt::WindingFill;
- } else if ((value->IsString() && engine->toString(value) == QStringLiteral("OddEvenFill"))
- ||(value->IsNumber() && value->NumberValue() == Qt::OddEvenFill)) {
- r->context->state.fillRule = Qt::OddEvenFill;
- } else {
- //error
- }
- r->context->m_path.setFillRule(r->context->state.fillRule);
-}
-/*!
- \qmlproperty variant QtQuick2::Context2D::strokeStyle
- Holds the current color or style to use for the lines around shapes,
- The style can be either a string containing a CSS color, a CanvasGradient or CanvasPattern object.
- Invalid values are ignored.
-
- The default value is '#000000'.
-
- \sa QtQuick2::Context2D::createLinearGradient
- \sa QtQuick2::Context2D::createRadialGradient
- \sa QtQuick2::Context2D::createPattern
- \sa QtQuick2::Context2D::fillStyle
- */
-v8::Handle<v8::Value> ctx2d_strokeStyle(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- QColor color = r->context->state.strokeStyle.color();
- if (color.isValid()) {
- if (color.alpha() == 255)
- return engine->toString(color.name());
- QString alphaString = QString::number(color.alphaF(), 'f');
- while (alphaString.endsWith(QLatin1Char('0')))
- alphaString.chop(1);
- if (alphaString.endsWith(QLatin1Char('.')))
- alphaString += QLatin1Char('0');
- return engine->toString(QString::fromLatin1("rgba(%1, %2, %3, %4)").arg(color.red()).arg(color.green()).arg(color.blue()).arg(alphaString));
- }
- return r->context->m_strokeStyle;
-}
-
-static void ctx2d_strokeStyle_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- if (value->IsObject()) {
- QColor color = engine->toVariant(value, qMetaTypeId<QColor>()).value<QColor>();
- if (color.isValid()) {
- r->context->state.fillStyle = color;
- r->context->buffer()->setStrokeStyle(color);
- r->context->m_strokeStyle = value;
- } else {
- QV8Context2DStyleResource *style = v8_resource_cast<QV8Context2DStyleResource>(value->ToObject());
- if (style && style->brush != r->context->state.strokeStyle) {
- r->context->state.strokeStyle = style->brush;
- r->context->buffer()->setStrokeStyle(style->brush, style->patternRepeatX, style->patternRepeatY);
- r->context->m_strokeStyle = value;
- r->context->state.strokePatternRepeatX = style->patternRepeatX;
- r->context->state.strokePatternRepeatY = style->patternRepeatY;
-
- }
- }
- } else if (value->IsString()) {
- QColor color = qt_color_from_string(value);
- if (color.isValid() && r->context->state.strokeStyle != QBrush(color)) {
- r->context->state.strokeStyle = QBrush(color);
- r->context->buffer()->setStrokeStyle(r->context->state.strokeStyle);
- r->context->m_strokeStyle = value;
- }
- }
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::createLinearGradient(real x0, real y0, real x1, real y1)
- Returns a CanvasGradient object that represents a linear gradient that transitions the color along a line between
- the start point (\a x0, \a y0) and the end point (\a x1, \a y1).
-
- A gradient is a smooth transition between colors. There are two types of gradients: linear and radial.
- Gradients must have two or more color stops, representing color shifts positioned from 0 to 1 between
- to the gradient's starting and end points or circles.
-
- \sa QtQuick2::Context2D::CanvasGradient::addColorStop
- \sa QtQuick2::Context2D::createRadialGradient
- \sa QtQuick2::Context2D::ctx2d_createConicalGradient
- \sa QtQuick2::Context2D::createPattern
- \sa QtQuick2::Context2D::fillStyle
- \sa QtQuick2::Context2D::strokeStyle
- */
-
-static v8::Handle<v8::Value> ctx2d_createLinearGradient(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- QV8Engine *engine = V8ENGINE();
-
- if (args.Length() == 4) {
- QQuickContext2DEngineData *ed = engineData(engine);
- v8::Local<v8::Object> gradient = ed->constructorGradient->NewInstance();
- QV8Context2DStyleResource *r = new QV8Context2DStyleResource(engine);
- qreal x0 = args[0]->NumberValue();
- qreal y0 = args[1]->NumberValue();
- qreal x1 = args[2]->NumberValue();
- qreal y1 = args[3]->NumberValue();
-
- if (!qIsFinite(x0)
- || !qIsFinite(y0)
- || !qIsFinite(x1)
- || !qIsFinite(y1))
- V8THROW_DOM(DOMEXCEPTION_NOT_SUPPORTED_ERR, "createLinearGradient(): Incorrect arguments")
-
- r->brush = QLinearGradient(x0, y0, x1, y1);
- gradient->SetExternalResource(r);
- return gradient;
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::createRadialGradient(real x0, real y0, real r0, real x1, real y1, real r1)
- Returns a CanvasGradient object that represents a radial gradient that paints along the cone given by the start circle with
- origin (x0, y0) and radius r0, and the end circle with origin (x1, y1) and radius r1.
-
- \sa QtQuick2::Context2D::CanvasGradient::addColorStop
- \sa QtQuick2::Context2D::createLinearGradient
- \sa QtQuick2::Context2D::ctx2d_createConicalGradient
- \sa QtQuick2::Context2D::createPattern
- \sa QtQuick2::Context2D::fillStyle
- \sa QtQuick2::Context2D::strokeStyle
- */
-
-static v8::Handle<v8::Value> ctx2d_createRadialGradient(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- QV8Engine *engine = V8ENGINE();
-
- if (args.Length() == 6) {
- QQuickContext2DEngineData *ed = engineData(engine);
- v8::Local<v8::Object> gradient = ed->constructorGradient->NewInstance();
- QV8Context2DStyleResource *r = new QV8Context2DStyleResource(engine);
-
- qreal x0 = args[0]->NumberValue();
- qreal y0 = args[1]->NumberValue();
- qreal r0 = args[2]->NumberValue();
- qreal x1 = args[3]->NumberValue();
- qreal y1 = args[4]->NumberValue();
- qreal r1 = args[5]->NumberValue();
-
- if (!qIsFinite(x0)
- || !qIsFinite(y0)
- || !qIsFinite(x1)
- || !qIsFinite(r0)
- || !qIsFinite(r1)
- || !qIsFinite(y1))
- V8THROW_DOM(DOMEXCEPTION_NOT_SUPPORTED_ERR, "createRadialGradient(): Incorrect arguments")
-
- if (r0 < 0 || r1 < 0)
- V8THROW_DOM(DOMEXCEPTION_INDEX_SIZE_ERR, "createRadialGradient(): Incorrect arguments")
-
-
- r->brush = QRadialGradient(QPointF(x1, y1), r0+r1, QPointF(x0, y0));
- gradient->SetExternalResource(r);
- return gradient;
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::createConicalGradient(real x, real y, real angle)
- Returns a CanvasGradient object that represents a conical gradient that interpolate colors counter-clockwise around a center point (\c x, \c y)
- with start angle \c angle in units of radians.
-
- \sa QtQuick2::Context2D::CanvasGradient::addColorStop
- \sa QtQuick2::Context2D::createLinearGradient
- \sa QtQuick2::Context2D::ctx2d_createRadialGradient
- \sa QtQuick2::Context2D::createPattern
- \sa QtQuick2::Context2D::fillStyle
- \sa QtQuick2::Context2D::strokeStyle
- */
-
-static v8::Handle<v8::Value> ctx2d_createConicalGradient(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- QV8Engine *engine = V8ENGINE();
-
- if (args.Length() == 6) {
- QQuickContext2DEngineData *ed = engineData(engine);
- v8::Local<v8::Object> gradient = ed->constructorGradient->NewInstance();
- QV8Context2DStyleResource *r = new QV8Context2DStyleResource(engine);
-
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
- qreal angle = DEGREES(args[2]->NumberValue());
- if (!qIsFinite(x) || !qIsFinite(y))
- V8THROW_DOM(DOMEXCEPTION_NOT_SUPPORTED_ERR, "createConicalGradient(): Incorrect arguments");
-
- if (!qIsFinite(angle))
- V8THROW_DOM(DOMEXCEPTION_INDEX_SIZE_ERR, "createConicalGradient(): Incorrect arguments");
-
- r->brush = QConicalGradient(x, y, angle);
- gradient->SetExternalResource(r);
- return gradient;
- }
-
- return args.This();
-}
-/*!
- \qmlmethod variant createPattern(Color color, enumeration patternMode)
- This is a overload function.
- Returns a CanvasPattern object that uses the given \c color and \c patternMode.
- The valid pattern modes are:
- \list
- \o Qt.SolidPattern
- \o Qt.Dense1Pattern
- \o Qt.Dense2Pattern
- \o Qt.Dense3Pattern
- \o Qt.Dense4Pattern
- \o Qt.Dense5Pattern
- \o Qt.Dense6Pattern
- \o Qt.Dense7Pattern
- \o Qt.HorPattern
- \o Qt.VerPattern
- \o Qt.CrossPattern
- \o Qt.BDiagPattern
- \o Qt.FDiagPattern
- \o Qt.DiagCrossPattern
-\endlist
- \sa Qt::BrushStyle
- */
-/*!
- \qmlmethod variant createPattern(Image image, string repetition)
- Returns a CanvasPattern object that uses the given image and repeats in the direction(s) given by the repetition argument.
-
- The \a image parameter must be a valid Image item, a valid \a QtQuick2::CanvasImageData object or loaded image url, if there is no image data, throws an INVALID_STATE_ERR exception.
-
- The allowed values for \a repetition are:
-
- \list
- \o "repeat" - both directions
- \o "repeat-x - horizontal only
- \o "repeat-y" - vertical only
- \o "no-repeat" - neither
- \endlist
-
- If the repetition argument is empty or null, the value "repeat" is used.
-
- \sa QtQuick2::Context2D::strokeStyle
- \sa QtQuick2::Context2D::fillStyle
- */
-static v8::Handle<v8::Value> ctx2d_createPattern(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- QV8Engine *engine = V8ENGINE();
-
- if (args.Length() == 2) {
- QQuickContext2DEngineData *ed = engineData(engine);
- QV8Context2DStyleResource *styleResouce = new QV8Context2DStyleResource(engine);
-
- QColor color = engine->toVariant(args[0], qMetaTypeId<QColor>()).value<QColor>();
- if (color.isValid()) {
- int patternMode = args[1]->IntegerValue();
- Qt::BrushStyle style = Qt::SolidPattern;
- if (patternMode >= 0 && patternMode < Qt::LinearGradientPattern) {
- style = static_cast<Qt::BrushStyle>(patternMode);
- }
- styleResouce->brush = QBrush(color, style);
- } else {
- QImage patternTexture;
-
- if (args[0]->IsObject()) {
- QV8Context2DPixelArrayResource *pixelData = v8_resource_cast<QV8Context2DPixelArrayResource>(args[0]->ToObject()->Get(v8::String::New("data"))->ToObject());
- if (pixelData) {
- patternTexture = pixelData->image;
- }
- } else {
- patternTexture = r->context->createImage(QUrl(engine->toString(args[0]->ToString())));
- }
-
- if (!patternTexture.isNull()) {
- styleResouce->brush.setTextureImage(patternTexture);
-
- QString repetition = engine->toString(args[1]);
- if (repetition == QStringLiteral("repeat") || repetition.isEmpty()) {
- styleResouce->patternRepeatX = true;
- styleResouce->patternRepeatY = true;
- } else if (repetition == QStringLiteral("repeat-x")) {
- styleResouce->patternRepeatX = true;
- } else if (repetition == QStringLiteral("repeat-y")) {
- styleResouce->patternRepeatY = true;
- } else if (repetition == QStringLiteral("no-repeat")) {
- styleResouce->patternRepeatY = false;
- styleResouce->patternRepeatY = false;
- } else {
- //TODO: exception: SYNTAX_ERR
- }
-
- }
- }
-
- v8::Local<v8::Object> pattern = ed->constructorPattern->NewInstance();
- pattern->SetExternalResource(styleResouce);
- return pattern;
-
- }
- return v8::Undefined();
-}
-
-// line styles
-/*!
- \qmlproperty string QtQuick2::Context2D::lineCap
- Holds the the current line cap style.
- The possible line cap styles are:
- \list
- \o butt - the end of each line has a flat edge perpendicular to the direction of the line, this is the default line cap value.
- \o round - a semi-circle with the diameter equal to the width of the line must then be added on to the end of the line.
- \o square - a rectangle with the length of the line width and the width of half the line width, placed flat against the edge perpendicular to the direction of the line.
- \endlist
- Other values are ignored.
-*/
-v8::Handle<v8::Value> ctx2d_lineCap(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
- switch (r->context->state.lineCap) {
- case Qt::RoundCap:
- return engine->toString(QLatin1String("round"));
- case Qt::FlatCap:
- return engine->toString(QLatin1String("butt"));
- case Qt::SquareCap:
- return engine->toString(QLatin1String("square"));
- default:
- break;
- }
- return engine->toString(QLatin1String("butt"));;
-}
-
-static void ctx2d_lineCap_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- QString lineCap = engine->toString(value);
- Qt::PenCapStyle cap;
- if (lineCap == QLatin1String("round"))
- cap = Qt::RoundCap;
- else if (lineCap == QLatin1String("butt"))
- cap = Qt::FlatCap;
- else if (lineCap == QLatin1String("square"))
- cap = Qt::SquareCap;
- else
- return;
-
- if (cap != r->context->state.lineCap) {
- r->context->state.lineCap = cap;
- r->context->buffer()->setLineCap(cap);
- }
-}
-
-/*!
- \qmlproperty string QtQuick2::Context2D::lineJoin
- Holds the the current line join style. A join exists at any point in a subpath
- shared by two consecutive lines. When a subpath is closed, then a join also exists
- at its first point (equivalent to its last point) connecting the first and last lines in the subpath.
-
- The possible line join styles are:
- \list
- \o bevel - this is all that is rendered at joins.
- \o round - a filled arc connecting the two aforementioned corners of the join, abutting (and not overlapping) the aforementioned triangle, with the diameter equal to the line width and the origin at the point of the join, must be rendered at joins.
- \o miter - a second filled triangle must (if it can given the miter length) be rendered at the join, this is the default line join style.
- \endlist
- Other values are ignored.
-*/
-v8::Handle<v8::Value> ctx2d_lineJoin(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
- switch (r->context->state.lineJoin) {
- case Qt::RoundJoin:
- return engine->toString(QLatin1String("round"));
- case Qt::BevelJoin:
- return engine->toString(QLatin1String("bevel"));
- case Qt::MiterJoin:
- return engine->toString(QLatin1String("miter"));
- default:
- break;
- }
- return engine->toString(QLatin1String("miter"));
-}
-
-static void ctx2d_lineJoin_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- QString lineJoin = engine->toString(value);
- Qt::PenJoinStyle join;
- if (lineJoin == QLatin1String("round"))
- join = Qt::RoundJoin;
- else if (lineJoin == QLatin1String("bevel"))
- join = Qt::BevelJoin;
- else if (lineJoin == QLatin1String("miter"))
- join = Qt::MiterJoin;
- else
- return;
-
- if (join != r->context->state.lineJoin) {
- r->context->state.lineJoin = join;
- r->context->buffer()->setLineJoin(join);
- }
-}
-
-/*!
- \qmlproperty real QtQuick2::Context2D::lineWidth
- Holds the the current line width. Values that are not finite values greater than zero are ignored.
- */
-v8::Handle<v8::Value> ctx2d_lineWidth(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
-
- return v8::Number::New(r->context->state.lineWidth);
-}
-
-static void ctx2d_lineWidth_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- qreal w = value->NumberValue();
-
- if (w > 0 && qIsFinite(w) && w != r->context->state.lineWidth) {
- r->context->state.lineWidth = w;
- r->context->buffer()->setLineWidth(w);
- }
-}
-
-/*!
- \qmlproperty real QtQuick2::Context2D::miterLimit
- Holds the current miter limit ratio.
- The default miter limit value is 10.0.
- */
-v8::Handle<v8::Value> ctx2d_miterLimit(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
-
- return v8::Number::New(r->context->state.miterLimit);
-}
-
-static void ctx2d_miterLimit_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- qreal ml = value->NumberValue();
-
- if (ml > 0 && qIsFinite(ml) && ml != r->context->state.miterLimit) {
- r->context->state.miterLimit = ml;
- r->context->buffer()->setMiterLimit(ml);
- }
-}
-
-// shadows
-/*!
- \qmlproperty real QtQuick2::Context2D::shadowBlur
- Holds the current level of blur applied to shadows
- */
-v8::Handle<v8::Value> ctx2d_shadowBlur(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
-
- return v8::Number::New(r->context->state.shadowBlur);
-}
-
-static void ctx2d_shadowBlur_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
- qreal blur = value->NumberValue();
-
- if (blur > 0 && qIsFinite(blur) && blur != r->context->state.shadowBlur) {
- r->context->state.shadowBlur = blur;
- r->context->buffer()->setShadowBlur(blur);
- }
-}
-
-/*!
- \qmlproperty string QtQuick2::Context2D::shadowColor
- Holds the current shadow color.
- */
-v8::Handle<v8::Value> ctx2d_shadowColor(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- return engine->toString(r->context->state.shadowColor.name());
-}
-
-static void ctx2d_shadowColor_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- QColor color = qt_color_from_string(value);
-
- if (color.isValid() && color != r->context->state.shadowColor) {
- r->context->state.shadowColor = color;
- r->context->buffer()->setShadowColor(color);
- }
-}
-
-
-/*!
- \qmlproperty qreal QtQuick2::Context2D::shadowOffsetX
- Holds the current shadow offset in the positive horizontal distance.
-
- \sa QtQuick2::Context2D::shadowOffsetY
- */
-v8::Handle<v8::Value> ctx2d_shadowOffsetX(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
-
- return v8::Number::New(r->context->state.shadowOffsetX);
-}
-
-static void ctx2d_shadowOffsetX_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- qreal offsetX = value->NumberValue();
- if (qIsFinite(offsetX) && offsetX != r->context->state.shadowOffsetX) {
- r->context->state.shadowOffsetX = offsetX;
- r->context->buffer()->setShadowOffsetX(offsetX);
- }
-}
-/*!
- \qmlproperty qreal QtQuick2::Context2D::shadowOffsetY
- Holds the current shadow offset in the positive vertical distance.
-
- \sa QtQuick2::Context2D::shadowOffsetX
- */
-v8::Handle<v8::Value> ctx2d_shadowOffsetY(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
-
- return v8::Number::New(r->context->state.shadowOffsetY);
-}
-
-static void ctx2d_shadowOffsetY_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- qreal offsetY = value->NumberValue();
- if (qIsFinite(offsetY) && offsetY != r->context->state.shadowOffsetY) {
- r->context->state.shadowOffsetY = offsetY;
- r->context->buffer()->setShadowOffsetY(offsetY);
- }
-}
-
-v8::Handle<v8::Value> ctx2d_path(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
- return r->context->m_v8path;
-}
-
-static void ctx2d_path_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- r->context->beginPath();
- if (value->IsObject()) {
- QDeclarativePath* path = qobject_cast<QDeclarativePath*>(engine->toQObject(value));
- if (path)
- r->context->m_path = path->path();
- } else {
- QString path = engine->toString(value->ToString());
- QDeclarativeSvgParser::parsePathDataFast(path, r->context->m_path);
- }
- r->context->m_v8path = value;
-}
-
-//rects
-/*!
- \qmlmethod object QtQuick2::Context2D::clearRect(real x, real y, real w, real h)
- Clears all pixels on the canvas in the given rectangle to transparent black.
- */
-static v8::Handle<v8::Value> ctx2d_clearRect(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- if (args.Length() == 4) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
- qreal w = args[2]->NumberValue();
- qreal h = args[3]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(w) || !qIsFinite(h))
- return args.This();
-
- r->context->buffer()->clearRect(x, y, w, h);
- }
-
- return args.This();
-}
-/*!
- \qmlmethod object QtQuick2::Context2D::fillRect(real x, real y, real w, real h)
- Paint the specified rectangular area using the fillStyle.
-
- \sa QtQuick2::Context2D::fillStyle
- */
-static v8::Handle<v8::Value> ctx2d_fillRect(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- if (args.Length() == 4) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
- qreal w = args[2]->NumberValue();
- qreal h = args[3]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(w) || !qIsFinite(h))
- return args.This();
-
- r->context->buffer()->fillRect(x, y, w, h);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::fillRect(real x, real y, real w, real h)
- Stroke the specified rectangle's path using the strokeStyle, lineWidth, lineJoin,
- and (if appropriate) miterLimit attributes.
-
- \sa QtQuick2::Context2D::strokeStyle
- \sa QtQuick2::Context2D::lineWidth
- \sa QtQuick2::Context2D::lineJoin
- \sa QtQuick2::Context2D::miterLimit
- */
-static v8::Handle<v8::Value> ctx2d_strokeRect(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- if (args.Length() == 4) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
- qreal w = args[2]->NumberValue();
- qreal h = args[3]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(w) || !qIsFinite(h))
- return args.This();
-
- r->context->buffer()->strokeRect(x, y, w, h);
- }
-
- return args.This();
-}
-
-// Complex shapes (paths) API
-/*!
- \qmlmethod object QtQuick2::Context2D::arc(real x, real y, real radius, real startAngle, real endAngle, bool anticlockwise)
- Adds an arc to the current subpath that lies on the circumference of the circle whose center is at the point (\c x,\cy) and whose radius is \c radius.
- \image qml-item-canvas-arcTo2.png
- \sa QtQuick2::Context2D::arcTo
- See {http://www.w3.org/TR/2dcontext/#dom-context-2d-arc}{W3C 2d context standard for arc}
- */
-static v8::Handle<v8::Value> ctx2d_arc(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- if (args.Length() >= 5) {
- bool antiClockwise = false;
-
- if (args.Length() == 6)
- antiClockwise = args[5]->BooleanValue();
-
- qreal radius = args[2]->NumberValue();
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
- qreal sa = args[3]->NumberValue();
- qreal ea = args[4]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(sa) || !qIsFinite(ea))
- return args.This();
-
- if (radius < 0)
- V8THROW_DOM(DOMEXCEPTION_INDEX_SIZE_ERR, "Incorrect argument radius");
-
- r->context->arc(args[0]->NumberValue(),
- args[1]->NumberValue(),
- radius,
- args[3]->NumberValue(),
- args[4]->NumberValue(),
- antiClockwise);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::arcTo(real x1, real y1, real x2, real y2, real radius)
-
- Adds an arc with the given control points and radius to the current subpath, connected to the previous point by a straight line.
- To draw an arc, you begin with the same steps your followed to create a line:
- \list
- \o Call the context.beginPath() method to set a new path.
- \o Call the context.moveTo(\c x, \c y) method to set your starting position on the canvas at the point (\c x,\c y).
- \o To draw an arc or circle, call the context.arcTo(\c x1, \c y1, \c x2, \c y2,\c radius) method.
- This adds an arc with starting point (\c x1,\c y1), ending point (\c x2, \c y2), and radius \c radius to the current subpath and connects
- it to the previous subpath by a straight line.
- \endlist
- \image qml-item-canvas-arcTo.png
- Both startAngle and endAngle are measured from the x axis in units of radians.
-
- \image qml-item-canvas-startAngle.png
- The anticlockwise has the value TRUE for each arc in the figure above because they are all drawn in the counterclockwise direction.
- \sa QtQuick2::Context2D::arc
- \sa {http://www.w3.org/TR/2dcontext/#dom-context-2d-arcto}{W3C 2d context standard for arcTo}
- */
-static v8::Handle<v8::Value> ctx2d_arcTo(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
-
- if (args.Length() == 5) {
- qreal x1 = args[0]->NumberValue();
- qreal y1 = args[1]->NumberValue();
- qreal x2 = args[2]->NumberValue();
- qreal y2 = args[3]->NumberValue();
-
- if (!qIsFinite(x1) || !qIsFinite(y1) || !qIsFinite(x2) || !qIsFinite(y2))
- return args.This();
-
- qreal radius = args[4]->NumberValue();
- if (radius < 0)
- V8THROW_DOM(DOMEXCEPTION_INDEX_SIZE_ERR, "Incorrect argument radius");
- r->context->arcTo(args[0]->NumberValue(),
- args[1]->NumberValue(),
- args[2]->NumberValue(),
- args[3]->NumberValue(),
- args[4]->NumberValue());
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::beginPath()
-
- Resets the current path to a new path.
- */
-static v8::Handle<v8::Value> ctx2d_beginPath(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- r->context->beginPath();
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::bezierCurveTo(real cp1x, real cp1y, real cp2x, real cp2y, real x, real y)
-
- Adds a cubic Bezier curve between the current position and the given endPoint using the control points specified by (\c cp1x, cp1y),
- and (\c cp2x, \c cp2y).
- After the curve is added, the current position is updated to be at the end point (\c x, \c y) of the curve.
- The following code produces the path shown below:
- \code
- ctx.strokeStyle = Qt.rgba(0, 0, 0, 1);
- ctx.lineWidth = 1;
- ctx.beginPath();
- ctx.moveTo(20, 0);//start point
- ctx.bezierCurveTo(-10, 90, 210, 90, 180, 0);
- ctx.stroke();
- \endcode
- \image qml-item-canvas-bezierCurveTo.png
- \sa {http://www.w3.org/TR/2dcontext/#dom-context-2d-beziercurveto}{W3C 2d context standard for bezierCurveTo}
- \sa {http://www.openrise.com/lab/FlowerPower/}{The beautiful flower demo by using bezierCurveTo}
- */
-static v8::Handle<v8::Value> ctx2d_bezierCurveTo(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- if (args.Length() == 6) {
- qreal cp1x = args[0]->NumberValue();
- qreal cp1y = args[1]->NumberValue();
- qreal cp2x = args[2]->NumberValue();
- qreal cp2y = args[3]->NumberValue();
- qreal x = args[4]->NumberValue();
- qreal y = args[5]->NumberValue();
-
- if (!qIsFinite(cp1x) || !qIsFinite(cp1y) || !qIsFinite(cp2x) || !qIsFinite(cp2y) || !qIsFinite(x) || !qIsFinite(y))
- return args.This();
-
- r->context->bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::clip()
-
- Creates the clipping region from the current path.
- Any parts of the shape outside the clipping path are not displayed.
- To create a complex shape using the \a clip() method:
-
- \list 1
- \o Call the \c{context.beginPath()} method to set the clipping path.
- \o Define the clipping path by calling any combination of the \c{lineTo},
- \c{arcTo}, \c{arc}, \c{moveTo}, etc and \c{closePath} methods.
- \o Call the \c{context.clip()} method.
- \endlist
-
- The new shape displays. The following shows how a clipping path can
- modify how an image displays:
-
- \image qml-canvas-clip-complex.png
- \sa QtQuick2::Context2D::beginPath()
- \sa QtQuick2::Context2D::closePath()
- \sa QtQuick2::Context2D::stroke()
- \sa QtQuick2::Context2D::fill()
- \sa {http://www.w3.org/TR/2dcontext/#dom-context-2d-clip}{W3C 2d context standard for clip}
- */
-static v8::Handle<v8::Value> ctx2d_clip(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- QPainterPath clipPath = r->context->m_path;
- clipPath.closeSubpath();
- if (!r->context->state.clipPath.isEmpty())
- r->context->state.clipPath = clipPath.intersected(r->context->state.clipPath);
- else
- r->context->state.clipPath = clipPath;
- r->context->buffer()->clip(r->context->state.clipPath);
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::closePath()
- Closes the current subpath by drawing a line to the beginning of the subpath, automatically starting a new path.
- The current point of the new path is the previous subpath's first point.
-
- \sa {http://www.w3.org/TR/2dcontext/#dom-context-2d-closepath}{W3C 2d context standard for closePath}
- */
-static v8::Handle<v8::Value> ctx2d_closePath(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- r->context->closePath();
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::fill()
-
- Fills the subpaths with the current fill style.
-
- \sa {http://www.w3.org/TR/2dcontext/#dom-context-2d-fill}{W3C 2d context standard for fill}
-
- \sa QtQuick2::Context2D::fillStyle
- */
-static v8::Handle<v8::Value> ctx2d_fill(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r);
-
- r->context->buffer()->fill(r->context->m_path);
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::lineTo(real x, real y)
-
- Draws a line from the current position to the point (x, y).
- */
-static v8::Handle<v8::Value> ctx2d_lineTo(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- if (args.Length() == 2) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y))
- return args.This();
-
- r->context->lineTo(x, y);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::moveTo(real x, real y)
-
- Creates a new subpath with the given point.
- */
-static v8::Handle<v8::Value> ctx2d_moveTo(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- if (args.Length() == 2) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y))
- return args.This();
- r->context->moveTo(x, y);
- }
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::quadraticCurveTo(real cpx, real cpy, real x, real y)
-
- Adds a quadratic Bezier curve between the current point and the endpoint (\c x, \c y) with the control point specified by (\c cpx, \c cpy).
-
- See {http://www.w3.org/TR/2dcontext/#dom-context-2d-quadraticcurveto}{W3C 2d context standard for for quadraticCurveTo}
- */
-static v8::Handle<v8::Value> ctx2d_quadraticCurveTo(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- if (args.Length() == 4) {
- qreal cpx = args[0]->NumberValue();
- qreal cpy = args[1]->NumberValue();
- qreal x = args[2]->NumberValue();
- qreal y = args[3]->NumberValue();
-
- if (!qIsFinite(cpx) || !qIsFinite(cpy) || !qIsFinite(x) || !qIsFinite(y))
- return args.This();
-
- r->context->quadraticCurveTo(cpx, cpy, x, y);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::rect(real x, real y, real w, real h)
-
- Adds a rectangle at position (\c x, \c y), with the given width \c w and height \c h, as a closed subpath.
- */
-static v8::Handle<v8::Value> ctx2d_rect(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- if (args.Length() == 4) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
- qreal w = args[2]->NumberValue();
- qreal h = args[3]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(w) || !qIsFinite(h))
- return args.This();
-
- r->context->rect(x, y, w, h);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::roundedRect(real x, real y, real w, real h, real xRadius, real yRadius)
-
- Adds the given rectangle rect with rounded corners to the path. The \c xRadius and \c yRadius arguments specify the radius of the
- ellipses defining the corners of the rounded rectangle.
- */
-static v8::Handle<v8::Value> ctx2d_roundedRect(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- if (args.Length() == 6) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
- qreal w = args[2]->NumberValue();
- qreal h = args[3]->NumberValue();
- qreal xr = args[4]->NumberValue();
- qreal yr = args[5]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(w) || !qIsFinite(h))
- return args.This();
-
- if (!qIsFinite(xr) || !qIsFinite(yr))
- V8THROW_DOM(DOMEXCEPTION_INDEX_SIZE_ERR, "roundedRect(): Invalid arguments");
-
- r->context->roundedRect(x, y, w, h, xr, yr);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::ellipse(real x, real y, real w, real h)
-
- Creates an ellipse within the bounding rectangle defined by its top-left corner at (\a x, \ y), width \a w and height \a h,
- and adds it to the path as a closed subpath.
-
- The ellipse is composed of a clockwise curve, starting and finishing at zero degrees (the 3 o'clock position).
- */
-static v8::Handle<v8::Value> ctx2d_ellipse(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- if (args.Length() == 4) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
- qreal w = args[2]->NumberValue();
- qreal h = args[3]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(w) || !qIsFinite(h))
- return args.This();
-
-
- r->context->ellipse(x, y, w, h);
- }
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::text(string text, real x, real y)
-
- Adds the given \c text to the path as a set of closed subpaths created from the current context font supplied.
- The subpaths are positioned so that the left end of the text's baseline lies at the point specified by (\c x, \c y).
- */
-static v8::Handle<v8::Value> ctx2d_text(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE();
- if (args.Length() == 3) {
- qreal x = args[1]->NumberValue();
- qreal y = args[2]->NumberValue();
-
- if (!qIsFinite(x) || !qIsFinite(y))
- return args.This();
- r->context->text(engine->toString(args[0]), x, y);
- }
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::stroke()
-
- Strokes the subpaths with the current stroke style.
-
- See {http://www.w3.org/TR/2dcontext/#dom-context-2d-stroke}{W3C 2d context standard for stroke}
-
- \sa QtQuick2::Context2D::strokeStyle
- */
-static v8::Handle<v8::Value> ctx2d_stroke(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
-
- r->context->buffer()->stroke(r->context->m_path);
-
- return args.This();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::isPointInPath(real x, real y)
-
- Returns true if the given point is in the current path.
-
- \sa {http://www.w3.org/TR/2dcontext/#dom-context-2d-ispointinpath}{W3C 2d context standard for isPointInPath}
- */
-static v8::Handle<v8::Value> ctx2d_isPointInPath(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- bool pointInPath = false;
- if (args.Length() == 2) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
- if (!qIsFinite(x) || !qIsFinite(y))
- return v8::Boolean::New(false);
- pointInPath = r->context->isPointInPath(x, y);
- }
- return v8::Boolean::New(pointInPath);
-}
-
-static v8::Handle<v8::Value> ctx2d_drawFocusRing(const v8::Arguments &args)
-{
- V8THROW_DOM(DOMEXCEPTION_NOT_SUPPORTED_ERR, "Context2D::drawFocusRing is not supported");
- return args.This();
-}
-
-static v8::Handle<v8::Value> ctx2d_setCaretSelectionRect(const v8::Arguments &args)
-{
- V8THROW_DOM(DOMEXCEPTION_NOT_SUPPORTED_ERR, "Context2D::setCaretSelectionRect is not supported");
- return args.This();
-}
-
-static v8::Handle<v8::Value> ctx2d_caretBlinkRate(const v8::Arguments &args)
-{
- V8THROW_DOM(DOMEXCEPTION_NOT_SUPPORTED_ERR, "Context2D::caretBlinkRate is not supported");
- return args.This();
-}
-// text
-/*!
- \qmlproperty string QtQuick2::Context2D::font
- Holds the current font settings.
-
- The default font value is "10px sans-serif".
- See {http://www.w3.org/TR/2dcontext/#dom-context-2d-font}{w3C 2d context standard for font}
- */
-v8::Handle<v8::Value> ctx2d_font(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- return engine->toString(r->context->state.font.toString());
-}
-
-static void ctx2d_font_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
- QString fs = engine->toString(value);
- QFont font = qt_font_from_string(fs);
- if (font != r->context->state.font) {
- r->context->state.font = font;
- }
-}
-
-/*!
- \qmlproperty string QtQuick2::Context2D::textAlign
-
- Holds the current text alignment settings.
- The possible values are:
- \list
- \o start
- \o end
- \o left
- \o right
- \o center
- \endlist
- Other values are ignored. The default value is "start".
- */
-v8::Handle<v8::Value> ctx2d_textAlign(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
- QV8Engine *engine = V8ENGINE_ACCESSOR();
- switch (r->context->state.textAlign) {
- case QQuickContext2D::Start:
- return engine->toString(QLatin1String("start"));
- case QQuickContext2D::End:
- return engine->toString(QLatin1String("end"));
- case QQuickContext2D::Left:
- return engine->toString(QLatin1String("left"));
- case QQuickContext2D::Right:
- return engine->toString(QLatin1String("right"));
- case QQuickContext2D::Center:
- return engine->toString(QLatin1String("center"));
- default:
- break;
- }
- return engine->toString(QLatin1String("start"));
-}
-
-static void ctx2d_textAlign_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
- QV8Engine *engine = V8ENGINE_ACCESSOR();
-
- QString textAlign = engine->toString(value);
-
- QQuickContext2D::TextAlignType ta;
- if (textAlign == QLatin1String("start"))
- ta = QQuickContext2D::Start;
- else if (textAlign == QLatin1String("end"))
- ta = QQuickContext2D::End;
- else if (textAlign == QLatin1String("left"))
- ta = QQuickContext2D::Left;
- else if (textAlign == QLatin1String("right"))
- ta = QQuickContext2D::Right;
- else if (textAlign == QLatin1String("center"))
- ta = QQuickContext2D::Center;
- else
- return;
-
- if (ta != r->context->state.textAlign) {
- r->context->state.textAlign = ta;
- }
-}
-
-/*!
- \qmlproperty string QtQuick2::Context2D::textBaseline
-
- Holds the current baseline alignment settings.
- The possible values are:
- \list
- \o top
- \o hanging
- \o middle
- \o alphabetic
- \o ideographic
- \o bottom
- \endlist
- Other values are ignored. The default value is "alphabetic".
- */
-v8::Handle<v8::Value> ctx2d_textBaseline(v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE_ACCESSOR();
- switch (r->context->state.textBaseline) {
- case QQuickContext2D::Alphabetic:
- return engine->toString(QLatin1String("alphabetic"));
- case QQuickContext2D::Hanging:
- return engine->toString(QLatin1String("hanging"));
- case QQuickContext2D::Top:
- return engine->toString(QLatin1String("top"));
- case QQuickContext2D::Bottom:
- return engine->toString(QLatin1String("bottom"));
- case QQuickContext2D::Middle:
- return engine->toString(QLatin1String("middle"));
- default:
- break;
- }
- return engine->toString(QLatin1String("alphabetic"));
-}
-
-static void ctx2d_textBaseline_set(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(info.This());
- CHECK_CONTEXT_SETTER(r)
- QV8Engine *engine = V8ENGINE_ACCESSOR();
- QString textBaseline = engine->toString(value);
-
- QQuickContext2D::TextBaseLineType tb;
- if (textBaseline == QLatin1String("alphabetic"))
- tb = QQuickContext2D::Alphabetic;
- else if (textBaseline == QLatin1String("hanging"))
- tb = QQuickContext2D::Hanging;
- else if (textBaseline == QLatin1String("top"))
- tb = QQuickContext2D::Top;
- else if (textBaseline == QLatin1String("bottom"))
- tb = QQuickContext2D::Bottom;
- else if (textBaseline == QLatin1String("middle"))
- tb = QQuickContext2D::Middle;
- else
- return;
-
- if (tb != r->context->state.textBaseline) {
- r->context->state.textBaseline = tb;
- }
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::fillText(text, x, y)
- Fills the given text at the given position.
- \sa QtQuick2::Context2D::font
- \sa QtQuick2::Context2D::textAlign
- \sa QtQuick2::Context2D::textBaseline
- \sa QtQuick2::Context2D::strokeText
- */
-static v8::Handle<v8::Value> ctx2d_fillText(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE();
- if (args.Length() == 3) {
- qreal x = args[1]->NumberValue();
- qreal y = args[2]->NumberValue();
- if (!qIsFinite(x) || !qIsFinite(y))
- return args.This();
- QPainterPath textPath = r->context->createTextGlyphs(x, y, engine->toString(args[0]));
- r->context->buffer()->fill(textPath);
- }
- return args.This();
-}
-/*!
- \qmlmethod object QtQuick2::Context2D::strokeText(text, x, y)
- Strokes the given text at the given position.
- \sa QtQuick2::Context2D::font
- \sa QtQuick2::Context2D::textAlign
- \sa QtQuick2::Context2D::textBaseline
- \sa QtQuick2::Context2D::fillText
- */
-static v8::Handle<v8::Value> ctx2d_strokeText(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE();
- if (args.Length() == 3) {
- qreal x = args[1]->NumberValue();
- qreal y = args[2]->NumberValue();
- if (!qIsFinite(x) || !qIsFinite(y))
- return args.This();
- QPainterPath textPath = r->context->createTextGlyphs(x, y, engine->toString(args[0]));
- r->context->buffer()->stroke(textPath);
- }
- return args.This();
-}
-/*!
- \qmlclass QtQuick2::TextMetrics
- \inqmlmodule QtQuick 2
- \since QtQuick 2.0
- \brief The Context2D TextMetrics interface.
- The TextMetrics object can be created by QtQuick2::Context2D::measureText method.
- See {http://www.w3.org/TR/2dcontext/#textmetrics}{W3C 2d context TexMetrics} for more details.
-
- \sa QtQuick2::Context2D::measureText
- \sa QtQuick2::TextMetrics::width
- */
-
-/*!
- \qmlproperty int QtQuick2::TextMetrics::width
- Holds the advance width of the text that was passed to the QtQuick2::Context2D::measureText() method.
- This property is read only.
- */
-
-/*!
- \qmlmethod variant QtQuick2::Context2D::measureText(text)
- Returns a TextMetrics object with the metrics of the given text in the current font.
- */
-static v8::Handle<v8::Value> ctx2d_measureText(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE();
-
- if (args.Length() == 1) {
- QFontMetrics fm(r->context->state.font);
- uint width = fm.width(engine->toString(args[0]));
- v8::Local<v8::Object> tm = v8::Object::New();
- tm->Set(v8::String::New("width"), v8::Number::New(width));
- return tm;
- }
- return v8::Undefined();
-}
-
-// drawing images
-/*!
- \qmlmethod QtQuick2::Context2D::drawImage(variant image, real dx, real dy)
- Draws the given \a image on the canvas at position (\a dx, \a dy).
- Note:
- The \a image type can be an Image item, an image url or a \a {QtQuick2::CanvasImageData} object.
- When given as Image item, if the image isn't fully loaded, this method draws nothing.
- When given as url string, the image should be loaded by calling Canvas item's \a QtQuick2::Canvas::loadImage() method first.
- This image been drawing is subject to the current context clip path, even the given \c image is a {QtQuick2::CanvasImageData} object.
-
- \sa QtQuick2::CanvasImageData
- \sa QtQuick2::Image
- \sa QtQuick2::Canvas::loadImage
- \sa QtQuick2::Canvas::isImageLoaded
- \sa QtQuick2::Canvas::imageLoaded
-
- \sa {http://www.w3.org/TR/2dcontext/#dom-context-2d-drawimage}{W3C 2d context standard for drawImage}
- */
-/*!
- \qmlmethod QtQuick2::Context2D::drawImage(variant image, real dx, real dy, real dw, real dh)
- This is an overloaded function.
- Draws the given item as \a image onto the canvas at point (\a dx, \a dy) and with width \a dw,
- height \a dh.
-
- Note:
- The \a image type can be an Image item, an image url or a \a {QtQuick2::CanvasImageData} object.
- When given as Image item, if the image isn't fully loaded, this method draws nothing.
- When given as url string, the image should be loaded by calling Canvas item's \a QtQuick2::Canvas::loadImage() method first.
- This image been drawing is subject to the current context clip path, even the given \c image is a {QtQuick2::CanvasImageData} object.
-
- \sa QtQuick2::CanvasImageData
- \sa QtQuick2::Image
- \sa QtQuick2::Canvas::loadImage
- \sa QtQuick2::Canvas::isImageLoaded
- \sa QtQuick2::Canvas::imageLoaded
-
- \sa {http://www.w3.org/TR/2dcontext/#dom-context-2d-drawimage}{W3C 2d context standard for drawImage}
- */
-/*!
- \qmlmethod QtQuick2::Context2D::drawImage(variant image, real sx, real sy, real sw, sh, real dx, real dy, real dw, dh)
- This is an overloaded function.
- Draws the given item as \a image from source point (\a sx, \a sy) and source width \sw, source height \sh
- onto the canvas at point (\a dx, \a dy) and with width \a dw, height \a dh.
-
-
- Note:
- The \a image type can be an Image or Canvas item, an image url or a \a {QtQuick2::CanvasImageData} object.
- When given as Image item, if the image isn't fully loaded, this method draws nothing.
- When given as url string, the image should be loaded by calling Canvas item's \a QtQuick2::Canvas::loadImage() method first.
- This image been drawing is subject to the current context clip path, even the given \c image is a {QtQuick2::CanvasImageData} object.
-
- \sa QtQuick2::CanvasImageData
- \sa QtQuick2::Image
- \sa QtQuick2::Canvas::loadImage
- \sa QtQuick2::Canvas::isImageLoaded
- \sa QtQuick2::Canvas::imageLoaded
-
- \sa {http://www.w3.org/TR/2dcontext/#dom-context-2d-drawimage}{W3C 2d context standard for drawImage}
-*/
-static v8::Handle<v8::Value> ctx2d_drawImage(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE();
- qreal sx, sy, sw, sh, dx, dy, dw, dh;
-
- if (!args.Length())
- return args.This();
-
- QImage image;
- if (args[0]->IsString()) {
- QUrl url(engine->toString(args[0]->ToString()));
- if (!url.isValid())
- V8THROW_DOM(DOMEXCEPTION_TYPE_MISMATCH_ERR, "drawImage(), type mismatch");
-
- image = r->context->createImage(url);
- } else if (args[0]->IsObject()) {
- QQuickImage *imageItem = qobject_cast<QQuickImage*>(engine->toQObject(args[0]->ToObject()));
- QQuickCanvasItem *canvas = qobject_cast<QQuickCanvasItem*>(engine->toQObject(args[0]->ToObject()));
-
- QV8Context2DPixelArrayResource *pix = v8_resource_cast<QV8Context2DPixelArrayResource>(args[0]->ToObject()->GetInternalField(0)->ToObject());
- if (pix) {
- image = pix->image;
- } else if (imageItem) {
- image = imageItem->image();
- } else if (canvas) {
- image = canvas->toImage();
- } else {
- V8THROW_DOM(DOMEXCEPTION_TYPE_MISMATCH_ERR, "drawImage(), type mismatch");
- }
- } else {
- V8THROW_DOM(DOMEXCEPTION_TYPE_MISMATCH_ERR, "drawImage(), type mismatch");
- }
- if (args.Length() == 3) {
- dx = args[1]->NumberValue();
- dy = args[2]->NumberValue();
- sx = 0;
- sy = 0;
- sw = image.width();
- sh = image.height();
- dw = sw;
- dh = sh;
- } else if (args.Length() == 5) {
- sx = 0;
- sy = 0;
- sw = image.width();
- sh = image.height();
- dx = args[1]->NumberValue();
- dy = args[2]->NumberValue();
- dw = args[3]->NumberValue();
- dh = args[4]->NumberValue();
- } else if (args.Length() == 9) {
- sx = args[1]->NumberValue();
- sy = args[2]->NumberValue();
- sw = args[3]->NumberValue();
- sh = args[4]->NumberValue();
- dx = args[5]->NumberValue();
- dy = args[6]->NumberValue();
- dw = args[7]->NumberValue();
- dh = args[8]->NumberValue();
- } else {
- return args.This();
- }
-
- if (!qIsFinite(sx)
- || !qIsFinite(sy)
- || !qIsFinite(sw)
- || !qIsFinite(sh)
- || !qIsFinite(dx)
- || !qIsFinite(dy)
- || !qIsFinite(dw)
- || !qIsFinite(dh))
- return args.This();
-
- if (!image.isNull()) {
- if (sx < 0 || sy < 0 || sw == 0 || sh == 0
- || sx + sw > image.width() || sy + sh > image.height()
- || sx + sw < 0 || sy + sh < 0) {
- V8THROW_DOM(DOMEXCEPTION_INDEX_SIZE_ERR, "drawImage(), index size error");
- }
-
- r->context->buffer()->drawImage(image,sx, sy, sw, sh, dx, dy, dw, dh);
- }
-
- return args.This();
-}
-
-// pixel manipulation
-/*!
- \qmlclass QtQuick2::CanvasImageData
- The \a QtQuick2::CanvasImageData object holds the image pixel data.
-
- The \a QtQuick2::CanvasImageData object has the actual dimensions of the data stored in
- this object and holds the one-dimensional array containing the data in RGBA order,
- as integers in the range 0 to 255.
-
- \sa QtQuick2::CanvasImageData::width
- \sa QtQuick2::CanvasImageData::height
- \sa QtQuick2::CanvasImageData::data
- \sa QtQuick2::Context2D::createImageData
- \sa QtQuick2::Context2D::getImageData
- \sa QtQuick2::Context2D::putImageData
- */
-/*!
- \qmlproperty QtQuick2::CanvasImageData::width
- Holds the actual width dimension of the data in the ImageData object, in device pixels.
- */
-v8::Handle<v8::Value> ctx2d_imageData_width(v8::Local<v8::String>, const v8::AccessorInfo &args)
-{
- QV8Context2DPixelArrayResource *r = v8_resource_cast<QV8Context2DPixelArrayResource>(args.This()->GetInternalField(0)->ToObject());
- if (!r)
- return v8::Integer::New(0);
- return v8::Integer::New(r->image.width());
-}
-
-/*!
- \qmlproperty QtQuick2::CanvasImageData::height
- Holds the actual height dimension of the data in the ImageData object, in device pixels.
- */
-v8::Handle<v8::Value> ctx2d_imageData_height(v8::Local<v8::String>, const v8::AccessorInfo &args)
-{
- QV8Context2DPixelArrayResource *r = v8_resource_cast<QV8Context2DPixelArrayResource>(args.This()->GetInternalField(0)->ToObject());
- if (!r)
- return v8::Integer::New(0);
-
- return v8::Integer::New(r->image.height());
-}
-
-/*!
- \qmlproperty QtQuick2::CanvasImageData::data
- Holds the one-dimensional array containing the data in RGBA order, as integers in the range 0 to 255.
- */
-v8::Handle<v8::Value> ctx2d_imageData_data(v8::Local<v8::String>, const v8::AccessorInfo &args)
-{
- return args.This()->GetInternalField(0);
-}
-
-/*!
- \qmlmethod void QtQuick2::CanvasImageData::mirrr( bool horizontal = false, bool vertical = true)
- Mirrors the image data in place in the \c horizontal and/or the \c vertical direction depending on
- whether horizontal and vertical are set to true or false.
- The default \c horizontal value is false, the default \c vertical value is true.
-*/
-static v8::Handle<v8::Value> ctx2d_imageData_mirror(const v8::Arguments &args)
-{
- bool horizontal = false, vertical = true;
- QV8Context2DPixelArrayResource *r = v8_resource_cast<QV8Context2DPixelArrayResource>(args.This()->GetInternalField(0)->ToObject());
-
- if (!r) {
- //error
- return v8::Undefined();
- }
-
- if (args.Length() > 2) {
- //error
- return v8::Undefined();
- }
-
- if (args.Length() == 1) {
- horizontal = args[0]->BooleanValue();
- } else if (args.Length() == 2) {
- horizontal = args[0]->BooleanValue();
- vertical = args[1]->BooleanValue();
- }
- r->image = r->image.mirrored(horizontal, vertical);
- return args.This();
-}
-
-/*!
- \qmlmethod void QtQuick2::CanvasImageData::filter(enumeration mode, args)
- Filters the image data as defined by one of the following modes:
- \list
- \o Canvas.Threshold - converts the image to black and white pixels depending
- if they are above or below the threshold defined by the level parameter.
- The level must be between 0.0 (black) and 1.0(white).
- If no level is specified, 0.5 is used.
- \o Canvas.Mono - converts the image to the 1-bit per pixel format.
- \o Canvas.GrayScale - converts any colors in the image to grayscale equivalents.
- \o Canvas.Brightness -increase/decrease a fixed \c adjustment value to each pixel's RGB channel value.
- \o Canvas.Invert - sets each pixel to its inverse value.
- \o Canvas.Blur - executes a box blur with the pixel \c radius parameter specifying the range of the blurring for each pixel.
- the default blur \c radius is 3. This filter also accepts another \c quality parameter, if true, the filter will
- execute 3-passes box blur to simulate the Guassian blur. The default \c quality value is false.
- \o Canvas.Opaque - sets the alpha channel to entirely opaque.
- \o Canvas.Convolute - executes a generic {http://en.wikipedia.org/wiki/Convolution}{Convolution} filter, the second
- parameter contains the convoluton matrix data as a number array.
- \endlist
-
-*/
-static v8::Handle<v8::Value> ctx2d_imageData_filter(const v8::Arguments &args)
-{
- QV8Context2DPixelArrayResource *r = v8_resource_cast<QV8Context2DPixelArrayResource>(args.This()->GetInternalField(0)->ToObject());
-
- if (!r) {
- //error
- return v8::Undefined();
- }
-
- if (args.Length() >= 1) {
- int filterFlag = args[0]->IntegerValue();
- switch (filterFlag) {
- case QQuickCanvasItem::Mono :
- {
- r->image = r->image.convertToFormat(QImage::Format_Mono).convertToFormat(QImage::Format_ARGB32_Premultiplied);
- }
- break;
- case QQuickCanvasItem::GrayScale :
- {
- for (int y = 0; y < r->image.height(); ++y) {
- QRgb *row = (QRgb*)r->image.scanLine(y);
- for (int x = 0; x < r->image.width(); ++x) {
- unsigned char* rgb = ((unsigned char*)&row[x]);
- rgb[0] = rgb[1] = rgb[2] = qGray(rgb[0], rgb[1], rgb[2]);
- }
- }
- }
- break;
- case QQuickCanvasItem::Threshold :
- {
- qreal threshold = 0.5;
- if (args.Length() > 1)
- threshold = args[1]->NumberValue();
-
- for (int y = 0; y < r->image.height(); ++y) {
- QRgb *row = (QRgb*)r->image.scanLine(y);
- for (int x = 0; x < r->image.width(); ++x) {
- unsigned char* rgb = ((unsigned char*)&row[x]);
- unsigned char v = qGray(rgb[0], rgb[1], rgb[2]) >= threshold*255 ? 255 : 0;
- rgb[0] = rgb[1] = rgb[2] = v;
- }
- }
- }
- break;
- case QQuickCanvasItem::Brightness :
- {
- int adjustment = 1;
- if (args.Length() > 1)
- adjustment = args[1]->IntegerValue();
-
- for (int y = 0; y < r->image.height(); ++y) {
- QRgb *row = (QRgb*)r->image.scanLine(y);
- for (int x = 0; x < r->image.width(); ++x) {
- ((unsigned char*)&row[x])[0] += adjustment;
- ((unsigned char*)&row[x])[1] += adjustment;
- ((unsigned char*)&row[x])[2] += adjustment;
- }
- }
- }
- break;
- case QQuickCanvasItem::Invert :
- {
- r->image.invertPixels();
- }
- break;
- case QQuickCanvasItem::Blur :
- {
- int radius = 3;
- bool quality = false;
-
- if (args.Length() > 1)
- radius = args[1]->IntegerValue() / 2;
- if (args.Length() > 2)
- quality = args[2]->BooleanValue();
-
- qt_image_boxblur(r->image, radius, quality);
- }
- break;
- case QQuickCanvasItem::Opaque :
- {
- for (int y = 0; y < r->image.height(); ++y) {
- QRgb *row = (QRgb*)r->image.scanLine(y);
- for (int x = 0; x < r->image.width(); ++x) {
- ((unsigned char*)&row[x])[3] = 255;
- }
- }
- }
- break;
- case QQuickCanvasItem::Convolute :
- {
- if (args.Length() > 1 && args[1]->IsArray()) {
- v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(args[1]);
- QVector<qreal> weights;
- for (uint32_t i = 0; i < array->Length(); ++i)
- weights.append(array->Get(i)->NumberValue());
- r->image = qt_image_convolute_filter(r->image, weights);
- } else {
- //error
- }
- }
- break;
- default:
- break;
- }
- }
-
- return args.This();
-}
-/*!
- \qmlclass QtQuick2::CanvasPixelArray
- The CanvasPixelArray object provides ordered, indexed access to the color components of each pixel of the image data.
- The CanvasPixelArray can be accessed as normal Javascript array.
- \sa QtQuick2::CanvasImageData
- \sa {http://www.w3.org/TR/2dcontext/#canvaspixelarray}{W3C 2d context standard for PixelArray}
- */
-
-/*!
- \qmlproperty QtQuick2::CanvasPixelArray::length
- The CanvasPixelArray object represents h×w×4 integers which w and h comes from CanvasImageData.
- The length attribute of a CanvasPixelArray object must return this h×w×4 number value.
- This property is read only.
-*/
-v8::Handle<v8::Value> ctx2d_pixelArray_length(v8::Local<v8::String>, const v8::AccessorInfo &args)
-{
- QV8Context2DPixelArrayResource *r = v8_resource_cast<QV8Context2DPixelArrayResource>(args.This());
- if (!r || r->image.isNull()) return v8::Undefined();
-
- return v8::Integer::New(r->image.width() * r->image.height() * 4);
-}
-
-v8::Handle<v8::Value> ctx2d_pixelArray_indexed(uint32_t index, const v8::AccessorInfo& args)
-{
- QV8Context2DPixelArrayResource *r = v8_resource_cast<QV8Context2DPixelArrayResource>(args.This());
-
- if (r && index < static_cast<quint32>(r->image.width() * r->image.height() * 4)) {
- const quint32 w = r->image.width();
- const quint32 row = (index / 4) / w;
- const quint32 col = (index / 4) % w;
- const QRgb* pixel = reinterpret_cast<const QRgb*>(r->image.constScanLine(row));
- pixel += col;
- switch (index % 4) {
- case 0:
- return v8::Integer::New(qRed(*pixel));
- case 1:
- return v8::Integer::New(qGreen(*pixel));
- case 2:
- return v8::Integer::New(qBlue(*pixel));
- case 3:
- return v8::Integer::New(qAlpha(*pixel));
- }
- }
- return v8::Undefined();
-}
-
-v8::Handle<v8::Value> ctx2d_pixelArray_indexed_set(uint32_t index, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
-{
- QV8Context2DPixelArrayResource *r = v8_resource_cast<QV8Context2DPixelArrayResource>(info.This());
-
- const int v = value->Uint32Value();
- if (r && index < static_cast<quint32>(r->image.width() * r->image.height() * 4) && v > 0 && v <= 255) {
- const quint32 w = r->image.width();
- const quint32 row = (index / 4) / w;
- const quint32 col = (index / 4) % w;
-
- QRgb* pixel = reinterpret_cast<QRgb*>(r->image.scanLine(row));
- pixel += col;
- switch (index % 4) {
- case 0:
- *pixel = qRgba(v, qGreen(*pixel), qBlue(*pixel), qAlpha(*pixel));
- break;
- case 1:
- *pixel = qRgba(qRed(*pixel), v, qBlue(*pixel), qAlpha(*pixel));
- break;
- case 2:
- *pixel = qRgba(qRed(*pixel), qGreen(*pixel), v, qAlpha(*pixel));
- break;
- case 3:
- *pixel = qRgba(qRed(*pixel), qGreen(*pixel), qBlue(*pixel), v);
- break;
- }
- }
- return v8::Undefined();
-}
-/*!
- \qmlmethod QtQuick2::CanvasImageData createImageData(real sw, real sh)
- Creates a CanvasImageData object with the given dimensions(\a sw, \a sh).
- */
-/*!
- \qmlmethod QtQuick2::CanvasImageData createImageData(QtQuick2::CanvasImageData imageData)
- Creates a CanvasImageData object with the same dimensions as the argument.
- */
-/*!
- \qmlmethod QtQuick2::CanvasImageData createImageData(Url imageUrl)
- Creates a CanvasImageData object with the given image loaded from \a imageUrl.
- Note:The \a imageUrl must be already loaded before this function call, if not, an empty
- CanvasImageData obect will be returned.
-
- \sa QtQuick2::Canvas::loadImage, QtQuick2::Canvas::unloadImage, QtQuick2::Canvas::isImageLoaded
- */
-static v8::Handle<v8::Value> ctx2d_createImageData(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE();
-
- if (args.Length() == 1) {
- if (args[0]->IsObject()) {
- v8::Local<v8::Object> imgData = args[0]->ToObject();
- QV8Context2DPixelArrayResource *pa = v8_resource_cast<QV8Context2DPixelArrayResource>(imgData->GetInternalField(0)->ToObject());
- if (pa) {
- qreal w = imgData->Get(v8::String::New("width"))->NumberValue();
- qreal h = imgData->Get(v8::String::New("height"))->NumberValue();
- return qt_create_image_data(w, h, engine, QImage());
- }
- } else if (args[0]->IsString()) {
- QImage image = r->context->createImage(QUrl(engine->toString(args[0]->ToString())));
- return qt_create_image_data(image.width(), image.height(), engine, image);
- }
- } else if (args.Length() == 2) {
- qreal w = args[0]->NumberValue();
- qreal h = args[1]->NumberValue();
-
- if (!qIsFinite(w) || !qIsFinite(h))
- V8THROW_DOM(DOMEXCEPTION_NOT_SUPPORTED_ERR, "createImageData(): invalid arguments");
-
- if (w > 0 && h > 0)
- return qt_create_image_data(w, h, engine, QImage());
- else
- V8THROW_DOM(DOMEXCEPTION_INDEX_SIZE_ERR, "createImageData(): invalid arguments");
- }
- return v8::Undefined();
-}
-
-/*!
- \qmlmethod QtQuick2::CanvasImageData getImageData(real sx, real sy, real sw, real sh)
- Returns an CanvasImageData object containing the image data for the given rectangle of the canvas.
- */
-static v8::Handle<v8::Value> ctx2d_getImageData(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
-
- QV8Engine *engine = V8ENGINE();
- if (args.Length() == 4) {
- qreal x = args[0]->NumberValue();
- qreal y = args[1]->NumberValue();
- qreal w = args[2]->NumberValue();
- qreal h = args[3]->NumberValue();
- if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(w) || !qIsFinite(w))
- V8THROW_DOM(DOMEXCEPTION_NOT_SUPPORTED_ERR, "getImageData(): Invalid arguments");
-
- if (w <= 0 || h <= 0)
- V8THROW_DOM(DOMEXCEPTION_INDEX_SIZE_ERR, "getImageData(): Invalid arguments");
-
- QImage image = r->context->canvas()->toImage(QRectF(x, y, w, h));
- v8::Local<v8::Object> imageData = qt_create_image_data(w, h, engine, image);
-
- return imageData;
- }
- return v8::Null();
-}
-
-/*!
- \qmlmethod object QtQuick2::Context2D::putImageData(QtQuick2::CanvasImageData imageData, real dx, real dy, real dirtyX, real dirtyY, real dirtyWidth, real dirtyHeight)
- Paints the data from the given ImageData object onto the canvas. If a dirty rectangle (\a dirtyX, \a dirtyY, \a dirtyWidth, \a dirtyHeight) is provided, only the pixels from that rectangle are painted.
- */
-static v8::Handle<v8::Value> ctx2d_putImageData(const v8::Arguments &args)
-{
- QV8Context2DResource *r = v8_resource_cast<QV8Context2DResource>(args.This());
- CHECK_CONTEXT(r)
- if (args.Length() != 3 && args.Length() != 7)
- return v8::Undefined();
-
- if (args[0]->IsNull() || !args[0]->IsObject()) {
- V8THROW_DOM(DOMEXCEPTION_TYPE_MISMATCH_ERR, "Context2D::putImageData, the image data type mismatch");
- }
- qreal dx = args[1]->NumberValue();
- qreal dy = args[2]->NumberValue();
- qreal w, h, dirtyX, dirtyY, dirtyWidth, dirtyHeight;
-
- if (!qIsFinite(dx) || !qIsFinite(dy))
- V8THROW_DOM(DOMEXCEPTION_NOT_SUPPORTED_ERR, "putImageData() : Invalid arguments");
-
- v8::Local<v8::Object> imageData = args[0]->ToObject();
- QV8Context2DPixelArrayResource *pixelArray = v8_resource_cast<QV8Context2DPixelArrayResource>(imageData->Get(v8::String::New("data"))->ToObject());
- if (pixelArray) {
- w = imageData->Get(v8::String::New("width"))->NumberValue();
- h = imageData->Get(v8::String::New("height"))->NumberValue();
-
- if (args.Length() == 7) {
- dirtyX = args[3]->NumberValue();
- dirtyY = args[4]->NumberValue();
- dirtyWidth = args[5]->NumberValue();
- dirtyHeight = args[6]->NumberValue();
-
- if (!qIsFinite(dirtyX) || !qIsFinite(dirtyY) || !qIsFinite(dirtyWidth) || !qIsFinite(dirtyHeight))
- V8THROW_DOM(DOMEXCEPTION_NOT_SUPPORTED_ERR, "putImageData() : Invalid arguments");
-
-
- if (dirtyWidth < 0) {
- dirtyX = dirtyX+dirtyWidth;
- dirtyWidth = -dirtyWidth;
- }
-
- if (dirtyHeight < 0) {
- dirtyY = dirtyY+dirtyHeight;
- dirtyHeight = -dirtyHeight;
- }
-
- if (dirtyX < 0) {
- dirtyWidth = dirtyWidth+dirtyX;
- dirtyX = 0;
- }
-
- if (dirtyY < 0) {
- dirtyHeight = dirtyHeight+dirtyY;
- dirtyY = 0;
- }
-
- if (dirtyX+dirtyWidth > w) {
- dirtyWidth = w - dirtyX;
- }
-
- if (dirtyY+dirtyHeight > h) {
- dirtyHeight = h - dirtyY;
- }
-
- if (dirtyWidth <=0 || dirtyHeight <= 0)
- return args.This();
- } else {
- dirtyX = 0;
- dirtyY = 0;
- dirtyWidth = w;
- dirtyHeight = h;
- }
-
- QImage image = pixelArray->image.copy(dirtyX, dirtyY, dirtyWidth, dirtyHeight);
- r->context->buffer()->drawImage(image, dirtyX, dirtyY, dirtyWidth, dirtyHeight, dx, dy, dirtyWidth, dirtyHeight);
- }
- return args.This();
-}
-
-/*!
- \qmlclass QtQuick2::CanvasGradient
- \inqmlmodule QtQuick 2
- \since QtQuick 2.0
- \brief The Context2D opaque CanvasGradient interface.
- */
-
-/*!
- \qmlmethod QtQuick2::CanvasGradient QtQuick2::CanvasGradient::addColorStop(real offsetof, string color)
- Adds a color stop with the given color to the gradient at the given offset.
- 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end.
-
- For example:
- \code
- var gradient = ctx.createLinearGradient(0, 0, 100, 100);
- gradient.addColorStop(0.3, Qt.rgba(1, 0, 0, 1));
- gradient.addColorStop(0.7, 'rgba(0, 255, 255, 1');
- \endcode
- */
-static v8::Handle<v8::Value> ctx2d_gradient_addColorStop(const v8::Arguments &args)
-{
- QV8Context2DStyleResource *style = v8_resource_cast<QV8Context2DStyleResource>(args.This());
- if (!style)
- V8THROW_ERROR("Not a CanvasGradient object");
-
- QV8Engine *engine = V8ENGINE();
-
- if (args.Length() == 2) {
-
- if (!style->brush.gradient())
- V8THROW_ERROR("Not a valid CanvasGradient object, can't get the gradient information");
- QGradient gradient = *(style->brush.gradient());
- qreal pos = args[0]->NumberValue();
- QColor color;
-
- if (args[1]->IsObject()) {
- color = engine->toVariant(args[1], qMetaTypeId<QColor>()).value<QColor>();
- } else {
- color = qt_color_from_string(args[1]);
- }
- if (pos < 0.0 || pos > 1.0 || !qIsFinite(pos)) {
- V8THROW_DOM(DOMEXCEPTION_INDEX_SIZE_ERR, "CanvasGradient: parameter offset out of range");
- }
-
- if (color.isValid()) {
- gradient.setColorAt(pos, color);
- } else {
- V8THROW_DOM(DOMEXCEPTION_SYNTAX_ERR, "CanvasGradient: parameter color is not a valid color string");
- }
- style->brush = gradient;
- }
-
- return args.This();
-}
-
-
-void QQuickContext2D::beginPath()
-{
- m_path = QPainterPath();
- m_path.setFillRule(state.fillRule);
-}
-
-void QQuickContext2D::closePath()
-{
- if (m_path.isEmpty())
- return;
-
- QRectF boundRect = m_path.boundingRect();
- if (boundRect.width() || boundRect.height())
- m_path.closeSubpath();
- //FIXME:QPainterPath set the current point to (0,0) after close subpath
- //should be the first point of the previous subpath
-}
-
-void QQuickContext2D::moveTo( qreal x, qreal y)
-{
- //FIXME: moveTo should not close the previous subpath
- m_path.moveTo(state.matrix.map(QPointF(x, y)));
-}
-
-void QQuickContext2D::lineTo( qreal x, qreal y)
-{
- m_path.lineTo(state.matrix.map(QPointF(x, y)));
-}
-
-void QQuickContext2D::quadraticCurveTo(qreal cpx, qreal cpy,
- qreal x, qreal y)
-{
- m_path.quadTo(state.matrix.map(QPointF(cpx, cpy)),
- state.matrix.map(QPointF(x, y)));
-}
-
-void QQuickContext2D::bezierCurveTo(qreal cp1x, qreal cp1y,
- qreal cp2x, qreal cp2y,
- qreal x, qreal y)
-{
- m_path.cubicTo(state.matrix.map(QPointF(cp1x, cp1y)),
- state.matrix.map(QPointF(cp2x, cp2y)),
- state.matrix.map(QPointF(x, y)));
-}
-
-void QQuickContext2D::addArcTo(const QPointF& p1, const QPointF& p2, float radius)
-{
- QPointF p0(m_path.currentPosition());
-
- QPointF p1p0((p0.x() - p1.x()), (p0.y() - p1.y()));
- QPointF p1p2((p2.x() - p1.x()), (p2.y() - p1.y()));
- float p1p0_length = qSqrt(p1p0.x() * p1p0.x() + p1p0.y() * p1p0.y());
- float p1p2_length = qSqrt(p1p2.x() * p1p2.x() + p1p2.y() * p1p2.y());
-
- double cos_phi = (p1p0.x() * p1p2.x() + p1p0.y() * p1p2.y()) / (p1p0_length * p1p2_length);
-
- // The points p0, p1, and p2 are on the same straight line (HTML5, 4.8.11.1.8)
- // We could have used areCollinear() here, but since we're reusing
- // the variables computed above later on we keep this logic.
- if (qFuzzyCompare(qAbs(cos_phi), 1.0)) {
- m_path.lineTo(p1);
- return;
- }
-
- float tangent = radius / tan(acos(cos_phi) / 2);
- float factor_p1p0 = tangent / p1p0_length;
- QPointF t_p1p0((p1.x() + factor_p1p0 * p1p0.x()), (p1.y() + factor_p1p0 * p1p0.y()));
-
- QPointF orth_p1p0(p1p0.y(), -p1p0.x());
- float orth_p1p0_length = sqrt(orth_p1p0.x() * orth_p1p0.x() + orth_p1p0.y() * orth_p1p0.y());
- float factor_ra = radius / orth_p1p0_length;
-
- // angle between orth_p1p0 and p1p2 to get the right vector orthographic to p1p0
- double cos_alpha = (orth_p1p0.x() * p1p2.x() + orth_p1p0.y() * p1p2.y()) / (orth_p1p0_length * p1p2_length);
- if (cos_alpha < 0.f)
- orth_p1p0 = QPointF(-orth_p1p0.x(), -orth_p1p0.y());
-
- QPointF p((t_p1p0.x() + factor_ra * orth_p1p0.x()), (t_p1p0.y() + factor_ra * orth_p1p0.y()));
-
- // calculate angles for addArc
- orth_p1p0 = QPointF(-orth_p1p0.x(), -orth_p1p0.y());
- float sa = acos(orth_p1p0.x() / orth_p1p0_length);
- if (orth_p1p0.y() < 0.f)
- sa = 2 * Q_PI - sa;
-
- // anticlockwise logic
- bool anticlockwise = false;
-
- float factor_p1p2 = tangent / p1p2_length;
- QPointF t_p1p2((p1.x() + factor_p1p2 * p1p2.x()), (p1.y() + factor_p1p2 * p1p2.y()));
- QPointF orth_p1p2((t_p1p2.x() - p.x()), (t_p1p2.y() - p.y()));
- float orth_p1p2_length = sqrtf(orth_p1p2.x() * orth_p1p2.x() + orth_p1p2.y() * orth_p1p2.y());
- float ea = acos(orth_p1p2.x() / orth_p1p2_length);
- if (orth_p1p2.y() < 0)
- ea = 2 * Q_PI - ea;
- if ((sa > ea) && ((sa - ea) < Q_PI))
- anticlockwise = true;
- if ((sa < ea) && ((ea - sa) > Q_PI))
- anticlockwise = true;
-
- arc(p.x(), p.y(), radius, sa, ea, anticlockwise, false);
-}
-
-void QQuickContext2D::arcTo(qreal x1, qreal y1,
- qreal x2, qreal y2,
- qreal radius)
-{
- QPointF st = state.matrix.map(QPointF(x1, y1));
- QPointF end = state.matrix.map(QPointF(x2, y2));
-
- if (!m_path.elementCount()) {
- m_path.moveTo(st);
- } else if (st == m_path.currentPosition() || st == end || !radius) {
- m_path.lineTo(st);
- } else {
- addArcTo(st, end, radius);
- }
-}
-
-void QQuickContext2D::rect(qreal x, qreal y,
- qreal w, qreal h)
-{
- m_path.addPolygon(state.matrix.map(QRectF(x, y, w, h)));
-}
-
-void QQuickContext2D::roundedRect(qreal x, qreal y,
- qreal w, qreal h,
- qreal xr, qreal yr)
-{
- QPainterPath path;
- path.addRoundedRect(QRectF(x, y, w, h), xr, yr, Qt::AbsoluteSize);
- m_path.addPath(state.matrix.map(path));
-}
-
-void QQuickContext2D::ellipse(qreal x, qreal y,
- qreal w, qreal h)
-{
- QPainterPath path;
- path.addEllipse(x, y, w, h);
- m_path.addPath(state.matrix.map(path));
-}
-
-void QQuickContext2D::text(const QString& str, qreal x, qreal y)
-{
- QPainterPath path;
- path.addText(x, y, state.font, str);
- m_path.addPath(state.matrix.map(path));
-}
-
-void QQuickContext2D::arc(qreal xc,
- qreal yc,
- qreal radius,
- qreal sar,
- qreal ear,
- bool antiClockWise,
- bool transform)
-{
-
- if (transform) {
- QPointF point = state.matrix.map(QPointF(xc, yc));
- xc = point.x();
- yc = point.y();
- }
- //### HACK
-
- // In Qt we don't switch the coordinate system for degrees
- // and still use the 0,0 as bottom left for degrees so we need
- // to switch
- sar = -sar;
- ear = -ear;
- antiClockWise = !antiClockWise;
- //end hack
-
- float sa = DEGREES(sar);
- float ea = DEGREES(ear);
-
- double span = 0;
-
- double xs = xc - radius;
- double ys = yc - radius;
- double width = radius*2;
- double height = radius*2;
- if ((!antiClockWise && (ea - sa >= 360)) || (antiClockWise && (sa - ea >= 360)))
- // If the anticlockwise argument is false and endAngle-startAngle is equal to or greater than 2*PI, or, if the
- // anticlockwise argument is true and startAngle-endAngle is equal to or greater than 2*PI, then the arc is the whole
- // circumference of this circle.
- span = 360;
- else {
- if (!antiClockWise && (ea < sa)) {
- span += 360;
- } else if (antiClockWise && (sa < ea)) {
- span -= 360;
- }
- //### this is also due to switched coordinate system
- // we would end up with a 0 span instead of 360
- if (!(qFuzzyCompare(span + (ea - sa) + 1, 1) &&
- qFuzzyCompare(qAbs(span), 360))) {
- span += ea - sa;
- }
- if (!m_path.elementCount())
- m_path.moveTo(xs, ys);
- }
-
-
- if (transform) {
- QPointF currentPos = m_path.currentPosition();
- QPointF startPos = QPointF(xc + radius * qCos(sar),
- yc - radius * qSin(sar));
- if (currentPos != startPos)
- m_path.lineTo(startPos);
- }
-
- m_path.arcTo(xs, ys, width, height, sa, span);
-}
-
-int baseLineOffset(QQuickContext2D::TextBaseLineType value, const QFontMetrics &metrics)
-{
- int offset = 0;
- switch (value) {
- case QQuickContext2D::Top:
- break;
- case QQuickContext2D::Alphabetic:
- case QQuickContext2D::Middle:
- case QQuickContext2D::Hanging:
- offset = metrics.ascent();
- break;
- case QQuickContext2D::Bottom:
- offset = metrics.height();
- break;
- }
- return offset;
-}
-
-static int textAlignOffset(QQuickContext2D::TextAlignType value, const QFontMetrics &metrics, const QString &text)
-{
- int offset = 0;
- if (value == QQuickContext2D::Start)
- value = QGuiApplication::layoutDirection() == Qt::LeftToRight ? QQuickContext2D::Left : QQuickContext2D::Right;
- else if (value == QQuickContext2D::End)
- value = QGuiApplication::layoutDirection() == Qt::LeftToRight ? QQuickContext2D::Right: QQuickContext2D::Left;
- switch (value) {
- case QQuickContext2D::Center:
- offset = metrics.width(text)/2;
- break;
- case QQuickContext2D::Right:
- offset = metrics.width(text);
- case QQuickContext2D::Left:
- default:
- break;
- }
- return offset;
-}
-
-
-QImage QQuickContext2D::createImage(const QUrl& url)
-{
- return m_canvas->loadedImage(url);
-}
-
-QPainterPath QQuickContext2D::createTextGlyphs(qreal x, qreal y, const QString& text)
-{
- const QFontMetrics metrics(state.font);
- int yoffset = baseLineOffset(static_cast<QQuickContext2D::TextBaseLineType>(state.textBaseline), metrics);
- int xoffset = textAlignOffset(static_cast<QQuickContext2D::TextAlignType>(state.textAlign), metrics, text);
-
- QPainterPath textPath;
-
- textPath.addText(x - xoffset, y - yoffset+metrics.ascent(), state.font, text);
- textPath = state.matrix.map(textPath);
- return textPath;
-}
-
-
-bool QQuickContext2D::isPointInPath(qreal x, qreal y) const
-{
- return m_path.contains(QPointF(x, y));
-}
-
-QQuickContext2D::QQuickContext2D(QQuickCanvasItem* item)
- : m_canvas(item)
- , m_buffer(new QQuickContext2DCommandBuffer)
- , m_v8engine(0)
-{
- reset();
-}
-
-QQuickContext2D::~QQuickContext2D()
-{
- delete m_buffer;
-}
-
-v8::Handle<v8::Object> QQuickContext2D::v8value() const
-{
- return m_v8value;
-}
-
-QQuickContext2DEngineData::QQuickContext2DEngineData(QV8Engine *engine)
-{
- v8::HandleScope handle_scope;
- v8::Context::Scope scope(engine->context());
-
- v8::Local<v8::FunctionTemplate> ft = v8::FunctionTemplate::New();
- ft->InstanceTemplate()->SetHasExternalResource(true);
- ft->PrototypeTemplate()->SetAccessor(v8::String::New("canvas"), ctx2d_canvas, 0, v8::External::Wrap(engine));
- ft->PrototypeTemplate()->Set(v8::String::New("restore"), V8FUNCTION(ctx2d_restore, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("reset"), V8FUNCTION(ctx2d_reset, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("save"), V8FUNCTION(ctx2d_save, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("rotate"), V8FUNCTION(ctx2d_rotate, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("scale"), V8FUNCTION(ctx2d_scale, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("resetTransform"), V8FUNCTION(ctx2d_resetTransform, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("setTransform"), V8FUNCTION(ctx2d_setTransform, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("transform"), V8FUNCTION(ctx2d_transform, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("translate"), V8FUNCTION(ctx2d_translate, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("shear"), V8FUNCTION(ctx2d_shear, engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("globalAlpha"), ctx2d_globalAlpha, ctx2d_globalAlpha_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("globalCompositeOperation"), ctx2d_globalCompositeOperation, ctx2d_globalCompositeOperation_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("fillRule"), ctx2d_fillRule, ctx2d_fillRule_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("fillStyle"), ctx2d_fillStyle, ctx2d_fillStyle_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("strokeStyle"), ctx2d_strokeStyle, ctx2d_strokeStyle_set, v8::External::Wrap(engine));
- ft->PrototypeTemplate()->Set(v8::String::New("createLinearGradient"), V8FUNCTION(ctx2d_createLinearGradient, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("createRadialGradient"), V8FUNCTION(ctx2d_createRadialGradient, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("createConicalGradient"), V8FUNCTION(ctx2d_createConicalGradient, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("createPattern"), V8FUNCTION(ctx2d_createPattern, engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("lineCap"), ctx2d_lineCap, ctx2d_lineCap_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("lineJoin"), ctx2d_lineJoin, ctx2d_lineJoin_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("lineWidth"), ctx2d_lineWidth, ctx2d_lineWidth_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("miterLimit"), ctx2d_miterLimit, ctx2d_miterLimit_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("shadowBlur"), ctx2d_shadowBlur, ctx2d_shadowBlur_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("shadowColor"), ctx2d_shadowColor, ctx2d_shadowColor_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("shadowOffsetX"), ctx2d_shadowOffsetX, ctx2d_shadowOffsetX_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("shadowOffsetY"), ctx2d_shadowOffsetY, ctx2d_shadowOffsetY_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("path"), ctx2d_path, ctx2d_path_set, v8::External::Wrap(engine));
- ft->PrototypeTemplate()->Set(v8::String::New("clearRect"), V8FUNCTION(ctx2d_clearRect, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("fillRect"), V8FUNCTION(ctx2d_fillRect, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("strokeRect"), V8FUNCTION(ctx2d_strokeRect, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("arc"), V8FUNCTION(ctx2d_arc, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("arcTo"), V8FUNCTION(ctx2d_arcTo, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("beginPath"), V8FUNCTION(ctx2d_beginPath, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("bezierCurveTo"), V8FUNCTION(ctx2d_bezierCurveTo, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("clip"), V8FUNCTION(ctx2d_clip, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("closePath"), V8FUNCTION(ctx2d_closePath, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("fill"), V8FUNCTION(ctx2d_fill, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("lineTo"), V8FUNCTION(ctx2d_lineTo, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("moveTo"), V8FUNCTION(ctx2d_moveTo, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("quadraticCurveTo"), V8FUNCTION(ctx2d_quadraticCurveTo, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("rect"), V8FUNCTION(ctx2d_rect, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("roundedRect"), V8FUNCTION(ctx2d_roundedRect, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("text"), V8FUNCTION(ctx2d_text, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("ellipse"), V8FUNCTION(ctx2d_ellipse, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("stroke"), V8FUNCTION(ctx2d_stroke, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("isPointInPath"), V8FUNCTION(ctx2d_isPointInPath, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("drawFocusRing"), V8FUNCTION(ctx2d_drawFocusRing, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("caretBlinkRate"), V8FUNCTION(ctx2d_caretBlinkRate, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("setCaretSelectionRect"), V8FUNCTION(ctx2d_setCaretSelectionRect, engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("font"), ctx2d_font, ctx2d_font_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("textAlign"), ctx2d_textAlign, ctx2d_textAlign_set, v8::External::Wrap(engine));
- ft->InstanceTemplate()->SetAccessor(v8::String::New("textBaseline"), ctx2d_textBaseline, ctx2d_textBaseline_set, v8::External::Wrap(engine));
- ft->PrototypeTemplate()->Set(v8::String::New("fillText"), V8FUNCTION(ctx2d_fillText, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("measureText"), V8FUNCTION(ctx2d_measureText, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("strokeText"), V8FUNCTION(ctx2d_strokeText, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("drawImage"), V8FUNCTION(ctx2d_drawImage, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("createImageData"), V8FUNCTION(ctx2d_createImageData, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("getImageData"), V8FUNCTION(ctx2d_getImageData, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("putImageData"), V8FUNCTION(ctx2d_putImageData, engine));
-
- constructorContext = qPersistentNew(ft->GetFunction());
-
- v8::Local<v8::FunctionTemplate> ftGradient = v8::FunctionTemplate::New();
- ftGradient->InstanceTemplate()->SetHasExternalResource(true);
- ftGradient->PrototypeTemplate()->Set(v8::String::New("addColorStop"), V8FUNCTION(ctx2d_gradient_addColorStop, engine));
- constructorGradient = qPersistentNew(ftGradient->GetFunction());
-
- v8::Local<v8::FunctionTemplate> ftPattern = v8::FunctionTemplate::New();
- ftPattern->InstanceTemplate()->SetHasExternalResource(true);
- constructorPattern = qPersistentNew(ftPattern->GetFunction());
-
- v8::Local<v8::FunctionTemplate> ftPixelArray = v8::FunctionTemplate::New();
- ftPixelArray->InstanceTemplate()->SetHasExternalResource(true);
- ftPixelArray->InstanceTemplate()->SetAccessor(v8::String::New("length"), ctx2d_pixelArray_length, 0, v8::External::Wrap(engine));
- ftPixelArray->InstanceTemplate()->SetIndexedPropertyHandler(ctx2d_pixelArray_indexed, ctx2d_pixelArray_indexed_set, 0, 0, 0, v8::External::Wrap(engine));
- constructorPixelArray = qPersistentNew(ftPixelArray->GetFunction());
-
- v8::Local<v8::FunctionTemplate> ftImageData = v8::FunctionTemplate::New();
- ftImageData->InstanceTemplate()->SetAccessor(v8::String::New("width"), ctx2d_imageData_width, 0, v8::External::Wrap(engine));
- ftImageData->InstanceTemplate()->SetAccessor(v8::String::New("height"), ctx2d_imageData_height, 0, v8::External::Wrap(engine));
- ftImageData->InstanceTemplate()->SetAccessor(v8::String::New("data"), ctx2d_imageData_data, 0, v8::External::Wrap(engine));
- ftImageData->PrototypeTemplate()->Set(v8::String::New("mirror"), V8FUNCTION(ctx2d_imageData_mirror, engine));
- ftImageData->PrototypeTemplate()->Set(v8::String::New("filter"), V8FUNCTION(ctx2d_imageData_filter, engine));
- ftImageData->InstanceTemplate()->SetInternalFieldCount(1);
- constructorImageData = qPersistentNew(ftImageData->GetFunction());
-}
-
-QQuickContext2DEngineData::~QQuickContext2DEngineData()
-{
- qPersistentDispose(constructorContext);
- qPersistentDispose(constructorGradient);
- qPersistentDispose(constructorPattern);
- qPersistentDispose(constructorImageData);
- qPersistentDispose(constructorPixelArray);
-}
-
-void QQuickContext2D::popState()
-{
- if (m_stateStack.isEmpty())
- return;
-
- QQuickContext2D::State newState = m_stateStack.pop();
-
- if (state.matrix != newState.matrix)
- buffer()->updateMatrix(newState.matrix);
-
- if (newState.globalAlpha != state.globalAlpha)
- buffer()->setGlobalAlpha(newState.globalAlpha);
-
- if (newState.globalCompositeOperation != state.globalCompositeOperation)
- buffer()->setGlobalCompositeOperation(newState.globalCompositeOperation);
-
- if (newState.fillStyle != state.fillStyle)
- buffer()->setFillStyle(newState.fillStyle);
-
- if (newState.strokeStyle != state.strokeStyle)
- buffer()->setStrokeStyle(newState.strokeStyle);
-
- if (newState.lineWidth != state.lineWidth)
- buffer()->setLineWidth(newState.lineWidth);
-
- if (newState.lineCap != state.lineCap)
- buffer()->setLineCap(newState.lineCap);
-
- if (newState.lineJoin != state.lineJoin)
- buffer()->setLineJoin(newState.lineJoin);
-
- if (newState.miterLimit != state.miterLimit)
- buffer()->setMiterLimit(newState.miterLimit);
-
- if (newState.clipPath != state.clipPath) {
- buffer()->clip(newState.clipPath);
- }
-
- if (newState.shadowBlur != state.shadowBlur)
- buffer()->setShadowBlur(newState.shadowBlur);
-
- if (newState.shadowColor != state.shadowColor)
- buffer()->setShadowColor(newState.shadowColor);
-
- if (newState.shadowOffsetX != state.shadowOffsetX)
- buffer()->setShadowOffsetX(newState.shadowOffsetX);
-
- if (newState.shadowOffsetY != state.shadowOffsetY)
- buffer()->setShadowOffsetY(newState.shadowOffsetY);
- state = newState;
-}
-void QQuickContext2D::pushState()
-{
- m_stateStack.push(state);
-}
-
-void QQuickContext2D::reset()
-{
- QQuickContext2D::State newState;
- newState.matrix = QTransform();
-
- QPainterPath defaultClipPath;
-
- QRect r(0, 0, m_canvas->canvasSize().width(), m_canvas->canvasSize().height());
- r = r.united(m_canvas->canvasWindow().toRect());
- defaultClipPath.addRect(r);
- newState.clipPath = defaultClipPath;
- newState.clipPath.setFillRule(Qt::WindingFill);
-
- newState.strokeStyle = QColor("#000000");
- newState.fillStyle = QColor("#000000");
- newState.fillPatternRepeatX = false;
- newState.fillPatternRepeatY = false;
- newState.strokePatternRepeatX = false;
- newState.strokePatternRepeatY = false;
- newState.fillRule = Qt::WindingFill;
- newState.globalAlpha = 1.0;
- newState.lineWidth = 1;
- newState.lineCap = Qt::FlatCap;
- newState.lineJoin = Qt::MiterJoin;
- newState.miterLimit = 10;
- newState.shadowOffsetX = 0;
- newState.shadowOffsetY = 0;
- newState.shadowBlur = 0;
- newState.shadowColor = qRgba(0, 0, 0, 0);
- newState.globalCompositeOperation = QPainter::CompositionMode_SourceOver;
- newState.font = QFont(QLatin1String("sans-serif"), 10);
- newState.textAlign = QQuickContext2D::Start;
- newState.textBaseline = QQuickContext2D::Alphabetic;
-
- m_stateStack.clear();
- m_stateStack.push(newState);
- popState();
- m_buffer->clearRect(0, 0, m_canvas->width(), m_canvas->height());
-}
-
-void QQuickContext2D::setV8Engine(QV8Engine *engine)
-{
- v8::HandleScope handle_scope;
- v8::Context::Scope scope(engine->context());
-
- if (m_v8engine != engine) {
- m_v8engine = engine;
-
- qPersistentDispose(m_v8value);
-
- if (m_v8engine == 0)
- return;
-
- QQuickContext2DEngineData *ed = engineData(engine);
- m_v8value = qPersistentNew(ed->constructorContext->NewInstance());
- QV8Context2DResource *r = new QV8Context2DResource(engine);
- r->context = this;
- m_v8value->SetExternalResource(r);
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/context2d/qquickcontext2d_p.h b/src/declarative/items/context2d/qquickcontext2d_p.h
deleted file mode 100644
index c5634d2b18..0000000000
--- a/src/declarative/items/context2d/qquickcontext2d_p.h
+++ /dev/null
@@ -1,211 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKCONTEXT2D_P_H
-#define QQUICKCONTEXT2D_P_H
-
-#include <QtDeclarative/qdeclarative.h>
-#include <QtDeclarative/qdeclarativecomponent.h>
-
-#include <QtGui/qpainter.h>
-#include <QtGui/qpainterpath.h>
-#include <QtCore/qstring.h>
-#include <QtCore/qstack.h>
-#include <private/qv8engine_p.h>
-
-
-
-#define QQUICKCONTEXT2D_DEBUG //enable this for just DEBUG purpose!
-
-#ifdef QQUICKCONTEXT2D_DEBUG
-#include <QElapsedTimer>
-#endif
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickCanvasItem;
-class QQuickContext2DCommandBuffer;
-class QDeclarativePixmap;
-
-class Q_DECLARATIVE_EXPORT QQuickContext2D
-{
-public:
- enum TextBaseLineType { Alphabetic=0, Top, Middle, Bottom, Hanging};
- enum TextAlignType { Start=0, End, Left, Right, Center};
- enum PaintCommand {
- Invalid = 0,
- UpdateMatrix,
- ClearRect,
- FillRect,
- StrokeRect,
- Fill,
- Stroke,
- Clip,
- UpdateBrush,
- GlobalAlpha,
- GlobalCompositeOperation,
- StrokeStyle,
- FillStyle,
- LineWidth,
- LineCap,
- LineJoin,
- MiterLimit,
- ShadowOffsetX,
- ShadowOffsetY,
- ShadowBlur,
- ShadowColor,
- Font,
- TextBaseline,
- TextAlign,
- FillText,
- StrokeText,
- DrawImage,
- GetImageData
- };
-
-
- struct State {
- State()
- : strokeStyle(QColor("#000000"))
- , fillStyle(QColor("#000000"))
- , fillPatternRepeatX(false)
- , fillPatternRepeatY(false)
- , strokePatternRepeatX(false)
- , strokePatternRepeatY(false)
- , fillRule(Qt::WindingFill)
- , globalAlpha(1.0)
- , lineWidth(1)
- , lineCap(Qt::FlatCap)
- , lineJoin(Qt::MiterJoin)
- , miterLimit(10)
- , shadowOffsetX(0)
- , shadowOffsetY(0)
- , shadowBlur(0)
- , shadowColor(qRgba(0, 0, 0, 0))
- , globalCompositeOperation(QPainter::CompositionMode_SourceOver)
- , font(QFont(QLatin1String("sans-serif"), 10))
- , textAlign(QQuickContext2D::Start)
- , textBaseline(QQuickContext2D::Alphabetic)
- {
- }
-
- QTransform matrix;
- QPainterPath clipPath;
- QBrush strokeStyle;
- QBrush fillStyle;
- bool fillPatternRepeatX:1;
- bool fillPatternRepeatY:1;
- bool strokePatternRepeatX:1;
- bool strokePatternRepeatY:1;
- Qt::FillRule fillRule;
- qreal globalAlpha;
- qreal lineWidth;
- Qt::PenCapStyle lineCap;
- Qt::PenJoinStyle lineJoin;
- qreal miterLimit;
- qreal shadowOffsetX;
- qreal shadowOffsetY;
- qreal shadowBlur;
- QColor shadowColor;
- QPainter::CompositionMode globalCompositeOperation;
- QFont font;
- QQuickContext2D::TextAlignType textAlign;
- QQuickContext2D::TextBaseLineType textBaseline;
- };
-
- QQuickContext2D(QQuickCanvasItem* item);
- ~QQuickContext2D();
-
- inline QQuickCanvasItem* canvas() const {return m_canvas;}
- inline QQuickContext2DCommandBuffer* buffer() const {return m_buffer;}
-
- v8::Handle<v8::Object> v8value() const;
- void setV8Engine(QV8Engine *eng);
- void popState();
- void pushState();
- void reset();
-
- // path API
- void beginPath();
- void closePath();
- void moveTo(qreal x, qreal y);
- void lineTo(qreal x, qreal y);
- void quadraticCurveTo(qreal cpx, qreal cpy, qreal x, qreal y);
- void bezierCurveTo(qreal cp1x, qreal cp1y,
- qreal cp2x, qreal cp2y, qreal x, qreal y);
- void arcTo(qreal x1, qreal y1, qreal x2, qreal y2, qreal radius);
- void rect(qreal x, qreal y, qreal w, qreal h);
- void roundedRect(qreal x, qreal y,qreal w, qreal h, qreal xr, qreal yr);
- void ellipse(qreal x, qreal y,qreal w, qreal h);
- void text(const QString& str, qreal x, qreal y);
- void arc(qreal x, qreal y, qreal radius,
- qreal startAngle, qreal endAngle,
- bool anticlockwise, bool transform=true);
- void addArcTo(const QPointF& p1, const QPointF& p2, float radius);
-
- bool isPointInPath(qreal x, qreal y) const;
-
- QPainterPath createTextGlyphs(qreal x, qreal y, const QString& text);
- QImage createImage(const QUrl& url);
-
- State state;
- QStack<QQuickContext2D::State> m_stateStack;
- QQuickCanvasItem* m_canvas;
- QQuickContext2DCommandBuffer* m_buffer;
- QPainterPath m_path;
- v8::Local<v8::Value> m_fillStyle;
- v8::Local<v8::Value> m_strokeStyle;
- v8::Handle<v8::Value> m_v8path;
- QV8Engine *m_v8engine;
- v8::Persistent<v8::Object> m_v8value;
-};
-
-
-QT_END_NAMESPACE
-QML_DECLARE_TYPE(QQuickContext2D)
-
-QT_END_HEADER
-
-#endif // QQUICKCONTEXT2D_P_H
diff --git a/src/declarative/items/context2d/qquickcontext2dcommandbuffer.cpp b/src/declarative/items/context2d/qquickcontext2dcommandbuffer.cpp
deleted file mode 100644
index 476e7e2cf8..0000000000
--- a/src/declarative/items/context2d/qquickcontext2dcommandbuffer.cpp
+++ /dev/null
@@ -1,469 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickcontext2dcommandbuffer_p.h"
-#include "qquickcanvasitem_p.h"
-#include <qdeclarative.h>
-#include <QtCore/QMutex>
-
-#define HAS_SHADOW(offsetX, offsetY, blur, color) (color.isValid() && color.alpha() && (blur || offsetX || offsetY))
-
-QT_BEGIN_NAMESPACE
-
-void qt_image_boxblur(QImage& image, int radius, bool quality);
-
-static QImage makeShadowImage(const QImage& image, qreal offsetX, qreal offsetY, qreal blur, const QColor& color)
-{
- QImage shadowImg(image.width() + blur + qAbs(offsetX),
- image.height() + blur + qAbs(offsetY),
- QImage::Format_ARGB32_Premultiplied);
- shadowImg.fill(0);
- QPainter tmpPainter(&shadowImg);
- tmpPainter.setCompositionMode(QPainter::CompositionMode_Source);
- qreal shadowX = offsetX > 0? offsetX : 0;
- qreal shadowY = offsetY > 0? offsetY : 0;
-
- tmpPainter.drawImage(shadowX, shadowY, image);
- tmpPainter.end();
-
- if (blur > 0)
- qt_image_boxblur(shadowImg, blur/2, true);
-
- // blacken the image with shadow color...
- tmpPainter.begin(&shadowImg);
- tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
- tmpPainter.fillRect(shadowImg.rect(), color);
- tmpPainter.end();
- return shadowImg;
-}
-
-static void fillRectShadow(QPainter* p, QRectF shadowRect, qreal offsetX, qreal offsetY, qreal blur, const QColor& color)
-{
- QRectF r = shadowRect;
- r.moveTo(0, 0);
-
- QImage shadowImage(r.size().width() + 1, r.size().height() + 1, QImage::Format_ARGB32_Premultiplied);
- QPainter tp;
- tp.begin(&shadowImage);
- tp.fillRect(r, p->brush());
- tp.end();
- shadowImage = makeShadowImage(shadowImage, offsetX, offsetY, blur, color);
-
- qreal dx = shadowRect.left() + (offsetX < 0? offsetX:0);
- qreal dy = shadowRect.top() + (offsetY < 0? offsetY:0);
-
- p->drawImage(dx, dy, shadowImage);
- p->fillRect(shadowRect, p->brush());
-}
-
-static void fillShadowPath(QPainter* p, const QPainterPath& path, qreal offsetX, qreal offsetY, qreal blur, const QColor& color)
-{
- QRectF r = path.boundingRect();
- QImage img(r.size().width() + r.left() + 1,
- r.size().height() + r.top() + 1,
- QImage::Format_ARGB32_Premultiplied);
- img.fill(0);
- QPainter tp(&img);
- tp.fillPath(path.translated(0, 0), p->brush());
- tp.end();
-
- QImage shadowImage = makeShadowImage(img, offsetX, offsetY, blur, color);
- qreal dx = r.left() + (offsetX < 0? offsetX:0);
- qreal dy = r.top() + (offsetY < 0? offsetY:0);
-
- p->drawImage(dx, dy, shadowImage);
- p->fillPath(path, p->brush());
-}
-
-static void strokeShadowPath(QPainter* p, const QPainterPath& path, qreal offsetX, qreal offsetY, qreal blur, const QColor& color)
-{
- QRectF r = path.boundingRect();
- QImage img(r.size().width() + r.left() + 1,
- r.size().height() + r.top() + 1,
- QImage::Format_ARGB32_Premultiplied);
- img.fill(0);
- QPainter tp(&img);
- tp.strokePath(path, p->pen());
- tp.end();
-
- QImage shadowImage = makeShadowImage(img, offsetX, offsetY, blur, color);
- qreal dx = r.left() + (offsetX < 0? offsetX:0);
- qreal dy = r.top() + (offsetY < 0? offsetY:0);
- p->drawImage(dx, dy, shadowImage);
- p->strokePath(path, p->pen());
-}
-static inline void drawRepeatPattern(QPainter* p, const QImage& image, const QRectF& rect, const bool repeatX, const bool repeatY)
-{
- // Patterns must be painted so that the top left of the first image is anchored at
- // the origin of the coordinate space
- if (!image.isNull()) {
- int w = image.width();
- int h = image.height();
- int startX, startY;
- QRect r(static_cast<int>(rect.x()), static_cast<int>(rect.y()), static_cast<int>(rect.width()), static_cast<int>(rect.height()));
-
- // startX, startY is the coordinate of the first image we need to put on the left-top of the rect
- if (repeatX && repeatY) {
- // repeat
- // startX, startY is at the left top side of the left-top of the rect
- startX = r.x() >=0 ? r.x() - (r.x() % w) : r.x() - (w - qAbs(r.x()) % w);
- startY = r.y() >=0 ? r.y() - (r.y() % h) : r.y() - (h - qAbs(r.y()) % h);
- } else {
- if (!repeatX && !repeatY) {
- // no-repeat
- // only draw the image once at orgin once, check if need to draw
- QRect imageRect(0, 0, w, h);
- if (imageRect.intersects(r)) {
- startX = 0;
- startY = 0;
- } else
- return;
- } else if (repeatX && !repeatY) {
- // repeat-x
- // startY is fixed, but startX change based on the left-top of the rect
- QRect imageRect(r.x(), 0, r.width(), h);
- if (imageRect.intersects(r)) {
- startX = r.x() >=0 ? r.x() - (r.x() % w) : r.x() - (w - qAbs(r.x()) % w);
- startY = 0;
- } else
- return;
- } else {
- // repeat-y
- // startX is fixed, but startY change based on the left-top of the rect
- QRect imageRect(0, r.y(), w, r.height());
- if (imageRect.intersects(r)) {
- startX = 0;
- startY = r.y() >=0 ? r.y() - (r.y() % h) : r.y() - (h - qAbs(r.y()) % h);
- } else
- return;
- }
- }
-
- int x = startX;
- int y = startY;
- do {
- // repeat Y
- do {
- // repeat X
- QRect imageRect(x, y, w, h);
- QRect intersectRect = imageRect.intersected(r);
- QPoint destStart(intersectRect.x(), intersectRect.y());
- QRect sourceRect(intersectRect.x() - imageRect.x(), intersectRect.y() - imageRect.y(), intersectRect.width(), intersectRect.height());
-
- p->drawImage(destStart, image, sourceRect);
- x += w;
- } while (repeatX && x < r.x() + r.width());
- x = startX;
- y += h;
- } while (repeatY && y < r.y() + r.height());
- }
-}
-
-QPen QQuickContext2DCommandBuffer::makePen(const QQuickContext2D::State& state)
-{
- QPen pen;
- pen.setWidthF(state.lineWidth);
- pen.setCapStyle(state.lineCap);
- pen.setJoinStyle(state.lineJoin);
- pen.setMiterLimit(state.miterLimit);
- pen.setBrush(state.strokeStyle);
- return pen;
-}
-
-void QQuickContext2DCommandBuffer::setPainterState(QPainter* p, const QQuickContext2D::State& state, const QPen& pen)
-{
- p->setTransform(state.matrix * p->transform());
-
- if (pen != p->pen())
- p->setPen(pen);
-
- if (state.fillStyle != p->brush())
- p->setBrush(state.fillStyle);
-
- if (state.font != p->font())
- p->setFont(state.font);
-
- if (state.globalAlpha != p->opacity()) {
- p->setOpacity(state.globalAlpha);
- }
-
- if (state.globalCompositeOperation != p->compositionMode())
- p->setCompositionMode(state.globalCompositeOperation);
-}
-
-void QQuickContext2DCommandBuffer::replay(QPainter* p, QQuickContext2D::State& state)
-{
- if (!p)
- return;
-
- reset();
-
- QTransform originMatrix = p->transform();
-
- QPen pen = makePen(state);
- setPainterState(p, state, pen);
-
- while (hasNext()) {
- QQuickContext2D::PaintCommand cmd = takeNextCommand();
- switch (cmd) {
- case QQuickContext2D::UpdateMatrix:
- {
- state.matrix = takeMatrix();
- p->setTransform(state.matrix * originMatrix);
- break;
- }
- case QQuickContext2D::ClearRect:
- {
- QPainter::CompositionMode cm = p->compositionMode();
- qreal alpha = p->opacity();
- p->setCompositionMode(QPainter::CompositionMode_Source);
- p->setOpacity(0);
- p->fillRect(takeRect(), QColor(qRgba(0, 0, 0, 0)));
- p->setCompositionMode(cm);
- p->setOpacity(alpha);
- break;
- }
- case QQuickContext2D::FillRect:
- {
- QRectF r = takeRect();
- if (HAS_SHADOW(state.shadowOffsetX, state.shadowOffsetY, state.shadowBlur, state.shadowColor))
- fillRectShadow(p, r, state.shadowOffsetX, state.shadowOffsetY, state.shadowBlur, state.shadowColor);
- else
- p->fillRect(r, p->brush());
- break;
- }
- case QQuickContext2D::ShadowColor:
- {
- state.shadowColor = takeColor();
- break;
- }
- case QQuickContext2D::ShadowBlur:
- {
- state.shadowBlur = takeShadowBlur();
- break;
- }
- case QQuickContext2D::ShadowOffsetX:
- {
- state.shadowOffsetX = takeShadowOffsetX();
- break;
- }
- case QQuickContext2D::ShadowOffsetY:
- {
- state.shadowOffsetY = takeShadowOffsetY();
- break;
- }
- case QQuickContext2D::FillStyle:
- {
- state.fillStyle = takeFillStyle();
- state.fillPatternRepeatX = takeBool();
- state.fillPatternRepeatY = takeBool();
- p->setBrush(state.fillStyle);
- break;
- }
- case QQuickContext2D::StrokeStyle:
- {
- state.strokeStyle = takeStrokeStyle();
- state.strokePatternRepeatX = takeBool();
- state.strokePatternRepeatY = takeBool();
- pen.setBrush(state.strokeStyle);
- p->setPen(pen);
- break;
- }
- case QQuickContext2D::LineWidth:
- {
- state.lineWidth = takeLineWidth();
- pen.setWidth(state.lineWidth);
- p->setPen(pen);
- break;
- }
- case QQuickContext2D::LineCap:
- {
- state.lineCap = takeLineCap();
- pen.setCapStyle(state.lineCap);
- p->setPen(pen);
- break;
- }
- case QQuickContext2D::LineJoin:
- {
- state.lineJoin = takeLineJoin();
- pen.setJoinStyle(state.lineJoin);
- p->setPen(pen);
- break;
- }
- case QQuickContext2D::MiterLimit:
- {
- state.miterLimit = takeMiterLimit();
- pen.setMiterLimit(state.miterLimit);
- p->setPen(pen);
- break;
- }
- case QQuickContext2D::TextAlign:
- case QQuickContext2D::TextBaseline:
- break;
- case QQuickContext2D::Fill:
- {
- QPainterPath path = takePath();
- path.closeSubpath();
- if (HAS_SHADOW(state.shadowOffsetX, state.shadowOffsetY, state.shadowBlur, state.shadowColor))
- fillShadowPath(p,path, state.shadowOffsetX, state.shadowOffsetY, state.shadowBlur, state.shadowColor);
- else
- p->fillPath(path, p->brush());
- break;
- }
- case QQuickContext2D::Stroke:
- {
- if (HAS_SHADOW(state.shadowOffsetX, state.shadowOffsetY, state.shadowBlur, state.shadowColor))
- strokeShadowPath(p,takePath(), state.shadowOffsetX, state.shadowOffsetY, state.shadowBlur, state.shadowColor);
- else
- p->strokePath(takePath(), p->pen());
- break;
- }
- case QQuickContext2D::Clip:
- {
- state.clipPath = takePath();
- p->setClipping(true);
- p->setClipPath(state.clipPath);
- break;
- }
- case QQuickContext2D::GlobalAlpha:
- {
- state.globalAlpha = takeGlobalAlpha();
- p->setOpacity(state.globalAlpha);
- break;
- }
- case QQuickContext2D::GlobalCompositeOperation:
- {
- state.globalCompositeOperation = takeGlobalCompositeOperation();
- p->setCompositionMode(state.globalCompositeOperation);
- break;
- }
- case QQuickContext2D::DrawImage:
- {
- qreal sx = takeReal();
- qreal sy = takeReal();
- qreal sw = takeReal();
- qreal sh = takeReal();
- qreal dx = takeReal();
- qreal dy = takeReal();
- qreal dw = takeReal();
- qreal dh = takeReal();
- QImage image = takeImage();
-
- if (!image.isNull()) {
- if (sw == -1 || sh == -1) {
- sw = image.width();
- sh = image.height();
- }
- if (sx != 0 || sy != 0 || sw != image.width() || sh != image.height())
- image = image.copy(sx, sy, sw, sh);
-
- image = image.scaled(dw, dh);
-
- if (HAS_SHADOW(state.shadowOffsetX, state.shadowOffsetY, state.shadowBlur, state.shadowColor)) {
- QImage shadow = makeShadowImage(image, state.shadowOffsetX, state.shadowOffsetY, state.shadowBlur, state.shadowColor);
- qreal shadow_dx = dx + (state.shadowOffsetX < 0? state.shadowOffsetY:0);
- qreal shadow_dy = dy + (state.shadowOffsetX < 0? state.shadowOffsetY:0);
- p->drawImage(shadow_dx, shadow_dy, shadow);
- }
- p->drawImage(dx, dy, image);
- }
- break;
- }
- case QQuickContext2D::GetImageData:
- {
- //TODO:
- break;
- }
- default:
- break;
- }
- }
-
- p->end();
-}
-
-QQuickContext2DCommandBuffer::QQuickContext2DCommandBuffer()
- : cmdIdx(0)
- , intIdx(0)
- , boolIdx(0)
- , realIdx(0)
- , colorIdx(0)
- , matrixIdx(0)
- , brushIdx(0)
- , pathIdx(0)
- , imageIdx(0)
-{
-}
-
-
-QQuickContext2DCommandBuffer::~QQuickContext2DCommandBuffer()
-{
-}
-
-void QQuickContext2DCommandBuffer::clear()
-{
- commands.clear();
- ints.clear();
- bools.clear();
- reals.clear();
- colors.clear();
- matrixes.clear();
- brushes.clear();
- pathes.clear();
- images.clear();
- reset();
-}
-
-void QQuickContext2DCommandBuffer::reset()
-{
- cmdIdx = 0;
- intIdx = 0;
- boolIdx = 0;
- realIdx = 0;
- colorIdx = 0;
- matrixIdx = 0;
- brushIdx = 0;
- pathIdx = 0;
- imageIdx = 0;
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/items/context2d/qquickcontext2dcommandbuffer_p.h b/src/declarative/items/context2d/qquickcontext2dcommandbuffer_p.h
deleted file mode 100644
index 7deb2fbd6e..0000000000
--- a/src/declarative/items/context2d/qquickcontext2dcommandbuffer_p.h
+++ /dev/null
@@ -1,268 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKCONTEXT2DCOMMANDBUFFER_P_H
-#define QQUICKCONTEXT2DCOMMANDBUFFER_P_H
-
-#include "qquickcontext2d_p.h"
-#include <private/qdeclarativepixmapcache_p.h>
-
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickCanvasItem;
-class QMutex;
-
-class QQuickContext2DCommandBuffer
-{
-public:
- QQuickContext2DCommandBuffer();
- ~QQuickContext2DCommandBuffer();
- void reset();
- void clear();
- inline int size() {return commands.size();}
- inline bool isEmpty() const {return commands.isEmpty(); }
- inline bool hasNext() const {return cmdIdx < commands.size(); }
- inline QQuickContext2D::PaintCommand takeNextCommand() { return commands[cmdIdx++]; }
-
- inline qreal takeGlobalAlpha() { return takeReal(); }
- inline QPainter::CompositionMode takeGlobalCompositeOperation(){ return static_cast<QPainter::CompositionMode>(takeInt()); }
- inline QBrush takeStrokeStyle() { return takeBrush(); }
- inline QBrush takeFillStyle() { return takeBrush(); }
-
- inline qreal takeLineWidth() { return takeReal(); }
- inline Qt::PenCapStyle takeLineCap() { return static_cast<Qt::PenCapStyle>(takeInt());}
- inline Qt::PenJoinStyle takeLineJoin(){ return static_cast<Qt::PenJoinStyle>(takeInt());}
- inline qreal takeMiterLimit() { return takeReal(); }
-
- inline void setGlobalAlpha( qreal alpha)
- {
- commands << QQuickContext2D::GlobalAlpha;
- reals << alpha;
- }
-
- inline void setGlobalCompositeOperation(QPainter::CompositionMode cm)
- {
- commands << QQuickContext2D::GlobalCompositeOperation;
- ints << cm;
- }
-
- inline void setStrokeStyle(const QBrush &style, bool repeatX = false, bool repeatY = false)
- {
- commands << QQuickContext2D::StrokeStyle;
- brushes << style;
- bools << repeatX << repeatY;
- }
-
- inline void drawImage(const QImage& image, qreal sx, qreal sy, qreal sw, qreal sh, qreal dx, qreal dy, qreal dw, qreal dh)
- {
- commands << QQuickContext2D::DrawImage;
- images << image;
- reals << sx << sy << sw << sh << dx << dy << dw << dh;
- }
-
- inline qreal takeShadowOffsetX() { return takeReal(); }
- inline qreal takeShadowOffsetY() { return takeReal(); }
- inline qreal takeShadowBlur() { return takeReal(); }
- inline QColor takeShadowColor() { return takeColor(); }
-
-
- inline void updateMatrix(const QTransform& matrix)
- {
- commands << QQuickContext2D::UpdateMatrix;
- matrixes << matrix;
- }
-
- inline void clearRect(qreal x, qreal y, qreal w, qreal h)
- {
- commands << QQuickContext2D::ClearRect;
- reals << x << y << w << h;
- }
-
- inline void fillRect(qreal x, qreal y, qreal w, qreal h)
- {
- commands << QQuickContext2D::FillRect;
- reals << x << y << w << h;
- }
-
- inline void strokeRect(qreal x, qreal y, qreal w, qreal h)
- {
- QPainterPath p;
- p.addRect(x, y, w, h);
-
- commands << QQuickContext2D::Stroke;
- pathes << p;
- }
-
-
- inline void fill(const QPainterPath& path)
- {
- commands << QQuickContext2D::Fill;
- pathes << path;
-
- }
-
- inline void stroke(const QPainterPath& path)
- {
- commands << QQuickContext2D::Stroke;
- pathes << path;
- }
-
- inline void clip(const QPainterPath& path)
- {
- commands << QQuickContext2D::Clip;
- pathes << path;
- }
-
-
-
- inline void setFillStyle(const QBrush &style, bool repeatX = false, bool repeatY = false)
- {
- commands << QQuickContext2D::FillStyle;
- brushes << style;
- bools << repeatX << repeatY;
- }
-
-
- inline void setLineWidth( qreal w)
- {
- commands << QQuickContext2D::LineWidth;
- reals << w;
- }
-
- inline void setLineCap(Qt::PenCapStyle cap)
- {
- commands << QQuickContext2D::LineCap;
- ints << cap;
- }
-
- inline void setLineJoin(Qt::PenJoinStyle join)
- {
- commands << QQuickContext2D::LineJoin;
- ints << join;
- }
-
- inline void setMiterLimit( qreal limit)
- {
- commands << QQuickContext2D::MiterLimit;
- reals << limit;
- }
-
- inline void setShadowOffsetX( qreal x)
- {
- commands << QQuickContext2D::ShadowOffsetX;
- reals << x;
- }
-
- inline void setShadowOffsetY( qreal y)
- {
- commands << QQuickContext2D::ShadowOffsetY;
- reals << y;
- }
-
- inline void setShadowBlur( qreal b)
- {
- commands << QQuickContext2D::ShadowBlur;
- reals << b;
- }
-
- inline void setShadowColor(const QColor &color)
- {
- commands << QQuickContext2D::ShadowColor;
- colors << color;
- }
-
- inline QTransform takeMatrix() { return matrixes[matrixIdx++]; }
-
- // rects
- inline QRectF takeRect() {
- qreal x, y, w, h;
- x = takeReal();
- y = takeReal();
- w = takeReal();
- h = takeReal();
- return QRectF(x, y, w ,h);
- }
-
- inline QPainterPath takePath() { return pathes[pathIdx++]; }
-
- inline const QImage& takeImage() { return images[imageIdx++]; }
-
- inline int takeInt() { return ints[intIdx++]; }
- inline bool takeBool() {return bools[boolIdx++]; }
- inline qreal takeReal() { return reals[realIdx++]; }
- inline QColor takeColor() { return colors[colorIdx++]; }
- inline QBrush takeBrush() { return brushes[brushIdx++]; }
-
- void replay(QPainter* painter, QQuickContext2D::State& state);
-private:
- QPen makePen(const QQuickContext2D::State& state);
- void setPainterState(QPainter* painter, const QQuickContext2D::State& state, const QPen& pen);
- int cmdIdx;
- int intIdx;
- int boolIdx;
- int realIdx;
- int colorIdx;
- int matrixIdx;
- int brushIdx;
- int pathIdx;
- int imageIdx;
- QVector<QQuickContext2D::PaintCommand> commands;
-
- QVector<int> ints;
- QVector<bool> bools;
- QVector<qreal> reals;
- QVector<QColor> colors;
- QVector<QTransform> matrixes;
- QVector<QBrush> brushes;
- QVector<QPainterPath> pathes;
- QVector<QImage> images;
-};
-
-QT_END_HEADER
-
-QT_END_NAMESPACE
-
-#endif // QQUICKCONTEXT2DCOMMANDBUFFER_P_H
diff --git a/src/declarative/items/context2d/qquickcontext2dnode.cpp b/src/declarative/items/context2d/qquickcontext2dnode.cpp
deleted file mode 100644
index 76b50d9747..0000000000
--- a/src/declarative/items/context2d/qquickcontext2dnode.cpp
+++ /dev/null
@@ -1,124 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickcontext2dnode_p.h"
-
-#include <private/qsgcontext_p.h>
-#include <QtCore/qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-
-QQuickContext2DNode::QQuickContext2DNode(QQuickCanvasItem* item)
- : QSGGeometryNode()
- , m_item(item)
- , m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
- , m_texture(0)
- , m_size(1, 1)
- , m_dirtyGeometry(false)
- , m_dirtyTexture(false)
-{
- setMaterial(&m_materialO);
- setOpaqueMaterial(&m_material);
- setGeometry(&m_geometry);
- setFlag(UsePreprocess, true);
-}
-
-QQuickContext2DNode::~QQuickContext2DNode()
-{
- delete m_texture;
-}
-
-void QQuickContext2DNode::setSize(const QSizeF& size)
-{
- if (m_size != size) {
- m_dirtyGeometry = true;
- m_size = size;
- }
-}
-
-void QQuickContext2DNode::preprocess()
-{
- bool doDirty = false;
- QSGDynamicTexture *t = qobject_cast<QSGDynamicTexture *>(m_material.texture());
- if (t) {
- doDirty = t->updateTexture();
- }
- if (doDirty) {
- m_dirtyTexture = true;
- markDirty(DirtyMaterial);
- }
-}
-void QQuickContext2DNode::setTexture(QQuickContext2DTexture* texture)
-{
- if (texture != m_texture) {
- m_dirtyTexture = true;
- m_texture = texture;
- }
-}
-
-void QQuickContext2DNode::update()
-{
- if (m_dirtyGeometry)
- updateGeometry();
- if (m_dirtyTexture)
- updateTexture();
-
- m_dirtyGeometry = false;
- m_dirtyTexture = false;
-}
-
-void QQuickContext2DNode::updateTexture()
-{
- m_material.setTexture(m_texture);
- m_materialO.setTexture(m_texture);
- markDirty(DirtyMaterial);
-}
-
-void QQuickContext2DNode::updateGeometry()
-{
- QRectF source = m_texture->textureSubRect();
- QSGGeometry::updateTexturedRectGeometry(&m_geometry,
- QRectF(0, 0, m_size.width(), m_size.height()),
- source);
- markDirty(DirtyGeometry);
-}
-QT_END_NAMESPACE
diff --git a/src/declarative/items/context2d/qquickcontext2dnode_p.h b/src/declarative/items/context2d/qquickcontext2dnode_p.h
deleted file mode 100644
index 7403acaf07..0000000000
--- a/src/declarative/items/context2d/qquickcontext2dnode_p.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKCONTEXT2DNODE_P_H
-#define QQUICKCONTEXT2DNODE_P_H
-
-#include <qsgnode.h>
-#include <qsgtexturematerial.h>
-
-#include "qquickcanvasitem_p.h"
-#include "qquickcontext2dtexture_p.h"
-#include "qquickcontext2d_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickContext2DNode : public QSGGeometryNode
-{
-public:
- QQuickContext2DNode(QQuickCanvasItem* item);
- virtual ~QQuickContext2DNode();
- void setTexture(QQuickContext2DTexture* texture);
- void update();
- void preprocess();
- void setSize(const QSizeF& size);
-private:
- void updateTexture();
- void updateGeometry();
-
- QQuickCanvasItem* m_item;
- QSGOpaqueTextureMaterial m_material;
- QSGTextureMaterial m_materialO;
- QSGGeometry m_geometry;
- QQuickContext2DTexture* m_texture;
- QSizeF m_size;
-
- bool m_dirtyGeometry;
- bool m_dirtyTexture;
-};
-
-QT_END_HEADER
-
-QT_END_NAMESPACE
-
-#endif // QQUICKCONTEXT2DNODE_P_H
diff --git a/src/declarative/items/context2d/qquickcontext2dtexture.cpp b/src/declarative/items/context2d/qquickcontext2dtexture.cpp
deleted file mode 100644
index 1128fa224f..0000000000
--- a/src/declarative/items/context2d/qquickcontext2dtexture.cpp
+++ /dev/null
@@ -1,778 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickcontext2dtexture_p.h"
-#include "qquickcontext2dtile_p.h"
-#include "qquickcanvasitem_p.h"
-#include <private/qquickitem_p.h>
-#include <private/qsgtexture_p.h>
-#include "qquickcontext2dcommandbuffer_p.h"
-#include <QOpenGLPaintDevice>
-
-#include <QOpenGLFramebufferObject>
-#include <QOpenGLFramebufferObjectFormat>
-#include <QtCore/QThread>
-
-#define QT_MINIMUM_FBO_SIZE 64
-
-static inline int qt_next_power_of_two(int v)
-{
- v--;
- v |= v >> 1;
- v |= v >> 2;
- v |= v >> 4;
- v |= v >> 8;
- v |= v >> 16;
- ++v;
- return v;
-}
-
-
-Q_GLOBAL_STATIC(QThread, globalCanvasThreadRenderInstance)
-
-
-QQuickContext2DTexture::QQuickContext2DTexture()
- : QSGDynamicTexture()
- , m_context(0)
- , m_item(0)
- , m_canvasSize(QSize(1, 1))
- , m_tileSize(QSize(1, 1))
- , m_canvasWindow(QRect(0, 0, 1, 1))
- , m_dirtyCanvas(false)
- , m_dirtyTexture(false)
- , m_threadRendering(false)
- , m_smooth(false)
- , m_tiledCanvas(false)
- , m_doGrabImage(false)
- , m_painting(false)
-{
-}
-
-QQuickContext2DTexture::~QQuickContext2DTexture()
-{
- clearTiles();
-}
-
-QSize QQuickContext2DTexture::textureSize() const
-{
- return m_canvasWindow.size();
-}
-
-void QQuickContext2DTexture::markDirtyTexture()
-{
- lock();
- m_dirtyTexture = true;
- unlock();
- emit textureChanged();
-}
-
-bool QQuickContext2DTexture::setCanvasSize(const QSize &size)
-{
- if (m_canvasSize != size) {
- m_canvasSize = size;
- m_dirtyCanvas = true;
- return true;
- }
- return false;
-}
-
-bool QQuickContext2DTexture::setTileSize(const QSize &size)
-{
- if (m_tileSize != size) {
- m_tileSize = size;
- m_dirtyCanvas = true;
- return true;
- }
- return false;
-}
-
-void QQuickContext2DTexture::setSmooth(bool smooth)
-{
- m_smooth = smooth;
-}
-
-void QQuickContext2DTexture::setItem(QQuickCanvasItem* item)
-{
- if (!item) {
- lock();
- m_item = 0;
- m_context = 0;
- unlock();
- wake();
- } else if (m_item != item) {
- lock();
- m_item = item;
- m_context = item->context();
- m_state = m_context->state;
- unlock();
- connect(this, SIGNAL(textureChanged()), m_item, SIGNAL(painted()));
- }
-}
-
-bool QQuickContext2DTexture::setCanvasWindow(const QRect& r)
-{
- if (m_canvasWindow != r) {
- m_canvasWindow = r;
- return true;
- }
- return false;
-}
-
-bool QQuickContext2DTexture::setDirtyRect(const QRect &r)
-{
- bool doDirty = false;
- if (m_tiledCanvas) {
- foreach (QQuickContext2DTile* t, m_tiles) {
- bool dirty = t->rect().intersected(r).isValid();
- t->markDirty(dirty);
- if (dirty)
- doDirty = true;
- }
- } else {
- doDirty = m_canvasWindow.intersected(r).isValid();
- }
- return doDirty;
-}
-
-void QQuickContext2DTexture::canvasChanged(const QSize& canvasSize, const QSize& tileSize, const QRect& canvasWindow, const QRect& dirtyRect, bool smooth)
-{
- lock();
-
- QSize ts = tileSize;
- if (ts.width() > canvasSize.width())
- ts.setWidth(canvasSize.width());
-
- if (ts.height() > canvasSize.height())
- ts.setHeight(canvasSize.height());
-
- setCanvasSize(canvasSize);
- setTileSize(ts);
-
- if (canvasSize == canvasWindow.size()) {
- m_tiledCanvas = false;
- m_dirtyCanvas = false;
- } else {
- m_tiledCanvas = true;
- }
-
- bool doDirty = false;
- if (dirtyRect.isValid())
- doDirty = setDirtyRect(dirtyRect);
-
- bool windowChanged = setCanvasWindow(canvasWindow);
- if (windowChanged || doDirty) {
- if (m_threadRendering)
- QMetaObject::invokeMethod(this, "paint", Qt::QueuedConnection);
- else if (supportDirectRendering()) {
- QMetaObject::invokeMethod(this, "paint", Qt::DirectConnection);
- }
- }
-
- setSmooth(smooth);
- unlock();
-}
-
-void QQuickContext2DTexture::paintWithoutTiles()
-{
- QQuickContext2DCommandBuffer* ccb = m_context->buffer();
-
- if (ccb->isEmpty() && m_threadRendering && !m_doGrabImage) {
- lock();
- if (m_item)
- QMetaObject::invokeMethod(m_item, "_doPainting", Qt::QueuedConnection, Q_ARG(QRectF, QRectF(0, 0, m_canvasSize.width(), m_canvasSize.height())));
- wait();
- unlock();
- }
- if (ccb->isEmpty()) {
- return;
- }
-
- QPaintDevice* device = beginPainting();
- if (!device) {
- endPainting();
- return;
- }
-
- QPainter p;
- p.begin(device);
- if (m_smooth)
- p.setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing
- | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
- else
- p.setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing
- | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform, false);
- p.setCompositionMode(QPainter::CompositionMode_SourceOver);
- ccb->replay(&p, m_state);
-
- ccb->clear();
- markDirtyTexture();
- endPainting();
-}
-
-bool QQuickContext2DTexture::canvasDestroyed()
-{
- bool noCanvas = false;
- lock();
- noCanvas = m_item == 0;
- unlock();
- return noCanvas;
-}
-
-void QQuickContext2DTexture::paint()
-{
- if (canvasDestroyed())
- return;
-
- if (!m_tiledCanvas) {
- paintWithoutTiles();
- } else {
- lock();
- QRect tiledRegion = createTiles(m_canvasWindow.intersected(QRect(QPoint(0, 0), m_canvasSize)));
- unlock();
-
- if (!tiledRegion.isEmpty()) {
- if (m_threadRendering && !m_doGrabImage) {
- QRect dirtyRect;
-
- lock();
- foreach (QQuickContext2DTile* tile, m_tiles) {
- if (tile->dirty()) {
- if (dirtyRect.isEmpty())
- dirtyRect = tile->rect();
- else
- dirtyRect |= tile->rect();
- }
- }
- unlock();
-
- if (dirtyRect.isValid()) {
- lock();
- if (m_item)
- QMetaObject::invokeMethod(m_item, "_doPainting", Qt::QueuedConnection, Q_ARG(QRectF, dirtyRect));
- wait();
- unlock();
- }
- }
-
- if (beginPainting()) {
- QQuickContext2D::State oldState = m_state;
- QQuickContext2DCommandBuffer* ccb = m_context->buffer();
- foreach (QQuickContext2DTile* tile, m_tiles) {
- bool dirtyTile = false, dirtyCanvas = false, smooth = false;
-
- lock();
- dirtyTile = tile->dirty();
- smooth = m_smooth;
- dirtyCanvas = m_dirtyCanvas;
- unlock();
-
- //canvas size or tile size may change during painting tiles
- if (dirtyCanvas) {
- if (m_threadRendering)
- QMetaObject::invokeMethod(this, "paint", Qt::QueuedConnection);
- endPainting();
- return;
- } else if (dirtyTile) {
- ccb->replay(tile->createPainter(smooth), oldState);
- tile->drawFinished();
- lock();
- tile->markDirty(false);
- unlock();
- }
-
- compositeTile(tile);
- }
- ccb->clear();
- endPainting();
- m_state = oldState;
- markDirtyTexture();
- }
- }
- }
-}
-
-QRect QQuickContext2DTexture::tiledRect(const QRectF& window, const QSize& tileSize)
-{
- if (window.isEmpty())
- return QRect();
-
- const int tw = tileSize.width();
- const int th = tileSize.height();
- const int h1 = window.left() / tw;
- const int v1 = window.top() / th;
-
- const int htiles = ((window.right() - h1 * tw) + tw - 1)/tw;
- const int vtiles = ((window.bottom() - v1 * th) + th - 1)/th;
-
- return QRect(h1 * tw, v1 * th, htiles * tw, vtiles * th);
-}
-
-QRect QQuickContext2DTexture::createTiles(const QRect& window)
-{
- QList<QQuickContext2DTile*> oldTiles = m_tiles;
- m_tiles.clear();
-
- if (window.isEmpty()) {
- m_dirtyCanvas = false;
- return QRect();
- }
-
- QRect r = tiledRect(window, m_tileSize);
-
- const int tw = m_tileSize.width();
- const int th = m_tileSize.height();
- const int h1 = window.left() / tw;
- const int v1 = window.top() / th;
-
-
- const int htiles = r.width() / tw;
- const int vtiles = r.height() / th;
-
- for (int yy = 0; yy < vtiles; ++yy) {
- for (int xx = 0; xx < htiles; ++xx) {
- int ht = xx + h1;
- int vt = yy + v1;
-
- QQuickContext2DTile* tile = 0;
-
- QPoint pos(ht * tw, vt * th);
- QRect rect(pos, m_tileSize);
-
- for (int i = 0; i < oldTiles.size(); i++) {
- if (oldTiles[i]->rect() == rect) {
- tile = oldTiles.takeAt(i);
- break;
- }
- }
-
- if (!tile)
- tile = createTile();
-
- tile->setRect(rect);
- m_tiles.append(tile);
- }
- }
-
- qDeleteAll(oldTiles);
-
- m_dirtyCanvas = false;
- return r;
-}
-
-void QQuickContext2DTexture::clearTiles()
-{
- qDeleteAll(m_tiles);
- m_tiles.clear();
-}
-
-QQuickContext2DFBOTexture::QQuickContext2DFBOTexture()
- : QQuickContext2DTexture()
- , m_fbo(0)
- , m_multisampledFbo(0)
- , m_paint_device(0)
-{
- m_threadRendering = false;
-}
-
-QQuickContext2DFBOTexture::~QQuickContext2DFBOTexture()
-{
- delete m_fbo;
- delete m_multisampledFbo;
- delete m_paint_device;
-}
-
-bool QQuickContext2DFBOTexture::setCanvasSize(const QSize &size)
-{
- QSize s = QSize(qMax(QT_MINIMUM_FBO_SIZE, qt_next_power_of_two(size.width()))
- , qMax(QT_MINIMUM_FBO_SIZE, qt_next_power_of_two(size.height())));
-
- if (m_canvasSize != s) {
- m_canvasSize = s;
- m_dirtyCanvas = true;
- return true;
- }
- return false;
-}
-
-bool QQuickContext2DFBOTexture::setTileSize(const QSize &size)
-{
- QSize s = QSize(qMax(QT_MINIMUM_FBO_SIZE, qt_next_power_of_two(size.width()))
- , qMax(QT_MINIMUM_FBO_SIZE, qt_next_power_of_two(size.height())));
- if (m_tileSize != s) {
- m_tileSize = s;
- m_dirtyCanvas = true;
- return true;
- }
- return false;
-}
-
-bool QQuickContext2DFBOTexture::setCanvasWindow(const QRect& canvasWindow)
-{
- QSize s = QSize(qMax(QT_MINIMUM_FBO_SIZE, qt_next_power_of_two(canvasWindow.size().width()))
- , qMax(QT_MINIMUM_FBO_SIZE, qt_next_power_of_two(canvasWindow.size().height())));
-
-
- bool doChanged = false;
- if (m_fboSize != s) {
- m_fboSize = s;
- doChanged = true;
- }
-
- if (m_canvasWindow != canvasWindow)
- m_canvasWindow = canvasWindow;
-
- return doChanged;
-}
-
-void QQuickContext2DFBOTexture::bind()
-{
- glBindTexture(GL_TEXTURE_2D, textureId());
- updateBindOptions();
-}
-
-QRectF QQuickContext2DFBOTexture::textureSubRect() const
-{
- return QRectF(0
- , 0
- , qreal(m_canvasWindow.width()) / m_fboSize.width()
- , qreal(m_canvasWindow.height()) / m_fboSize.height());
-}
-
-
-int QQuickContext2DFBOTexture::textureId() const
-{
- return m_fbo? m_fbo->texture() : 0;
-}
-
-
-bool QQuickContext2DFBOTexture::updateTexture()
-{
- if (!m_context->buffer()->isEmpty()) {
- paint();
- }
-
- bool textureUpdated = m_dirtyTexture;
-
- m_dirtyTexture = false;
-
- if (m_doGrabImage) {
- grabImage();
- m_condition.wakeOne();
- m_doGrabImage = false;
- }
- return textureUpdated;
-}
-
-QQuickContext2DTile* QQuickContext2DFBOTexture::createTile() const
-{
- return new QQuickContext2DFBOTile();
-}
-
-void QQuickContext2DFBOTexture::grabImage()
-{
- if (m_fbo) {
- m_grabedImage = m_fbo->toImage();
- }
-}
-
-bool QQuickContext2DFBOTexture::doMultisampling() const
-{
- static bool extensionsChecked = false;
- static bool multisamplingSupported = false;
-
- if (!extensionsChecked) {
- QList<QByteArray> extensions = QByteArray((const char *)glGetString(GL_EXTENSIONS)).split(' ');
- multisamplingSupported = extensions.contains("GL_EXT_framebuffer_multisample")
- && extensions.contains("GL_EXT_framebuffer_blit");
- extensionsChecked = true;
- }
-
- return multisamplingSupported && m_smooth;
-}
-
-QImage QQuickContext2DFBOTexture::toImage(const QRectF& region)
-{
-#define QML_CONTEXT2D_WAIT_MAX 5000
-
- m_doGrabImage = true;
- if (m_item)
- m_item->update();
-
- QImage grabbed;
- m_mutex.lock();
- bool ok = m_condition.wait(&m_mutex, QML_CONTEXT2D_WAIT_MAX);
-
- if (!ok)
- grabbed = QImage();
-
- if (region.isValid())
- grabbed = m_grabedImage.copy(region.toRect());
- else
- grabbed = m_grabedImage;
- m_grabedImage = QImage();
- return grabbed;
-}
-
-void QQuickContext2DFBOTexture::compositeTile(QQuickContext2DTile* tile)
-{
- QQuickContext2DFBOTile* t = static_cast<QQuickContext2DFBOTile*>(tile);
- QRect target = t->rect().intersect(m_canvasWindow);
- if (target.isValid()) {
- QRect source = target;
-
- source.moveTo(source.topLeft() - t->rect().topLeft());
- target.moveTo(target.topLeft() - m_canvasWindow.topLeft());
-
- QOpenGLFramebufferObject::blitFramebuffer(m_fbo, target, t->fbo(), source);
- }
-}
-QQuickCanvasItem::RenderTarget QQuickContext2DFBOTexture::renderTarget() const
-{
- return QQuickCanvasItem::FramebufferObject;
-}
-QPaintDevice* QQuickContext2DFBOTexture::beginPainting()
-{
- QQuickContext2DTexture::beginPainting();
-
- if (m_canvasWindow.size().isEmpty() && !m_threadRendering) {
- delete m_fbo;
- delete m_multisampledFbo;
- m_fbo = 0;
- m_multisampledFbo = 0;
- return 0;
- } else if (!m_fbo || m_fbo->size() != m_fboSize) {
- delete m_fbo;
- delete m_multisampledFbo;
- if (doMultisampling()) {
- {
- QOpenGLFramebufferObjectFormat format;
- format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
- format.setSamples(8);
- m_multisampledFbo = new QOpenGLFramebufferObject(m_fboSize, format);
- }
- {
- QOpenGLFramebufferObjectFormat format;
- format.setAttachment(QOpenGLFramebufferObject::NoAttachment);
- m_fbo = new QOpenGLFramebufferObject(m_fboSize, format);
- }
- } else {
- QOpenGLFramebufferObjectFormat format;
- format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
-
- m_fbo = new QOpenGLFramebufferObject(m_fboSize, format);
- }
- }
-
- if (doMultisampling())
- m_multisampledFbo->bind();
- else
- m_fbo->bind();
-
-
- if (!m_paint_device) {
- QOpenGLPaintDevice *gl_device = new QOpenGLPaintDevice(m_fbo->size());
- gl_device->setPaintFlipped(true);
- m_paint_device = gl_device;
- }
-
- return m_paint_device;
-}
-
-void QQuickContext2DFBOTexture::endPainting()
-{
- QQuickContext2DTexture::endPainting();
- if (m_multisampledFbo) {
- QOpenGLFramebufferObject::blitFramebuffer(m_fbo, m_multisampledFbo);
- m_multisampledFbo->release();
- } else if (m_fbo)
- m_fbo->release();
-}
-void qt_quit_context2d_render_thread()
-{
- QThread* thread = globalCanvasThreadRenderInstance();
-
- if (thread->isRunning()) {
- thread->exit(0);
- thread->wait(1000);
- }
-}
-
-QQuickContext2DImageTexture::QQuickContext2DImageTexture(bool threadRendering)
- : QQuickContext2DTexture()
- , m_texture(new QSGPlainTexture())
-{
- m_texture->setOwnsTexture(true);
- m_texture->setHasMipmaps(false);
-
- m_threadRendering = threadRendering;
-
- if (m_threadRendering) {
- QThread* thread = globalCanvasThreadRenderInstance();
- moveToThread(thread);
-
- if (!thread->isRunning()) {
- qAddPostRoutine(qt_quit_context2d_render_thread);
- thread->start();
- }
- }
-}
-
-QQuickContext2DImageTexture::~QQuickContext2DImageTexture()
-{
- delete m_texture;
-}
-
-int QQuickContext2DImageTexture::textureId() const
-{
- return m_texture->textureId();
-}
-
-void QQuickContext2DImageTexture::lock()
-{
- if (m_threadRendering)
- m_mutex.lock();
-}
-void QQuickContext2DImageTexture::unlock()
-{
- if (m_threadRendering)
- m_mutex.unlock();
-}
-
-void QQuickContext2DImageTexture::wait()
-{
- if (m_threadRendering)
- m_waitCondition.wait(&m_mutex);
-}
-
-void QQuickContext2DImageTexture::wake()
-{
- if (m_threadRendering)
- m_waitCondition.wakeOne();
-}
-
-bool QQuickContext2DImageTexture::supportDirectRendering() const
-{
- return !m_threadRendering;
-}
-
-QQuickCanvasItem::RenderTarget QQuickContext2DImageTexture::renderTarget() const
-{
- return QQuickCanvasItem::Image;
-}
-
-void QQuickContext2DImageTexture::bind()
-{
- m_texture->bind();
-}
-
-bool QQuickContext2DImageTexture::updateTexture()
-{
- lock();
- bool textureUpdated = m_dirtyTexture;
- if (m_dirtyTexture) {
- m_texture->setImage(m_image);
- m_dirtyTexture = false;
- }
- unlock();
- return textureUpdated;
-}
-
-QQuickContext2DTile* QQuickContext2DImageTexture::createTile() const
-{
- return new QQuickContext2DImageTile();
-}
-
-void QQuickContext2DImageTexture::grabImage(const QRect& r)
-{
- m_doGrabImage = true;
- paint();
- m_doGrabImage = false;
- m_grabedImage = m_image.copy(r);
-}
-
-QImage QQuickContext2DImageTexture::toImage(const QRectF& region)
-{
- QRect r = region.isValid() ? region.toRect() : QRect(QPoint(0, 0), m_canvasWindow.size());
- if (threadRendering()) {
- wake();
- QMetaObject::invokeMethod(this, "grabImage", Qt::BlockingQueuedConnection, Q_ARG(QRect, r));
- } else {
- QMetaObject::invokeMethod(this, "grabImage", Qt::DirectConnection, Q_ARG(QRect, r));
- }
- QImage image = m_grabedImage;
- m_grabedImage = QImage();
- return image;
-}
-
-QPaintDevice* QQuickContext2DImageTexture::beginPainting()
-{
- QQuickContext2DTexture::beginPainting();
-
- if (m_canvasWindow.size().isEmpty())
- return 0;
-
- lock();
- if (m_image.size() != m_canvasWindow.size()) {
- m_image = QImage(m_canvasWindow.size(), QImage::Format_ARGB32_Premultiplied);
- m_image.fill(0x00000000);
- }
- unlock();
- return &m_image;
-}
-
-void QQuickContext2DImageTexture::compositeTile(QQuickContext2DTile* tile)
-{
- Q_ASSERT(!tile->dirty());
- QQuickContext2DImageTile* t = static_cast<QQuickContext2DImageTile*>(tile);
- QRect target = t->rect().intersect(m_canvasWindow);
- if (target.isValid()) {
- QRect source = target;
- source.moveTo(source.topLeft() - t->rect().topLeft());
- target.moveTo(target.topLeft() - m_canvasWindow.topLeft());
-
- lock();
- m_painter.begin(&m_image);
- m_painter.setCompositionMode(QPainter::CompositionMode_Source);
- m_painter.drawImage(target, t->image(), source);
- m_painter.end();
- unlock();
- }
-}
diff --git a/src/declarative/items/context2d/qquickcontext2dtexture_p.h b/src/declarative/items/context2d/qquickcontext2dtexture_p.h
deleted file mode 100644
index ed45a09f7c..0000000000
--- a/src/declarative/items/context2d/qquickcontext2dtexture_p.h
+++ /dev/null
@@ -1,205 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKCONTEXT2DTEXTURE_P_H
-#define QQUICKCONTEXT2DTEXTURE_P_H
-
-#include <qsgtexture.h>
-#include "qquickcanvasitem_p.h"
-#include "qquickcontext2d_p.h"
-
-#include <QOpenGLContext>
-#include <QOpenGLFramebufferObject>
-
-#include <QtCore/QMutex>
-#include <QtCore/QWaitCondition>
-#include <QtCore/QThread>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickContext2DTile;
-class QQuickContext2DCommandBuffer;
-
-class QQuickContext2DTexture : public QSGDynamicTexture
-{
- Q_OBJECT
-public:
- QQuickContext2DTexture();
- ~QQuickContext2DTexture();
-
- virtual bool hasAlphaChannel() const {return true;}
- virtual bool hasMipmaps() const {return false;}
- virtual QSize textureSize() const;
- virtual void lock() {}
- virtual void unlock() {}
- virtual void wait() {}
- virtual void wake() {}
- bool threadRendering() const {return m_threadRendering;}
- virtual bool supportThreadRendering() const = 0;
- virtual bool supportDirectRendering() const = 0;
- virtual QQuickCanvasItem::RenderTarget renderTarget() const = 0;
- virtual QImage toImage(const QRectF& region = QRectF()) = 0;
- static QRect tiledRect(const QRectF& window, const QSize& tileSize);
-
- virtual bool setCanvasSize(const QSize &size);
- virtual bool setTileSize(const QSize &size);
- virtual bool setCanvasWindow(const QRect& canvasWindow);
- void setSmooth(bool smooth);
- bool setDirtyRect(const QRect &dirtyRect);
- virtual void canvasChanged(const QSize& canvasSize, const QSize& tileSize, const QRect& canvasWindow, const QRect& dirtyRect, bool smooth);
- bool canvasDestroyed();
-Q_SIGNALS:
- void textureChanged();
-
-public Q_SLOTS:
- void markDirtyTexture();
- void setItem(QQuickCanvasItem* item);
- void paint();
-
-protected:
- void paintWithoutTiles();
- virtual QPaintDevice* beginPainting() {m_painting = true; return 0; }
- virtual void endPainting() {m_painting = false;}
- virtual QQuickContext2DTile* createTile() const = 0;
- virtual void compositeTile(QQuickContext2DTile* tile) = 0;
-
- void clearTiles();
- QRect createTiles(const QRect& window);
-
- QList<QQuickContext2DTile*> m_tiles;
- QQuickContext2D* m_context;
-
- QQuickContext2D::State m_state;
-
- QQuickCanvasItem* m_item;
- QSize m_canvasSize;
- QSize m_tileSize;
- QRect m_canvasWindow;
-
- uint m_dirtyCanvas : 1;
- uint m_dirtyTexture : 1;
- uint m_threadRendering : 1;
- uint m_smooth : 1;
- uint m_tiledCanvas : 1;
- uint m_doGrabImage : 1;
- uint m_painting : 1;
-};
-
-class QQuickContext2DFBOTexture : public QQuickContext2DTexture
-{
- Q_OBJECT
-
-public:
- QQuickContext2DFBOTexture();
- ~QQuickContext2DFBOTexture();
- virtual int textureId() const;
- virtual bool updateTexture();
- virtual QQuickContext2DTile* createTile() const;
- virtual QImage toImage(const QRectF& region = QRectF());
- virtual QPaintDevice* beginPainting();
- virtual void endPainting();
- QRectF textureSubRect() const;
- virtual bool supportThreadRendering() const {return false;}
- virtual bool supportDirectRendering() const {return false;}
- virtual QQuickCanvasItem::RenderTarget renderTarget() const;
- virtual void compositeTile(QQuickContext2DTile* tile);
- virtual void bind();
- virtual bool setCanvasSize(const QSize &size);
- virtual bool setTileSize(const QSize &size);
- virtual bool setCanvasWindow(const QRect& canvasWindow);
-private Q_SLOTS:
- void grabImage();
-
-private:
- bool doMultisampling() const;
- QImage m_grabedImage;
- QOpenGLFramebufferObject *m_fbo;
- QOpenGLFramebufferObject *m_multisampledFbo;
- QMutex m_mutex;
- QWaitCondition m_condition;
- QSize m_fboSize;
- QPaintDevice *m_paint_device;
-};
-
-class QSGPlainTexture;
-class QQuickContext2DImageTexture : public QQuickContext2DTexture
-{
- Q_OBJECT
-
-public:
- QQuickContext2DImageTexture(bool threadRendering = true);
- ~QQuickContext2DImageTexture();
- virtual int textureId() const;
- virtual void bind();
- virtual bool supportThreadRendering() const {return true;}
- virtual bool supportDirectRendering() const;
- virtual QQuickCanvasItem::RenderTarget renderTarget() const;
- virtual void lock();
- virtual void unlock();
- virtual void wait();
- virtual void wake();
-
- virtual bool updateTexture();
- virtual QQuickContext2DTile* createTile() const;
- virtual QImage toImage(const QRectF& region = QRectF());
- virtual QPaintDevice* beginPainting();
- virtual void compositeTile(QQuickContext2DTile* tile);
-
-private Q_SLOTS:
- void grabImage(const QRect& r);
-private:
- QImage m_image;
- QImage m_grabedImage;
- QMutex m_mutex;
- QWaitCondition m_waitCondition;
- QPainter m_painter;
- QSGPlainTexture* m_texture;
-};
-
-QT_END_HEADER
-
-QT_END_NAMESPACE
-
-#endif // QQUICKCONTEXT2DTEXTURE_P_H
diff --git a/src/declarative/items/context2d/qquickcontext2dtile.cpp b/src/declarative/items/context2d/qquickcontext2dtile.cpp
deleted file mode 100644
index 6217c66094..0000000000
--- a/src/declarative/items/context2d/qquickcontext2dtile.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickcontext2dtile_p.h"
-
-#include <QOpenGLFramebufferObject>
-#include <QOpenGLFramebufferObjectFormat>
-#include <QOpenGLPaintDevice>
-
-QQuickContext2DTile::QQuickContext2DTile()
- : m_dirty(true)
- , m_rect(QRect(0, 0, 1, 1))
- , m_device(0)
-{
-}
-
-QQuickContext2DTile::~QQuickContext2DTile()
-{
- if (m_painter.isActive())
- m_painter.end();
-}
-
-QPainter* QQuickContext2DTile::createPainter(bool smooth)
-{
- if (m_painter.isActive())
- m_painter.end();
-
- if (m_device) {
- aboutToDraw();
- m_painter.begin(m_device);
- m_painter.resetTransform();
- m_painter.setCompositionMode(QPainter::CompositionMode_Source);
-
-#ifdef QQUICKCONTEXT2D_DEBUG
- int v = 100;
- int gray = (m_rect.x() / m_rect.width() + m_rect.y() / m_rect.height()) % 2;
- if (gray)
- v = 150;
- m_painter.fillRect(QRect(0, 0, m_rect.width(), m_rect.height()), QColor(v, v, v, 255));
-#endif
- if (smooth)
- m_painter.setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing
- | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
- else
- m_painter.setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing
- | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform, false);
-
- m_painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
- m_painter.translate(-m_rect.left(), -m_rect.top());
- m_painter.setClipRect(m_rect);
- m_painter.setClipping(false);
- return &m_painter;
- }
-
- return 0;
-}
-
-QQuickContext2DFBOTile::QQuickContext2DFBOTile()
- : QQuickContext2DTile()
- , m_fbo(0)
-{
-}
-
-
-QQuickContext2DFBOTile::~QQuickContext2DFBOTile()
-{
- delete m_fbo;
-}
-
-void QQuickContext2DFBOTile::aboutToDraw()
-{
- m_fbo->bind();
- if (!m_device) {
- QOpenGLPaintDevice *gl_device = new QOpenGLPaintDevice(rect().size());
- m_device = gl_device;
- QPainter p(m_device);
- p.fillRect(QRectF(0, 0, m_fbo->width(), m_fbo->height()), QColor(qRgba(0, 0, 0, 0)));
- p.end();
- }
-}
-
-void QQuickContext2DFBOTile::drawFinished()
-{
- m_fbo->release();
-}
-
-void QQuickContext2DFBOTile::setRect(const QRect& r)
-{
- if (m_rect == r)
- return;
- m_rect = r;
- m_dirty = true;
- if (!m_fbo || m_fbo->size() != r.size()) {
- QOpenGLFramebufferObjectFormat format;
- format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
- format.setInternalTextureFormat(GL_RGBA);
- format.setMipmap(false);
-
- if (m_painter.isActive())
- m_painter.end();
-
- delete m_fbo;
- m_fbo = new QOpenGLFramebufferObject(r.size(), format);
- }
-}
-
-
-QQuickContext2DImageTile::QQuickContext2DImageTile()
- : QQuickContext2DTile()
-{
-}
-
-QQuickContext2DImageTile::~QQuickContext2DImageTile()
-{
-}
-
-void QQuickContext2DImageTile::setRect(const QRect& r)
-{
- if (m_rect == r)
- return;
- m_rect = r;
- m_dirty = true;
- if (m_image.size() != r.size()) {
- m_image = QImage(r.size(), QImage::Format_ARGB32_Premultiplied);
- }
- m_device = &m_image;
-}
diff --git a/src/declarative/items/context2d/qquickcontext2dtile_p.h b/src/declarative/items/context2d/qquickcontext2dtile_p.h
deleted file mode 100644
index 92c59efbcf..0000000000
--- a/src/declarative/items/context2d/qquickcontext2dtile_p.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKCONTEXT2DTILE_P_H
-#define QQUICKCONTEXT2DTILE_P_H
-
-#include "qquickcontext2d_p.h"
-#include <QOpenGLFramebufferObject>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickContext2DTexture;
-class QQuickContext2DCommandBuffer;
-
-class QQuickContext2DTile
-{
-public:
- QQuickContext2DTile();
- ~QQuickContext2DTile();
-
- bool dirty() const {return m_dirty;}
- void markDirty(bool dirty) {m_dirty = dirty;}
-
- QRect rect() const {return m_rect;}
-
- virtual void setRect(const QRect& r) = 0;
- virtual QPainter* createPainter(bool smooth = false);
- virtual void drawFinished() {}
-
-protected:
- virtual void aboutToDraw() {}
- uint m_dirty : 1;
- QRect m_rect;
- QPaintDevice* m_device;
- QPainter m_painter;
-};
-
-
-class QQuickContext2DFBOTile : public QQuickContext2DTile
-{
-public:
- QQuickContext2DFBOTile();
- ~QQuickContext2DFBOTile();
- virtual void setRect(const QRect& r);
- QOpenGLFramebufferObject* fbo() const {return m_fbo;}
- void drawFinished();
-
-protected:
- void aboutToDraw();
-private:
-
-
- QOpenGLFramebufferObject *m_fbo;
-};
-
-class QQuickContext2DImageTile : public QQuickContext2DTile
-{
-public:
- QQuickContext2DImageTile();
- ~QQuickContext2DImageTile();
- void setRect(const QRect& r);
- const QImage& image() const {return m_image;}
-private:
- QImage m_image;
-};
-QT_END_HEADER
-
-QT_END_NAMESPACE
-
-#endif // QQUICKCONTEXT2DTILE_P_H
diff --git a/src/declarative/items/items.pri b/src/declarative/items/items.pri
deleted file mode 100644
index 308706f0b9..0000000000
--- a/src/declarative/items/items.pri
+++ /dev/null
@@ -1,131 +0,0 @@
-HEADERS += \
- $$PWD/qquickevents_p_p.h \
- $$PWD/qquickitemchangelistener_p.h \
- $$PWD/qquickanchors_p.h \
- $$PWD/qquickanchors_p_p.h \
- $$PWD/qquickitem.h \
- $$PWD/qquickitem_p.h \
- $$PWD/qquickrectangle_p.h \
- $$PWD/qquickrectangle_p_p.h \
- $$PWD/qquickcanvas.h \
- $$PWD/qquickcanvas_p.h \
- $$PWD/qquickfocusscope_p.h \
- $$PWD/qquickitemsmodule_p.h \
- $$PWD/qquickpainteditem.h \
- $$PWD/qquickpainteditem_p.h \
- $$PWD/qquicktext_p.h \
- $$PWD/qquicktext_p_p.h \
- $$PWD/qquicktextnode_p.h \
- $$PWD/qquicktextinput_p.h \
- $$PWD/qquicktextinput_p_p.h \
- $$PWD/qquicktextedit_p.h \
- $$PWD/qquicktextedit_p_p.h \
- $$PWD/qquickimagebase_p.h \
- $$PWD/qquickimagebase_p_p.h \
- $$PWD/qquickimage_p.h \
- $$PWD/qquickimage_p_p.h \
- $$PWD/qquickborderimage_p.h \
- $$PWD/qquickborderimage_p_p.h \
- $$PWD/qquickninepatchnode_p.h \
- $$PWD/qquickscalegrid_p_p.h \
- $$PWD/qquickmousearea_p.h \
- $$PWD/qquickmousearea_p_p.h \
- $$PWD/qquickpincharea_p.h \
- $$PWD/qquickpincharea_p_p.h \
- $$PWD/qquickflickable_p.h \
- $$PWD/qquickflickable_p_p.h \
- $$PWD/qquicklistview_p.h \
- $$PWD/qquickvisualadaptormodel_p.h \
- $$PWD/qquickvisualdatamodel_p.h \
- $$PWD/qquickvisualitemmodel_p.h \
- $$PWD/qquickrepeater_p.h \
- $$PWD/qquickrepeater_p_p.h \
- $$PWD/qquickgridview_p.h \
- $$PWD/qquickpathview_p.h \
- $$PWD/qquickpathview_p_p.h \
- $$PWD/qquickpositioners_p.h \
- $$PWD/qquickpositioners_p_p.h \
- $$PWD/qquickloader_p.h \
- $$PWD/qquickloader_p_p.h \
- $$PWD/qquickanimatedimage_p.h \
- $$PWD/qquickanimatedimage_p_p.h \
- $$PWD/qquickflipable_p.h \
- $$PWD/qquicktranslate_p.h \
- $$PWD/qquickclipnode_p.h \
- $$PWD/qquickview.h \
- $$PWD/qquickview_p.h \
- $$PWD/qquickanimation_p.h \
- $$PWD/qquickanimation_p_p.h \
- $$PWD/qquickstateoperations_p.h \
- $$PWD/qquickimplicitsizeitem_p.h \
- $$PWD/qquickimplicitsizeitem_p_p.h \
- $$PWD/qquickspriteengine_p.h \
- $$PWD/qquicksprite_p.h \
- $$PWD/qquickspriteimage_p.h \
- $$PWD/qquickdrag_p.h \
- $$PWD/qquickdroparea_p.h \
- $$PWD/qquickmultipointtoucharea_p.h \
- $$PWD/qquickitemview_p.h \
- $$PWD/qquickitemview_p_p.h \
- $$PWD/qquickwindowmodule_p.h
-
-SOURCES += \
- $$PWD/qquickevents.cpp \
- $$PWD/qquickanchors.cpp \
- $$PWD/qquickitem.cpp \
- $$PWD/qquickrectangle.cpp \
- $$PWD/qquickcanvas.cpp \
- $$PWD/qquickfocusscope.cpp \
- $$PWD/qquickitemsmodule.cpp \
- $$PWD/qquickpainteditem.cpp \
- $$PWD/qquicktext.cpp \
- $$PWD/qquicktextnode.cpp \
- $$PWD/qquicktextinput.cpp \
- $$PWD/qquicktextedit.cpp \
- $$PWD/qquickimagebase.cpp \
- $$PWD/qquickimage.cpp \
- $$PWD/qquickborderimage.cpp \
- $$PWD/qquickninepatchnode.cpp \
- $$PWD/qquickscalegrid.cpp \
- $$PWD/qquickmousearea.cpp \
- $$PWD/qquickpincharea.cpp \
- $$PWD/qquickflickable.cpp \
- $$PWD/qquicklistview.cpp \
- $$PWD/qquickvisualadaptormodel.cpp \
- $$PWD/qquickvisualdatamodel.cpp \
- $$PWD/qquickvisualitemmodel.cpp \
- $$PWD/qquickrepeater.cpp \
- $$PWD/qquickgridview.cpp \
- $$PWD/qquickpathview.cpp \
- $$PWD/qquickpositioners.cpp \
- $$PWD/qquickloader.cpp \
- $$PWD/qquickanimatedimage.cpp \
- $$PWD/qquickflipable.cpp \
- $$PWD/qquicktranslate.cpp \
- $$PWD/qquickclipnode.cpp \
- $$PWD/qquickview.cpp \
- $$PWD/qquickanimation.cpp \
- $$PWD/qquickstateoperations.cpp \
- $$PWD/qquickimplicitsizeitem.cpp \
- $$PWD/qquickspriteengine.cpp \
- $$PWD/qquicksprite.cpp \
- $$PWD/qquickspriteimage.cpp \
- $$PWD/qquickdrag.cpp \
- $$PWD/qquickdroparea.cpp \
- $$PWD/qquickmultipointtoucharea.cpp \
- $$PWD/qquickitemview.cpp \
- $$PWD/qquickwindowmodule.cpp
-
-SOURCES += \
- $$PWD/qquickshadereffect.cpp \
- $$PWD/qquickshadereffectmesh.cpp \
- $$PWD/qquickshadereffectnode.cpp \
- $$PWD/qquickshadereffectsource.cpp \
-
-HEADERS += \
- $$PWD/qquickshadereffect_p.h \
- $$PWD/qquickshadereffectmesh_p.h \
- $$PWD/qquickshadereffectnode_p.h \
- $$PWD/qquickshadereffectsource_p.h \
-
-include(context2d/context2d.pri)
diff --git a/src/declarative/items/qquickanchors.cpp b/src/declarative/items/qquickanchors.cpp
deleted file mode 100644
index 8ebdc374fb..0000000000
--- a/src/declarative/items/qquickanchors.cpp
+++ /dev/null
@@ -1,1180 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickanchors_p_p.h"
-
-#include "qquickitem.h"
-#include "qquickitem_p.h"
-
-#include <qdeclarativeinfo.h>
-
-QT_BEGIN_NAMESPACE
-
-//TODO: should we cache relationships, so we don't have to check each time (parent-child or sibling)?
-//TODO: support non-parent, non-sibling (need to find lowest common ancestor)
-
-static qreal hcenter(QQuickItem *item)
-{
- qreal width = item->width();
- int iw = width;
- if (iw % 2)
- return (width + 1) / 2;
- else
- return width / 2;
-}
-
-static qreal vcenter(QQuickItem *item)
-{
- qreal height = item->height();
- int ih = height;
- if (ih % 2)
- return (height + 1) / 2;
- else
- return height / 2;
-}
-
-//### const item?
-//local position
-static qreal position(QQuickItem *item, QQuickAnchorLine::AnchorLine anchorLine)
-{
- qreal ret = 0.0;
- switch (anchorLine) {
- case QQuickAnchorLine::Left:
- ret = item->x();
- break;
- case QQuickAnchorLine::Right:
- ret = item->x() + item->width();
- break;
- case QQuickAnchorLine::Top:
- ret = item->y();
- break;
- case QQuickAnchorLine::Bottom:
- ret = item->y() + item->height();
- break;
- case QQuickAnchorLine::HCenter:
- ret = item->x() + hcenter(item);
- break;
- case QQuickAnchorLine::VCenter:
- ret = item->y() + vcenter(item);
- break;
- case QQuickAnchorLine::Baseline:
- ret = item->y() + item->baselineOffset();
- break;
- default:
- break;
- }
-
- return ret;
-}
-
-//position when origin is 0,0
-static qreal adjustedPosition(QQuickItem *item, QQuickAnchorLine::AnchorLine anchorLine)
-{
- qreal ret = 0.0;
- switch (anchorLine) {
- case QQuickAnchorLine::Left:
- ret = 0.0;
- break;
- case QQuickAnchorLine::Right:
- ret = item->width();
- break;
- case QQuickAnchorLine::Top:
- ret = 0.0;
- break;
- case QQuickAnchorLine::Bottom:
- ret = item->height();
- break;
- case QQuickAnchorLine::HCenter:
- ret = hcenter(item);
- break;
- case QQuickAnchorLine::VCenter:
- ret = vcenter(item);
- break;
- case QQuickAnchorLine::Baseline:
- ret = item->baselineOffset();
- break;
- default:
- break;
- }
-
- return ret;
-}
-
-QQuickAnchors::QQuickAnchors(QQuickItem *item, QObject *parent)
-: QObject(*new QQuickAnchorsPrivate(item), parent)
-{
-}
-
-QQuickAnchors::~QQuickAnchors()
-{
- Q_D(QQuickAnchors);
- d->inDestructor = true;
- d->remDepend(d->fill);
- d->remDepend(d->centerIn);
- d->remDepend(d->left.item);
- d->remDepend(d->right.item);
- d->remDepend(d->top.item);
- d->remDepend(d->bottom.item);
- d->remDepend(d->vCenter.item);
- d->remDepend(d->hCenter.item);
- d->remDepend(d->baseline.item);
-}
-
-void QQuickAnchorsPrivate::fillChanged()
-{
- Q_Q(QQuickAnchors);
- if (!fill || !isItemComplete())
- return;
-
- if (updatingFill < 2) {
- ++updatingFill;
-
- qreal horizontalMargin = q->mirrored() ? rightMargin : leftMargin;
-
- if (fill == item->parentItem()) { //child-parent
- setItemPos(QPointF(horizontalMargin, topMargin));
- } else if (fill->parentItem() == item->parentItem()) { //siblings
- setItemPos(QPointF(fill->x()+horizontalMargin, fill->y()+topMargin));
- }
- setItemSize(QSizeF(fill->width()-leftMargin-rightMargin, fill->height()-topMargin-bottomMargin));
-
- --updatingFill;
- } else {
- // ### Make this certain :)
- qmlInfo(item) << QQuickAnchors::tr("Possible anchor loop detected on fill.");
- }
-
-}
-
-void QQuickAnchorsPrivate::centerInChanged()
-{
- Q_Q(QQuickAnchors);
- if (!centerIn || fill || !isItemComplete())
- return;
-
- if (updatingCenterIn < 2) {
- ++updatingCenterIn;
-
- qreal effectiveHCenterOffset = q->mirrored() ? -hCenterOffset : hCenterOffset;
- if (centerIn == item->parentItem()) {
- QPointF p(hcenter(item->parentItem()) - hcenter(item) + effectiveHCenterOffset,
- vcenter(item->parentItem()) - vcenter(item) + vCenterOffset);
- setItemPos(p);
-
- } else if (centerIn->parentItem() == item->parentItem()) {
- QPointF p(centerIn->x() + hcenter(centerIn) - hcenter(item) + effectiveHCenterOffset,
- centerIn->y() + vcenter(centerIn) - vcenter(item) + vCenterOffset);
- setItemPos(p);
- }
-
- --updatingCenterIn;
- } else {
- // ### Make this certain :)
- qmlInfo(item) << QQuickAnchors::tr("Possible anchor loop detected on centerIn.");
- }
-}
-
-void QQuickAnchorsPrivate::clearItem(QQuickItem *item)
-{
- if (!item)
- return;
- if (fill == item)
- fill = 0;
- if (centerIn == item)
- centerIn = 0;
- if (left.item == item) {
- left.item = 0;
- usedAnchors &= ~QQuickAnchors::LeftAnchor;
- }
- if (right.item == item) {
- right.item = 0;
- usedAnchors &= ~QQuickAnchors::RightAnchor;
- }
- if (top.item == item) {
- top.item = 0;
- usedAnchors &= ~QQuickAnchors::TopAnchor;
- }
- if (bottom.item == item) {
- bottom.item = 0;
- usedAnchors &= ~QQuickAnchors::BottomAnchor;
- }
- if (vCenter.item == item) {
- vCenter.item = 0;
- usedAnchors &= ~QQuickAnchors::VCenterAnchor;
- }
- if (hCenter.item == item) {
- hCenter.item = 0;
- usedAnchors &= ~QQuickAnchors::HCenterAnchor;
- }
- if (baseline.item == item) {
- baseline.item = 0;
- usedAnchors &= ~QQuickAnchors::BaselineAnchor;
- }
-}
-
-int QQuickAnchorsPrivate::calculateDependency(QQuickItem *controlItem)
-{
- QQuickItemPrivate::GeometryChangeTypes dependency = QQuickItemPrivate::NoChange;
-
- if (!controlItem || inDestructor)
- return dependency;
-
- if (fill == controlItem) {
- if ((controlItem == item->parentItem()))
- dependency |= QQuickItemPrivate::SizeChange;
- else //sibling
- dependency |= QQuickItemPrivate::GeometryChange;
- return dependency; //exit early
- }
-
- if (centerIn == controlItem) {
- if ((controlItem == item->parentItem()))
- dependency |= QQuickItemPrivate::SizeChange;
- else //sibling
- dependency |= QQuickItemPrivate::GeometryChange;
- return dependency; //exit early
- }
-
- if ((usedAnchors & QQuickAnchors::LeftAnchor && left.item == controlItem) ||
- (usedAnchors & QQuickAnchors::RightAnchor && right.item == controlItem) ||
- (usedAnchors & QQuickAnchors::HCenterAnchor && hCenter.item == controlItem)) {
- if ((controlItem == item->parentItem()))
- dependency |= QQuickItemPrivate::WidthChange;
- else //sibling
- dependency |= QFlags<QQuickItemPrivate::GeometryChangeType>(QQuickItemPrivate::XChange | QQuickItemPrivate::WidthChange);
- }
-
- if ((usedAnchors & QQuickAnchors::TopAnchor && top.item == controlItem) ||
- (usedAnchors & QQuickAnchors::BottomAnchor && bottom.item == controlItem) ||
- (usedAnchors & QQuickAnchors::VCenterAnchor && vCenter.item == controlItem) ||
- (usedAnchors & QQuickAnchors::BaselineAnchor && baseline.item == controlItem)) {
- if ((controlItem == item->parentItem()))
- dependency |= QQuickItemPrivate::HeightChange;
- else //sibling
- dependency |= QFlags<QQuickItemPrivate::GeometryChangeType>(QQuickItemPrivate::YChange | QQuickItemPrivate::HeightChange);
- }
-
- return dependency;
-}
-
-void QQuickAnchorsPrivate::addDepend(QQuickItem *item)
-{
- if (!item || !componentComplete)
- return;
-
- QQuickItemPrivate *p = QQuickItemPrivate::get(item);
- p->updateOrAddGeometryChangeListener(this, QFlags<QQuickItemPrivate::GeometryChangeType>(calculateDependency(item)));
-}
-
-void QQuickAnchorsPrivate::remDepend(QQuickItem *item)
-{
- if (!item || !componentComplete)
- return;
-
- QQuickItemPrivate *p = QQuickItemPrivate::get(item);
- p->updateOrRemoveGeometryChangeListener(this, QFlags<QQuickItemPrivate::GeometryChangeType>(calculateDependency(item)));
-}
-
-bool QQuickAnchors::mirrored()
-{
- Q_D(QQuickAnchors);
- return QQuickItemPrivate::get(d->item)->effectiveLayoutMirror;
-}
-
-bool QQuickAnchorsPrivate::isItemComplete() const
-{
- return componentComplete;
-}
-
-void QQuickAnchors::classBegin()
-{
- Q_D(QQuickAnchors);
- d->componentComplete = false;
-}
-
-void QQuickAnchors::componentComplete()
-{
- Q_D(QQuickAnchors);
- d->componentComplete = true;
-}
-
-void QQuickAnchorsPrivate::setItemHeight(qreal v)
-{
- updatingMe = true;
- item->setHeight(v);
- updatingMe = false;
-}
-
-void QQuickAnchorsPrivate::setItemWidth(qreal v)
-{
- updatingMe = true;
- item->setWidth(v);
- updatingMe = false;
-}
-
-void QQuickAnchorsPrivate::setItemX(qreal v)
-{
- updatingMe = true;
- item->setX(v);
- updatingMe = false;
-}
-
-void QQuickAnchorsPrivate::setItemY(qreal v)
-{
- updatingMe = true;
- item->setY(v);
- updatingMe = false;
-}
-
-void QQuickAnchorsPrivate::setItemPos(const QPointF &v)
-{
- updatingMe = true;
- item->setPos(v);
- updatingMe = false;
-}
-
-void QQuickAnchorsPrivate::setItemSize(const QSizeF &v)
-{
- updatingMe = true;
- item->setSize(v);
- updatingMe = false;
-}
-
-void QQuickAnchorsPrivate::updateMe()
-{
- if (updatingMe) {
- updatingMe = false;
- return;
- }
-
- update();
-}
-
-void QQuickAnchorsPrivate::updateOnComplete()
-{
- //optimization to only set initial dependencies once, at completion time
- QSet<QQuickItem *> dependencies;
- dependencies << fill << centerIn
- << left.item << right.item << hCenter.item
- << top.item << bottom.item << vCenter.item << baseline.item;
-
- foreach (QQuickItem *dependency, dependencies)
- addDepend(dependency);
-
- update();
-}
-
-
-void QQuickAnchorsPrivate::update()
-{
- fillChanged();
- centerInChanged();
- if (usedAnchors & QQuickAnchorLine::Horizontal_Mask)
- updateHorizontalAnchors();
- if (usedAnchors & QQuickAnchorLine::Vertical_Mask)
- updateVerticalAnchors();
-}
-
-void QQuickAnchorsPrivate::itemGeometryChanged(QQuickItem *, const QRectF &newG, const QRectF &oldG)
-{
- fillChanged();
- centerInChanged();
- if ((usedAnchors & QQuickAnchorLine::Horizontal_Mask) && (newG.x() != oldG.x() || newG.width() != oldG.width()))
- updateHorizontalAnchors();
- if ((usedAnchors & QQuickAnchorLine::Vertical_Mask) && (newG.y() != oldG.y() || newG.height() != oldG.height()))
- updateVerticalAnchors();
-}
-
-QQuickItem *QQuickAnchors::fill() const
-{
- Q_D(const QQuickAnchors);
- return d->fill;
-}
-
-void QQuickAnchors::setFill(QQuickItem *f)
-{
- Q_D(QQuickAnchors);
- if (d->fill == f)
- return;
-
- if (!f) {
- QQuickItem *oldFill = d->fill;
- d->fill = f;
- d->remDepend(oldFill);
- emit fillChanged();
- return;
- }
- if (f != d->item->parentItem() && f->parentItem() != d->item->parentItem()){
- qmlInfo(d->item) << tr("Cannot anchor to an item that isn't a parent or sibling.");
- return;
- }
- QQuickItem *oldFill = d->fill;
- d->fill = f;
- d->remDepend(oldFill);
- d->addDepend(d->fill);
- emit fillChanged();
- d->fillChanged();
-}
-
-void QQuickAnchors::resetFill()
-{
- setFill(0);
-}
-
-QQuickItem *QQuickAnchors::centerIn() const
-{
- Q_D(const QQuickAnchors);
- return d->centerIn;
-}
-
-void QQuickAnchors::setCenterIn(QQuickItem* c)
-{
- Q_D(QQuickAnchors);
- if (d->centerIn == c)
- return;
-
- if (!c) {
- QQuickItem *oldCI = d->centerIn;
- d->centerIn = c;
- d->remDepend(oldCI);
- emit centerInChanged();
- return;
- }
- if (c != d->item->parentItem() && c->parentItem() != d->item->parentItem()){
- qmlInfo(d->item) << tr("Cannot anchor to an item that isn't a parent or sibling.");
- return;
- }
- QQuickItem *oldCI = d->centerIn;
- d->centerIn = c;
- d->remDepend(oldCI);
- d->addDepend(d->centerIn);
- emit centerInChanged();
- d->centerInChanged();
-}
-
-void QQuickAnchors::resetCenterIn()
-{
- setCenterIn(0);
-}
-
-bool QQuickAnchorsPrivate::calcStretch(const QQuickAnchorLine &edge1,
- const QQuickAnchorLine &edge2,
- qreal offset1,
- qreal offset2,
- QQuickAnchorLine::AnchorLine line,
- qreal &stretch)
-{
- bool edge1IsParent = (edge1.item == item->parentItem());
- bool edge2IsParent = (edge2.item == item->parentItem());
- bool edge1IsSibling = (edge1.item->parentItem() == item->parentItem());
- bool edge2IsSibling = (edge2.item->parentItem() == item->parentItem());
-
- bool invalid = false;
- if ((edge2IsParent && edge1IsParent) || (edge2IsSibling && edge1IsSibling)) {
- stretch = (position(edge2.item, edge2.anchorLine) + offset2)
- - (position(edge1.item, edge1.anchorLine) + offset1);
- } else if (edge2IsParent && edge1IsSibling) {
- stretch = (position(edge2.item, edge2.anchorLine) + offset2)
- - (position(item->parentItem(), line)
- + position(edge1.item, edge1.anchorLine) + offset1);
- } else if (edge2IsSibling && edge1IsParent) {
- stretch = (position(item->parentItem(), line) + position(edge2.item, edge2.anchorLine) + offset2)
- - (position(edge1.item, edge1.anchorLine) + offset1);
- } else
- invalid = true;
-
- return invalid;
-}
-
-void QQuickAnchorsPrivate::updateVerticalAnchors()
-{
- if (fill || centerIn || !isItemComplete())
- return;
-
- if (updatingVerticalAnchor < 2) {
- ++updatingVerticalAnchor;
- if (usedAnchors & QQuickAnchors::TopAnchor) {
- //Handle stretching
- bool invalid = true;
- qreal height = 0.0;
- if (usedAnchors & QQuickAnchors::BottomAnchor) {
- invalid = calcStretch(top, bottom, topMargin, -bottomMargin, QQuickAnchorLine::Top, height);
- } else if (usedAnchors & QQuickAnchors::VCenterAnchor) {
- invalid = calcStretch(top, vCenter, topMargin, vCenterOffset, QQuickAnchorLine::Top, height);
- height *= 2;
- }
- if (!invalid)
- setItemHeight(height);
-
- //Handle top
- if (top.item == item->parentItem()) {
- setItemY(adjustedPosition(top.item, top.anchorLine) + topMargin);
- } else if (top.item->parentItem() == item->parentItem()) {
- setItemY(position(top.item, top.anchorLine) + topMargin);
- }
- } else if (usedAnchors & QQuickAnchors::BottomAnchor) {
- //Handle stretching (top + bottom case is handled above)
- if (usedAnchors & QQuickAnchors::VCenterAnchor) {
- qreal height = 0.0;
- bool invalid = calcStretch(vCenter, bottom, vCenterOffset, -bottomMargin,
- QQuickAnchorLine::Top, height);
- if (!invalid)
- setItemHeight(height*2);
- }
-
- //Handle bottom
- if (bottom.item == item->parentItem()) {
- setItemY(adjustedPosition(bottom.item, bottom.anchorLine) - item->height() - bottomMargin);
- } else if (bottom.item->parentItem() == item->parentItem()) {
- setItemY(position(bottom.item, bottom.anchorLine) - item->height() - bottomMargin);
- }
- } else if (usedAnchors & QQuickAnchors::VCenterAnchor) {
- //(stetching handled above)
-
- //Handle vCenter
- if (vCenter.item == item->parentItem()) {
- setItemY(adjustedPosition(vCenter.item, vCenter.anchorLine)
- - vcenter(item) + vCenterOffset);
- } else if (vCenter.item->parentItem() == item->parentItem()) {
- setItemY(position(vCenter.item, vCenter.anchorLine) - vcenter(item) + vCenterOffset);
- }
- } else if (usedAnchors & QQuickAnchors::BaselineAnchor) {
- //Handle baseline
- if (baseline.item == item->parentItem()) {
- setItemY(adjustedPosition(baseline.item, baseline.anchorLine) - item->baselineOffset() + baselineOffset);
- } else if (baseline.item->parentItem() == item->parentItem()) {
- setItemY(position(baseline.item, baseline.anchorLine) - item->baselineOffset() + baselineOffset);
- }
- }
- --updatingVerticalAnchor;
- } else {
- // ### Make this certain :)
- qmlInfo(item) << QQuickAnchors::tr("Possible anchor loop detected on vertical anchor.");
- }
-}
-
-inline QQuickAnchorLine::AnchorLine reverseAnchorLine(QQuickAnchorLine::AnchorLine anchorLine)
-{
- if (anchorLine == QQuickAnchorLine::Left) {
- return QQuickAnchorLine::Right;
- } else if (anchorLine == QQuickAnchorLine::Right) {
- return QQuickAnchorLine::Left;
- } else {
- return anchorLine;
- }
-}
-
-void QQuickAnchorsPrivate::updateHorizontalAnchors()
-{
- Q_Q(QQuickAnchors);
- if (fill || centerIn || !isItemComplete())
- return;
-
- if (updatingHorizontalAnchor < 3) {
- ++updatingHorizontalAnchor;
- qreal effectiveRightMargin, effectiveLeftMargin, effectiveHorizontalCenterOffset;
- QQuickAnchorLine effectiveLeft, effectiveRight, effectiveHorizontalCenter;
- QQuickAnchors::Anchor effectiveLeftAnchor, effectiveRightAnchor;
- if (q->mirrored()) {
- effectiveLeftAnchor = QQuickAnchors::RightAnchor;
- effectiveRightAnchor = QQuickAnchors::LeftAnchor;
- effectiveLeft.item = right.item;
- effectiveLeft.anchorLine = reverseAnchorLine(right.anchorLine);
- effectiveRight.item = left.item;
- effectiveRight.anchorLine = reverseAnchorLine(left.anchorLine);
- effectiveHorizontalCenter.item = hCenter.item;
- effectiveHorizontalCenter.anchorLine = reverseAnchorLine(hCenter.anchorLine);
- effectiveLeftMargin = rightMargin;
- effectiveRightMargin = leftMargin;
- effectiveHorizontalCenterOffset = -hCenterOffset;
- } else {
- effectiveLeftAnchor = QQuickAnchors::LeftAnchor;
- effectiveRightAnchor = QQuickAnchors::RightAnchor;
- effectiveLeft = left;
- effectiveRight = right;
- effectiveHorizontalCenter = hCenter;
- effectiveLeftMargin = leftMargin;
- effectiveRightMargin = rightMargin;
- effectiveHorizontalCenterOffset = hCenterOffset;
- }
-
- if (usedAnchors & effectiveLeftAnchor) {
- //Handle stretching
- bool invalid = true;
- qreal width = 0.0;
- if (usedAnchors & effectiveRightAnchor) {
- invalid = calcStretch(effectiveLeft, effectiveRight, effectiveLeftMargin, -effectiveRightMargin, QQuickAnchorLine::Left, width);
- } else if (usedAnchors & QQuickAnchors::HCenterAnchor) {
- invalid = calcStretch(effectiveLeft, effectiveHorizontalCenter, effectiveLeftMargin, effectiveHorizontalCenterOffset, QQuickAnchorLine::Left, width);
- width *= 2;
- }
- if (!invalid)
- setItemWidth(width);
-
- //Handle left
- if (effectiveLeft.item == item->parentItem()) {
- setItemX(adjustedPosition(effectiveLeft.item, effectiveLeft.anchorLine) + effectiveLeftMargin);
- } else if (effectiveLeft.item->parentItem() == item->parentItem()) {
- setItemX(position(effectiveLeft.item, effectiveLeft.anchorLine) + effectiveLeftMargin);
- }
- } else if (usedAnchors & effectiveRightAnchor) {
- //Handle stretching (left + right case is handled in updateLeftAnchor)
- if (usedAnchors & QQuickAnchors::HCenterAnchor) {
- qreal width = 0.0;
- bool invalid = calcStretch(effectiveHorizontalCenter, effectiveRight, effectiveHorizontalCenterOffset, -effectiveRightMargin,
- QQuickAnchorLine::Left, width);
- if (!invalid)
- setItemWidth(width*2);
- }
-
- //Handle right
- if (effectiveRight.item == item->parentItem()) {
- setItemX(adjustedPosition(effectiveRight.item, effectiveRight.anchorLine) - item->width() - effectiveRightMargin);
- } else if (effectiveRight.item->parentItem() == item->parentItem()) {
- setItemX(position(effectiveRight.item, effectiveRight.anchorLine) - item->width() - effectiveRightMargin);
- }
- } else if (usedAnchors & QQuickAnchors::HCenterAnchor) {
- //Handle hCenter
- if (effectiveHorizontalCenter.item == item->parentItem()) {
- setItemX(adjustedPosition(effectiveHorizontalCenter.item, effectiveHorizontalCenter.anchorLine) - hcenter(item) + effectiveHorizontalCenterOffset);
- } else if (effectiveHorizontalCenter.item->parentItem() == item->parentItem()) {
- setItemX(position(effectiveHorizontalCenter.item, effectiveHorizontalCenter.anchorLine) - hcenter(item) + effectiveHorizontalCenterOffset);
- }
- }
- --updatingHorizontalAnchor;
- } else {
- // ### Make this certain :)
- qmlInfo(item) << QQuickAnchors::tr("Possible anchor loop detected on horizontal anchor.");
- }
-}
-
-QQuickAnchorLine QQuickAnchors::top() const
-{
- Q_D(const QQuickAnchors);
- return d->top;
-}
-
-void QQuickAnchors::setTop(const QQuickAnchorLine &edge)
-{
- Q_D(QQuickAnchors);
- if (!d->checkVAnchorValid(edge) || d->top == edge)
- return;
-
- d->usedAnchors |= TopAnchor;
-
- if (!d->checkVValid()) {
- d->usedAnchors &= ~TopAnchor;
- return;
- }
-
- QQuickItem *oldTop = d->top.item;
- d->top = edge;
- d->remDepend(oldTop);
- d->addDepend(d->top.item);
- emit topChanged();
- d->updateVerticalAnchors();
-}
-
-void QQuickAnchors::resetTop()
-{
- Q_D(QQuickAnchors);
- d->usedAnchors &= ~TopAnchor;
- d->remDepend(d->top.item);
- d->top = QQuickAnchorLine();
- emit topChanged();
- d->updateVerticalAnchors();
-}
-
-QQuickAnchorLine QQuickAnchors::bottom() const
-{
- Q_D(const QQuickAnchors);
- return d->bottom;
-}
-
-void QQuickAnchors::setBottom(const QQuickAnchorLine &edge)
-{
- Q_D(QQuickAnchors);
- if (!d->checkVAnchorValid(edge) || d->bottom == edge)
- return;
-
- d->usedAnchors |= BottomAnchor;
-
- if (!d->checkVValid()) {
- d->usedAnchors &= ~BottomAnchor;
- return;
- }
-
- QQuickItem *oldBottom = d->bottom.item;
- d->bottom = edge;
- d->remDepend(oldBottom);
- d->addDepend(d->bottom.item);
- emit bottomChanged();
- d->updateVerticalAnchors();
-}
-
-void QQuickAnchors::resetBottom()
-{
- Q_D(QQuickAnchors);
- d->usedAnchors &= ~BottomAnchor;
- d->remDepend(d->bottom.item);
- d->bottom = QQuickAnchorLine();
- emit bottomChanged();
- d->updateVerticalAnchors();
-}
-
-QQuickAnchorLine QQuickAnchors::verticalCenter() const
-{
- Q_D(const QQuickAnchors);
- return d->vCenter;
-}
-
-void QQuickAnchors::setVerticalCenter(const QQuickAnchorLine &edge)
-{
- Q_D(QQuickAnchors);
- if (!d->checkVAnchorValid(edge) || d->vCenter == edge)
- return;
-
- d->usedAnchors |= VCenterAnchor;
-
- if (!d->checkVValid()) {
- d->usedAnchors &= ~VCenterAnchor;
- return;
- }
-
- QQuickItem *oldVCenter = d->vCenter.item;
- d->vCenter = edge;
- d->remDepend(oldVCenter);
- d->addDepend(d->vCenter.item);
- emit verticalCenterChanged();
- d->updateVerticalAnchors();
-}
-
-void QQuickAnchors::resetVerticalCenter()
-{
- Q_D(QQuickAnchors);
- d->usedAnchors &= ~VCenterAnchor;
- d->remDepend(d->vCenter.item);
- d->vCenter = QQuickAnchorLine();
- emit verticalCenterChanged();
- d->updateVerticalAnchors();
-}
-
-QQuickAnchorLine QQuickAnchors::baseline() const
-{
- Q_D(const QQuickAnchors);
- return d->baseline;
-}
-
-void QQuickAnchors::setBaseline(const QQuickAnchorLine &edge)
-{
- Q_D(QQuickAnchors);
- if (!d->checkVAnchorValid(edge) || d->baseline == edge)
- return;
-
- d->usedAnchors |= BaselineAnchor;
-
- if (!d->checkVValid()) {
- d->usedAnchors &= ~BaselineAnchor;
- return;
- }
-
- QQuickItem *oldBaseline = d->baseline.item;
- d->baseline = edge;
- d->remDepend(oldBaseline);
- d->addDepend(d->baseline.item);
- emit baselineChanged();
- d->updateVerticalAnchors();
-}
-
-void QQuickAnchors::resetBaseline()
-{
- Q_D(QQuickAnchors);
- d->usedAnchors &= ~BaselineAnchor;
- d->remDepend(d->baseline.item);
- d->baseline = QQuickAnchorLine();
- emit baselineChanged();
- d->updateVerticalAnchors();
-}
-
-QQuickAnchorLine QQuickAnchors::left() const
-{
- Q_D(const QQuickAnchors);
- return d->left;
-}
-
-void QQuickAnchors::setLeft(const QQuickAnchorLine &edge)
-{
- Q_D(QQuickAnchors);
- if (!d->checkHAnchorValid(edge) || d->left == edge)
- return;
-
- d->usedAnchors |= LeftAnchor;
-
- if (!d->checkHValid()) {
- d->usedAnchors &= ~LeftAnchor;
- return;
- }
-
- QQuickItem *oldLeft = d->left.item;
- d->left = edge;
- d->remDepend(oldLeft);
- d->addDepend(d->left.item);
- emit leftChanged();
- d->updateHorizontalAnchors();
-}
-
-void QQuickAnchors::resetLeft()
-{
- Q_D(QQuickAnchors);
- d->usedAnchors &= ~LeftAnchor;
- d->remDepend(d->left.item);
- d->left = QQuickAnchorLine();
- emit leftChanged();
- d->updateHorizontalAnchors();
-}
-
-QQuickAnchorLine QQuickAnchors::right() const
-{
- Q_D(const QQuickAnchors);
- return d->right;
-}
-
-void QQuickAnchors::setRight(const QQuickAnchorLine &edge)
-{
- Q_D(QQuickAnchors);
- if (!d->checkHAnchorValid(edge) || d->right == edge)
- return;
-
- d->usedAnchors |= RightAnchor;
-
- if (!d->checkHValid()) {
- d->usedAnchors &= ~RightAnchor;
- return;
- }
-
- QQuickItem *oldRight = d->right.item;
- d->right = edge;
- d->remDepend(oldRight);
- d->addDepend(d->right.item);
- emit rightChanged();
- d->updateHorizontalAnchors();
-}
-
-void QQuickAnchors::resetRight()
-{
- Q_D(QQuickAnchors);
- d->usedAnchors &= ~RightAnchor;
- d->remDepend(d->right.item);
- d->right = QQuickAnchorLine();
- emit rightChanged();
- d->updateHorizontalAnchors();
-}
-
-QQuickAnchorLine QQuickAnchors::horizontalCenter() const
-{
- Q_D(const QQuickAnchors);
- return d->hCenter;
-}
-
-void QQuickAnchors::setHorizontalCenter(const QQuickAnchorLine &edge)
-{
- Q_D(QQuickAnchors);
- if (!d->checkHAnchorValid(edge) || d->hCenter == edge)
- return;
-
- d->usedAnchors |= HCenterAnchor;
-
- if (!d->checkHValid()) {
- d->usedAnchors &= ~HCenterAnchor;
- return;
- }
-
- QQuickItem *oldHCenter = d->hCenter.item;
- d->hCenter = edge;
- d->remDepend(oldHCenter);
- d->addDepend(d->hCenter.item);
- emit horizontalCenterChanged();
- d->updateHorizontalAnchors();
-}
-
-void QQuickAnchors::resetHorizontalCenter()
-{
- Q_D(QQuickAnchors);
- d->usedAnchors &= ~HCenterAnchor;
- d->remDepend(d->hCenter.item);
- d->hCenter = QQuickAnchorLine();
- emit horizontalCenterChanged();
- d->updateHorizontalAnchors();
-}
-
-qreal QQuickAnchors::leftMargin() const
-{
- Q_D(const QQuickAnchors);
- return d->leftMargin;
-}
-
-void QQuickAnchors::setLeftMargin(qreal offset)
-{
- Q_D(QQuickAnchors);
- if (d->leftMargin == offset)
- return;
- d->leftMargin = offset;
- if (d->fill)
- d->fillChanged();
- else
- d->updateHorizontalAnchors();
- emit leftMarginChanged();
-}
-
-qreal QQuickAnchors::rightMargin() const
-{
- Q_D(const QQuickAnchors);
- return d->rightMargin;
-}
-
-void QQuickAnchors::setRightMargin(qreal offset)
-{
- Q_D(QQuickAnchors);
- if (d->rightMargin == offset)
- return;
- d->rightMargin = offset;
- if (d->fill)
- d->fillChanged();
- else
- d->updateHorizontalAnchors();
- emit rightMarginChanged();
-}
-
-qreal QQuickAnchors::margins() const
-{
- Q_D(const QQuickAnchors);
- return d->margins;
-}
-
-void QQuickAnchors::setMargins(qreal offset)
-{
- Q_D(QQuickAnchors);
- if (d->margins == offset)
- return;
- //###Is it significantly faster to set them directly so we can call fillChanged only once?
- if (!d->rightMargin || d->rightMargin == d->margins)
- setRightMargin(offset);
- if (!d->leftMargin || d->leftMargin == d->margins)
- setLeftMargin(offset);
- if (!d->topMargin || d->topMargin == d->margins)
- setTopMargin(offset);
- if (!d->bottomMargin || d->bottomMargin == d->margins)
- setBottomMargin(offset);
- d->margins = offset;
- emit marginsChanged();
-
-}
-
-qreal QQuickAnchors::horizontalCenterOffset() const
-{
- Q_D(const QQuickAnchors);
- return d->hCenterOffset;
-}
-
-void QQuickAnchors::setHorizontalCenterOffset(qreal offset)
-{
- Q_D(QQuickAnchors);
- if (d->hCenterOffset == offset)
- return;
- d->hCenterOffset = offset;
- if (d->centerIn)
- d->centerInChanged();
- else
- d->updateHorizontalAnchors();
- emit horizontalCenterOffsetChanged();
-}
-
-qreal QQuickAnchors::topMargin() const
-{
- Q_D(const QQuickAnchors);
- return d->topMargin;
-}
-
-void QQuickAnchors::setTopMargin(qreal offset)
-{
- Q_D(QQuickAnchors);
- if (d->topMargin == offset)
- return;
- d->topMargin = offset;
- if (d->fill)
- d->fillChanged();
- else
- d->updateVerticalAnchors();
- emit topMarginChanged();
-}
-
-qreal QQuickAnchors::bottomMargin() const
-{
- Q_D(const QQuickAnchors);
- return d->bottomMargin;
-}
-
-void QQuickAnchors::setBottomMargin(qreal offset)
-{
- Q_D(QQuickAnchors);
- if (d->bottomMargin == offset)
- return;
- d->bottomMargin = offset;
- if (d->fill)
- d->fillChanged();
- else
- d->updateVerticalAnchors();
- emit bottomMarginChanged();
-}
-
-qreal QQuickAnchors::verticalCenterOffset() const
-{
- Q_D(const QQuickAnchors);
- return d->vCenterOffset;
-}
-
-void QQuickAnchors::setVerticalCenterOffset(qreal offset)
-{
- Q_D(QQuickAnchors);
- if (d->vCenterOffset == offset)
- return;
- d->vCenterOffset = offset;
- if (d->centerIn)
- d->centerInChanged();
- else
- d->updateVerticalAnchors();
- emit verticalCenterOffsetChanged();
-}
-
-qreal QQuickAnchors::baselineOffset() const
-{
- Q_D(const QQuickAnchors);
- return d->baselineOffset;
-}
-
-void QQuickAnchors::setBaselineOffset(qreal offset)
-{
- Q_D(QQuickAnchors);
- if (d->baselineOffset == offset)
- return;
- d->baselineOffset = offset;
- d->updateVerticalAnchors();
- emit baselineOffsetChanged();
-}
-
-QQuickAnchors::Anchors QQuickAnchors::usedAnchors() const
-{
- Q_D(const QQuickAnchors);
- return d->usedAnchors;
-}
-
-bool QQuickAnchorsPrivate::checkHValid() const
-{
- if (usedAnchors & QQuickAnchors::LeftAnchor &&
- usedAnchors & QQuickAnchors::RightAnchor &&
- usedAnchors & QQuickAnchors::HCenterAnchor) {
- qmlInfo(item) << QQuickAnchors::tr("Cannot specify left, right, and hcenter anchors.");
- return false;
- }
-
- return true;
-}
-
-bool QQuickAnchorsPrivate::checkHAnchorValid(QQuickAnchorLine anchor) const
-{
- if (!anchor.item) {
- qmlInfo(item) << QQuickAnchors::tr("Cannot anchor to a null item.");
- return false;
- } else if (anchor.anchorLine & QQuickAnchorLine::Vertical_Mask) {
- qmlInfo(item) << QQuickAnchors::tr("Cannot anchor a horizontal edge to a vertical edge.");
- return false;
- } else if (anchor.item != item->parentItem() && anchor.item->parentItem() != item->parentItem()){
- qmlInfo(item) << QQuickAnchors::tr("Cannot anchor to an item that isn't a parent or sibling.");
- return false;
- } else if (anchor.item == item) {
- qmlInfo(item) << QQuickAnchors::tr("Cannot anchor item to self.");
- return false;
- }
-
- return true;
-}
-
-bool QQuickAnchorsPrivate::checkVValid() const
-{
- if (usedAnchors & QQuickAnchors::TopAnchor &&
- usedAnchors & QQuickAnchors::BottomAnchor &&
- usedAnchors & QQuickAnchors::VCenterAnchor) {
- qmlInfo(item) << QQuickAnchors::tr("Cannot specify top, bottom, and vcenter anchors.");
- return false;
- } else if (usedAnchors & QQuickAnchors::BaselineAnchor &&
- (usedAnchors & QQuickAnchors::TopAnchor ||
- usedAnchors & QQuickAnchors::BottomAnchor ||
- usedAnchors & QQuickAnchors::VCenterAnchor)) {
- qmlInfo(item) << QQuickAnchors::tr("Baseline anchor cannot be used in conjunction with top, bottom, or vcenter anchors.");
- return false;
- }
-
- return true;
-}
-
-bool QQuickAnchorsPrivate::checkVAnchorValid(QQuickAnchorLine anchor) const
-{
- if (!anchor.item) {
- qmlInfo(item) << QQuickAnchors::tr("Cannot anchor to a null item.");
- return false;
- } else if (anchor.anchorLine & QQuickAnchorLine::Horizontal_Mask) {
- qmlInfo(item) << QQuickAnchors::tr("Cannot anchor a vertical edge to a horizontal edge.");
- return false;
- } else if (anchor.item != item->parentItem() && anchor.item->parentItem() != item->parentItem()){
- qmlInfo(item) << QQuickAnchors::tr("Cannot anchor to an item that isn't a parent or sibling.");
- return false;
- } else if (anchor.item == item){
- qmlInfo(item) << QQuickAnchors::tr("Cannot anchor item to self.");
- return false;
- }
-
- return true;
-}
-
-QT_END_NAMESPACE
-
-#include <moc_qquickanchors_p.cpp>
-
diff --git a/src/declarative/items/qquickanchors_p.h b/src/declarative/items/qquickanchors_p.h
deleted file mode 100644
index 5c66c2e17d..0000000000
--- a/src/declarative/items/qquickanchors_p.h
+++ /dev/null
@@ -1,201 +0,0 @@
-// Commit: 2c7cab4172f1acc86fd49345a2847417e162f2c3
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKANCHORS_P_H
-#define QQUICKANCHORS_P_H
-
-#include <qdeclarative.h>
-
-#include <QtCore/QObject>
-
-#include <private/qdeclarativeglobal_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickItem;
-class QQuickAnchorsPrivate;
-class QQuickAnchorLine;
-class Q_DECLARATIVE_PRIVATE_EXPORT QQuickAnchors : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QQuickAnchorLine left READ left WRITE setLeft RESET resetLeft NOTIFY leftChanged)
- Q_PROPERTY(QQuickAnchorLine right READ right WRITE setRight RESET resetRight NOTIFY rightChanged)
- Q_PROPERTY(QQuickAnchorLine horizontalCenter READ horizontalCenter WRITE setHorizontalCenter RESET resetHorizontalCenter NOTIFY horizontalCenterChanged)
- Q_PROPERTY(QQuickAnchorLine top READ top WRITE setTop RESET resetTop NOTIFY topChanged)
- Q_PROPERTY(QQuickAnchorLine bottom READ bottom WRITE setBottom RESET resetBottom NOTIFY bottomChanged)
- Q_PROPERTY(QQuickAnchorLine verticalCenter READ verticalCenter WRITE setVerticalCenter RESET resetVerticalCenter NOTIFY verticalCenterChanged)
- Q_PROPERTY(QQuickAnchorLine baseline READ baseline WRITE setBaseline RESET resetBaseline NOTIFY baselineChanged)
- Q_PROPERTY(qreal margins READ margins WRITE setMargins NOTIFY marginsChanged)
- Q_PROPERTY(qreal leftMargin READ leftMargin WRITE setLeftMargin NOTIFY leftMarginChanged)
- Q_PROPERTY(qreal rightMargin READ rightMargin WRITE setRightMargin NOTIFY rightMarginChanged)
- Q_PROPERTY(qreal horizontalCenterOffset READ horizontalCenterOffset WRITE setHorizontalCenterOffset NOTIFY horizontalCenterOffsetChanged)
- Q_PROPERTY(qreal topMargin READ topMargin WRITE setTopMargin NOTIFY topMarginChanged)
- Q_PROPERTY(qreal bottomMargin READ bottomMargin WRITE setBottomMargin NOTIFY bottomMarginChanged)
- Q_PROPERTY(qreal verticalCenterOffset READ verticalCenterOffset WRITE setVerticalCenterOffset NOTIFY verticalCenterOffsetChanged)
- Q_PROPERTY(qreal baselineOffset READ baselineOffset WRITE setBaselineOffset NOTIFY baselineOffsetChanged)
- Q_PROPERTY(QQuickItem *fill READ fill WRITE setFill RESET resetFill NOTIFY fillChanged)
- Q_PROPERTY(QQuickItem *centerIn READ centerIn WRITE setCenterIn RESET resetCenterIn NOTIFY centerInChanged)
- Q_PROPERTY(bool mirrored READ mirrored NOTIFY mirroredChanged)
-
-public:
- QQuickAnchors(QQuickItem *item, QObject *parent=0);
- virtual ~QQuickAnchors();
-
- enum Anchor {
- LeftAnchor = 0x01,
- RightAnchor = 0x02,
- TopAnchor = 0x04,
- BottomAnchor = 0x08,
- HCenterAnchor = 0x10,
- VCenterAnchor = 0x20,
- BaselineAnchor = 0x40,
- Horizontal_Mask = LeftAnchor | RightAnchor | HCenterAnchor,
- Vertical_Mask = TopAnchor | BottomAnchor | VCenterAnchor | BaselineAnchor
- };
- Q_DECLARE_FLAGS(Anchors, Anchor)
-
- QQuickAnchorLine left() const;
- void setLeft(const QQuickAnchorLine &edge);
- void resetLeft();
-
- QQuickAnchorLine right() const;
- void setRight(const QQuickAnchorLine &edge);
- void resetRight();
-
- QQuickAnchorLine horizontalCenter() const;
- void setHorizontalCenter(const QQuickAnchorLine &edge);
- void resetHorizontalCenter();
-
- QQuickAnchorLine top() const;
- void setTop(const QQuickAnchorLine &edge);
- void resetTop();
-
- QQuickAnchorLine bottom() const;
- void setBottom(const QQuickAnchorLine &edge);
- void resetBottom();
-
- QQuickAnchorLine verticalCenter() const;
- void setVerticalCenter(const QQuickAnchorLine &edge);
- void resetVerticalCenter();
-
- QQuickAnchorLine baseline() const;
- void setBaseline(const QQuickAnchorLine &edge);
- void resetBaseline();
-
- qreal leftMargin() const;
- void setLeftMargin(qreal);
-
- qreal rightMargin() const;
- void setRightMargin(qreal);
-
- qreal horizontalCenterOffset() const;
- void setHorizontalCenterOffset(qreal);
-
- qreal topMargin() const;
- void setTopMargin(qreal);
-
- qreal bottomMargin() const;
- void setBottomMargin(qreal);
-
- qreal margins() const;
- void setMargins(qreal);
-
- qreal verticalCenterOffset() const;
- void setVerticalCenterOffset(qreal);
-
- qreal baselineOffset() const;
- void setBaselineOffset(qreal);
-
- QQuickItem *fill() const;
- void setFill(QQuickItem *);
- void resetFill();
-
- QQuickItem *centerIn() const;
- void setCenterIn(QQuickItem *);
- void resetCenterIn();
-
- Anchors usedAnchors() const;
-
- bool mirrored();
-
- void classBegin();
- void componentComplete();
-
-Q_SIGNALS:
- void leftChanged();
- void rightChanged();
- void topChanged();
- void bottomChanged();
- void verticalCenterChanged();
- void horizontalCenterChanged();
- void baselineChanged();
- void fillChanged();
- void centerInChanged();
- void leftMarginChanged();
- void rightMarginChanged();
- void topMarginChanged();
- void bottomMarginChanged();
- void marginsChanged();
- void verticalCenterOffsetChanged();
- void horizontalCenterOffsetChanged();
- void baselineOffsetChanged();
- void mirroredChanged();
-
-private:
- friend class QQuickItemPrivate;
- Q_DISABLE_COPY(QQuickAnchors)
- Q_DECLARE_PRIVATE(QQuickAnchors)
-};
-Q_DECLARE_OPERATORS_FOR_FLAGS(QQuickAnchors::Anchors)
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickAnchors)
-
-QT_END_HEADER
-
-#endif // QQUICKANCHORS_P_H
diff --git a/src/declarative/items/qquickanchors_p_p.h b/src/declarative/items/qquickanchors_p_p.h
deleted file mode 100644
index 50d55b081f..0000000000
--- a/src/declarative/items/qquickanchors_p_p.h
+++ /dev/null
@@ -1,176 +0,0 @@
-// Commit: 2c7cab4172f1acc86fd49345a2847417e162f2c3
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKANCHORS_P_P_H
-#define QQUICKANCHORS_P_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 "qquickanchors_p.h"
-#include "qquickitemchangelistener_p.h"
-#include <private/qobject_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickAnchorLine
-{
-public:
- QQuickAnchorLine() : item(0), anchorLine(Invalid) {}
-
- enum AnchorLine {
- Invalid = 0x0,
- Left = 0x01,
- Right = 0x02,
- Top = 0x04,
- Bottom = 0x08,
- HCenter = 0x10,
- VCenter = 0x20,
- Baseline = 0x40,
- Horizontal_Mask = Left | Right | HCenter,
- Vertical_Mask = Top | Bottom | VCenter | Baseline
- };
-
- QQuickItem *item;
- AnchorLine anchorLine;
-};
-
-inline bool operator==(const QQuickAnchorLine& a, const QQuickAnchorLine& b)
-{
- return a.item == b.item && a.anchorLine == b.anchorLine;
-}
-
-class QQuickAnchorsPrivate : public QObjectPrivate, public QQuickItemChangeListener
-{
- Q_DECLARE_PUBLIC(QQuickAnchors)
-public:
- QQuickAnchorsPrivate(QQuickItem *i)
- : componentComplete(true), updatingMe(false), inDestructor(false), updatingHorizontalAnchor(0),
- updatingVerticalAnchor(0), updatingFill(0), updatingCenterIn(0), item(i), usedAnchors(0), fill(0),
- centerIn(0), leftMargin(0), rightMargin(0), topMargin(0), bottomMargin(0),
- margins(0), vCenterOffset(0), hCenterOffset(0), baselineOffset(0)
- {
- }
-
- void clearItem(QQuickItem *);
-
- int calculateDependency(QQuickItem *);
- void addDepend(QQuickItem *);
- void remDepend(QQuickItem *);
- bool isItemComplete() const;
-
- bool componentComplete:1;
- bool updatingMe:1;
- bool inDestructor:1;
- uint updatingHorizontalAnchor:2;
- uint updatingVerticalAnchor:2;
- uint updatingFill:2;
- uint updatingCenterIn:2;
-
- void setItemHeight(qreal);
- void setItemWidth(qreal);
- void setItemX(qreal);
- void setItemY(qreal);
- void setItemPos(const QPointF &);
- void setItemSize(const QSizeF &);
-
- void update();
- void updateOnComplete();
- void updateMe();
-
- // QQuickItemGeometryListener interface
- void itemGeometryChanged(QQuickItem *, const QRectF &, const QRectF &);
- QQuickAnchorsPrivate *anchorPrivate() { return this; }
-
- bool checkHValid() const;
- bool checkVValid() const;
- bool checkHAnchorValid(QQuickAnchorLine anchor) const;
- bool checkVAnchorValid(QQuickAnchorLine anchor) const;
- bool calcStretch(const QQuickAnchorLine &edge1, const QQuickAnchorLine &edge2, qreal offset1, qreal offset2, QQuickAnchorLine::AnchorLine line, qreal &stretch);
-
- bool isMirrored() const;
- void updateHorizontalAnchors();
- void updateVerticalAnchors();
- void fillChanged();
- void centerInChanged();
-
- QQuickItem *item;
- QQuickAnchors::Anchors usedAnchors;
-
- QQuickItem *fill;
- QQuickItem *centerIn;
-
- QQuickAnchorLine left;
- QQuickAnchorLine right;
- QQuickAnchorLine top;
- QQuickAnchorLine bottom;
- QQuickAnchorLine vCenter;
- QQuickAnchorLine hCenter;
- QQuickAnchorLine baseline;
-
- qreal leftMargin;
- qreal rightMargin;
- qreal topMargin;
- qreal bottomMargin;
- qreal margins;
- qreal vCenterOffset;
- qreal hCenterOffset;
- qreal baselineOffset;
-
- static inline QQuickAnchorsPrivate *get(QQuickAnchors *o) {
- return static_cast<QQuickAnchorsPrivate *>(QObjectPrivate::get(o));
- }
-};
-
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(QQuickAnchorLine)
-
-#endif
diff --git a/src/declarative/items/qquickanimatedimage.cpp b/src/declarative/items/qquickanimatedimage.cpp
deleted file mode 100644
index 61447c87e2..0000000000
--- a/src/declarative/items/qquickanimatedimage.cpp
+++ /dev/null
@@ -1,397 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickanimatedimage_p.h"
-#include "qquickanimatedimage_p_p.h"
-
-#ifndef QT_NO_MOVIE
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtGui/qmovie.h>
-#include <QtNetwork/qnetworkrequest.h>
-#include <QtNetwork/qnetworkreply.h>
-
-#include <private/qdeclarativeengine_p.h>
-
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass AnimatedImage QQuickAnimatedImage
- \inqmlmodule QtQuick 2
- \inherits Image
- \ingroup basic-visual-elements
-
- The AnimatedImage element extends the features of the \l Image element, providing
- a way to play animations stored as images containing a series of frames,
- such as those stored in GIF files.
-
- Information about the current frame and total length of the animation can be
- obtained using the \l currentFrame and \l frameCount properties. You can
- start, pause and stop the animation by changing the values of the \l playing
- and \l paused properties.
-
- The full list of supported formats can be determined with QMovie::supportedFormats().
-
- \section1 Example Usage
-
- \beginfloatleft
- \image animatedimageitem.gif
- \endfloat
-
- The following QML shows how to display an animated image and obtain information
- about its state, such as the current frame and total number of frames.
- The result is an animated image with a simple progress indicator underneath it.
-
- \bold Note: Unlike images, animated images are not cached or shared internally.
-
- \clearfloat
- \snippet doc/src/snippets/declarative/animatedimage.qml document
-
- \sa BorderImage, Image
-*/
-
-/*!
- \qmlproperty url QtQuick2::AnimatedImage::source
-
- This property holds the URL that refers to the source image.
-
- AnimatedImage can handle any image format supported by Qt, loaded from any
- URL scheme supported by Qt.
-
- \sa QDeclarativeImageProvider
-*/
-
-/*!
- \qmlproperty bool QtQuick2::AnimatedImage::asynchronous
-
- Specifies that images on the local filesystem should be loaded
- asynchronously in a separate thread. The default value is
- false, causing the user interface thread to block while the
- image is loaded. Setting \a asynchronous to true is useful where
- maintaining a responsive user interface is more desirable
- than having images immediately visible.
-
- Note that this property is only valid for images read from the
- local filesystem. Images loaded via a network resource (e.g. HTTP)
- are always loaded asynchronously.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::AnimatedImage::mirror
-
- This property holds whether the image should be horizontally inverted
- (effectively displaying a mirrored image).
-
- The default value is false.
-*/
-
-QQuickAnimatedImage::QQuickAnimatedImage(QQuickItem *parent)
- : QQuickImage(*(new QQuickAnimatedImagePrivate), parent)
-{
-}
-
-QQuickAnimatedImage::~QQuickAnimatedImage()
-{
- Q_D(QQuickAnimatedImage);
- delete d->_movie;
-}
-
-/*!
- \qmlproperty bool QtQuick2::AnimatedImage::paused
- This property holds whether the animated image is paused.
-
- By default, this property is false. Set it to true when you want to pause
- the animation.
-*/
-
-bool QQuickAnimatedImage::isPaused() const
-{
- Q_D(const QQuickAnimatedImage);
- if (!d->_movie)
- return false;
- return d->_movie->state()==QMovie::Paused;
-}
-
-void QQuickAnimatedImage::setPaused(bool pause)
-{
- Q_D(QQuickAnimatedImage);
- if (pause == d->paused)
- return;
- d->paused = pause;
- if (!d->_movie)
- return;
- d->_movie->setPaused(pause);
-}
-
-/*!
- \qmlproperty bool QtQuick2::AnimatedImage::playing
- This property holds whether the animated image is playing.
-
- By default, this property is true, meaning that the animation
- will start playing immediately.
-*/
-
-bool QQuickAnimatedImage::isPlaying() const
-{
- Q_D(const QQuickAnimatedImage);
- if (!d->_movie)
- return false;
- return d->_movie->state()!=QMovie::NotRunning;
-}
-
-void QQuickAnimatedImage::setPlaying(bool play)
-{
- Q_D(QQuickAnimatedImage);
- if (play == d->playing)
- return;
- d->playing = play;
- if (!d->_movie)
- return;
- if (play)
- d->_movie->start();
- else
- d->_movie->stop();
-}
-
-/*!
- \qmlproperty int QtQuick2::AnimatedImage::currentFrame
- \qmlproperty int QtQuick2::AnimatedImage::frameCount
-
- currentFrame is the frame that is currently visible. By monitoring this property
- for changes, you can animate other items at the same time as the image.
-
- frameCount is the number of frames in the animation. For some animation formats,
- frameCount is unknown and has a value of zero.
-*/
-int QQuickAnimatedImage::currentFrame() const
-{
- Q_D(const QQuickAnimatedImage);
- if (!d->_movie)
- return d->preset_currentframe;
- return d->_movie->currentFrameNumber();
-}
-
-void QQuickAnimatedImage::setCurrentFrame(int frame)
-{
- Q_D(QQuickAnimatedImage);
- if (!d->_movie) {
- d->preset_currentframe = frame;
- return;
- }
- d->_movie->jumpToFrame(frame);
-}
-
-int QQuickAnimatedImage::frameCount() const
-{
- Q_D(const QQuickAnimatedImage);
- if (!d->_movie)
- return 0;
- return d->_movie->frameCount();
-}
-
-void QQuickAnimatedImage::setSource(const QUrl &url)
-{
- Q_D(QQuickAnimatedImage);
- if (url == d->url)
- return;
-
- delete d->_movie;
- d->_movie = 0;
-
- if (d->reply) {
- d->reply->deleteLater();
- d->reply = 0;
- }
-
- d->url = url;
- emit sourceChanged(d->url);
-
- if (isComponentComplete())
- load();
-}
-
-void QQuickAnimatedImage::load()
-{
- Q_D(QQuickAnimatedImage);
-
- QQuickImageBase::Status oldStatus = d->status;
- qreal oldProgress = d->progress;
-
- if (d->url.isEmpty()) {
- delete d->_movie;
- d->setImage(QImage());
- d->progress = 0;
- d->status = Null;
- if (d->status != oldStatus)
- emit statusChanged(d->status);
- if (d->progress != oldProgress)
- emit progressChanged(d->progress);
- } else {
- QString lf = QDeclarativeEnginePrivate::urlToLocalFileOrQrc(d->url);
- if (!lf.isEmpty()) {
- //### should be unified with movieRequestFinished
- d->_movie = new QMovie(lf);
- if (!d->_movie->isValid()){
- qmlInfo(this) << "Error Reading Animated Image File " << d->url.toString();
- delete d->_movie;
- d->_movie = 0;
- d->status = Error;
- if (d->status != oldStatus)
- emit statusChanged(d->status);
- return;
- }
- connect(d->_movie, SIGNAL(stateChanged(QMovie::MovieState)),
- this, SLOT(playingStatusChanged()));
- connect(d->_movie, SIGNAL(frameChanged(int)),
- this, SLOT(movieUpdate()));
- d->_movie->setCacheMode(QMovie::CacheAll);
- if (d->playing)
- d->_movie->start();
- else
- d->_movie->jumpToFrame(0);
- if (d->paused)
- d->_movie->setPaused(true);
- d->setImage(d->_movie->currentPixmap().toImage());
- d->status = Ready;
- d->progress = 1.0;
- if (d->status != oldStatus)
- emit statusChanged(d->status);
- if (d->progress != oldProgress)
- emit progressChanged(d->progress);
- return;
- }
-
- d->status = Loading;
- d->progress = 0;
- emit statusChanged(d->status);
- emit progressChanged(d->progress);
- QNetworkRequest req(d->url);
- req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
- d->reply = qmlEngine(this)->networkAccessManager()->get(req);
- QObject::connect(d->reply, SIGNAL(finished()),
- this, SLOT(movieRequestFinished()));
- QObject::connect(d->reply, SIGNAL(downloadProgress(qint64,qint64)),
- this, SLOT(requestProgress(qint64,qint64)));
- }
-}
-
-#define ANIMATEDIMAGE_MAXIMUM_REDIRECT_RECURSION 16
-
-void QQuickAnimatedImage::movieRequestFinished()
-{
- Q_D(QQuickAnimatedImage);
-
- d->redirectCount++;
- if (d->redirectCount < ANIMATEDIMAGE_MAXIMUM_REDIRECT_RECURSION) {
- QVariant redirect = d->reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
- if (redirect.isValid()) {
- QUrl url = d->reply->url().resolved(redirect.toUrl());
- d->reply->deleteLater();
- d->reply = 0;
- setSource(url);
- return;
- }
- }
- d->redirectCount=0;
-
- d->_movie = new QMovie(d->reply);
- if (!d->_movie->isValid()){
-#ifndef QT_NO_DEBUG_STREAM
- qmlInfo(this) << "Error Reading Animated Image File " << d->url;
-#endif
- delete d->_movie;
- d->_movie = 0;
- d->status = Error;
- emit statusChanged(d->status);
- return;
- }
- connect(d->_movie, SIGNAL(stateChanged(QMovie::MovieState)),
- this, SLOT(playingStatusChanged()));
- connect(d->_movie, SIGNAL(frameChanged(int)),
- this, SLOT(movieUpdate()));
- d->_movie->setCacheMode(QMovie::CacheAll);
- if (d->playing)
- d->_movie->start();
- if (d->paused || !d->playing) {
- d->_movie->jumpToFrame(d->preset_currentframe);
- d->preset_currentframe = 0;
- }
- if (d->paused)
- d->_movie->setPaused(true);
- d->setImage(d->_movie->currentPixmap().toImage());
- d->status = Ready;
- emit statusChanged(d->status);
-}
-
-void QQuickAnimatedImage::movieUpdate()
-{
- Q_D(QQuickAnimatedImage);
- d->setImage(d->_movie->currentPixmap().toImage());
- emit frameChanged();
-}
-
-void QQuickAnimatedImage::playingStatusChanged()
-{
- Q_D(QQuickAnimatedImage);
- if ((d->_movie->state() != QMovie::NotRunning) != d->playing) {
- d->playing = (d->_movie->state() != QMovie::NotRunning);
- emit playingChanged();
- }
- if ((d->_movie->state() == QMovie::Paused) != d->paused) {
- d->playing = (d->_movie->state() == QMovie::Paused);
- emit pausedChanged();
- }
-}
-
-void QQuickAnimatedImage::componentComplete()
-{
- Q_D(QQuickAnimatedImage);
- QQuickItem::componentComplete(); // NOT QQuickImage
- if (d->url.isValid())
- load();
- if (!d->reply) {
- setCurrentFrame(d->preset_currentframe);
- d->preset_currentframe = 0;
- }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_MOVIE
diff --git a/src/declarative/items/qquickanimatedimage_p.h b/src/declarative/items/qquickanimatedimage_p.h
deleted file mode 100644
index ae96e4cc15..0000000000
--- a/src/declarative/items/qquickanimatedimage_p.h
+++ /dev/null
@@ -1,117 +0,0 @@
-// Commit: 80d0fe9cbd92288a08d5ced8767f1edb651dae37
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKANIMATEDIMAGE_P_H
-#define QQUICKANIMATEDIMAGE_P_H
-
-#include "qquickimage_p.h"
-
-#ifndef QT_NO_MOVIE
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QMovie;
-class QQuickAnimatedImagePrivate;
-
-class Q_AUTOTEST_EXPORT QQuickAnimatedImage : public QQuickImage
-{
- Q_OBJECT
-
- Q_PROPERTY(bool playing READ isPlaying WRITE setPlaying NOTIFY playingChanged)
- Q_PROPERTY(bool paused READ isPaused WRITE setPaused NOTIFY pausedChanged)
- Q_PROPERTY(int currentFrame READ currentFrame WRITE setCurrentFrame NOTIFY frameChanged)
- Q_PROPERTY(int frameCount READ frameCount)
-
- // read-only for AnimatedImage
- Q_PROPERTY(QSize sourceSize READ sourceSize NOTIFY sourceSizeChanged)
-
-public:
- QQuickAnimatedImage(QQuickItem *parent=0);
- ~QQuickAnimatedImage();
-
- bool isPlaying() const;
- void setPlaying(bool play);
-
- bool isPaused() const;
- void setPaused(bool pause);
-
- int currentFrame() const;
- void setCurrentFrame(int frame);
-
- int frameCount() const;
-
- // Extends QQuickImage's src property*/
- virtual void setSource(const QUrl&);
-
-Q_SIGNALS:
- void playingChanged();
- void pausedChanged();
- void frameChanged();
- void sourceSizeChanged();
-
-private Q_SLOTS:
- void movieUpdate();
- void movieRequestFinished();
- void playingStatusChanged();
-
-protected:
- virtual void load();
- void componentComplete();
-
-private:
- Q_DISABLE_COPY(QQuickAnimatedImage)
- Q_DECLARE_PRIVATE(QQuickAnimatedImage)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickAnimatedImage)
-
-QT_END_HEADER
-
-#endif // QT_NO_MOVIE
-
-#endif // QQUICKANIMATEDIMAGE_P_H
diff --git a/src/declarative/items/qquickanimatedimage_p_p.h b/src/declarative/items/qquickanimatedimage_p_p.h
deleted file mode 100644
index 0d5dd4a3b7..0000000000
--- a/src/declarative/items/qquickanimatedimage_p_p.h
+++ /dev/null
@@ -1,88 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKANIMATEDIMAGE_P_P_H
-#define QQUICKANIMATEDIMAGE_P_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 "qquickimage_p_p.h"
-
-#ifndef QT_NO_MOVIE
-
-QT_BEGIN_NAMESPACE
-
-class QMovie;
-class QNetworkReply;
-
-class QQuickAnimatedImagePrivate : public QQuickImagePrivate
-{
- Q_DECLARE_PUBLIC(QQuickAnimatedImage)
-
-public:
- QQuickAnimatedImagePrivate()
- : playing(true), paused(false), preset_currentframe(0), _movie(0), reply(0), redirectCount(0)
- {
- }
-
- bool playing;
- bool paused;
- int preset_currentframe;
- QMovie *_movie;
- QNetworkReply *reply;
- int redirectCount;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_MOVIE
-
-#endif // QQUICKANIMATEDIMAGE_P_P_H
diff --git a/src/declarative/items/qquickanimation.cpp b/src/declarative/items/qquickanimation.cpp
deleted file mode 100644
index 55eb4e2e13..0000000000
--- a/src/declarative/items/qquickanimation.cpp
+++ /dev/null
@@ -1,792 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickanimation_p.h"
-#include "qquickanimation_p_p.h"
-#include "qquickstateoperations_p.h"
-
-#include <private/qdeclarativeproperty_p.h>
-#include <private/qdeclarativepath_p.h>
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtCore/qmath.h>
-#include <QtCore/qsequentialanimationgroup.h>
-#include <QtCore/qparallelanimationgroup.h>
-#include <QtGui/qtransform.h>
-
-QT_BEGIN_NAMESPACE
-
-QQuickParentAnimation::QQuickParentAnimation(QObject *parent)
- : QDeclarativeAnimationGroup(*(new QQuickParentAnimationPrivate), parent)
-{
- Q_D(QQuickParentAnimation);
- d->topLevelGroup = new QSequentialAnimationGroup;
- QDeclarative_setParent_noEvent(d->topLevelGroup, this);
-
- d->startAction = new QActionAnimation;
- QDeclarative_setParent_noEvent(d->startAction, d->topLevelGroup);
- d->topLevelGroup->addAnimation(d->startAction);
-
- d->ag = new QParallelAnimationGroup;
- QDeclarative_setParent_noEvent(d->ag, d->topLevelGroup);
- d->topLevelGroup->addAnimation(d->ag);
-
- d->endAction = new QActionAnimation;
- QDeclarative_setParent_noEvent(d->endAction, d->topLevelGroup);
- d->topLevelGroup->addAnimation(d->endAction);
-}
-
-QQuickParentAnimation::~QQuickParentAnimation()
-{
-}
-
-QQuickItem *QQuickParentAnimation::target() const
-{
- Q_D(const QQuickParentAnimation);
- return d->target;
-}
-
-void QQuickParentAnimation::setTarget(QQuickItem *target)
-{
- Q_D(QQuickParentAnimation);
- if (target == d->target)
- return;
-
- d->target = target;
- emit targetChanged();
-}
-
-QQuickItem *QQuickParentAnimation::newParent() const
-{
- Q_D(const QQuickParentAnimation);
- return d->newParent;
-}
-
-void QQuickParentAnimation::setNewParent(QQuickItem *newParent)
-{
- Q_D(QQuickParentAnimation);
- if (newParent == d->newParent)
- return;
-
- d->newParent = newParent;
- emit newParentChanged();
-}
-
-QQuickItem *QQuickParentAnimation::via() const
-{
- Q_D(const QQuickParentAnimation);
- return d->via;
-}
-
-void QQuickParentAnimation::setVia(QQuickItem *via)
-{
- Q_D(QQuickParentAnimation);
- if (via == d->via)
- return;
-
- d->via = via;
- emit viaChanged();
-}
-
-//### mirrors same-named function in QQuickItem
-QPointF QQuickParentAnimationPrivate::computeTransformOrigin(QQuickItem::TransformOrigin origin, qreal width, qreal height) const
-{
- switch (origin) {
- default:
- case QQuickItem::TopLeft:
- return QPointF(0, 0);
- case QQuickItem::Top:
- return QPointF(width / 2., 0);
- case QQuickItem::TopRight:
- return QPointF(width, 0);
- case QQuickItem::Left:
- return QPointF(0, height / 2.);
- case QQuickItem::Center:
- return QPointF(width / 2., height / 2.);
- case QQuickItem::Right:
- return QPointF(width, height / 2.);
- case QQuickItem::BottomLeft:
- return QPointF(0, height);
- case QQuickItem::Bottom:
- return QPointF(width / 2., height);
- case QQuickItem::BottomRight:
- return QPointF(width, height);
- }
-}
-
-void QQuickParentAnimation::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_D(QQuickParentAnimation);
-
- struct QQuickParentAnimationData : public QAbstractAnimationAction
- {
- QQuickParentAnimationData() {}
- ~QQuickParentAnimationData() { qDeleteAll(pc); }
-
- QDeclarativeStateActions actions;
- //### reverse should probably apply on a per-action basis
- bool reverse;
- QList<QQuickParentChange *> pc;
- virtual void doAction()
- {
- for (int ii = 0; ii < actions.count(); ++ii) {
- const QDeclarativeAction &action = actions.at(ii);
- if (reverse)
- action.event->reverse();
- else
- action.event->execute();
- }
- }
- };
-
- QQuickParentAnimationData *data = new QQuickParentAnimationData;
- QQuickParentAnimationData *viaData = new QQuickParentAnimationData;
-
- bool hasExplicit = false;
- if (d->target && d->newParent) {
- data->reverse = false;
- QDeclarativeAction myAction;
- QQuickParentChange *pc = new QQuickParentChange;
- pc->setObject(d->target);
- pc->setParent(d->newParent);
- myAction.event = pc;
- data->pc << pc;
- data->actions << myAction;
- hasExplicit = true;
- if (d->via) {
- viaData->reverse = false;
- QDeclarativeAction myVAction;
- QQuickParentChange *vpc = new QQuickParentChange;
- vpc->setObject(d->target);
- vpc->setParent(d->via);
- myVAction.event = vpc;
- viaData->pc << vpc;
- viaData->actions << myVAction;
- }
- //### once actions have concept of modified,
- // loop to match appropriate ParentChanges and mark as modified
- }
-
- if (!hasExplicit)
- for (int i = 0; i < actions.size(); ++i) {
- QDeclarativeAction &action = actions[i];
- if (action.event && action.event->typeName() == QLatin1String("ParentChange")
- && (!d->target || static_cast<QQuickParentChange*>(action.event)->object() == d->target)) {
-
- QQuickParentChange *pc = static_cast<QQuickParentChange*>(action.event);
- QDeclarativeAction myAction = action;
- data->reverse = action.reverseEvent;
-
- //### this logic differs from PropertyAnimation
- // (probably a result of modified vs. done)
- if (d->newParent) {
- QQuickParentChange *epc = new QQuickParentChange;
- epc->setObject(static_cast<QQuickParentChange*>(action.event)->object());
- epc->setParent(d->newParent);
- myAction.event = epc;
- data->pc << epc;
- data->actions << myAction;
- pc = epc;
- } else {
- action.actionDone = true;
- data->actions << myAction;
- }
-
- if (d->via) {
- viaData->reverse = false;
- QDeclarativeAction myAction;
- QQuickParentChange *vpc = new QQuickParentChange;
- vpc->setObject(pc->object());
- vpc->setParent(d->via);
- myAction.event = vpc;
- viaData->pc << vpc;
- viaData->actions << myAction;
- QDeclarativeAction dummyAction;
- QDeclarativeAction &xAction = pc->xIsSet() && i < actions.size()-1 ? actions[++i] : dummyAction;
- QDeclarativeAction &yAction = pc->yIsSet() && i < actions.size()-1 ? actions[++i] : dummyAction;
- QDeclarativeAction &sAction = pc->scaleIsSet() && i < actions.size()-1 ? actions[++i] : dummyAction;
- QDeclarativeAction &rAction = pc->rotationIsSet() && i < actions.size()-1 ? actions[++i] : dummyAction;
- QQuickItem *target = pc->object();
- QQuickItem *targetParent = action.reverseEvent ? pc->originalParent() : pc->parent();
-
- //### this mirrors the logic in QQuickParentChange.
- bool ok;
- const QTransform &transform = targetParent->itemTransform(d->via, &ok);
- if (transform.type() >= QTransform::TxShear || !ok) {
- qmlInfo(this) << QQuickParentAnimation::tr("Unable to preserve appearance under complex transform");
- ok = false;
- }
-
- qreal scale = 1;
- qreal rotation = 0;
- bool isRotate = (transform.type() == QTransform::TxRotate) || (transform.m11() < 0);
- if (ok && !isRotate) {
- if (transform.m11() == transform.m22())
- scale = transform.m11();
- else {
- qmlInfo(this) << QQuickParentAnimation::tr("Unable to preserve appearance under non-uniform scale");
- ok = false;
- }
- } else if (ok && isRotate) {
- if (transform.m11() == transform.m22())
- scale = qSqrt(transform.m11()*transform.m11() + transform.m12()*transform.m12());
- else {
- qmlInfo(this) << QQuickParentAnimation::tr("Unable to preserve appearance under non-uniform scale");
- ok = false;
- }
-
- if (scale != 0)
- rotation = atan2(transform.m12()/scale, transform.m11()/scale) * 180/M_PI;
- else {
- qmlInfo(this) << QQuickParentAnimation::tr("Unable to preserve appearance under scale of 0");
- ok = false;
- }
- }
-
- const QPointF &point = transform.map(QPointF(xAction.toValue.toReal(),yAction.toValue.toReal()));
- qreal x = point.x();
- qreal y = point.y();
- if (ok && target->transformOrigin() != QQuickItem::TopLeft) {
- qreal w = target->width();
- qreal h = target->height();
- if (pc->widthIsSet() && i < actions.size() - 1)
- w = actions[++i].toValue.toReal();
- if (pc->heightIsSet() && i < actions.size() - 1)
- h = actions[++i].toValue.toReal();
- const QPointF &transformOrigin
- = d->computeTransformOrigin(target->transformOrigin(), w,h);
- qreal tempxt = transformOrigin.x();
- qreal tempyt = transformOrigin.y();
- QTransform t;
- t.translate(-tempxt, -tempyt);
- t.rotate(rotation);
- t.scale(scale, scale);
- t.translate(tempxt, tempyt);
- const QPointF &offset = t.map(QPointF(0,0));
- x += offset.x();
- y += offset.y();
- }
-
- if (ok) {
- //qDebug() << x << y << rotation << scale;
- xAction.toValue = x;
- yAction.toValue = y;
- sAction.toValue = sAction.toValue.toReal() * scale;
- rAction.toValue = rAction.toValue.toReal() + rotation;
- }
- }
- }
- }
-
- if (data->actions.count()) {
- if (direction == QDeclarativeAbstractAnimation::Forward) {
- d->startAction->setAnimAction(d->via ? viaData : data, QActionAnimation::DeleteWhenStopped);
- d->endAction->setAnimAction(d->via ? data : 0, QActionAnimation::DeleteWhenStopped);
- } else {
- d->endAction->setAnimAction(d->via ? viaData : data, QActionAnimation::DeleteWhenStopped);
- d->startAction->setAnimAction(d->via ? data : 0, QActionAnimation::DeleteWhenStopped);
- }
- } else {
- delete data;
- delete viaData;
- }
-
- //take care of any child animations
- bool valid = d->defaultProperty.isValid();
- for (int ii = 0; ii < d->animations.count(); ++ii) {
- if (valid)
- d->animations.at(ii)->setDefaultTarget(d->defaultProperty);
- d->animations.at(ii)->transition(actions, modified, direction);
- }
-
-}
-
-QAbstractAnimation *QQuickParentAnimation::qtAnimation()
-{
- Q_D(QQuickParentAnimation);
- return d->topLevelGroup;
-}
-
-QQuickAnchorAnimation::QQuickAnchorAnimation(QObject *parent)
-: QDeclarativeAbstractAnimation(*(new QQuickAnchorAnimationPrivate), parent)
-{
- Q_D(QQuickAnchorAnimation);
- d->va = new QDeclarativeBulkValueAnimator;
- QDeclarative_setParent_noEvent(d->va, this);
-}
-
-QQuickAnchorAnimation::~QQuickAnchorAnimation()
-{
-}
-
-QAbstractAnimation *QQuickAnchorAnimation::qtAnimation()
-{
- Q_D(QQuickAnchorAnimation);
- return d->va;
-}
-
-QDeclarativeListProperty<QQuickItem> QQuickAnchorAnimation::targets()
-{
- Q_D(QQuickAnchorAnimation);
- return QDeclarativeListProperty<QQuickItem>(this, d->targets);
-}
-
-int QQuickAnchorAnimation::duration() const
-{
- Q_D(const QQuickAnchorAnimation);
- return d->va->duration();
-}
-
-void QQuickAnchorAnimation::setDuration(int duration)
-{
- if (duration < 0) {
- qmlInfo(this) << tr("Cannot set a duration of < 0");
- return;
- }
-
- Q_D(QQuickAnchorAnimation);
- if (d->va->duration() == duration)
- return;
- d->va->setDuration(duration);
- emit durationChanged(duration);
-}
-
-QEasingCurve QQuickAnchorAnimation::easing() const
-{
- Q_D(const QQuickAnchorAnimation);
- return d->va->easingCurve();
-}
-
-void QQuickAnchorAnimation::setEasing(const QEasingCurve &e)
-{
- Q_D(QQuickAnchorAnimation);
- if (d->va->easingCurve() == e)
- return;
-
- d->va->setEasingCurve(e);
- emit easingChanged(e);
-}
-
-void QQuickAnchorAnimation::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_UNUSED(modified);
- Q_D(QQuickAnchorAnimation);
- QDeclarativeAnimationPropertyUpdater *data = new QDeclarativeAnimationPropertyUpdater;
- data->interpolatorType = QMetaType::QReal;
- data->interpolator = d->interpolator;
-
- data->reverse = direction == Backward ? true : false;
- data->fromSourced = false;
- data->fromDefined = false;
-
- for (int ii = 0; ii < actions.count(); ++ii) {
- QDeclarativeAction &action = actions[ii];
- if (action.event && action.event->typeName() == QLatin1String("AnchorChanges")
- && (d->targets.isEmpty() || d->targets.contains(static_cast<QQuickAnchorChanges*>(action.event)->object()))) {
- data->actions << static_cast<QQuickAnchorChanges*>(action.event)->additionalActions();
- }
- }
-
- if (data->actions.count()) {
- if (!d->rangeIsSet) {
- d->va->setStartValue(qreal(0));
- d->va->setEndValue(qreal(1));
- d->rangeIsSet = true;
- }
- d->va->setAnimValue(data, QAbstractAnimation::DeleteWhenStopped);
- d->va->setFromSourcedValue(&data->fromSourced);
- } else {
- delete data;
- }
-}
-
-QQuickPathAnimation::QQuickPathAnimation(QObject *parent)
-: QDeclarativeAbstractAnimation(*(new QQuickPathAnimationPrivate), parent)
-{
- Q_D(QQuickPathAnimation);
- d->pa = new QDeclarativeBulkValueAnimator;
- QDeclarative_setParent_noEvent(d->pa, this);
-}
-
-QQuickPathAnimation::~QQuickPathAnimation()
-{
-}
-
-int QQuickPathAnimation::duration() const
-{
- Q_D(const QQuickPathAnimation);
- return d->pa->duration();
-}
-
-void QQuickPathAnimation::setDuration(int duration)
-{
- if (duration < 0) {
- qmlInfo(this) << tr("Cannot set a duration of < 0");
- return;
- }
-
- Q_D(QQuickPathAnimation);
- if (d->pa->duration() == duration)
- return;
- d->pa->setDuration(duration);
- emit durationChanged(duration);
-}
-
-QEasingCurve QQuickPathAnimation::easing() const
-{
- Q_D(const QQuickPathAnimation);
- return d->pa->easingCurve();
-}
-
-void QQuickPathAnimation::setEasing(const QEasingCurve &e)
-{
- Q_D(QQuickPathAnimation);
- if (d->pa->easingCurve() == e)
- return;
-
- d->pa->setEasingCurve(e);
- emit easingChanged(e);
-}
-
-QDeclarativePath *QQuickPathAnimation::path() const
-{
- Q_D(const QQuickPathAnimation);
- return d->path;
-}
-
-void QQuickPathAnimation::setPath(QDeclarativePath *path)
-{
- Q_D(QQuickPathAnimation);
- if (d->path == path)
- return;
-
- d->path = path;
- emit pathChanged();
-}
-
-QQuickItem *QQuickPathAnimation::target() const
-{
- Q_D(const QQuickPathAnimation);
- return d->target;
-}
-
-void QQuickPathAnimation::setTarget(QQuickItem *target)
-{
- Q_D(QQuickPathAnimation);
- if (d->target == target)
- return;
-
- d->target = target;
- emit targetChanged();
-}
-
-QQuickPathAnimation::Orientation QQuickPathAnimation::orientation() const
-{
- Q_D(const QQuickPathAnimation);
- return d->orientation;
-}
-
-void QQuickPathAnimation::setOrientation(Orientation orientation)
-{
- Q_D(QQuickPathAnimation);
- if (d->orientation == orientation)
- return;
-
- d->orientation = orientation;
- emit orientationChanged(d->orientation);
-}
-
-QPointF QQuickPathAnimation::anchorPoint() const
-{
- Q_D(const QQuickPathAnimation);
- return d->anchorPoint;
-}
-
-void QQuickPathAnimation::setAnchorPoint(const QPointF &point)
-{
- Q_D(QQuickPathAnimation);
- if (d->anchorPoint == point)
- return;
-
- d->anchorPoint = point;
- emit anchorPointChanged(point);
-}
-
-qreal QQuickPathAnimation::orientationEntryInterval() const
-{
- Q_D(const QQuickPathAnimation);
- return d->entryInterval;
-}
-
-void QQuickPathAnimation::setOrientationEntryInterval(qreal interval)
-{
- Q_D(QQuickPathAnimation);
- if (d->entryInterval == interval)
- return;
- d->entryInterval = interval;
- emit orientationEntryIntervalChanged(interval);
-}
-
-qreal QQuickPathAnimation::orientationExitInterval() const
-{
- Q_D(const QQuickPathAnimation);
- return d->exitInterval;
-}
-
-void QQuickPathAnimation::setOrientationExitInterval(qreal interval)
-{
- Q_D(QQuickPathAnimation);
- if (d->exitInterval == interval)
- return;
- d->exitInterval = interval;
- emit orientationExitIntervalChanged(interval);
-}
-
-qreal QQuickPathAnimation::endRotation() const
-{
- Q_D(const QQuickPathAnimation);
- return d->endRotation.isNull ? qreal(0) : d->endRotation.value;
-}
-
-void QQuickPathAnimation::setEndRotation(qreal rotation)
-{
- Q_D(QQuickPathAnimation);
- if (!d->endRotation.isNull && d->endRotation == rotation)
- return;
-
- d->endRotation = rotation;
- emit endRotationChanged(d->endRotation);
-}
-
-
-QAbstractAnimation *QQuickPathAnimation::qtAnimation()
-{
- Q_D(QQuickPathAnimation);
- return d->pa;
-}
-
-void QQuickPathAnimation::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_D(QQuickPathAnimation);
- QQuickPathAnimationUpdater *data = new QQuickPathAnimationUpdater;
-
- data->orientation = d->orientation;
- data->anchorPoint = d->anchorPoint;
- data->entryInterval = d->entryInterval;
- data->exitInterval = d->exitInterval;
- data->endRotation = d->endRotation;
- data->reverse = direction == Backward ? true : false;
- data->fromSourced = false;
- data->fromDefined = (d->path && d->path->hasStartX() && d->path->hasStartY()) ? true : false;
- data->toDefined = d->path ? d->path->hasEnd() : false;
- int origModifiedSize = modified.count();
-
- for (int i = 0; i < actions.count(); ++i) {
- QDeclarativeAction &action = actions[i];
- if (action.event)
- continue;
- if (action.specifiedObject == d->target && action.property.name() == QLatin1String("x")) {
- data->toX = action.toValue.toReal();
- modified << action.property;
- action.fromValue = action.toValue;
- }
- if (action.specifiedObject == d->target && action.property.name() == QLatin1String("y")) {
- data->toY = action.toValue.toReal();
- modified << action.property;
- action.fromValue = action.toValue;
- }
- }
-
- if (d->target && d->path &&
- (modified.count() > origModifiedSize || data->toDefined)) {
- data->target = d->target;
- data->path = d->path;
- if (!d->rangeIsSet) {
- d->pa->setStartValue(qreal(0));
- d->pa->setEndValue(qreal(1));
- d->rangeIsSet = true;
- }
- /*
- NOTE: The following block relies on the fact that the previous value hasn't
- yet been deleted, and has the same target, etc, which may be a bit fragile.
- */
- if (d->pa->getAnimValue()) {
- QQuickPathAnimationUpdater *prevData = static_cast<QQuickPathAnimationUpdater*>(d->pa->getAnimValue());
-
- // get the original start angle that was used (so we can exactly reverse).
- data->startRotation = prevData->startRotation;
-
- // treat interruptions specially, otherwise we end up with strange paths
- if ((data->reverse || prevData->reverse) && prevData->currentV > 0 && prevData->currentV < 1) {
- if (!data->fromDefined && !data->toDefined && !prevData->painterPath.isEmpty()) {
- QPointF pathPos = QDeclarativePath::sequentialPointAt(prevData->painterPath, prevData->pathLength, prevData->attributePoints, prevData->prevBez, prevData->currentV);
- if (!prevData->anchorPoint.isNull())
- pathPos -= prevData->anchorPoint;
- if (pathPos == data->target->pos()) { //only treat as interruption if we interrupted ourself
- data->painterPath = prevData->painterPath;
- data->toDefined = data->fromDefined = data->fromSourced = true;
- data->prevBez.isValid = false;
- data->interruptStart = prevData->currentV;
- data->startRotation = prevData->startRotation;
- data->pathLength = prevData->pathLength;
- data->attributePoints = prevData->attributePoints;
- }
- }
- }
- }
- d->pa->setFromSourcedValue(&data->fromSourced);
- d->pa->setAnimValue(data, QAbstractAnimation::DeleteWhenStopped);
- } else {
- d->pa->setFromSourcedValue(0);
- d->pa->setAnimValue(0, QAbstractAnimation::DeleteWhenStopped);
- delete data;
- }
-}
-
-void QQuickPathAnimationUpdater::setValue(qreal v)
-{
- if (interruptStart.isValid()) {
- if (reverse)
- v = 1 - v;
- qreal end = reverse ? 0.0 : 1.0;
- v = interruptStart + v * (end-interruptStart);
- }
- currentV = v;
- bool atStart = ((reverse && v == 1.0) || (!reverse && v == 0.0));
- if (!fromSourced && (!fromDefined || !toDefined)) {
- qreal startX = reverse ? toX + anchorPoint.x() : target->x() + anchorPoint.x();
- qreal startY = reverse ? toY + anchorPoint.y() : target->y() + anchorPoint.y();
- qreal endX = reverse ? target->x() + anchorPoint.x() : toX + anchorPoint.x();
- qreal endY = reverse ? target->y() + anchorPoint.y() : toY + anchorPoint.y();
-
- prevBez.isValid = false;
- painterPath = path->createPath(QPointF(startX, startY), QPointF(endX, endY), QStringList(), pathLength, attributePoints);
- fromSourced = true;
- }
-
- qreal angle;
- bool fixed = orientation == QQuickPathAnimation::Fixed;
- QPointF currentPos = !painterPath.isEmpty() ? path->sequentialPointAt(painterPath, pathLength, attributePoints, prevBez, v, fixed ? 0 : &angle) : path->sequentialPointAt(v, fixed ? 0 : &angle);
-
- //adjust position according to anchor point
- if (!anchorPoint.isNull()) {
- currentPos -= anchorPoint;
- if (atStart) {
- if (!anchorPoint.isNull() && !fixed)
- target->setTransformOriginPoint(anchorPoint);
- }
- }
-
- //### could cache properties rather than reconstructing each time
- QDeclarativePropertyPrivate::write(QDeclarativeProperty(target, QStringLiteral("x")), currentPos.x(), QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
- QDeclarativePropertyPrivate::write(QDeclarativeProperty(target, QStringLiteral("y")), currentPos.y(), QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
-
- //adjust angle according to orientation
- if (!fixed) {
- switch (orientation) {
- case QQuickPathAnimation::RightFirst:
- angle = -angle;
- break;
- case QQuickPathAnimation::TopFirst:
- angle = -angle + 90;
- break;
- case QQuickPathAnimation::LeftFirst:
- angle = -angle + 180;
- break;
- case QQuickPathAnimation::BottomFirst:
- angle = -angle + 270;
- break;
- default:
- angle = 0;
- break;
- }
-
- if (atStart && !reverse) {
- startRotation = target->rotation();
-
- //shortest distance to correct orientation
- qreal diff = angle - startRotation;
- while (diff > 180.0) {
- startRotation.value += 360.0;
- diff -= 360.0;
- }
- while (diff < -180.0) {
- startRotation.value -= 360.0;
- diff += 360.0;
- }
- }
-
- //smoothly transition to the desired orientation
- if (startRotation.isValid()) {
- if (reverse && v == 0.0)
- angle = startRotation;
- else if (v < entryInterval)
- angle = angle * v / entryInterval + startRotation * (entryInterval - v) / entryInterval;
- }
- if (endRotation.isValid()) {
- qreal exitStart = 1 - exitInterval;
- if (!reverse && v == 1.0)
- angle = endRotation;
- else if (v > exitStart)
- angle = endRotation * (v - exitStart) / exitInterval + angle * (exitInterval - (v - exitStart)) / exitInterval;
- }
- QDeclarativePropertyPrivate::write(QDeclarativeProperty(target, QStringLiteral("rotation")), angle, QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
- }
-
- /*
- NOTE: we don't always reset the transform origin, as it can cause a
- visual jump if ending on an angle. This means that in some cases
- (anchor point and orientation both specified, and ending at an angle)
- the transform origin will always be set after running the path animation.
- */
- if ((reverse && v == 0.0) || (!reverse && v == 1.0)) {
- if (!anchorPoint.isNull() && !fixed && qFuzzyIsNull(angle))
- target->setTransformOriginPoint(QPointF());
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickanimation_p.h b/src/declarative/items/qquickanimation_p.h
deleted file mode 100644
index 2ce72249e2..0000000000
--- a/src/declarative/items/qquickanimation_p.h
+++ /dev/null
@@ -1,209 +0,0 @@
-// Commit: e39a2e39451bf106a9845f8a60fc571faaa4dde5
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKANIMATION_H
-#define QQUICKANIMATION_H
-
-#include "qquickitem.h"
-
-#include <private/qdeclarativeanimation_p.h>
-
-#include <QtCore/qabstractanimation.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickParentAnimationPrivate;
-class QQuickParentAnimation : public QDeclarativeAnimationGroup
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickParentAnimation)
-
- Q_PROPERTY(QQuickItem *target READ target WRITE setTarget NOTIFY targetChanged)
- Q_PROPERTY(QQuickItem *newParent READ newParent WRITE setNewParent NOTIFY newParentChanged)
- Q_PROPERTY(QQuickItem *via READ via WRITE setVia NOTIFY viaChanged)
-
-public:
- QQuickParentAnimation(QObject *parent=0);
- virtual ~QQuickParentAnimation();
-
- QQuickItem *target() const;
- void setTarget(QQuickItem *);
-
- QQuickItem *newParent() const;
- void setNewParent(QQuickItem *);
-
- QQuickItem *via() const;
- void setVia(QQuickItem *);
-
-Q_SIGNALS:
- void targetChanged();
- void newParentChanged();
- void viaChanged();
-
-protected:
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
- virtual QAbstractAnimation *qtAnimation();
-};
-
-class QQuickAnchorAnimationPrivate;
-class QQuickAnchorAnimation : public QDeclarativeAbstractAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickAnchorAnimation)
- Q_PROPERTY(QDeclarativeListProperty<QQuickItem> targets READ targets)
- Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged)
- Q_PROPERTY(QEasingCurve easing READ easing WRITE setEasing NOTIFY easingChanged)
-
-public:
- QQuickAnchorAnimation(QObject *parent=0);
- virtual ~QQuickAnchorAnimation();
-
- QDeclarativeListProperty<QQuickItem> targets();
-
- int duration() const;
- void setDuration(int);
-
- QEasingCurve easing() const;
- void setEasing(const QEasingCurve &);
-
-Q_SIGNALS:
- void durationChanged(int);
- void easingChanged(const QEasingCurve&);
-
-protected:
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
- virtual QAbstractAnimation *qtAnimation();
-};
-
-class QQuickItem;
-class QDeclarativePath;
-class QQuickPathAnimationPrivate;
-class Q_AUTOTEST_EXPORT QQuickPathAnimation : public QDeclarativeAbstractAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickPathAnimation)
-
- Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged)
- Q_PROPERTY(QEasingCurve easing READ easing WRITE setEasing NOTIFY easingChanged)
- Q_PROPERTY(QDeclarativePath *path READ path WRITE setPath NOTIFY pathChanged)
- Q_PROPERTY(QQuickItem *target READ target WRITE setTarget NOTIFY targetChanged)
- Q_PROPERTY(Orientation orientation READ orientation WRITE setOrientation NOTIFY orientationChanged)
- Q_PROPERTY(QPointF anchorPoint READ anchorPoint WRITE setAnchorPoint NOTIFY anchorPointChanged)
- Q_PROPERTY(qreal orientationEntryInterval READ orientationEntryInterval WRITE setOrientationEntryInterval NOTIFY orientationEntryIntervalChanged)
- Q_PROPERTY(qreal orientationExitInterval READ orientationExitInterval WRITE setOrientationExitInterval NOTIFY orientationExitIntervalChanged)
- Q_PROPERTY(qreal endRotation READ endRotation WRITE setEndRotation NOTIFY endRotationChanged)
-
-public:
- QQuickPathAnimation(QObject *parent=0);
- virtual ~QQuickPathAnimation();
-
- enum Orientation {
- Fixed,
- RightFirst,
- LeftFirst,
- BottomFirst,
- TopFirst
- };
- Q_ENUMS(Orientation)
-
- int duration() const;
- void setDuration(int);
-
- QEasingCurve easing() const;
- void setEasing(const QEasingCurve &);
-
- QDeclarativePath *path() const;
- void setPath(QDeclarativePath *);
-
- QQuickItem *target() const;
- void setTarget(QQuickItem *);
-
- Orientation orientation() const;
- void setOrientation(Orientation orientation);
-
- QPointF anchorPoint() const;
- void setAnchorPoint(const QPointF &point);
-
- qreal orientationEntryInterval() const;
- void setOrientationEntryInterval(qreal);
-
- qreal orientationExitInterval() const;
- void setOrientationExitInterval(qreal);
-
- qreal endRotation() const;
- void setEndRotation(qreal);
-
-protected:
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
- virtual QAbstractAnimation *qtAnimation();
-
-Q_SIGNALS:
- void durationChanged(int);
- void easingChanged(const QEasingCurve &);
- void pathChanged();
- void targetChanged();
- void orientationChanged(Orientation);
- void anchorPointChanged(const QPointF &);
- void orientationEntryIntervalChanged(qreal);
- void orientationExitIntervalChanged(qreal);
- void endRotationChanged(qreal);
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickParentAnimation)
-QML_DECLARE_TYPE(QQuickAnchorAnimation)
-QML_DECLARE_TYPE(QQuickPathAnimation)
-
-QT_END_HEADER
-
-#endif // QQUICKANIMATION_H
diff --git a/src/declarative/items/qquickanimation_p_p.h b/src/declarative/items/qquickanimation_p_p.h
deleted file mode 100644
index de2b6d42f9..0000000000
--- a/src/declarative/items/qquickanimation_p_p.h
+++ /dev/null
@@ -1,153 +0,0 @@
-// Commit: 0ade09152067324f74678f2de4d447b6e0280600
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKANIMATION_P_H
-#define QQUICKANIMATION_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 "qquickanimation_p.h"
-
-#include <private/qdeclarativepath_p.h>
-#include <private/qdeclarativeanimation_p_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickParentAnimationPrivate : public QDeclarativeAnimationGroupPrivate
-{
- Q_DECLARE_PUBLIC(QQuickParentAnimation)
-public:
- QQuickParentAnimationPrivate()
- : QDeclarativeAnimationGroupPrivate(), target(0), newParent(0),
- via(0), topLevelGroup(0), startAction(0), endAction(0) {}
-
- QQuickItem *target;
- QQuickItem *newParent;
- QQuickItem *via;
-
- QSequentialAnimationGroup *topLevelGroup;
- QActionAnimation *startAction;
- QActionAnimation *endAction;
-
- QPointF computeTransformOrigin(QQuickItem::TransformOrigin origin, qreal width, qreal height) const;
-};
-
-class QQuickAnchorAnimationPrivate : public QDeclarativeAbstractAnimationPrivate
-{
- Q_DECLARE_PUBLIC(QQuickAnchorAnimation)
-public:
- QQuickAnchorAnimationPrivate() : rangeIsSet(false), va(0),
- interpolator(QVariantAnimationPrivate::getInterpolator(QMetaType::QReal)) {}
-
- bool rangeIsSet;
- QDeclarativeBulkValueAnimator *va;
- QVariantAnimation::Interpolator interpolator;
- QList<QQuickItem*> targets;
-};
-
-class QQuickPathAnimationUpdater : public QDeclarativeBulkValueUpdater
-{
-public:
- QQuickPathAnimationUpdater() : path(0), target(0), reverse(false),
- fromSourced(false), fromDefined(false), toDefined(false),
- toX(0), toY(0), currentV(0), orientation(QQuickPathAnimation::Fixed),
- entryInterval(0), exitInterval(0) {}
- ~QQuickPathAnimationUpdater() {}
-
- void setValue(qreal v);
-
- QDeclarativePath *path;
-
- QPainterPath painterPath;
- QDeclarativeCachedBezier prevBez;
- qreal pathLength;
- QList<QDeclarativePath::AttributePoint> attributePoints;
-
- QQuickItem *target;
- bool reverse;
- bool fromSourced;
- bool fromDefined;
- bool toDefined;
- qreal toX;
- qreal toY;
- qreal currentV;
- QDeclarativeNullableValue<qreal> interruptStart;
- //TODO: bundle below into common struct
- QQuickPathAnimation::Orientation orientation;
- QPointF anchorPoint;
- qreal entryInterval;
- qreal exitInterval;
- QDeclarativeNullableValue<qreal> endRotation;
- QDeclarativeNullableValue<qreal> startRotation;
-};
-
-class QQuickPathAnimationPrivate : public QDeclarativeAbstractAnimationPrivate
-{
- Q_DECLARE_PUBLIC(QQuickPathAnimation)
-public:
- QQuickPathAnimationPrivate() : path(0), target(0),
- rangeIsSet(false), orientation(QQuickPathAnimation::Fixed), entryInterval(0), exitInterval(0), pa(0) {}
-
- QDeclarativePath *path;
- QQuickItem *target;
- bool rangeIsSet;
- QQuickPathAnimation::Orientation orientation;
- QPointF anchorPoint;
- qreal entryInterval;
- qreal exitInterval;
- QDeclarativeNullableValue<qreal> endRotation;
- QDeclarativeBulkValueAnimator *pa;
-};
-
-
-QT_END_NAMESPACE
-
-#endif // QQUICKANIMATION_P_H
diff --git a/src/declarative/items/qquickborderimage.cpp b/src/declarative/items/qquickborderimage.cpp
deleted file mode 100644
index e0ffd716aa..0000000000
--- a/src/declarative/items/qquickborderimage.cpp
+++ /dev/null
@@ -1,600 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickborderimage_p.h"
-#include "qquickborderimage_p_p.h"
-#include "qquickninepatchnode_p.h"
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtCore/qfile.h>
-
-#include <private/qdeclarativeengine_p.h>
-
-QT_BEGIN_NAMESPACE
-
-
-/*!
- \qmlclass BorderImage QQuickBorderImage
- \inqmlmodule QtQuick 2
- \brief The BorderImage element provides an image that can be used as a border.
- \inherits Item
- \ingroup qml-basic-visual-elements
-
- The BorderImage element is used to create borders out of images by scaling or tiling
- parts of each image.
-
- A BorderImage element breaks a source image, specified using the \l url property,
- into 9 regions, as shown below:
-
- \image declarative-scalegrid.png
-
- When the image is scaled, regions of the source image are scaled or tiled to
- create the displayed border image in the following way:
-
- \list
- \i The corners (regions 1, 3, 7, and 9) are not scaled at all.
- \i Regions 2 and 8 are scaled according to
- \l{BorderImage::horizontalTileMode}{horizontalTileMode}.
- \i Regions 4 and 6 are scaled according to
- \l{BorderImage::verticalTileMode}{verticalTileMode}.
- \i The middle (region 5) is scaled according to both
- \l{BorderImage::horizontalTileMode}{horizontalTileMode} and
- \l{BorderImage::verticalTileMode}{verticalTileMode}.
- \endlist
-
- The regions of the image are defined using the \l border property group, which
- describes the distance from each edge of the source image to use as a border.
-
- \section1 Example Usage
-
- The following examples show the effects of the different modes on an image.
- Guide lines are overlaid onto the image to show the different regions of the
- image as described above.
-
- \beginfloatleft
- \image qml-borderimage-normal-image.png
- \endfloat
-
- An unscaled image is displayed using an Image element. The \l border property is
- used to determine the parts of the image that will lie inside the unscaled corner
- areas and the parts that will be stretched horizontally and vertically.
-
- \snippet doc/src/snippets/declarative/borderimage/normal-image.qml normal image
-
- \clearfloat
- \beginfloatleft
- \image qml-borderimage-scaled.png
- \endfloat
-
- A BorderImage element is used to display the image, and it is given a size that is
- larger than the original image. Since the \l horizontalTileMode property is set to
- \l{BorderImage::horizontalTileMode}{BorderImage.Stretch}, the parts of image in
- regions 2 and 8 are stretched horizontally. Since the \l verticalTileMode property
- is set to \l{BorderImage::verticalTileMode}{BorderImage.Stretch}, the parts of image
- in regions 4 and 6 are stretched vertically.
-
- \snippet doc/src/snippets/declarative/borderimage/borderimage-scaled.qml scaled border image
-
- \clearfloat
- \beginfloatleft
- \image qml-borderimage-tiled.png
- \endfloat
-
- Again, a large BorderImage element is used to display the image. With the
- \l horizontalTileMode property set to \l{BorderImage::horizontalTileMode}{BorderImage.Repeat},
- the parts of image in regions 2 and 8 are tiled so that they fill the space at the
- top and bottom of the element. Similarly, the \l verticalTileMode property is set to
- \l{BorderImage::verticalTileMode}{BorderImage.Repeat}, the parts of image in regions
- 4 and 6 are tiled so that they fill the space at the left and right of the element.
-
- \snippet doc/src/snippets/declarative/borderimage/borderimage-tiled.qml tiled border image
-
- \clearfloat
- In some situations, the width of regions 2 and 8 may not be an exact multiple of the width
- of the corresponding regions in the source image. Similarly, the height of regions 4 and 6
- may not be an exact multiple of the height of the corresponding regions. It can be useful
- to use \l{BorderImage::horizontalTileMode}{BorderImage.Round} instead of
- \l{BorderImage::horizontalTileMode}{BorderImage.Repeat} in cases like these.
-
- The \l{declarative/imageelements/borderimage}{BorderImage example} shows how a BorderImage
- can be used to simulate a shadow effect on a rectangular item.
-
- \section1 Quality and Performance
-
- By default, any scaled regions of the image are rendered without smoothing to improve
- rendering speed. Setting the \l smooth property improves rendering quality of scaled
- regions, but may slow down rendering.
-
- The source image may not be loaded instantaneously, depending on its original location.
- Loading progress can be monitored with the \l progress property.
-
- \sa Image, AnimatedImage
- */
-
-/*!
- \qmlproperty bool QtQuick2::BorderImage::asynchronous
-
- Specifies that images on the local filesystem should be loaded
- asynchronously in a separate thread. The default value is
- false, causing the user interface thread to block while the
- image is loaded. Setting \a asynchronous to true is useful where
- maintaining a responsive user interface is more desirable
- than having images immediately visible.
-
- Note that this property is only valid for images read from the
- local filesystem. Images loaded via a network resource (e.g. HTTP)
- are always loaded asynchronously.
-*/
-QQuickBorderImage::QQuickBorderImage(QQuickItem *parent)
-: QQuickImageBase(*(new QQuickBorderImagePrivate), parent)
-{
-}
-
-QQuickBorderImage::~QQuickBorderImage()
-{
- Q_D(QQuickBorderImage);
- if (d->sciReply)
- d->sciReply->deleteLater();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::BorderImage::status
-
- This property describes the status of image loading. It can be one of:
-
- \list
- \o BorderImage.Null - no image has been set
- \o BorderImage.Ready - the image has been loaded
- \o BorderImage.Loading - the image is currently being loaded
- \o BorderImage.Error - an error occurred while loading the image
- \endlist
-
- \sa progress
-*/
-
-/*!
- \qmlproperty real QtQuick2::BorderImage::progress
-
- This property holds the progress of image loading, from 0.0 (nothing loaded)
- to 1.0 (finished).
-
- \sa status
-*/
-
-/*!
- \qmlproperty bool QtQuick2::BorderImage::smooth
-
- Set this property if you want the image to be smoothly filtered when scaled or
- transformed. Smooth filtering gives better visual quality, but is slower. If
- the image is displayed at its natural size, this property has no visual or
- performance effect.
-
- By default, this property is set to false.
-
- \note Generally scaling artifacts are only visible if the image is stationary on
- the screen. A common pattern when animating an image is to disable smooth
- filtering at the beginning of the animation and enable it at the conclusion.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::BorderImage::cache
-
- Specifies whether the image should be cached. The default value is
- true. Setting \a cache to false is useful when dealing with large images,
- to make sure that they aren't cached at the expense of small 'ui element' images.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::BorderImage::mirror
-
- This property holds whether the image should be horizontally inverted
- (effectively displaying a mirrored image).
-
- The default value is false.
-*/
-
-/*!
- \qmlproperty url QtQuick2::BorderImage::source
-
- This property holds the URL that refers to the source image.
-
- BorderImage can handle any image format supported by Qt, loaded from any
- URL scheme supported by Qt.
-
- This property can also be used to refer to .sci files, which are
- written in a QML-specific, text-based format that specifies the
- borders, the image file and the tile rules for a given border image.
-
- The following .sci file sets the borders to 10 on each side for the
- image \c picture.png:
-
- \code
- border.left: 10
- border.top: 10
- border.bottom: 10
- border.right: 10
- source: "picture.png"
- \endcode
-
- The URL may be absolute, or relative to the URL of the component.
-
- \sa QDeclarativeImageProvider
-*/
-
-/*!
- \qmlproperty QSize QtQuick2::BorderImage::sourceSize
-
- This property holds the actual width and height of the loaded image.
-
- In BorderImage, this property is read-only.
-
- \sa Image::sourceSize
-*/
-void QQuickBorderImage::setSource(const QUrl &url)
-{
- Q_D(QQuickBorderImage);
- //equality is fairly expensive, so we bypass for simple, common case
- if ((d->url.isEmpty() == url.isEmpty()) && url == d->url)
- return;
-
- if (d->sciReply) {
- d->sciReply->deleteLater();
- d->sciReply = 0;
- }
-
- d->url = url;
- d->sciurl = QUrl();
- emit sourceChanged(d->url);
-
- if (isComponentComplete())
- load();
-}
-
-void QQuickBorderImage::load()
-{
- Q_D(QQuickBorderImage);
- if (d->progress != 0.0) {
- d->progress = 0.0;
- emit progressChanged(d->progress);
- }
-
- if (d->url.isEmpty()) {
- d->pix.clear(this);
- d->status = Null;
- setImplicitSize(0, 0);
- emit statusChanged(d->status);
- update();
- } else {
- d->status = Loading;
- if (d->url.path().endsWith(QLatin1String("sci"))) {
- QString lf = QDeclarativeEnginePrivate::urlToLocalFileOrQrc(d->url);
- if (!lf.isEmpty()) {
- QFile file(lf);
- file.open(QIODevice::ReadOnly);
- setGridScaledImage(QQuickGridScaledImage(&file));
- } else {
- QNetworkRequest req(d->url);
- d->sciReply = qmlEngine(this)->networkAccessManager()->get(req);
- FAST_CONNECT(d->sciReply, SIGNAL(finished()), this, SLOT(sciRequestFinished()))
- }
- } else {
-
- QDeclarativePixmap::Options options;
- if (d->async)
- options |= QDeclarativePixmap::Asynchronous;
- if (d->cache)
- options |= QDeclarativePixmap::Cache;
- d->pix.clear(this);
- d->pix.load(qmlEngine(this), d->url, options);
-
- if (d->pix.isLoading()) {
- d->pix.connectFinished(this, SLOT(requestFinished()));
- d->pix.connectDownloadProgress(this, SLOT(requestProgress(qint64,qint64)));
- } else {
- QSize impsize = d->pix.implicitSize();
- setImplicitSize(impsize.width(), impsize.height());
-
- if (d->pix.isReady()) {
- d->status = Ready;
- } else {
- d->status = Error;
- qmlInfo(this) << d->pix.error();
- }
-
- d->progress = 1.0;
- emit statusChanged(d->status);
- emit progressChanged(d->progress);
- update();
- }
- }
- }
-
- emit statusChanged(d->status);
-}
-
-/*!
- \qmlproperty int QtQuick2::BorderImage::border.left
- \qmlproperty int QtQuick2::BorderImage::border.right
- \qmlproperty int QtQuick2::BorderImage::border.top
- \qmlproperty int QtQuick2::BorderImage::border.bottom
-
- The 4 border lines (2 horizontal and 2 vertical) break the image into 9 sections,
- as shown below:
-
- \image declarative-scalegrid.png
-
- Each border line (left, right, top, and bottom) specifies an offset in pixels
- from the respective edge of the source image. By default, each border line has
- a value of 0.
-
- For example, the following definition sets the bottom line 10 pixels up from
- the bottom of the image:
-
- \qml
- BorderImage {
- border.bottom: 10
- // ...
- }
- \endqml
-
- The border lines can also be specified using a
- \l {BorderImage::source}{.sci file}.
-*/
-
-QQuickScaleGrid *QQuickBorderImage::border()
-{
- Q_D(QQuickBorderImage);
- return d->getScaleGrid();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::BorderImage::horizontalTileMode
- \qmlproperty enumeration QtQuick2::BorderImage::verticalTileMode
-
- This property describes how to repeat or stretch the middle parts of the border image.
-
- \list
- \o BorderImage.Stretch - Scales the image to fit to the available area.
- \o BorderImage.Repeat - Tile the image until there is no more space. May crop the last image.
- \o BorderImage.Round - Like Repeat, but scales the images down to ensure that the last image is not cropped.
- \endlist
-
- The default tile mode for each property is BorderImage.Stretch.
-*/
-QQuickBorderImage::TileMode QQuickBorderImage::horizontalTileMode() const
-{
- Q_D(const QQuickBorderImage);
- return d->horizontalTileMode;
-}
-
-void QQuickBorderImage::setHorizontalTileMode(TileMode t)
-{
- Q_D(QQuickBorderImage);
- if (t != d->horizontalTileMode) {
- d->horizontalTileMode = t;
- emit horizontalTileModeChanged();
- update();
- }
-}
-
-QQuickBorderImage::TileMode QQuickBorderImage::verticalTileMode() const
-{
- Q_D(const QQuickBorderImage);
- return d->verticalTileMode;
-}
-
-void QQuickBorderImage::setVerticalTileMode(TileMode t)
-{
- Q_D(QQuickBorderImage);
- if (t != d->verticalTileMode) {
- d->verticalTileMode = t;
- emit verticalTileModeChanged();
- update();
- }
-}
-
-void QQuickBorderImage::setGridScaledImage(const QQuickGridScaledImage& sci)
-{
- Q_D(QQuickBorderImage);
- if (!sci.isValid()) {
- d->status = Error;
- emit statusChanged(d->status);
- } else {
- QQuickScaleGrid *sg = border();
- sg->setTop(sci.gridTop());
- sg->setBottom(sci.gridBottom());
- sg->setLeft(sci.gridLeft());
- sg->setRight(sci.gridRight());
- d->horizontalTileMode = sci.horizontalTileRule();
- d->verticalTileMode = sci.verticalTileRule();
-
- d->sciurl = d->url.resolved(QUrl(sci.pixmapUrl()));
-
- QDeclarativePixmap::Options options;
- if (d->async)
- options |= QDeclarativePixmap::Asynchronous;
- if (d->cache)
- options |= QDeclarativePixmap::Cache;
- d->pix.clear(this);
- d->pix.load(qmlEngine(this), d->sciurl, options);
-
- if (d->pix.isLoading()) {
- static int thisRequestProgress = -1;
- static int thisRequestFinished = -1;
- if (thisRequestProgress == -1) {
- thisRequestProgress =
- QQuickBorderImage::staticMetaObject.indexOfSlot("requestProgress(qint64,qint64)");
- thisRequestFinished =
- QQuickBorderImage::staticMetaObject.indexOfSlot("requestFinished()");
- }
-
- d->pix.connectFinished(this, thisRequestFinished);
- d->pix.connectDownloadProgress(this, thisRequestProgress);
-
- } else {
-
- QSize impsize = d->pix.implicitSize();
- setImplicitSize(impsize.width(), impsize.height());
-
- if (d->pix.isReady()) {
- d->status = Ready;
- } else {
- d->status = Error;
- qmlInfo(this) << d->pix.error();
- }
-
- d->progress = 1.0;
- emit statusChanged(d->status);
- emit progressChanged(1.0);
- update();
-
- }
- }
-}
-
-void QQuickBorderImage::requestFinished()
-{
- Q_D(QQuickBorderImage);
-
- QSize impsize = d->pix.implicitSize();
- if (d->pix.isError()) {
- d->status = Error;
- qmlInfo(this) << d->pix.error();
- } else {
- d->status = Ready;
- }
-
- setImplicitSize(impsize.width(), impsize.height());
-
- if (d->sourcesize.width() != d->pix.width() || d->sourcesize.height() != d->pix.height())
- emit sourceSizeChanged();
-
- d->progress = 1.0;
- emit statusChanged(d->status);
- emit progressChanged(1.0);
- update();
-}
-
-#define BORDERIMAGE_MAX_REDIRECT 16
-
-void QQuickBorderImage::sciRequestFinished()
-{
- Q_D(QQuickBorderImage);
-
- d->redirectCount++;
- if (d->redirectCount < BORDERIMAGE_MAX_REDIRECT) {
- QVariant redirect = d->sciReply->attribute(QNetworkRequest::RedirectionTargetAttribute);
- if (redirect.isValid()) {
- QUrl url = d->sciReply->url().resolved(redirect.toUrl());
- setSource(url);
- return;
- }
- }
- d->redirectCount=0;
-
- if (d->sciReply->error() != QNetworkReply::NoError) {
- d->status = Error;
- d->sciReply->deleteLater();
- d->sciReply = 0;
- emit statusChanged(d->status);
- } else {
- QQuickGridScaledImage sci(d->sciReply);
- d->sciReply->deleteLater();
- d->sciReply = 0;
- setGridScaledImage(sci);
- }
-}
-
-void QQuickBorderImage::doUpdate()
-{
- update();
-}
-
-QSGNode *QQuickBorderImage::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
-{
- Q_D(QQuickBorderImage);
-
- QSGTexture *texture = d->sceneGraphContext()->textureForFactory(d->pix.textureFactory());
-
- if (!texture || width() <= 0 || height() <= 0) {
- delete oldNode;
- return 0;
- }
-
- QQuickNinePatchNode *node = static_cast<QQuickNinePatchNode *>(oldNode);
-
- if (!node) {
- node = new QQuickNinePatchNode();
- }
-
- node->setTexture(texture);
-
- // Don't implicitly create the scalegrid in the rendering thread...
- if (d->border) {
- const QQuickScaleGrid *border = d->getScaleGrid();
- node->setInnerRect(QRectF(border->left(),
- border->top(),
- qMax(1, d->pix.width() - border->right() - border->left()),
- qMax(1, d->pix.height() - border->bottom() - border->top())));
- } else {
- node->setInnerRect(QRectF(0, 0, d->pix.width(), d->pix.height()));
- }
- node->setRect(QRectF(0, 0, width(), height()));
- node->setFiltering(d->smooth ? QSGTexture::Linear : QSGTexture::Nearest);
- node->setHorzontalTileMode(d->horizontalTileMode);
- node->setVerticalTileMode(d->verticalTileMode);
- node->setMirror(d->mirror);
- node->update();
-
- return node;
-}
-
-void QQuickBorderImage::pixmapChange()
-{
- Q_D(QQuickBorderImage);
-
- d->pixmapChanged = true;
-
- // When the pixmap changes, such as being deleted, we need to update the textures
- update();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickborderimage_p.h b/src/declarative/items/qquickborderimage_p.h
deleted file mode 100644
index 0af6fca55d..0000000000
--- a/src/declarative/items/qquickborderimage_p.h
+++ /dev/null
@@ -1,110 +0,0 @@
-// Commit: ebd4bc73c46c2962742a682b6a391fb68c482aec
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKBORDERIMAGE_P_H
-#define QQUICKBORDERIMAGE_P_H
-
-#include "qquickimagebase_p.h"
-
-QT_BEGIN_HEADER
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickScaleGrid;
-class QQuickGridScaledImage;
-class QQuickBorderImagePrivate;
-class Q_AUTOTEST_EXPORT QQuickBorderImage : public QQuickImageBase
-{
- Q_OBJECT
- Q_ENUMS(TileMode)
-
- Q_PROPERTY(QQuickScaleGrid *border READ border CONSTANT)
- Q_PROPERTY(TileMode horizontalTileMode READ horizontalTileMode WRITE setHorizontalTileMode NOTIFY horizontalTileModeChanged)
- Q_PROPERTY(TileMode verticalTileMode READ verticalTileMode WRITE setVerticalTileMode NOTIFY verticalTileModeChanged)
- // read-only for BorderImage
- Q_PROPERTY(QSize sourceSize READ sourceSize NOTIFY sourceSizeChanged)
-
-public:
- QQuickBorderImage(QQuickItem *parent=0);
- ~QQuickBorderImage();
-
- QQuickScaleGrid *border();
-
- enum TileMode { Stretch = Qt::StretchTile, Repeat = Qt::RepeatTile, Round = Qt::RoundTile };
-
- TileMode horizontalTileMode() const;
- void setHorizontalTileMode(TileMode);
-
- TileMode verticalTileMode() const;
- void setVerticalTileMode(TileMode);
-
- void setSource(const QUrl &url);
-
-Q_SIGNALS:
- void horizontalTileModeChanged();
- void verticalTileModeChanged();
- void sourceSizeChanged();
-
-protected:
- virtual void load();
- virtual void pixmapChange();
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
-
-private:
- void setGridScaledImage(const QQuickGridScaledImage& sci);
-
-private Q_SLOTS:
- void doUpdate();
- void requestFinished();
- void sciRequestFinished();
-
-private:
- Q_DISABLE_COPY(QQuickBorderImage)
- Q_DECLARE_PRIVATE(QQuickBorderImage)
-};
-
-QT_END_NAMESPACE
-QML_DECLARE_TYPE(QQuickBorderImage)
-QT_END_HEADER
-
-#endif // QQUICKBORDERIMAGE_P_H
diff --git a/src/declarative/items/qquickborderimage_p_p.h b/src/declarative/items/qquickborderimage_p_p.h
deleted file mode 100644
index 1875dc082a..0000000000
--- a/src/declarative/items/qquickborderimage_p_p.h
+++ /dev/null
@@ -1,103 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKBORDERIMAGE_P_P_H
-#define QQUICKBORDERIMAGE_P_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 "qquickimagebase_p_p.h"
-#include "qquickscalegrid_p_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QNetworkReply;
-class QQuickBorderImagePrivate : public QQuickImageBasePrivate
-{
- Q_DECLARE_PUBLIC(QQuickBorderImage)
-
-public:
- QQuickBorderImagePrivate()
- : border(0), sciReply(0),
- horizontalTileMode(QQuickBorderImage::Stretch),
- verticalTileMode(QQuickBorderImage::Stretch),
- redirectCount(0), pixmapChanged(false)
- {
- }
-
- ~QQuickBorderImagePrivate()
- {
- }
-
-
- QQuickScaleGrid *getScaleGrid()
- {
- Q_Q(QQuickBorderImage);
- if (!border) {
- border = new QQuickScaleGrid(q);
- FAST_CONNECT(border, SIGNAL(borderChanged()), q, SLOT(doUpdate()))
- }
- return border;
- }
-
- QQuickScaleGrid *border;
- QUrl sciurl;
- QNetworkReply *sciReply;
- QQuickBorderImage::TileMode horizontalTileMode;
- QQuickBorderImage::TileMode verticalTileMode;
- int redirectCount;
-
- bool pixmapChanged : 1;
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKBORDERIMAGE_P_P_H
diff --git a/src/declarative/items/qquickcanvas.cpp b/src/declarative/items/qquickcanvas.cpp
deleted file mode 100644
index 8022af98f4..0000000000
--- a/src/declarative/items/qquickcanvas.cpp
+++ /dev/null
@@ -1,2644 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickcanvas.h"
-#include "qquickcanvas_p.h"
-
-#include "qquickitem.h"
-#include "qquickitem_p.h"
-
-#include <private/qsgrenderer_p.h>
-#include <private/qsgtexture_p.h>
-#include <private/qsgflashnode_p.h>
-#include <qsgengine.h>
-
-#include <private/qguiapplication_p.h>
-#include <QtGui/QInputPanel>
-
-#include <private/qabstractanimation_p.h>
-
-#include <QtGui/qpainter.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qmatrix4x4.h>
-#include <QtCore/qvarlengtharray.h>
-#include <QtCore/qabstractanimation.h>
-#include <QtDeclarative/qdeclarativeincubator.h>
-
-#include <private/qdeclarativedebugtrace_p.h>
-
-QT_BEGIN_NAMESPACE
-
-#define QQUICK_CANVAS_TIMING
-#ifdef QQUICK_CANVAS_TIMING
-static bool qquick_canvas_timing = !qgetenv("QML_CANVAS_TIMING").isEmpty();
-static QTime threadTimer;
-static int syncTime;
-static int renderTime;
-static int swapTime;
-#endif
-
-DEFINE_BOOL_CONFIG_OPTION(qmlFixedAnimationStep, QML_FIXED_ANIMATION_STEP)
-DEFINE_BOOL_CONFIG_OPTION(qmlNoThreadedRenderer, QML_BAD_GUI_RENDER_LOOP)
-
-extern Q_GUI_EXPORT QImage qt_gl_read_framebuffer(const QSize &size, bool alpha_format, bool include_alpha);
-
-void QQuickCanvasPrivate::updateFocusItemTransform()
-{
- Q_Q(QQuickCanvas);
- QQuickItem *focus = q->activeFocusItem();
- if (focus && qApp->inputPanel()->inputItem() == focus)
- qApp->inputPanel()->setInputItemTransform(QQuickItemPrivate::get(focus)->itemToCanvasTransform());
-}
-
-class QQuickCanvasIncubationController : public QObject, public QDeclarativeIncubationController
-{
-public:
- QQuickCanvasIncubationController(QQuickCanvasPrivate *canvas)
- : m_canvas(canvas), m_eventSent(false) {}
-
-protected:
- virtual bool event(QEvent *e)
- {
- if (e->type() == QEvent::User) {
- Q_ASSERT(m_eventSent);
-
- bool *amtp = m_canvas->thread->allowMainThreadProcessing();
- while (incubatingObjectCount()) {
- if (amtp)
- incubateWhile(amtp);
- else
- incubateFor(5);
- QCoreApplication::processEvents();
- }
-
- m_eventSent = false;
- }
- return QObject::event(e);
- }
-
- virtual void incubatingObjectCountChanged(int count)
- {
- if (count && !m_eventSent) {
- m_eventSent = true;
- QCoreApplication::postEvent(this, new QEvent(QEvent::User));
- }
- }
-
-private:
- QQuickCanvasPrivate *m_canvas;
- bool m_eventSent;
-};
-
-class QQuickCanvasPlainRenderLoop : public QObject, public QQuickCanvasRenderLoop
-{
-public:
- QQuickCanvasPlainRenderLoop()
- : updatePending(false)
- , animationRunning(false)
- {
- }
-
- virtual void paint() {
- updatePending = false;
- if (animationRunning && animationDriver())
- animationDriver()->advance();
- polishItems();
- syncSceneGraph();
- makeCurrent();
- glViewport(0, 0, size.width(), size.height());
- renderSceneGraph(size);
- swapBuffers();
-
- if (animationRunning)
- maybeUpdate();
- }
-
- virtual QImage grab() {
- return qt_gl_read_framebuffer(size, false, false);
- }
-
- virtual void startRendering() {
- if (!glContext()) {
- createGLContext();
- makeCurrent();
- initializeSceneGraph();
- } else {
- makeCurrent();
- }
- maybeUpdate();
- }
-
- virtual void stopRendering() {
- cleanupNodesOnShutdown();
- }
-
- virtual void maybeUpdate() {
- if (!updatePending) {
- QCoreApplication::postEvent(this, new QEvent(QEvent::User));
- updatePending = true;
- }
- }
-
- virtual void animationStarted() {
- animationRunning = true;
- maybeUpdate();
- }
-
- virtual void animationStopped() {
- animationRunning = false;
- }
-
- virtual bool isRunning() const { return glContext(); } // Event loop is always running...
- virtual void resize(const QSize &s) { size = s; }
- virtual void setWindowSize(const QSize &s) { size = s; }
-
- bool event(QEvent *e) {
- if (e->type() == QEvent::User) {
- paint();
- return true;
- }
- return QObject::event(e);
- }
-
- QSize size;
-
- uint updatePending : 1;
- uint animationRunning : 1;
-};
-
-
-
-/*
-Focus behavior
-==============
-
-Prior to being added to a valid canvas items can set and clear focus with no
-effect. Only once items are added to a canvas (by way of having a parent set that
-already belongs to a canvas) do the focus rules apply. Focus goes back to
-having no effect if an item is removed from a canvas.
-
-When an item is moved into a new focus scope (either being added to a canvas
-for the first time, or having its parent changed), if the focus scope already has
-a scope focused item that takes precedence over the item being added. Otherwise,
-the focus of the added tree is used. In the case of of a tree of items being
-added to a canvas for the first time, which may have a conflicted focus state (two
-or more items in one scope having focus set), the same rule is applied item by item -
-thus the first item that has focus will get it (assuming the scope doesn't already
-have a scope focused item), and the other items will have their focus cleared.
-*/
-
-/*
- Threaded Rendering
- ==================
-
- The threaded rendering uses a number of different variables to track potential
- states used to handle resizing, initial paint, grabbing and driving animations
- while ALWAYS keeping the GL context in the rendering thread and keeping the
- overhead of normal one-shot paints and vblank driven animations at a minimum.
-
- Resize, initial show and grab suffer slightly in this model as they are locked
- to the rendering in the rendering thread, but this is a necessary evil for
- the system to work.
-
- Variables that are used:
-
- Private::animationRunning: This is true while the animations are running, and only
- written to inside locks.
-
- RenderThread::isGuiBlocked: This is used to indicate that the GUI thread owns the
- lock. This variable is an integer to allow for recursive calls to lockInGui()
- without using a recursive mutex. See isGuiBlockPending.
-
- RenderThread::isPaintComplete: This variable is cleared when rendering starts and
- set once rendering is complete. It is monitored in the paintEvent(),
- resizeEvent() and grab() functions to force them to wait for rendering to
- complete.
-
- RenderThread::isGuiBlockPending: This variable is set in the render thread just
- before the sync event is sent to the GUI thread. It is used to avoid deadlocks
- in the case where render thread waits while waiting for GUI to pick up the sync
- event and GUI thread gets a resizeEvent, the initial paintEvent or a grab.
- When this happens, we use the
- exhaustSyncEvent() function to do the sync right there and mark the coming
- sync event to be discarded. There can only ever be one sync incoming.
-
- RenderThread::isRenderBlock: This variable is true when animations are not
- running and the render thread has gone to sleep, waiting for more to do.
-
- RenderThread::isExternalUpdatePending: This variable is set to false when
- a new render pass is started and to true in maybeUpdate(). It is an
- indication to the render thread that another render pass needs to take
- place, rather than the render thread going to sleep after completing its swap.
-
- RenderThread::doGrab: This variable is set by the grab() function and
- tells the renderer to do a grab after rendering is complete and before
- swapping happens.
-
- RenderThread::shouldExit: This variable is used to determine if the render
- thread should do a nother pass. It is typically set as a result of show()
- and unset as a result of hide() or during shutdown()
-
- RenderThread::hasExited: Used by the GUI thread to synchronize the shutdown
- after shouldExit has been set to true.
- */
-
-// #define FOCUS_DEBUG
-// #define MOUSE_DEBUG
-// #define TOUCH_DEBUG
-// #define DIRTY_DEBUG
-// #define THREAD_DEBUG
-
-// #define FRAME_TIMING
-
-#ifdef FRAME_TIMING
-static QTime frameTimer;
-int sceneGraphRenderTime;
-int readbackTime;
-#endif
-
-QQuickItem::UpdatePaintNodeData::UpdatePaintNodeData()
-: transformNode(0)
-{
-}
-
-QQuickRootItem::QQuickRootItem()
-{
-}
-
-void QQuickCanvas::exposeEvent(QExposeEvent *)
-{
- Q_D(QQuickCanvas);
- d->thread->paint();
-}
-
-void QQuickCanvas::resizeEvent(QResizeEvent *)
-{
- Q_D(QQuickCanvas);
- d->thread->resize(size());
-}
-
-void QQuickCanvas::animationStarted()
-{
- d_func()->thread->animationStarted();
-}
-
-void QQuickCanvas::animationStopped()
-{
- d_func()->thread->animationStopped();
-}
-
-void QQuickCanvas::showEvent(QShowEvent *)
-{
- Q_D(QQuickCanvas);
- if (d->vsyncAnimations) {
- if (!d->animationDriver) {
- d->animationDriver = d->context->createAnimationDriver(this);
- connect(d->animationDriver, SIGNAL(started()), this, SLOT(animationStarted()), Qt::DirectConnection);
- connect(d->animationDriver, SIGNAL(stopped()), this, SLOT(animationStopped()), Qt::DirectConnection);
- }
- d->animationDriver->install();
- }
-
- if (!d->thread->isRunning()) {
- d->thread->setWindowSize(size());
- d->thread->startRendering();
- }
-}
-
-void QQuickCanvas::hideEvent(QHideEvent *)
-{
- Q_D(QQuickCanvas);
- d->thread->stopRendering();
-}
-
-void QQuickCanvas::focusOutEvent(QFocusEvent *)
-{
- Q_D(QQuickCanvas);
- d->rootItem->setFocus(false);
-}
-
-void QQuickCanvas::focusInEvent(QFocusEvent *)
-{
- Q_D(QQuickCanvas);
- d->rootItem->setFocus(true);
-}
-
-
-/*!
- Sets weither this canvas should use vsync driven animations.
-
- This option can only be set on one single QQuickCanvas, and that it's
- vsync signal will then be used to drive all animations in the
- process.
-
- This feature is primarily useful for single QQuickCanvas, QML-only
- applications.
-
- \warning Enabling vsync on multiple QQuickCanvas instances has
- undefined behavior.
- */
-void QQuickCanvas::setVSyncAnimations(bool enabled)
-{
- Q_D(QQuickCanvas);
- if (visible()) {
- qWarning("QQuickCanvas::setVSyncAnimations: Cannot be changed when widget is shown");
- return;
- }
- d->vsyncAnimations = enabled;
-}
-
-
-
-/*!
- Returns true if this canvas should use vsync driven animations;
- otherwise returns false.
- */
-bool QQuickCanvas::vsyncAnimations() const
-{
- Q_D(const QQuickCanvas);
- return d->vsyncAnimations;
-}
-
-void QQuickCanvasPrivate::initializeSceneGraph()
-{
- if (!context)
- context = QSGContext::createDefaultContext();
-
- if (context->isReady())
- return;
-
- QOpenGLContext *glctx = const_cast<QOpenGLContext *>(QOpenGLContext::currentContext());
- context->initialize(glctx);
-
- Q_Q(QQuickCanvas);
-
- if (!QQuickItemPrivate::get(rootItem)->itemNode()->parent()) {
- context->rootNode()->appendChildNode(QQuickItemPrivate::get(rootItem)->itemNode());
- }
-
- engine = new QSGEngine();
- engine->setCanvas(q);
-
- emit q_func()->sceneGraphInitialized();
-}
-
-void QQuickCanvasPrivate::polishItems()
-{
- while (!itemsToPolish.isEmpty()) {
- QSet<QQuickItem *>::Iterator iter = itemsToPolish.begin();
- QQuickItem *item = *iter;
- itemsToPolish.erase(iter);
- QQuickItemPrivate::get(item)->polishScheduled = false;
- item->updatePolish();
- }
- updateFocusItemTransform();
-}
-
-
-void QQuickCanvasPrivate::syncSceneGraph()
-{
- updateDirtyNodes();
-
- // Copy the current state of clearing from canvas into renderer.
- context->renderer()->setClearColor(clearColor);
- QSGRenderer::ClearMode mode = QSGRenderer::ClearStencilBuffer | QSGRenderer::ClearDepthBuffer;
- if (clearBeforeRendering)
- mode |= QSGRenderer::ClearColorBuffer;
- context->renderer()->setClearMode(mode);
-}
-
-
-void QQuickCanvasPrivate::renderSceneGraph(const QSize &size)
-{
- Q_Q(QQuickCanvas);
- context->renderer()->setDeviceRect(QRect(QPoint(0, 0), size));
- context->renderer()->setViewportRect(QRect(QPoint(0, 0), renderTarget ? renderTarget->size() : size));
- context->renderer()->setProjectionMatrixToDeviceRect();
-
- emit q->beforeRendering();
- context->renderNextFrame(renderTarget);
- emit q->afterRendering();
-
-#ifdef FRAME_TIMING
- sceneGraphRenderTime = frameTimer.elapsed();
-#endif
-
-#ifdef FRAME_TIMING
-// int pixel;
-// glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixel);
- readbackTime = frameTimer.elapsed();
-#endif
-}
-
-
-QQuickCanvasPrivate::QQuickCanvasPrivate()
- : rootItem(0)
- , activeFocusItem(0)
- , mouseGrabberItem(0)
- , dirtyItemList(0)
- , context(0)
- , clearColor(Qt::white)
- , vsyncAnimations(false)
- , clearBeforeRendering(true)
- , thread(0)
- , animationDriver(0)
- , renderTarget(0)
- , incubationController(0)
-{
-}
-
-QQuickCanvasPrivate::~QQuickCanvasPrivate()
-{
-}
-
-void QQuickCanvasPrivate::init(QQuickCanvas *c)
-{
- QUnifiedTimer* ut = QUnifiedTimer::instance(true);
- if (qmlFixedAnimationStep())
- ut->setConsistentTiming(true);
-
- q_ptr = c;
-
- Q_Q(QQuickCanvas);
-
- rootItem = new QQuickRootItem;
- QQuickItemPrivate *rootItemPrivate = QQuickItemPrivate::get(rootItem);
- rootItemPrivate->canvas = q;
- rootItemPrivate->flags |= QQuickItem::ItemIsFocusScope;
-
- // In the absence of a focus in event on some platforms assume the window will
- // be activated immediately and set focus on the rootItem
- // ### Remove when QTBUG-22415 is resolved.
- //It is important that this call happens after the rootItem has a canvas..
- rootItem->setFocus(true);
-
- bool threaded = !qmlNoThreadedRenderer();
-
- if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL)) {
- qWarning("QQuickCanvas: platform does not support threaded rendering!");
- threaded = false;
- }
-
- if (threaded)
- thread = new QQuickCanvasRenderThread();
- else
- thread = new QQuickCanvasPlainRenderLoop();
-
- thread->renderer = q;
- thread->d = this;
-
- context = QSGContext::createDefaultContext();
- thread->moveContextToThread(context);
-
- q->setSurfaceType(QWindow::OpenGLSurface);
- q->setFormat(context->defaultSurfaceFormat());
-}
-
-QDeclarativeListProperty<QObject> QQuickCanvasPrivate::data()
-{
- initRootItem();
- return QQuickItemPrivate::get(rootItem)->data();
-}
-
-void QQuickCanvasPrivate::initRootItem()
-{
- Q_Q(QQuickCanvas);
- q->connect(q, SIGNAL(widthChanged(int)),
- rootItem, SLOT(setWidth(int)));
- q->connect(q, SIGNAL(heightChanged(int)),
- rootItem, SLOT(setHeight(int)));
- rootItem->setWidth(q->width());
- rootItem->setHeight(q->height());
-}
-
-void QQuickCanvasPrivate::transformTouchPoints(QList<QTouchEvent::TouchPoint> &touchPoints, const QTransform &transform)
-{
- for (int i=0; i<touchPoints.count(); i++) {
- QTouchEvent::TouchPoint &touchPoint = touchPoints[i];
- touchPoint.setRect(transform.mapRect(touchPoint.sceneRect()));
- touchPoint.setStartPos(transform.map(touchPoint.startScenePos()));
- touchPoint.setLastPos(transform.map(touchPoint.lastScenePos()));
- }
-}
-
-
-/*!
-Translates the data in \a touchEvent to this canvas. This method leaves the item local positions in
-\a touchEvent untouched (these are filled in later).
-*/
-void QQuickCanvasPrivate::translateTouchEvent(QTouchEvent *touchEvent)
-{
-// Q_Q(QQuickCanvas);
-
-// touchEvent->setWidget(q); // ### refactor...
-
- QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();
- for (int i = 0; i < touchPoints.count(); ++i) {
- QTouchEvent::TouchPoint &touchPoint = touchPoints[i];
-
- touchPoint.setScreenRect(touchPoint.sceneRect());
- touchPoint.setStartScreenPos(touchPoint.startScenePos());
- touchPoint.setLastScreenPos(touchPoint.lastScenePos());
-
- touchPoint.setSceneRect(touchPoint.rect());
- touchPoint.setStartScenePos(touchPoint.startPos());
- touchPoint.setLastScenePos(touchPoint.lastPos());
-
- if (touchPoint.isPrimary())
- lastMousePosition = touchPoint.pos().toPoint();
- }
- touchEvent->setTouchPoints(touchPoints);
-}
-
-void QQuickCanvasPrivate::setFocusInScope(QQuickItem *scope, QQuickItem *item, FocusOptions options)
-{
- Q_Q(QQuickCanvas);
-
- Q_ASSERT(item);
- Q_ASSERT(scope || item == rootItem);
-
-#ifdef FOCUS_DEBUG
- qWarning() << "QQuickCanvasPrivate::setFocusInScope():";
- qWarning() << " scope:" << (QObject *)scope;
- if (scope)
- qWarning() << " scopeSubFocusItem:" << (QObject *)QQuickItemPrivate::get(scope)->subFocusItem;
- qWarning() << " item:" << (QObject *)item;
- qWarning() << " activeFocusItem:" << (QObject *)activeFocusItem;
-#endif
-
- QQuickItemPrivate *scopePrivate = scope ? QQuickItemPrivate::get(scope) : 0;
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
-
- QQuickItem *oldActiveFocusItem = 0;
- QQuickItem *newActiveFocusItem = 0;
-
- QVarLengthArray<QQuickItem *, 20> changed;
-
- // Does this change the active focus?
- if (item == rootItem || scopePrivate->activeFocus) {
- oldActiveFocusItem = activeFocusItem;
- newActiveFocusItem = item;
- while (newActiveFocusItem->isFocusScope() && newActiveFocusItem->scopedFocusItem())
- newActiveFocusItem = newActiveFocusItem->scopedFocusItem();
-
- if (oldActiveFocusItem) {
-#ifndef QT_NO_IM
- qApp->inputPanel()->commit();
-#endif
-
- activeFocusItem = 0;
- QFocusEvent event(QEvent::FocusOut, Qt::OtherFocusReason);
- q->sendEvent(oldActiveFocusItem, &event);
-
- QQuickItem *afi = oldActiveFocusItem;
- while (afi != scope) {
- if (QQuickItemPrivate::get(afi)->activeFocus) {
- QQuickItemPrivate::get(afi)->activeFocus = false;
- changed << afi;
- }
- afi = afi->parentItem();
- }
- }
- }
-
- if (item != rootItem) {
- QQuickItem *oldSubFocusItem = scopePrivate->subFocusItem;
- // Correct focus chain in scope
- if (oldSubFocusItem) {
- QQuickItem *sfi = scopePrivate->subFocusItem->parentItem();
- while (sfi != scope) {
- QQuickItemPrivate::get(sfi)->subFocusItem = 0;
- sfi = sfi->parentItem();
- }
- }
- {
- scopePrivate->subFocusItem = item;
- QQuickItem *sfi = scopePrivate->subFocusItem->parentItem();
- while (sfi != scope) {
- QQuickItemPrivate::get(sfi)->subFocusItem = item;
- sfi = sfi->parentItem();
- }
- }
-
- if (oldSubFocusItem) {
- QQuickItemPrivate::get(oldSubFocusItem)->focus = false;
- changed << oldSubFocusItem;
- }
- }
-
- if (!(options & DontChangeFocusProperty)) {
-// if (item != rootItem || QGuiApplication::focusWindow() == q) { // QTBUG-22415
- itemPrivate->focus = true;
- changed << item;
-// }
- }
-
- if (newActiveFocusItem && rootItem->hasFocus()) {
- activeFocusItem = newActiveFocusItem;
-
- QQuickItemPrivate::get(newActiveFocusItem)->activeFocus = true;
- changed << newActiveFocusItem;
-
- QQuickItem *afi = newActiveFocusItem->parentItem();
- while (afi && afi != scope) {
- if (afi->isFocusScope()) {
- QQuickItemPrivate::get(afi)->activeFocus = true;
- changed << afi;
- }
- afi = afi->parentItem();
- }
-
- updateInputMethodData();
-
- QFocusEvent event(QEvent::FocusIn, Qt::OtherFocusReason);
- q->sendEvent(newActiveFocusItem, &event);
- } else {
- updateInputMethodData();
- }
-
- if (!changed.isEmpty())
- notifyFocusChangesRecur(changed.data(), changed.count() - 1);
-}
-
-void QQuickCanvasPrivate::clearFocusInScope(QQuickItem *scope, QQuickItem *item, FocusOptions options)
-{
- Q_Q(QQuickCanvas);
-
- Q_UNUSED(item);
- Q_ASSERT(item);
- Q_ASSERT(scope || item == rootItem);
-
-#ifdef FOCUS_DEBUG
- qWarning() << "QQuickCanvasPrivate::clearFocusInScope():";
- qWarning() << " scope:" << (QObject *)scope;
- qWarning() << " item:" << (QObject *)item;
- qWarning() << " activeFocusItem:" << (QObject *)activeFocusItem;
-#endif
-
- QQuickItemPrivate *scopePrivate = scope ? QQuickItemPrivate::get(scope) : 0;
-
- QQuickItem *oldActiveFocusItem = 0;
- QQuickItem *newActiveFocusItem = 0;
-
- QVarLengthArray<QQuickItem *, 20> changed;
-
- Q_ASSERT(item == rootItem || item == scopePrivate->subFocusItem);
-
- // Does this change the active focus?
- if (item == rootItem || scopePrivate->activeFocus) {
- oldActiveFocusItem = activeFocusItem;
- newActiveFocusItem = scope;
-
- Q_ASSERT(oldActiveFocusItem);
-
-#ifndef QT_NO_IM
- qApp->inputPanel()->commit();
-#endif
-
- activeFocusItem = 0;
- QFocusEvent event(QEvent::FocusOut, Qt::OtherFocusReason);
- q->sendEvent(oldActiveFocusItem, &event);
-
- QQuickItem *afi = oldActiveFocusItem;
- while (afi != scope) {
- if (QQuickItemPrivate::get(afi)->activeFocus) {
- QQuickItemPrivate::get(afi)->activeFocus = false;
- changed << afi;
- }
- afi = afi->parentItem();
- }
- }
-
- if (item != rootItem) {
- QQuickItem *oldSubFocusItem = scopePrivate->subFocusItem;
- // Correct focus chain in scope
- if (oldSubFocusItem) {
- QQuickItem *sfi = scopePrivate->subFocusItem->parentItem();
- while (sfi != scope) {
- QQuickItemPrivate::get(sfi)->subFocusItem = 0;
- sfi = sfi->parentItem();
- }
- }
- scopePrivate->subFocusItem = 0;
-
- if (oldSubFocusItem && !(options & DontChangeFocusProperty)) {
- QQuickItemPrivate::get(oldSubFocusItem)->focus = false;
- changed << oldSubFocusItem;
- }
- } else if (!(options & DontChangeFocusProperty)) {
- QQuickItemPrivate::get(item)->focus = false;
- changed << item;
- }
-
- if (newActiveFocusItem) {
- Q_ASSERT(newActiveFocusItem == scope);
- activeFocusItem = scope;
-
- updateInputMethodData();
-
- QFocusEvent event(QEvent::FocusIn, Qt::OtherFocusReason);
- q->sendEvent(newActiveFocusItem, &event);
- } else {
- updateInputMethodData();
- }
-
- if (!changed.isEmpty())
- notifyFocusChangesRecur(changed.data(), changed.count() - 1);
-}
-
-void QQuickCanvasPrivate::notifyFocusChangesRecur(QQuickItem **items, int remaining)
-{
- QDeclarativeGuard<QQuickItem> item(*items);
-
- if (remaining)
- notifyFocusChangesRecur(items + 1, remaining - 1);
-
- if (item) {
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
-
- if (itemPrivate->notifiedFocus != itemPrivate->focus) {
- itemPrivate->notifiedFocus = itemPrivate->focus;
- emit item->focusChanged(itemPrivate->focus);
- }
-
- if (item && itemPrivate->notifiedActiveFocus != itemPrivate->activeFocus) {
- itemPrivate->notifiedActiveFocus = itemPrivate->activeFocus;
- itemPrivate->itemChange(QQuickItem::ItemActiveFocusHasChanged, itemPrivate->activeFocus);
- emit item->activeFocusChanged(itemPrivate->activeFocus);
- }
- }
-}
-
-void QQuickCanvasPrivate::updateInputMethodData()
-{
- QQuickItem *inputItem = 0;
- if (activeFocusItem && activeFocusItem->flags() & QQuickItem::ItemAcceptsInputMethod)
- inputItem = activeFocusItem;
- qApp->inputPanel()->setInputItem(inputItem);
-}
-
-void QQuickCanvasPrivate::dirtyItem(QQuickItem *)
-{
- Q_Q(QQuickCanvas);
- q->maybeUpdate();
-}
-
-void QQuickCanvasPrivate::cleanup(QSGNode *n)
-{
- Q_Q(QQuickCanvas);
-
- Q_ASSERT(!cleanupNodeList.contains(n));
- cleanupNodeList.append(n);
- q->maybeUpdate();
-}
-
-
-/*!
- \qmlclass Window QQuickCanvas
- \inqmlmodule QtQuick.Window 2
- \brief The Window object creates a new top-level window.
-
- The Window object creates a new top-level window for a QtQuick scene. It automatically sets up the
- window for use with QtQuick 2.0 graphical elements.
-*/
-/*!
- \class QQuickCanvas
- \since QtQuick 2.0
- \brief The QQuickCanvas class provides the canvas for displaying a graphical QML scene
-
- QQuickCanvas provides the graphical scene management needed to interact with and display
- a scene of QQuickItems.
-
- A QQuickCanvas always has a single invisible root item. To add items to this canvas,
- reparent the items to the root item or to an existing item in the scene.
-
- For easily displaying a scene from a QML file, see \l{QQuickView}.
-*/
-QQuickCanvas::QQuickCanvas(QWindow *parent)
- : QWindow(*(new QQuickCanvasPrivate), parent)
-{
- Q_D(QQuickCanvas);
- d->init(this);
-}
-
-QQuickCanvas::QQuickCanvas(QQuickCanvasPrivate &dd, QWindow *parent)
- : QWindow(dd, parent)
-{
- Q_D(QQuickCanvas);
- d->init(this);
-}
-
-QQuickCanvas::~QQuickCanvas()
-{
- Q_D(QQuickCanvas);
-
- if (d->thread->isRunning())
- d->thread->stopRendering();
-
- // ### should we change ~QQuickItem to handle this better?
- // manually cleanup for the root item (item destructor only handles these when an item is parented)
- QQuickItemPrivate *rootItemPrivate = QQuickItemPrivate::get(d->rootItem);
- rootItemPrivate->removeFromDirtyList();
-
- delete d->incubationController; d->incubationController = 0;
-
- delete d->rootItem; d->rootItem = 0;
-
- delete d->thread; d->thread = 0;
-}
-
-/*!
- Returns the invisible root item of the scene.
-
- A QQuickCanvas always has a single invisible root item. To add items to this canvas,
- reparent the items to the root item or to an existing item in the scene.
-*/
-QQuickItem *QQuickCanvas::rootItem() const
-{
- Q_D(const QQuickCanvas);
-
- return d->rootItem;
-}
-
-/*!
- Returns the item which currently has active focus.
-*/
-QQuickItem *QQuickCanvas::activeFocusItem() const
-{
- Q_D(const QQuickCanvas);
-
- return d->activeFocusItem;
-}
-
-/*!
- Returns the item which currently has the mouse grab.
-*/
-QQuickItem *QQuickCanvas::mouseGrabberItem() const
-{
- Q_D(const QQuickCanvas);
-
- return d->mouseGrabberItem;
-}
-
-
-/*!
- \qmlproperty color QtQuick2.Window::Window::color
-
- The background color for the window.
-
- Setting this property is more efficient than using a separate Rectangle.
-*/
-
-bool QQuickCanvasPrivate::clearHover()
-{
- if (hoverItems.isEmpty())
- return false;
-
- QPointF pos = QCursor::pos(); // ### refactor: q->mapFromGlobal(QCursor::pos());
-
- bool accepted = false;
- foreach (QQuickItem* item, hoverItems)
- accepted = sendHoverEvent(QEvent::HoverLeave, item, pos, pos, QGuiApplication::keyboardModifiers(), true) || accepted;
- hoverItems.clear();
- return accepted;
-}
-
-
-bool QQuickCanvas::event(QEvent *e)
-{
- Q_D(QQuickCanvas);
-
- switch (e->type()) {
-
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- {
- QTouchEvent *touch = static_cast<QTouchEvent *>(e);
- d->translateTouchEvent(touch);
- d->deliverTouchEvent(touch);
- if (!touch->isAccepted())
- return false;
- break;
- }
- case QEvent::Leave:
- d->clearHover();
- d->lastMousePosition = QPoint();
- break;
- case QEvent::DragEnter:
- case QEvent::DragLeave:
- case QEvent::DragMove:
- case QEvent::Drop:
- d->deliverDragEvent(&d->dragGrabber, e);
- break;
- case QEvent::WindowDeactivate:
- rootItem()->windowDeactivateEvent();
- break;
- default:
- break;
- }
-
- return QWindow::event(e);
-}
-
-void QQuickCanvas::keyPressEvent(QKeyEvent *e)
-{
- Q_D(QQuickCanvas);
-
- if (d->activeFocusItem)
- sendEvent(d->activeFocusItem, e);
-}
-
-void QQuickCanvas::keyReleaseEvent(QKeyEvent *e)
-{
- Q_D(QQuickCanvas);
-
- if (d->activeFocusItem)
- sendEvent(d->activeFocusItem, e);
-}
-
-bool QQuickCanvasPrivate::deliverInitialMousePressEvent(QQuickItem *item, QMouseEvent *event)
-{
- Q_Q(QQuickCanvas);
-
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
- if (itemPrivate->opacity == 0.0)
- return false;
-
- if (itemPrivate->flags & QQuickItem::ItemClipsChildrenToShape) {
- QPointF p = item->mapFromScene(event->windowPos());
- if (!QRectF(0, 0, item->width(), item->height()).contains(p))
- return false;
- }
-
- QList<QQuickItem *> children = itemPrivate->paintOrderChildItems();
- for (int ii = children.count() - 1; ii >= 0; --ii) {
- QQuickItem *child = children.at(ii);
- if (!child->isVisible() || !child->isEnabled())
- continue;
- if (deliverInitialMousePressEvent(child, event))
- return true;
- }
-
- if (itemPrivate->acceptedMouseButtons & event->button()) {
- QPointF p = item->mapFromScene(event->windowPos());
- if (QRectF(0, 0, item->width(), item->height()).contains(p)) {
- QMouseEvent me(event->type(), p, event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers());
- me.accept();
- mouseGrabberItem = item;
- q->sendEvent(item, &me);
- event->setAccepted(me.isAccepted());
- if (me.isAccepted())
- return true;
- mouseGrabberItem->ungrabMouse();
- mouseGrabberItem = 0;
- }
- }
-
- return false;
-}
-
-bool QQuickCanvasPrivate::deliverMouseEvent(QMouseEvent *event)
-{
- Q_Q(QQuickCanvas);
-
- lastMousePosition = event->windowPos();
-
- if (!mouseGrabberItem &&
- event->type() == QEvent::MouseButtonPress &&
- (event->button() & event->buttons()) == event->buttons()) {
- return deliverInitialMousePressEvent(rootItem, event);
- }
-
- if (mouseGrabberItem) {
- QQuickItemPrivate *mgPrivate = QQuickItemPrivate::get(mouseGrabberItem);
- const QTransform &transform = mgPrivate->canvasToItemTransform();
- QMouseEvent me(event->type(), transform.map(event->windowPos()), event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers());
- me.accept();
- q->sendEvent(mouseGrabberItem, &me);
- event->setAccepted(me.isAccepted());
- if (me.isAccepted())
- return true;
- }
-
- return false;
-}
-
-void QQuickCanvas::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QQuickCanvas);
-
-#ifdef MOUSE_DEBUG
- qWarning() << "QQuickCanvas::mousePressEvent()" << event->pos() << event->button() << event->buttons();
-#endif
-
- d->deliverMouseEvent(event);
-}
-
-void QQuickCanvas::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QQuickCanvas);
-
-#ifdef MOUSE_DEBUG
- qWarning() << "QQuickCanvas::mouseReleaseEvent()" << event->pos() << event->button() << event->buttons();
-#endif
-
- if (!d->mouseGrabberItem) {
- QWindow::mouseReleaseEvent(event);
- return;
- }
-
- d->deliverMouseEvent(event);
- d->mouseGrabberItem = 0;
-}
-
-void QQuickCanvas::mouseDoubleClickEvent(QMouseEvent *event)
-{
- Q_D(QQuickCanvas);
-
-#ifdef MOUSE_DEBUG
- qWarning() << "QQuickCanvas::mouseDoubleClickEvent()" << event->pos() << event->button() << event->buttons();
-#endif
-
- if (!d->mouseGrabberItem && (event->button() & event->buttons()) == event->buttons()) {
- if (d->deliverInitialMousePressEvent(d->rootItem, event))
- event->accept();
- else
- event->ignore();
- return;
- }
-
- d->deliverMouseEvent(event);
-}
-
-bool QQuickCanvasPrivate::sendHoverEvent(QEvent::Type type, QQuickItem *item,
- const QPointF &scenePos, const QPointF &lastScenePos,
- Qt::KeyboardModifiers modifiers, bool accepted)
-{
- Q_Q(QQuickCanvas);
- const QTransform transform = QQuickItemPrivate::get(item)->canvasToItemTransform();
-
- //create copy of event
- QHoverEvent hoverEvent(type, transform.map(scenePos), transform.map(lastScenePos), modifiers);
- hoverEvent.setAccepted(accepted);
-
- q->sendEvent(item, &hoverEvent);
-
- return hoverEvent.isAccepted();
-}
-
-void QQuickCanvas::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QQuickCanvas);
-
-#ifdef MOUSE_DEBUG
- qWarning() << "QQuickCanvas::mouseMoveEvent()" << event->pos() << event->button() << event->buttons();
-#endif
-
- if (!d->mouseGrabberItem) {
- if (d->lastMousePosition.isNull())
- d->lastMousePosition = event->windowPos();
- QPointF last = d->lastMousePosition;
- d->lastMousePosition = event->windowPos();
-
- bool accepted = event->isAccepted();
- bool delivered = d->deliverHoverEvent(d->rootItem, event->windowPos(), last, event->modifiers(), accepted);
- if (!delivered) {
- //take care of any exits
- accepted = d->clearHover();
- }
- event->setAccepted(accepted);
- return;
- }
-
- d->deliverMouseEvent(event);
-}
-
-bool QQuickCanvasPrivate::deliverHoverEvent(QQuickItem *item, const QPointF &scenePos, const QPointF &lastScenePos,
- Qt::KeyboardModifiers modifiers, bool &accepted)
-{
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
- if (itemPrivate->opacity == 0.0)
- return false;
-
- if (itemPrivate->flags & QQuickItem::ItemClipsChildrenToShape) {
- QPointF p = item->mapFromScene(scenePos);
- if (!QRectF(0, 0, item->width(), item->height()).contains(p))
- return false;
- }
-
- QList<QQuickItem *> children = itemPrivate->paintOrderChildItems();
- for (int ii = children.count() - 1; ii >= 0; --ii) {
- QQuickItem *child = children.at(ii);
- if (!child->isVisible() || !child->isEnabled())
- continue;
- if (deliverHoverEvent(child, scenePos, lastScenePos, modifiers, accepted))
- return true;
- }
-
- if (itemPrivate->hoverEnabled) {
- QPointF p = item->mapFromScene(scenePos);
- if (QRectF(0, 0, item->width(), item->height()).contains(p)) {
- if (!hoverItems.isEmpty() && hoverItems[0] == item) {
- //move
- accepted = sendHoverEvent(QEvent::HoverMove, item, scenePos, lastScenePos, modifiers, accepted);
- } else {
- QList<QQuickItem *> itemsToHover;
- QQuickItem* parent = item;
- itemsToHover << item;
- while ((parent = parent->parentItem()))
- itemsToHover << parent;
-
- // Leaving from previous hovered items until we reach the item or one of its ancestors.
- while (!hoverItems.isEmpty() && !itemsToHover.contains(hoverItems[0])) {
- sendHoverEvent(QEvent::HoverLeave, hoverItems[0], scenePos, lastScenePos, modifiers, accepted);
- hoverItems.removeFirst();
- }
-
- if (!hoverItems.isEmpty() && hoverItems[0] == item){//Not entering a new Item
- // ### Shouldn't we send moves for the parent items as well?
- accepted = sendHoverEvent(QEvent::HoverMove, item, scenePos, lastScenePos, modifiers, accepted);
- } else {
- // Enter items that are not entered yet.
- int startIdx = -1;
- if (!hoverItems.isEmpty())
- startIdx = itemsToHover.indexOf(hoverItems[0]) - 1;
- if (startIdx == -1)
- startIdx = itemsToHover.count() - 1;
-
- for (int i = startIdx; i >= 0; i--) {
- QQuickItem *itemToHover = itemsToHover[i];
- if (QQuickItemPrivate::get(itemToHover)->hoverEnabled) {
- hoverItems.prepend(itemToHover);
- sendHoverEvent(QEvent::HoverEnter, itemToHover, scenePos, lastScenePos, modifiers, accepted);
- }
- }
- }
- }
- return true;
- }
- }
-
- return false;
-}
-
-bool QQuickCanvasPrivate::deliverWheelEvent(QQuickItem *item, QWheelEvent *event)
-{
- Q_Q(QQuickCanvas);
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
- if (itemPrivate->opacity == 0.0)
- return false;
-
- if (itemPrivate->flags & QQuickItem::ItemClipsChildrenToShape) {
- QPointF p = item->mapFromScene(event->posF());
- if (!QRectF(0, 0, item->width(), item->height()).contains(p))
- return false;
- }
-
- QList<QQuickItem *> children = itemPrivate->paintOrderChildItems();
- for (int ii = children.count() - 1; ii >= 0; --ii) {
- QQuickItem *child = children.at(ii);
- if (!child->isVisible() || !child->isEnabled())
- continue;
- if (deliverWheelEvent(child, event))
- return true;
- }
-
- QPointF p = item->mapFromScene(event->posF());
- if (QRectF(0, 0, item->width(), item->height()).contains(p)) {
- QWheelEvent wheel(p, event->delta(), event->buttons(), event->modifiers(), event->orientation());
- wheel.accept();
- q->sendEvent(item, &wheel);
- if (wheel.isAccepted()) {
- event->accept();
- return true;
- }
- }
-
- return false;
-}
-
-#ifndef QT_NO_WHEELEVENT
-void QQuickCanvas::wheelEvent(QWheelEvent *event)
-{
- Q_D(QQuickCanvas);
-#ifdef MOUSE_DEBUG
- qWarning() << "QQuickCanvas::wheelEvent()" << event->pos() << event->delta() << event->orientation();
-#endif
- event->ignore();
- d->deliverWheelEvent(d->rootItem, event);
-}
-#endif // QT_NO_WHEELEVENT
-
-bool QQuickCanvasPrivate::deliverTouchEvent(QTouchEvent *event)
-{
-#ifdef TOUCH_DEBUG
- if (event->type() == QEvent::TouchBegin)
- qWarning("touchBeginEvent");
- else if (event->type() == QEvent::TouchUpdate)
- qWarning("touchUpdateEvent");
- else if (event->type() == QEvent::TouchEnd)
- qWarning("touchEndEvent");
-#endif
-
- QHash<QQuickItem *, QList<QTouchEvent::TouchPoint> > updatedPoints;
-
- if (event->type() == QTouchEvent::TouchBegin) { // all points are new touch points
- QSet<int> acceptedNewPoints;
- deliverTouchPoints(rootItem, event, event->touchPoints(), &acceptedNewPoints, &updatedPoints);
- if (acceptedNewPoints.count() > 0)
- event->accept();
- return event->isAccepted();
- }
-
- const QList<QTouchEvent::TouchPoint> &touchPoints = event->touchPoints();
- QList<QTouchEvent::TouchPoint> newPoints;
- QQuickItem *item = 0;
- for (int i=0; i<touchPoints.count(); i++) {
- const QTouchEvent::TouchPoint &touchPoint = touchPoints[i];
- switch (touchPoint.state()) {
- case Qt::TouchPointPressed:
- newPoints << touchPoint;
- break;
- case Qt::TouchPointMoved:
- case Qt::TouchPointStationary:
- case Qt::TouchPointReleased:
- if (itemForTouchPointId.contains(touchPoint.id())) {
- item = itemForTouchPointId[touchPoint.id()];
- if (item)
- updatedPoints[item].append(touchPoint);
- }
- break;
- default:
- break;
- }
- }
-
- if (newPoints.count() > 0 || updatedPoints.count() > 0) {
- QSet<int> acceptedNewPoints;
- int prevCount = updatedPoints.count();
- deliverTouchPoints(rootItem, event, newPoints, &acceptedNewPoints, &updatedPoints);
- if (acceptedNewPoints.count() > 0 || updatedPoints.count() != prevCount)
- event->accept();
- }
-
- if (event->touchPointStates() & Qt::TouchPointReleased) {
- for (int i=0; i<touchPoints.count(); i++) {
- if (touchPoints[i].state() == Qt::TouchPointReleased)
- itemForTouchPointId.remove(touchPoints[i].id());
- }
- }
-
- return event->isAccepted();
-}
-
-bool QQuickCanvasPrivate::deliverTouchPoints(QQuickItem *item, QTouchEvent *event, const QList<QTouchEvent::TouchPoint> &newPoints, QSet<int> *acceptedNewPoints, QHash<QQuickItem *, QList<QTouchEvent::TouchPoint> > *updatedPoints)
-{
- Q_Q(QQuickCanvas);
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
-
- if (itemPrivate->opacity == 0.0)
- return false;
-
- if (itemPrivate->flags & QQuickItem::ItemClipsChildrenToShape) {
- QRectF bounds(0, 0, item->width(), item->height());
- for (int i=0; i<newPoints.count(); i++) {
- QPointF p = item->mapFromScene(newPoints[i].scenePos());
- if (!bounds.contains(p))
- return false;
- }
- }
-
- QList<QQuickItem *> children = itemPrivate->paintOrderChildItems();
- for (int ii = children.count() - 1; ii >= 0; --ii) {
- QQuickItem *child = children.at(ii);
- if (!child->isEnabled())
- continue;
- if (deliverTouchPoints(child, event, newPoints, acceptedNewPoints, updatedPoints))
- return true;
- }
-
- QList<QTouchEvent::TouchPoint> matchingPoints;
- if (newPoints.count() > 0 && acceptedNewPoints->count() < newPoints.count()) {
- QRectF bounds(0, 0, item->width(), item->height());
- for (int i=0; i<newPoints.count(); i++) {
- if (acceptedNewPoints->contains(newPoints[i].id()))
- continue;
- QPointF p = item->mapFromScene(newPoints[i].scenePos());
- if (bounds.contains(p))
- matchingPoints << newPoints[i];
- }
- }
-
- if (matchingPoints.count() > 0 || (*updatedPoints)[item].count() > 0) {
- QList<QTouchEvent::TouchPoint> &eventPoints = (*updatedPoints)[item];
- eventPoints.append(matchingPoints);
- transformTouchPoints(eventPoints, itemPrivate->canvasToItemTransform());
-
- Qt::TouchPointStates eventStates;
- for (int i=0; i<eventPoints.count(); i++)
- eventStates |= eventPoints[i].state();
- // if all points have the same state, set the event type accordingly
- QEvent::Type eventType;
- switch (eventStates) {
- case Qt::TouchPointPressed:
- eventType = QEvent::TouchBegin;
- break;
- case Qt::TouchPointReleased:
- eventType = QEvent::TouchEnd;
- break;
- default:
- eventType = QEvent::TouchUpdate;
- break;
- }
-
- if (eventStates != Qt::TouchPointStationary) {
- QTouchEvent touchEvent(eventType);
- // touchEvent.setWidget(q); // ### refactor: what is the consequence of not setting the widget?
- touchEvent.setDeviceType(event->deviceType());
- touchEvent.setModifiers(event->modifiers());
- touchEvent.setTouchPointStates(eventStates);
- touchEvent.setTouchPoints(eventPoints);
- touchEvent.setTimestamp(event->timestamp());
-
- touchEvent.accept();
- q->sendEvent(item, &touchEvent);
-
- if (touchEvent.isAccepted()) {
- for (int i=0; i<matchingPoints.count(); i++) {
- itemForTouchPointId[matchingPoints[i].id()] = item;
- acceptedNewPoints->insert(matchingPoints[i].id());
- }
- }
- }
- }
-
- updatedPoints->remove(item);
- if (acceptedNewPoints->count() == newPoints.count() && updatedPoints->isEmpty())
- return true;
-
- return false;
-}
-
-void QQuickCanvasPrivate::deliverDragEvent(QQuickDragGrabber *grabber, QEvent *event)
-{
- Q_Q(QQuickCanvas);
- grabber->resetTarget();
- QQuickDragGrabber::iterator grabItem = grabber->begin();
- if (grabItem != grabber->end()) {
- Q_ASSERT(event->type() != QEvent::DragEnter);
- if (event->type() == QEvent::Drop) {
- QDropEvent *e = static_cast<QDropEvent *>(event);
- for (e->setAccepted(false); !e->isAccepted() && grabItem != grabber->end(); grabItem = grabber->release(grabItem)) {
- QPointF p = (**grabItem)->mapFromScene(e->pos());
- QDropEvent translatedEvent(
- p.toPoint(),
- e->possibleActions(),
- e->mimeData(),
- e->mouseButtons(),
- e->keyboardModifiers());
- QQuickDropEventEx::copyActions(&translatedEvent, *e);
- q->sendEvent(**grabItem, &translatedEvent);
- e->setAccepted(translatedEvent.isAccepted());
- e->setDropAction(translatedEvent.dropAction());
- grabber->setTarget(**grabItem);
- }
- }
- if (event->type() != QEvent::DragMove) { // Either an accepted drop or a leave.
- QDragLeaveEvent leaveEvent;
- for (; grabItem != grabber->end(); grabItem = grabber->release(grabItem))
- q->sendEvent(**grabItem, &leaveEvent);
- return;
- } else for (; grabItem != grabber->end(); grabItem = grabber->release(grabItem)) {
- QDragMoveEvent *moveEvent = static_cast<QDragMoveEvent *>(event);
- if (deliverDragEvent(grabber, **grabItem, moveEvent)) {
- moveEvent->setAccepted(true);
- for (++grabItem; grabItem != grabber->end();) {
- QPointF p = (**grabItem)->mapFromScene(moveEvent->pos());
- if (QRectF(0, 0, (**grabItem)->width(), (**grabItem)->height()).contains(p)) {
- QDragMoveEvent translatedEvent(
- p.toPoint(),
- moveEvent->possibleActions(),
- moveEvent->mimeData(),
- moveEvent->mouseButtons(),
- moveEvent->keyboardModifiers());
- QQuickDropEventEx::copyActions(&translatedEvent, *moveEvent);
- q->sendEvent(**grabItem, &translatedEvent);
- ++grabItem;
- } else {
- QDragLeaveEvent leaveEvent;
- q->sendEvent(**grabItem, &leaveEvent);
- grabItem = grabber->release(grabItem);
- }
- }
- return;
- } else {
- QDragLeaveEvent leaveEvent;
- q->sendEvent(**grabItem, &leaveEvent);
- }
- }
- }
- if (event->type() == QEvent::DragEnter || event->type() == QEvent::DragMove) {
- QDragMoveEvent *e = static_cast<QDragMoveEvent *>(event);
- QDragEnterEvent enterEvent(
- e->pos(),
- e->possibleActions(),
- e->mimeData(),
- e->mouseButtons(),
- e->keyboardModifiers());
- QQuickDropEventEx::copyActions(&enterEvent, *e);
- event->setAccepted(deliverDragEvent(grabber, rootItem, &enterEvent));
- }
-}
-
-bool QQuickCanvasPrivate::deliverDragEvent(QQuickDragGrabber *grabber, QQuickItem *item, QDragMoveEvent *event)
-{
- Q_Q(QQuickCanvas);
- bool accepted = false;
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
- if (itemPrivate->opacity == 0.0 || !item->isVisible() || !item->isEnabled())
- return false;
-
- QPointF p = item->mapFromScene(event->pos());
- if (QRectF(0, 0, item->width(), item->height()).contains(p)) {
- if (event->type() == QEvent::DragMove || itemPrivate->flags & QQuickItem::ItemAcceptsDrops) {
- QDragMoveEvent translatedEvent(
- p.toPoint(),
- event->possibleActions(),
- event->mimeData(),
- event->mouseButtons(),
- event->keyboardModifiers(),
- event->type());
- QQuickDropEventEx::copyActions(&translatedEvent, *event);
- q->sendEvent(item, &translatedEvent);
- if (event->type() == QEvent::DragEnter) {
- if (translatedEvent.isAccepted()) {
- grabber->grab(item);
- accepted = true;
- }
- } else {
- accepted = true;
- }
- }
- } else if (itemPrivate->flags & QQuickItem::ItemClipsChildrenToShape) {
- return false;
- }
-
- QDragEnterEvent enterEvent(
- event->pos(),
- event->possibleActions(),
- event->mimeData(),
- event->mouseButtons(),
- event->keyboardModifiers());
- QQuickDropEventEx::copyActions(&enterEvent, *event);
- QList<QQuickItem *> children = itemPrivate->paintOrderChildItems();
- for (int ii = children.count() - 1; ii >= 0; --ii) {
- if (deliverDragEvent(grabber, children.at(ii), &enterEvent))
- return true;
- }
-
- return accepted;
-}
-
-bool QQuickCanvasPrivate::sendFilteredMouseEvent(QQuickItem *target, QQuickItem *item, QEvent *event)
-{
- if (!target)
- return false;
-
- QQuickItemPrivate *targetPrivate = QQuickItemPrivate::get(target);
- if (targetPrivate->filtersChildMouseEvents)
- if (target->childMouseEventFilter(item, event))
- return true;
-
- if (sendFilteredMouseEvent(target->parentItem(), item, event))
- return true;
-
- return false;
-}
-
-/*!
- Propagates an event to a QQuickItem on the canvas
-*/
-bool QQuickCanvas::sendEvent(QQuickItem *item, QEvent *e)
-{
- Q_D(QQuickCanvas);
-
- if (!item) {
- qWarning("QQuickCanvas::sendEvent: Cannot send event to a null item");
- return false;
- }
-
- Q_ASSERT(e);
-
- switch (e->type()) {
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- e->accept();
- QQuickItemPrivate::get(item)->deliverKeyEvent(static_cast<QKeyEvent *>(e));
- while (!e->isAccepted() && (item = item->parentItem())) {
- e->accept();
- QQuickItemPrivate::get(item)->deliverKeyEvent(static_cast<QKeyEvent *>(e));
- }
- break;
- case QEvent::FocusIn:
- case QEvent::FocusOut:
- QQuickItemPrivate::get(item)->deliverFocusEvent(static_cast<QFocusEvent *>(e));
- break;
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseMove:
- // XXX todo - should sendEvent be doing this? how does it relate to forwarded events?
- if (!d->sendFilteredMouseEvent(item->parentItem(), item, e)) {
- e->accept();
- QQuickItemPrivate::get(item)->deliverMouseEvent(static_cast<QMouseEvent *>(e));
- }
- break;
- case QEvent::Wheel:
- QQuickItemPrivate::get(item)->deliverWheelEvent(static_cast<QWheelEvent *>(e));
- break;
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- case QEvent::HoverMove:
- QQuickItemPrivate::get(item)->deliverHoverEvent(static_cast<QHoverEvent *>(e));
- break;
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- // XXX todo - should sendEvent be doing this? how does it relate to forwarded events?
- if (!d->sendFilteredMouseEvent(item->parentItem(), item, e)) {
- e->accept();
- QQuickItemPrivate::get(item)->deliverTouchEvent(static_cast<QTouchEvent *>(e));
- }
- break;
- case QEvent::DragEnter:
- case QEvent::DragMove:
- case QEvent::DragLeave:
- case QEvent::Drop:
- QQuickItemPrivate::get(item)->deliverDragEvent(e);
- break;
- default:
- break;
- }
-
- return false;
-}
-
-void QQuickCanvasPrivate::cleanupNodes()
-{
- for (int ii = 0; ii < cleanupNodeList.count(); ++ii)
- delete cleanupNodeList.at(ii);
- cleanupNodeList.clear();
-}
-
-void QQuickCanvasPrivate::cleanupNodesOnShutdown(QQuickItem *item)
-{
- QQuickItemPrivate *p = QQuickItemPrivate::get(item);
- if (p->itemNodeInstance) {
- delete p->itemNodeInstance;
- p->itemNodeInstance = 0;
- p->opacityNode = 0;
- p->clipNode = 0;
- p->groupNode = 0;
- p->paintNode = 0;
- }
-
- for (int ii = 0; ii < p->childItems.count(); ++ii)
- cleanupNodesOnShutdown(p->childItems.at(ii));
-}
-
-// This must be called from the render thread, with the main thread frozen
-void QQuickCanvasPrivate::cleanupNodesOnShutdown()
-{
- cleanupNodes();
-
- cleanupNodesOnShutdown(rootItem);
-}
-
-void QQuickCanvasPrivate::updateDirtyNodes()
-{
-#ifdef DIRTY_DEBUG
- qWarning() << "QQuickCanvasPrivate::updateDirtyNodes():";
-#endif
-
- cleanupNodes();
-
- QQuickItem *updateList = dirtyItemList;
- dirtyItemList = 0;
- if (updateList) QQuickItemPrivate::get(updateList)->prevDirtyItem = &updateList;
-
- while (updateList) {
- QQuickItem *item = updateList;
- QQuickItemPrivate *itemPriv = QQuickItemPrivate::get(item);
- itemPriv->removeFromDirtyList();
-
-#ifdef DIRTY_DEBUG
- qWarning() << " QSGNode:" << item << qPrintable(itemPriv->dirtyToString());
-#endif
- updateDirtyNode(item);
- }
-}
-
-void QQuickCanvasPrivate::updateDirtyNode(QQuickItem *item)
-{
-#ifdef QML_RUNTIME_TESTING
- bool didFlash = false;
-#endif
-
- QQuickItemPrivate *itemPriv = QQuickItemPrivate::get(item);
- quint32 dirty = itemPriv->dirtyAttributes;
- itemPriv->dirtyAttributes = 0;
-
- if ((dirty & QQuickItemPrivate::TransformUpdateMask) ||
- (dirty & QQuickItemPrivate::Size && itemPriv->origin != QQuickItem::TopLeft &&
- (itemPriv->scale != 1. || itemPriv->rotation != 0.))) {
-
- QMatrix4x4 matrix;
-
- if (itemPriv->x != 0. || itemPriv->y != 0.)
- matrix.translate(itemPriv->x, itemPriv->y);
-
- for (int ii = itemPriv->transforms.count() - 1; ii >= 0; --ii)
- itemPriv->transforms.at(ii)->applyTo(&matrix);
-
- if (itemPriv->scale != 1. || itemPriv->rotation != 0.) {
- QPointF origin = item->transformOriginPoint();
- matrix.translate(origin.x(), origin.y());
- if (itemPriv->scale != 1.)
- matrix.scale(itemPriv->scale, itemPriv->scale);
- if (itemPriv->rotation != 0.)
- matrix.rotate(itemPriv->rotation, 0, 0, 1);
- matrix.translate(-origin.x(), -origin.y());
- }
-
- itemPriv->itemNode()->setMatrix(matrix);
- }
-
- bool clipEffectivelyChanged = dirty & QQuickItemPrivate::Clip &&
- ((item->clip() == false) != (itemPriv->clipNode == 0));
- bool effectRefEffectivelyChanged = dirty & QQuickItemPrivate::EffectReference &&
- ((itemPriv->effectRefCount == 0) != (itemPriv->rootNode == 0));
-
- if (clipEffectivelyChanged) {
- QSGNode *parent = itemPriv->opacityNode ? (QSGNode *) itemPriv->opacityNode : (QSGNode *)itemPriv->itemNode();
- QSGNode *child = itemPriv->rootNode ? (QSGNode *)itemPriv->rootNode : (QSGNode *)itemPriv->groupNode;
-
- if (item->clip()) {
- Q_ASSERT(itemPriv->clipNode == 0);
- itemPriv->clipNode = new QQuickDefaultClipNode(item->boundingRect());
- itemPriv->clipNode->update();
-
- if (child)
- parent->removeChildNode(child);
- parent->appendChildNode(itemPriv->clipNode);
- if (child)
- itemPriv->clipNode->appendChildNode(child);
-
- } else {
- Q_ASSERT(itemPriv->clipNode != 0);
- parent->removeChildNode(itemPriv->clipNode);
- if (child)
- itemPriv->clipNode->removeChildNode(child);
- delete itemPriv->clipNode;
- itemPriv->clipNode = 0;
- if (child)
- parent->appendChildNode(child);
- }
- }
-
- if (dirty & QQuickItemPrivate::ChildrenUpdateMask)
- itemPriv->childContainerNode()->removeAllChildNodes();
-
- if (effectRefEffectivelyChanged) {
- QSGNode *parent = itemPriv->clipNode;
- if (!parent)
- parent = itemPriv->opacityNode;
- if (!parent)
- parent = itemPriv->itemNode();
- QSGNode *child = itemPriv->groupNode;
-
- if (itemPriv->effectRefCount) {
- Q_ASSERT(itemPriv->rootNode == 0);
- itemPriv->rootNode = new QSGRootNode;
-
- if (child)
- parent->removeChildNode(child);
- parent->appendChildNode(itemPriv->rootNode);
- if (child)
- itemPriv->rootNode->appendChildNode(child);
- } else {
- Q_ASSERT(itemPriv->rootNode != 0);
- parent->removeChildNode(itemPriv->rootNode);
- if (child)
- itemPriv->rootNode->removeChildNode(child);
- delete itemPriv->rootNode;
- itemPriv->rootNode = 0;
- if (child)
- parent->appendChildNode(child);
- }
- }
-
- if (dirty & QQuickItemPrivate::ChildrenUpdateMask) {
- QSGNode *groupNode = itemPriv->groupNode;
- if (groupNode)
- groupNode->removeAllChildNodes();
-
- QList<QQuickItem *> orderedChildren = itemPriv->paintOrderChildItems();
- int ii = 0;
-
- for (; ii < orderedChildren.count() && orderedChildren.at(ii)->z() < 0; ++ii) {
- QQuickItemPrivate *childPrivate = QQuickItemPrivate::get(orderedChildren.at(ii));
- if (!childPrivate->explicitVisible && !childPrivate->effectRefCount)
- continue;
- if (childPrivate->itemNode()->parent())
- childPrivate->itemNode()->parent()->removeChildNode(childPrivate->itemNode());
-
- itemPriv->childContainerNode()->appendChildNode(childPrivate->itemNode());
- }
- itemPriv->beforePaintNode = itemPriv->groupNode ? itemPriv->groupNode->lastChild() : 0;
-
- if (itemPriv->paintNode)
- itemPriv->childContainerNode()->appendChildNode(itemPriv->paintNode);
-
- for (; ii < orderedChildren.count(); ++ii) {
- QQuickItemPrivate *childPrivate = QQuickItemPrivate::get(orderedChildren.at(ii));
- if (!childPrivate->explicitVisible && !childPrivate->effectRefCount)
- continue;
- if (childPrivate->itemNode()->parent())
- childPrivate->itemNode()->parent()->removeChildNode(childPrivate->itemNode());
-
- itemPriv->childContainerNode()->appendChildNode(childPrivate->itemNode());
- }
- }
-
- if ((dirty & QQuickItemPrivate::Size) && itemPriv->clipNode) {
- itemPriv->clipNode->setRect(item->boundingRect());
- itemPriv->clipNode->update();
- }
-
- if (dirty & (QQuickItemPrivate::OpacityValue | QQuickItemPrivate::Visible | QQuickItemPrivate::HideReference)) {
- qreal opacity = itemPriv->explicitVisible && itemPriv->hideRefCount == 0
- ? itemPriv->opacity : qreal(0);
-
- if (opacity != 1 && !itemPriv->opacityNode) {
- itemPriv->opacityNode = new QSGOpacityNode;
-
- QSGNode *parent = itemPriv->itemNode();
- QSGNode *child = itemPriv->clipNode;
- if (!child)
- child = itemPriv->rootNode;
- if (!child)
- child = itemPriv->groupNode;
-
- if (child)
- parent->removeChildNode(child);
- parent->appendChildNode(itemPriv->opacityNode);
- if (child)
- itemPriv->opacityNode->appendChildNode(child);
- }
- if (itemPriv->opacityNode)
- itemPriv->opacityNode->setOpacity(opacity);
- }
-
- if (dirty & QQuickItemPrivate::ContentUpdateMask) {
-
- if (itemPriv->flags & QQuickItem::ItemHasContents) {
- updatePaintNodeData.transformNode = itemPriv->itemNode();
- itemPriv->paintNode = item->updatePaintNode(itemPriv->paintNode, &updatePaintNodeData);
-
- Q_ASSERT(itemPriv->paintNode == 0 ||
- itemPriv->paintNode->parent() == 0 ||
- itemPriv->paintNode->parent() == itemPriv->childContainerNode());
-
- if (itemPriv->paintNode && itemPriv->paintNode->parent() == 0) {
- if (itemPriv->beforePaintNode)
- itemPriv->childContainerNode()->insertChildNodeAfter(itemPriv->paintNode, itemPriv->beforePaintNode);
- else
- itemPriv->childContainerNode()->prependChildNode(itemPriv->paintNode);
- }
- } else if (itemPriv->paintNode) {
- delete itemPriv->paintNode;
- itemPriv->paintNode = 0;
- }
- }
-
-#ifndef QT_NO_DEBUG
- // Check consistency.
- const QSGNode *nodeChain[] = {
- itemPriv->itemNodeInstance,
- itemPriv->opacityNode,
- itemPriv->clipNode,
- itemPriv->rootNode,
- itemPriv->groupNode,
- itemPriv->paintNode,
- };
-
- int ip = 0;
- for (;;) {
- while (ip < 5 && nodeChain[ip] == 0)
- ++ip;
- if (ip == 5)
- break;
- int ic = ip + 1;
- while (ic < 5 && nodeChain[ic] == 0)
- ++ic;
- const QSGNode *parent = nodeChain[ip];
- const QSGNode *child = nodeChain[ic];
- if (child == 0) {
- Q_ASSERT(parent == itemPriv->groupNode || parent->childCount() == 0);
- } else {
- Q_ASSERT(parent == itemPriv->groupNode || parent->childCount() == 1);
- Q_ASSERT(child->parent() == parent);
- bool containsChild = false;
- for (QSGNode *n = parent->firstChild(); n; n = n->nextSibling())
- containsChild |= (n == child);
- Q_ASSERT(containsChild);
- }
- ip = ic;
- }
-#endif
-
-#ifdef QML_RUNTIME_TESTING
- if (itemPriv->sceneGraphContext()->isFlashModeEnabled()) {
- QSGFlashNode *flash = new QSGFlashNode();
- flash->setRect(item->boundingRect());
- itemPriv->childContainerNode()->appendChildNode(flash);
- didFlash = true;
- }
- Q_Q(QQuickCanvas);
- if (didFlash) {
- q->maybeUpdate();
- }
-#endif
-
-}
-
-void QQuickCanvas::maybeUpdate()
-{
- Q_D(QQuickCanvas);
-
- if (d->thread && d->thread->isRunning())
- d->thread->maybeUpdate();
-}
-
-/*!
- \fn void QSGEngine::sceneGraphInitialized();
-
- This signal is emitted when the scene graph has been initialized.
-
- This signal will be emitted from the scene graph rendering thread.
- */
-
-/*!
- Returns the QSGEngine used for this scene.
-
- The engine will only be available once the scene graph has been
- initialized. Register for the sceneGraphEngine() signal to get
- notification about this.
-
- \deprecated
- */
-
-QSGEngine *QQuickCanvas::sceneGraphEngine() const
-{
- Q_D(const QQuickCanvas);
- qWarning("QQuickCanvas::sceneGraphEngine() is deprecated, use members of QQuickCanvas instead");
- if (d->context && d->context->isReady())
- return d->engine;
- return 0;
-}
-
-
-
-/*!
- Sets the render target for this canvas to be \a fbo.
-
- The specified fbo must be created in the context of the canvas
- or one that shares with it.
-
- \warning
- This function can only be called from the thread doing
- the rendering.
- */
-
-void QQuickCanvas::setRenderTarget(QOpenGLFramebufferObject *fbo)
-{
- Q_D(QQuickCanvas);
- if (d->context && d->context && QThread::currentThread() != d->context->thread()) {
- qWarning("QQuickCanvas::setRenderThread: Cannot set render target from outside the rendering thread");
- return;
- }
-
- d->renderTarget = fbo;
-}
-
-
-
-/*!
- Returns the render target for this canvas.
-
- The default is to render to the surface of the canvas, in which
- case the render target is 0.
- */
-QOpenGLFramebufferObject *QQuickCanvas::renderTarget() const
-{
- Q_D(const QQuickCanvas);
- return d->renderTarget;
-}
-
-
-/*!
- Grabs the contents of the framebuffer and returns it as an image.
-
- This function might not work if the view is not visible.
-
- \warning Calling this function will cause performance problems.
-
- \warning This function can only be called from the GUI thread.
- */
-QImage QQuickCanvas::grabFrameBuffer()
-{
- Q_D(QQuickCanvas);
- return d->thread ? d->thread->grab() : QImage();
-}
-
-/*!
- Returns an incubation controller that splices incubation between frames
- for this canvas. QQuickView automatically installs this controller for you,
- otherwise you will need to install it yourself using \l{QDeclarativeEngine::setIncubationController}
-
- The controller is owned by the canvas and will be destroyed when the canvas
- is deleted.
-*/
-QDeclarativeIncubationController *QQuickCanvas::incubationController() const
-{
- Q_D(const QQuickCanvas);
-
- if (!d->incubationController)
- d->incubationController = new QQuickCanvasIncubationController(const_cast<QQuickCanvasPrivate *>(d));
- return d->incubationController;
-}
-
-
-
-/*!
- \enum QQuickCanvas::CreateTextureOption
-
- The CreateTextureOption enums are used to customize a texture is wrapped.
-
- \value TextureHasAlphaChannel The texture has an alpha channel and should
- be drawn using blending.
-
- \value TextureHasMipmaps The texture has mipmaps and can be drawn with
- mipmapping enabled.
-
- \value TextureOwnsGLTexture The texture object owns the texture id and
- will delete the GL texture when the texture object is deleted.
- */
-
-/*!
- \fn void QQuickCanvas::beforeRendering()
-
- This signal is emitted before the scene starts rendering.
-
- Combined with the modes for clearing the background, this option
- can be used to paint using raw GL under QML content.
-
- The GL context used for rendering the scene graph will be bound
- at this point.
-
- Since this signal is emitted from the scene graph rendering thread, the receiver should
- be on the scene graph thread or the connection should be Qt::DirectConnection.
-
-*/
-
-/*!
- \fn void QQuickCanvas::afterRendering()
-
- This signal is emitted after the scene has completed rendering, before swapbuffers is called.
-
- This signal can be used to paint using raw GL on top of QML content,
- or to do screen scraping of the current frame buffer.
-
- The GL context used for rendering the scene graph will be bound at this point.
-
- Since this signal is emitted from the scene graph rendering thread, the receiver should
- be on the scene graph thread or the connection should be Qt::DirectConnection.
- */
-
-
-
-/*!
- Sets weither the scene graph rendering of QML should clear the color buffer
- before it starts rendering to \a enbled.
-
- By disabling clearing of the color buffer, it is possible to do GL painting
- under the scene graph.
-
- The color buffer is cleared by default.
-
- \sa beforeRendering()
- */
-
-void QQuickCanvas::setClearBeforeRendering(bool enabled)
-{
- Q_D(QQuickCanvas);
- d->clearBeforeRendering = enabled;
-}
-
-
-
-/*!
- Returns weither clearing of the color buffer is done before rendering or not.
- */
-
-bool QQuickCanvas::clearBeforeRendering() const
-{
- Q_D(const QQuickCanvas);
- return d->clearBeforeRendering;
-}
-
-
-
-/*!
- Creates a new QSGTexture from the supplied \a image. If the image has an
- alpha channel, the corresponding texture will have an alpha channel.
-
- The caller of the function is responsible for deleting the returned texture.
- The actual GL texture will be deleted when the texture object is deleted.
-
- \warning This function will return 0 if the scene graph has not yet been
- initialized.
-
- This function can be called both from the GUI thread and the rendering thread.
-
- \sa sceneGraphInitialized()
- */
-
-QSGTexture *QQuickCanvas::createTextureFromImage(const QImage &image) const
-{
- Q_D(const QQuickCanvas);
- if (d->context)
- return d->context->createTexture(image);
- else
- return 0;
-}
-
-
-
-/*!
- Creates a new QSGTexture object from an existing GL texture \a id.
-
- The caller of the function is responsible for deleting the returned texture.
-
- Use \a options to customize the texture attributes.
-
- \warning This function will return 0 if the scenegraph has not yet been
- initialized.
-
- \sa sceneGraphInitialized()
- */
-QSGTexture *QQuickCanvas::createTextureFromId(uint id, const QSize &size, CreateTextureOptions options) const
-{
- Q_D(const QQuickCanvas);
- if (d->context) {
- QSGPlainTexture *texture = new QSGPlainTexture();
- texture->setTextureId(id);
- texture->setHasAlphaChannel(options & TextureHasAlphaChannel);
- texture->setHasMipmaps(options & TextureHasMipmaps);
- texture->setOwnsTexture(options & TextureOwnsGLTexture);
- texture->setTextureSize(size);
- return texture;
- }
- return 0;
-}
-
-
-/*!
- Sets the color used to clear the opengl context to \a color.
-
- Setting the clear color has no effect when clearing is disabled.
-
- \sa setClearBeforeRendering()
- */
-
-void QQuickCanvas::setClearColor(const QColor &color)
-{
- if (color == d_func()->clearColor)
- return;
- d_func()->clearColor = color;
- emit clearColorChanged(color);
-}
-
-
-
-/*!
- Returns the color used to clear the opengl context.
- */
-
-QColor QQuickCanvas::clearColor() const
-{
- return d_func()->clearColor;
-}
-
-
-
-void QQuickCanvasRenderLoop::createGLContext()
-{
- gl = new QOpenGLContext();
- gl->setFormat(renderer->requestedFormat());
- gl->create();
-}
-
-void QQuickCanvasRenderThread::run()
-{
-#ifdef THREAD_DEBUG
- qDebug("QML Rendering Thread Started");
-#endif
-
- if (!glContext()) {
- createGLContext();
- makeCurrent();
- initializeSceneGraph();
- } else {
- makeCurrent();
- }
-
- while (!shouldExit) {
- lock();
-
- bool sizeChanged = false;
- isExternalUpdatePending = false;
-
- if (renderedSize != windowSize) {
-#ifdef THREAD_DEBUG
- printf(" RenderThread: window has changed size...\n");
-#endif
- glViewport(0, 0, windowSize.width(), windowSize.height());
- sizeChanged = true;
- }
-
-#ifdef THREAD_DEBUG
- printf(" RenderThread: preparing to sync...\n");
-#endif
-
- if (!isGuiBlocked) {
- isGuiBlockPending = true;
-
-#ifdef THREAD_DEBUG
- printf(" RenderThread: aquired sync lock...\n");
-#endif
- allowMainThreadProcessingFlag = false;
- QCoreApplication::postEvent(this, new QEvent(QEvent::User));
-#ifdef THREAD_DEBUG
- printf(" RenderThread: going to sleep...\n");
-#endif
- wait();
-
- isGuiBlockPending = false;
- }
-
-#ifdef THREAD_DEBUG
- printf(" RenderThread: Doing locked sync\n");
-#endif
-#ifdef QQUICK_CANVAS_TIMING
- if (qquick_canvas_timing)
- threadTimer.start();
-#endif
- inSync = true;
- syncSceneGraph();
- inSync = false;
-
- // Wake GUI after sync to let it continue animating and event processing.
- allowMainThreadProcessingFlag = true;
- wake();
- unlock();
-#ifdef THREAD_DEBUG
- printf(" RenderThread: sync done\n");
-#endif
-#ifdef QQUICK_CANVAS_TIMING
- if (qquick_canvas_timing)
- syncTime = threadTimer.elapsed();
-#endif
-
-#ifdef THREAD_DEBUG
- printf(" RenderThread: rendering... %d x %d\n", windowSize.width(), windowSize.height());
-#endif
-
- renderSceneGraph(windowSize);
-#ifdef QQUICK_CANVAS_TIMING
- if (qquick_canvas_timing)
- renderTime = threadTimer.elapsed() - syncTime;
-#endif
-
- // The content of the target buffer is undefined after swap() so grab needs
- // to happen before swap();
- if (doGrab) {
-#ifdef THREAD_DEBUG
- printf(" RenderThread: doing a grab...\n");
-#endif
- grabContent = qt_gl_read_framebuffer(windowSize, false, false);
- doGrab = false;
- }
-
-#ifdef THREAD_DEBUG
- printf(" RenderThread: wait for swap...\n");
-#endif
-
- swapBuffers();
-#ifdef THREAD_DEBUG
- printf(" RenderThread: swap complete...\n");
-#endif
-#ifdef QQUICK_CANVAS_TIMING
- if (qquick_canvas_timing) {
- swapTime = threadTimer.elapsed() - renderTime;
- qDebug() << "- Breakdown of frame time: sync:" << syncTime
- << "ms render:" << renderTime << "ms swap:" << swapTime
- << "ms total:" << swapTime + renderTime << "ms";
- }
-#endif
-
- lock();
- isPaintCompleted = true;
- if (sizeChanged)
- renderedSize = windowSize;
-
- // Wake the GUI thread now that rendering is complete, to signal that painting
- // is done, resizing is done or grabbing is completed. For grabbing, we're
- // signalling this much later than needed (we could have done it before swap)
- // but we don't want to lock an extra time.
- wake();
-
- if (!animationRunning && !isExternalUpdatePending && !shouldExit && !doGrab) {
-#ifdef THREAD_DEBUG
- printf(" RenderThread: nothing to do, going to sleep...\n");
-#endif
- isRenderBlocked = true;
- wait();
- isRenderBlocked = false;
- }
-
- unlock();
-
- QCoreApplication::processEvents();
-
- // Process any "deleteLater" objects...
- QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
- }
-
-#ifdef THREAD_DEBUG
- printf(" RenderThread: deleting all outstanding nodes\n");
-#endif
- cleanupNodesOnShutdown();
-
-#ifdef THREAD_DEBUG
- printf(" RenderThread: render loop exited... Good Night!\n");
-#endif
-
- doneCurrent();
-
- lock();
- hasExited = true;
-#ifdef THREAD_DEBUG
- printf(" RenderThread: waking GUI for final sleep..\n");
-#endif
- wake();
- unlock();
-
-#ifdef THREAD_DEBUG
- printf(" RenderThread: All done...\n");
-#endif
-}
-
-
-
-bool QQuickCanvasRenderThread::event(QEvent *e)
-{
- Q_ASSERT(QThread::currentThread() == qApp->thread());
-
- if (e->type() == QEvent::User) {
- if (!syncAlreadyHappened)
- sync(false);
-
- syncAlreadyHappened = false;
-
- if (animationRunning && animationDriver()) {
-#ifdef THREAD_DEBUG
- qDebug("GUI: Advancing animations...\n");
-#endif
-
- animationDriver()->advance();
-
-#ifdef THREAD_DEBUG
- qDebug("GUI: Animations advanced...\n");
-#endif
- }
-
- return true;
- }
-
- return QThread::event(e);
-}
-
-
-
-void QQuickCanvasRenderThread::exhaustSyncEvent()
-{
- if (isGuiBlockPending) {
- sync(true);
- syncAlreadyHappened = true;
- }
-}
-
-
-
-void QQuickCanvasRenderThread::sync(bool guiAlreadyLocked)
-{
-#ifdef THREAD_DEBUG
- printf("GUI: sync - %s\n", guiAlreadyLocked ? "outside event" : "inside event");
-#endif
- if (!guiAlreadyLocked)
- lockInGui();
-
- renderThreadAwakened = false;
-
- polishItems();
-
- wake();
- wait();
-
- if (!guiAlreadyLocked)
- unlockInGui();
-}
-
-
-
-
-/*!
- Acquires the mutex for the GUI thread. The function uses the isGuiBlocked
- variable to keep track of how many recursion levels the gui is locked with.
- We only actually acquire the mutex for the first level to avoid deadlocking
- ourselves.
- */
-
-void QQuickCanvasRenderThread::lockInGui()
-{
- // We must avoid recursive locking in the GUI thread, hence we
- // only lock when we are the first one to try to block.
- if (!isGuiBlocked)
- lock();
-
- isGuiBlocked++;
-
-#ifdef THREAD_DEBUG
- printf("GUI: aquired lock... %d\n", isGuiBlocked);
-#endif
-}
-
-
-
-void QQuickCanvasRenderThread::unlockInGui()
-{
-#ifdef THREAD_DEBUG
- printf("GUI: releasing lock... %d\n", isGuiBlocked);
-#endif
- --isGuiBlocked;
- if (!isGuiBlocked)
- unlock();
-}
-
-
-
-
-void QQuickCanvasRenderThread::animationStarted()
-{
-#ifdef THREAD_DEBUG
- printf("GUI: animationStarted()\n");
-#endif
-
- lockInGui();
-
- animationRunning = true;
-
- if (isRenderBlocked)
- wake();
-
- unlockInGui();
-}
-
-
-
-void QQuickCanvasRenderThread::animationStopped()
-{
-#ifdef THREAD_DEBUG
- printf("GUI: animationStopped()...\n");
-#endif
-
- lockInGui();
- animationRunning = false;
- unlockInGui();
-}
-
-
-void QQuickCanvasRenderThread::paint()
-{
-#ifdef THREAD_DEBUG
- printf("GUI: paint called..\n");
-#endif
-
- lockInGui();
- exhaustSyncEvent();
-
- isPaintCompleted = false;
- while (isRunning() && !isPaintCompleted) {
- if (isRenderBlocked)
- wake();
- wait();
- }
- unlockInGui();
-}
-
-
-
-void QQuickCanvasRenderThread::resize(const QSize &size)
-{
-#ifdef THREAD_DEBUG
- printf("GUI: Resize Event: %dx%d\n", size.width(), size.height());
-#endif
-
- if (!isRunning()) {
- windowSize = size;
- return;
- }
-
- lockInGui();
- exhaustSyncEvent();
-
- windowSize = size;
-
- while (isRunning() && renderedSize != windowSize) {
- if (isRenderBlocked)
- wake();
- wait();
- }
- unlockInGui();
-}
-
-
-
-void QQuickCanvasRenderThread::startRendering()
-{
-#ifdef THREAD_DEBUG
- printf("GUI: Starting Render Thread\n");
-#endif
- hasExited = false;
- shouldExit = false;
- isGuiBlocked = 0;
- isGuiBlockPending = false;
- start();
-}
-
-
-
-void QQuickCanvasRenderThread::stopRendering()
-{
-#ifdef THREAD_DEBUG
- printf("GUI: stopping render thread\n");
-#endif
-
- lockInGui();
- exhaustSyncEvent();
- shouldExit = true;
-
- if (isRenderBlocked) {
-#ifdef THREAD_DEBUG
- printf("GUI: waking up render thread\n");
-#endif
- wake();
- }
-
- while (!hasExited) {
-#ifdef THREAD_DEBUG
- printf("GUI: waiting for render thread to have exited..\n");
-#endif
- wait();
- }
-
- unlockInGui();
-
-#ifdef THREAD_DEBUG
- printf("GUI: waiting for render thread to terminate..\n");
-#endif
- // Actually wait for the thread to terminate. Otherwise we can delete it
- // too early and crash.
- QThread::wait();
-
-#ifdef THREAD_DEBUG
- printf("GUI: thread has terminated and we're all good..\n");
-#endif
-
-}
-
-
-
-QImage QQuickCanvasRenderThread::grab()
-{
- if (!isRunning())
- return QImage();
-
- if (QThread::currentThread() != qApp->thread()) {
- qWarning("QQuickCanvas::grabFrameBuffer: can only be called from the GUI thread");
- return QImage();
- }
-
-#ifdef THREAD_DEBUG
- printf("GUI: doing a pixelwise grab..\n");
-#endif
-
- lockInGui();
- exhaustSyncEvent();
-
- doGrab = true;
- isPaintCompleted = false;
- while (isRunning() && !isPaintCompleted) {
- if (isRenderBlocked)
- wake();
- wait();
- }
-
- QImage grabbed = grabContent;
- grabContent = QImage();
-
- unlockInGui();
-
- return grabbed;
-}
-
-
-
-void QQuickCanvasRenderThread::maybeUpdate()
-{
- Q_ASSERT_X(QThread::currentThread() == QCoreApplication::instance()->thread() || inSync,
- "QQuickCanvas::update",
- "Function can only be called from GUI thread or during QQuickItem::updatePaintNode()");
-
- if (inSync) {
- isExternalUpdatePending = true;
-
- } else if (!renderThreadAwakened) {
-#ifdef THREAD_DEBUG
- printf("GUI: doing update...\n");
-#endif
- renderThreadAwakened = true;
- lockInGui();
- isExternalUpdatePending = true;
- if (isRenderBlocked)
- wake();
- unlockInGui();
- }
-}
-
-
-#include "moc_qquickcanvas.cpp"
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickcanvas.h b/src/declarative/items/qquickcanvas.h
deleted file mode 100644
index c27776f234..0000000000
--- a/src/declarative/items/qquickcanvas.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKCANVAS_H
-#define QQUICKCANVAS_H
-
-#include <QtCore/qmetatype.h>
-#include <QtGui/qopengl.h>
-#include <QtGui/qwindow.h>
-#include <QtGui/qevent.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGEngine;
-class QQuickItem;
-class QSGTexture;
-class QInputMethodEvent;
-class QQuickCanvasPrivate;
-class QOpenGLFramebufferObject;
-class QDeclarativeIncubationController;
-class QInputMethodEvent;
-
-class Q_DECLARATIVE_EXPORT QQuickCanvas : public QWindow
-{
- Q_OBJECT
- Q_PRIVATE_PROPERTY(QQuickCanvas::d_func(), QDeclarativeListProperty<QObject> data READ data DESIGNABLE false)
- Q_PROPERTY(QColor color READ clearColor WRITE setClearColor NOTIFY clearColorChanged)
- Q_CLASSINFO("DefaultProperty", "data")
- Q_DECLARE_PRIVATE(QQuickCanvas)
-public:
- enum CreateTextureOption {
- TextureHasAlphaChannel = 0x0001,
- TextureHasMipmaps = 0x0002,
- TextureOwnsGLTexture = 0x0004
- };
-
- Q_DECLARE_FLAGS(CreateTextureOptions, CreateTextureOption)
-
- QQuickCanvas(QWindow *parent = 0);
-
- virtual ~QQuickCanvas();
-
- QQuickItem *rootItem() const;
- QQuickItem *activeFocusItem() const;
-
- QQuickItem *mouseGrabberItem() const;
-
- bool sendEvent(QQuickItem *, QEvent *);
-
- QSGEngine *sceneGraphEngine() const;
-
- void setVSyncAnimations(bool enabled);
- bool vsyncAnimations() const;
-
- QImage grabFrameBuffer();
-
- void setRenderTarget(QOpenGLFramebufferObject *fbo);
- QOpenGLFramebufferObject *renderTarget() const;
-
- QDeclarativeIncubationController *incubationController() const;
-
- // Scene graph specific functions
- QSGTexture *createTextureFromImage(const QImage &image) const;
- QSGTexture *createTextureFromId(uint id, const QSize &size, CreateTextureOptions options = CreateTextureOption(0)) const;
-
- void setClearBeforeRendering(bool enabled);
- bool clearBeforeRendering() const;
-
- void setClearColor(const QColor &color);
- QColor clearColor() const;
-
- QOpenGLContext *openglContext() const;
-
-Q_SIGNALS:
- void frameSwapped();
- void sceneGraphInitialized();
- void beforeRendering();
- void afterRendering();
- void clearColorChanged(const QColor &);
-
-protected:
- QQuickCanvas(QQuickCanvasPrivate &dd, QWindow *parent = 0);
-
- virtual void exposeEvent(QExposeEvent *);
- virtual void resizeEvent(QResizeEvent *);
-
- virtual void showEvent(QShowEvent *);
- virtual void hideEvent(QHideEvent *);
-
- virtual void focusInEvent(QFocusEvent *);
- virtual void focusOutEvent(QFocusEvent *);
-
- virtual bool event(QEvent *);
- virtual void keyPressEvent(QKeyEvent *);
- virtual void keyReleaseEvent(QKeyEvent *);
- virtual void mousePressEvent(QMouseEvent *);
- virtual void mouseReleaseEvent(QMouseEvent *);
- virtual void mouseDoubleClickEvent(QMouseEvent *);
- virtual void mouseMoveEvent(QMouseEvent *);
-#ifndef QT_NO_WHEELEVENT
- virtual void wheelEvent(QWheelEvent *);
-#endif
-
-private Q_SLOTS:
- void maybeUpdate();
- void animationStarted();
- void animationStopped();
-
-private:
- friend class QQuickItem;
- friend class QQuickCanvasRenderLoop;
- Q_DISABLE_COPY(QQuickCanvas)
-};
-
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(QQuickCanvas *)
-
-QT_END_HEADER
-
-#endif // QQUICKCANVAS_H
-
diff --git a/src/declarative/items/qquickcanvas_p.h b/src/declarative/items/qquickcanvas_p.h
deleted file mode 100644
index 13ca288cb1..0000000000
--- a/src/declarative/items/qquickcanvas_p.h
+++ /dev/null
@@ -1,323 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKCANVAS_P_H
-#define QQUICKCANVAS_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 "qquickitem.h"
-#include "qquickcanvas.h"
-#include <private/qdeclarativeguard_p.h>
-
-#include <private/qsgcontext_p.h>
-#include <private/qquickdrag_p.h>
-
-#include <QtCore/qthread.h>
-#include <QtCore/qmutex.h>
-#include <QtCore/qwaitcondition.h>
-#include <private/qwindow_p.h>
-#include <private/qopengl_p.h>
-#include <qopenglcontext.h>
-#include <QtGui/qopenglframebufferobject.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qinputpanel.h>
-
-QT_BEGIN_NAMESPACE
-
-//Make it easy to identify and customize the root item if needed
-
-class QQuickRootItem : public QQuickItem
-{
- Q_OBJECT
-public:
- QQuickRootItem();
-public Q_SLOTS:
- void setWidth(int w) {QQuickItem::setWidth(qreal(w));}
- void setHeight(int h) {QQuickItem::setHeight(qreal(h));}
-};
-
-class QQuickItemPrivate;
-class QQuickCanvasPrivate;
-
-class QTouchEvent;
-class QQuickCanvasRenderLoop;
-class QQuickCanvasIncubationController;
-
-class QQuickCanvasPrivate : public QWindowPrivate
-{
-public:
- Q_DECLARE_PUBLIC(QQuickCanvas)
-
- static inline QQuickCanvasPrivate *get(QQuickCanvas *c) { return c->d_func(); }
-
- QQuickCanvasPrivate();
- virtual ~QQuickCanvasPrivate();
-
- void init(QQuickCanvas *);
- void initRootItem();//Currently only used if items added in QML
-
- QQuickRootItem *rootItem;
- QDeclarativeListProperty<QObject> data();
-
- QQuickItem *activeFocusItem;
- QQuickItem *mouseGrabberItem;
- QQuickDragGrabber dragGrabber;
-
- // Mouse positions are saved in widget coordinates
- QPointF lastMousePosition;
- void translateTouchEvent(QTouchEvent *touchEvent);
- static void transformTouchPoints(QList<QTouchEvent::TouchPoint> &touchPoints, const QTransform &transform);
- bool deliverInitialMousePressEvent(QQuickItem *, QMouseEvent *);
- bool deliverMouseEvent(QMouseEvent *);
- bool sendFilteredMouseEvent(QQuickItem *, QQuickItem *, QEvent *);
- bool deliverWheelEvent(QQuickItem *, QWheelEvent *);
- bool deliverTouchPoints(QQuickItem *, QTouchEvent *, const QList<QTouchEvent::TouchPoint> &, QSet<int> *,
- QHash<QQuickItem *, QList<QTouchEvent::TouchPoint> > *);
- bool deliverTouchEvent(QTouchEvent *);
- bool deliverHoverEvent(QQuickItem *, const QPointF &scenePos, const QPointF &lastScenePos, Qt::KeyboardModifiers modifiers, bool &accepted);
- bool sendHoverEvent(QEvent::Type, QQuickItem *, const QPointF &scenePos, const QPointF &lastScenePos,
- Qt::KeyboardModifiers modifiers, bool accepted);
- bool clearHover();
- void deliverDragEvent(QQuickDragGrabber *, QEvent *);
- bool deliverDragEvent(QQuickDragGrabber *, QQuickItem *, QDragMoveEvent *);
-
- QList<QQuickItem*> hoverItems;
- enum FocusOption {
- DontChangeFocusProperty = 0x01,
- };
- Q_DECLARE_FLAGS(FocusOptions, FocusOption)
-
- void setFocusInScope(QQuickItem *scope, QQuickItem *item, FocusOptions = 0);
- void clearFocusInScope(QQuickItem *scope, QQuickItem *item, FocusOptions = 0);
- void notifyFocusChangesRecur(QQuickItem **item, int remaining);
-
- void updateInputMethodData();
- void updateFocusItemTransform();
-
- void dirtyItem(QQuickItem *);
- void cleanup(QSGNode *);
-
- void initializeSceneGraph();
- void polishItems();
- void syncSceneGraph();
- void renderSceneGraph(const QSize &size);
-
- QQuickItem::UpdatePaintNodeData updatePaintNodeData;
-
- QQuickItem *dirtyItemList;
- QList<QSGNode *> cleanupNodeList;
-
- QSet<QQuickItem *> itemsToPolish;
-
- void updateDirtyNodes();
- void cleanupNodes();
- void cleanupNodesOnShutdown();
- bool updateEffectiveOpacity(QQuickItem *);
- void updateEffectiveOpacityRoot(QQuickItem *, qreal);
- void updateDirtyNode(QQuickItem *);
-
- QSGEngine *engine;
- QSGContext *context;
- QColor clearColor;
-
- uint vsyncAnimations : 1;
- uint clearBeforeRendering : 1;
-
- QQuickCanvasRenderLoop *thread;
- QSize widgetSize;
- QSize viewportSize;
-
- QAnimationDriver *animationDriver;
-
- QOpenGLFramebufferObject *renderTarget;
-
- QHash<int, QQuickItem *> itemForTouchPointId;
-
- mutable QQuickCanvasIncubationController *incubationController;
-
-private:
- static void cleanupNodesOnShutdown(QQuickItem *);
-};
-
-class QQuickCanvasRenderLoop
-{
-public:
- QQuickCanvasRenderLoop()
- : d(0)
- , renderer(0)
- , gl(0)
- {
- }
- virtual ~QQuickCanvasRenderLoop()
- {
- delete gl;
- }
-
- friend class QQuickCanvasPrivate;
-
- virtual void paint() = 0;
- virtual void resize(const QSize &size) = 0;
- virtual void startRendering() = 0;
- virtual void stopRendering() = 0;
- virtual QImage grab() = 0;
- virtual void setWindowSize(const QSize &size) = 0;
- virtual void maybeUpdate() = 0;
- virtual bool isRunning() const = 0;
- virtual void animationStarted() = 0;
- virtual void animationStopped() = 0;
- virtual void moveContextToThread(QSGContext *) { }
- virtual bool *allowMainThreadProcessing() { return 0; }
-
-protected:
- void initializeSceneGraph() { d->initializeSceneGraph(); }
- void syncSceneGraph() { d->syncSceneGraph(); }
- void cleanupNodesOnShutdown() { d->cleanupNodesOnShutdown(); }
- void renderSceneGraph(const QSize &size) { d->renderSceneGraph(size); }
- void polishItems() { d->polishItems(); }
- QAnimationDriver *animationDriver() const { return d->animationDriver; }
-
- inline QOpenGLContext *glContext() const { return gl; }
- void createGLContext();
- void makeCurrent() { gl->makeCurrent(renderer); }
- void doneCurrent() { gl->doneCurrent(); }
- void swapBuffers() {
- gl->swapBuffers(renderer);
- emit renderer->frameSwapped();
- }
-
-private:
- QQuickCanvasPrivate *d;
- QQuickCanvas *renderer;
-
- QOpenGLContext *gl;
-};
-
-class QQuickCanvasRenderThread : public QThread, public QQuickCanvasRenderLoop
-{
- Q_OBJECT
-public:
- QQuickCanvasRenderThread()
- : mutex(QMutex::NonRecursive)
- , allowMainThreadProcessingFlag(true)
- , animationRunning(false)
- , isGuiBlocked(0)
- , isPaintCompleted(false)
- , isGuiBlockPending(false)
- , isRenderBlocked(false)
- , isExternalUpdatePending(false)
- , syncAlreadyHappened(false)
- , inSync(false)
- , doGrab(false)
- , shouldExit(false)
- , hasExited(false)
- , renderThreadAwakened(false)
- {}
-
- inline void lock() { mutex.lock(); }
- inline void unlock() { mutex.unlock(); }
- inline void wait() { condition.wait(&mutex); }
- inline void wake() { condition.wakeOne(); }
-
- void lockInGui();
- void unlockInGui();
-
- void paint();
- void resize(const QSize &size);
- void startRendering();
- void stopRendering();
- void exhaustSyncEvent();
- void sync(bool guiAlreadyLocked);
- bool isRunning() const { return QThread::isRunning(); }
- void setWindowSize(const QSize &size) { windowSize = size; }
- void maybeUpdate();
- void moveContextToThread(QSGContext *c) { c->moveToThread(this); }
- bool *allowMainThreadProcessing() { return &allowMainThreadProcessingFlag; }
-
- bool event(QEvent *);
-
- QImage grab();
-
-public slots:
- void animationStarted();
- void animationStopped();
-
-public:
- QMutex mutex;
- QWaitCondition condition;
-
- bool allowMainThreadProcessingFlag;
-
- QSize windowSize;
- QSize renderedSize;
-
- uint animationRunning: 1;
- int isGuiBlocked;
- uint isPaintCompleted : 1;
- uint isGuiBlockPending : 1;
- uint isRenderBlocked : 1;
- uint isExternalUpdatePending : 1;
- uint syncAlreadyHappened : 1;
- uint inSync : 1;
- uint doGrab : 1;
- uint shouldExit : 1;
- uint hasExited : 1;
- uint renderThreadAwakened : 1;
-
- QImage grabContent;
-
- void run();
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QQuickCanvasPrivate::FocusOptions)
-
-QT_END_NAMESPACE
-
-#endif // QQUICKCANVAS_P_H
diff --git a/src/declarative/items/qquickclipnode.cpp b/src/declarative/items/qquickclipnode.cpp
deleted file mode 100644
index 4aeb2dcf69..0000000000
--- a/src/declarative/items/qquickclipnode.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qquickclipnode_p.h"
-
-#include <QtGui/qvector2d.h>
-#include <QtCore/qmath.h>
-
-QQuickDefaultClipNode::QQuickDefaultClipNode(const QRectF &rect)
- : m_rect(rect)
- , m_radius(0)
- , m_dirty_geometry(true)
- , m_geometry(QSGGeometry::defaultAttributes_Point2D(), 0)
-{
- setGeometry(&m_geometry);
- setIsRectangular(true);
-}
-
-void QQuickDefaultClipNode::setRect(const QRectF &rect)
-{
- m_rect = rect;
- m_dirty_geometry = true;
-}
-
-void QQuickDefaultClipNode::setRadius(qreal radius)
-{
- m_radius = radius;
- m_dirty_geometry = true;
- setIsRectangular(radius == 0);
-}
-
-void QQuickDefaultClipNode::update()
-{
- if (m_dirty_geometry) {
- updateGeometry();
- m_dirty_geometry = false;
- }
-}
-
-void QQuickDefaultClipNode::updateGeometry()
-{
- QSGGeometry *g = geometry();
-
- if (qFuzzyIsNull(m_radius)) {
- g->allocate(4);
- QSGGeometry::updateRectGeometry(g, m_rect);
-
- } else {
- int vertexCount = 0;
-
- // Radius should never exceeds half of the width or half of the height
- qreal radius = qMin(qMin(m_rect.width() / 2, m_rect.height() / 2), m_radius);
- QRectF rect = m_rect;
- rect.adjust(radius, radius, -radius, -radius);
-
- int segments = qMin(30, qCeil(radius)); // Number of segments per corner.
-
- g->allocate((segments + 1) * 2);
-
- QVector2D *vertices = (QVector2D *)g->vertexData();
-
- for (int part = 0; part < 2; ++part) {
- for (int i = 0; i <= segments; ++i) {
- //### Should change to calculate sin/cos only once.
- qreal angle = qreal(0.5 * M_PI) * (part + i / qreal(segments));
- qreal s = qFastSin(angle);
- qreal c = qFastCos(angle);
- qreal y = (part ? rect.bottom() : rect.top()) - radius * c; // current inner y-coordinate.
- qreal lx = rect.left() - radius * s; // current inner left x-coordinate.
- qreal rx = rect.right() + radius * s; // current inner right x-coordinate.
-
- vertices[vertexCount++] = QVector2D(rx, y);
- vertices[vertexCount++] = QVector2D(lx, y);
- }
- }
-
- markDirty(DirtyGeometry);
- }
- setClipRect(m_rect);
-}
-
diff --git a/src/declarative/items/qquickclipnode_p.h b/src/declarative/items/qquickclipnode_p.h
deleted file mode 100644
index 0323c9a24a..0000000000
--- a/src/declarative/items/qquickclipnode_p.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKCLIPNODE_P_H
-#define QQUICKCLIPNODE_P_H
-
-#include <qsgnode.h>
-
-class QQuickDefaultClipNode : public QSGClipNode
-{
-public:
- QQuickDefaultClipNode(const QRectF &);
-
- void setRect(const QRectF &);
- QRectF rect() const { return m_rect; }
-
- void setRadius(qreal radius);
- qreal radius() const { return m_radius; }
-
- virtual void update();
-
-private:
- void updateGeometry();
- QRectF m_rect;
- qreal m_radius;
-
- uint m_dirty_geometry : 1;
- uint m_reserved : 31;
-
- QSGGeometry m_geometry;
-};
-
-#endif // QQUICKCLIPNODE_P_H
diff --git a/src/declarative/items/qquickdrag.cpp b/src/declarative/items/qquickdrag.cpp
deleted file mode 100644
index 9dcc4ac7fe..0000000000
--- a/src/declarative/items/qquickdrag.cpp
+++ /dev/null
@@ -1,462 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickdrag_p.h"
-
-#include <private/qquickitem_p.h>
-#include <private/qquickevents_p_p.h>
-#include <private/qquickitemchangelistener_p.h>
-#include <private/qv8engine_p.h>
-
-#include <QtGui/qevent.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickDragAttachedPrivate : public QObjectPrivate, public QQuickItemChangeListener
-{
- Q_DECLARE_PUBLIC(QQuickDragAttached)
-public:
- static QQuickDragAttachedPrivate *get(QQuickDragAttached *attached) {
- return static_cast<QQuickDragAttachedPrivate *>(QObjectPrivate::get(attached)); }
-
- QQuickDragAttachedPrivate()
- : attachedItem(0)
- , mimeData(0)
- , proposedAction(Qt::MoveAction)
- , supportedActions(Qt::MoveAction | Qt::CopyAction | Qt::LinkAction)
- , active(false)
- , listening(false)
- {
- }
-
- void itemGeometryChanged(QQuickItem *, const QRectF &, const QRectF &);
- void start() { start(supportedActions); }
- void start(Qt::DropActions supportedActions);
- void setTarget(QQuickItem *item);
-
- QQuickDragGrabber dragGrabber;
-
- QDeclarativeGuard<QObject> source;
- QDeclarativeGuard<QObject> target;
- QQuickItem *attachedItem;
- QQuickDragMimeData *mimeData;
- Qt::DropAction proposedAction;
- Qt::DropActions supportedActions;
- bool active : 1;
- bool listening : 1;
- QPointF hotSpot;
- QStringList keys;
-};
-
-/*!
- \qmlclass Drag QQuickDrag
- \inqmlmodule QtQuick 2
- \brief The Drag attached property provides drag and drop events for moved Items.
-
- Using the Drag attached property any Item can made a source of drag and drop
- events within a scene.
-
- When a drag is \l active on an item any change in that items position will
- generate a drag events that will be sent to any DropArea that intersects
- the with new position of the item. Other items which implement drag and
- drop event handlers can also receive these events.
-
- The following snippet shows how an item can be dragged with a MouseArea.
- However, dragging is not limited to mouse drags, anything that can move an item
- can generate drag events, this can include touch events, animations and bindings.
-
- \snippet doc/src/snippets/declarative/drag.qml 0
-
- A drag can be terminated either by canceling it with Drag.cancel() or setting
- Drag.active to false, or it can be terminated with a drop event by calling
- Drag.drop(). If the drop event is accepted Drag.drop() will return the
- \l {supportedActions}{drop action} chosen by the recipient of the event,
- otherwise it will return Qt.IgnoreAction.
-
-*/
-
-void QQuickDragAttachedPrivate::itemGeometryChanged(QQuickItem *, const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_Q(QQuickDragAttached);
- if (newGeometry.topLeft() == oldGeometry.topLeft() || !active)
- return;
-
- if (QQuickCanvas *canvas = attachedItem->canvas()) {
- QPoint scenePos = attachedItem->mapToScene(hotSpot).toPoint();
- QDragMoveEvent event(scenePos, mimeData->m_supportedActions, mimeData, Qt::NoButton, Qt::NoModifier);
- QQuickDropEventEx::setProposedAction(&event, proposedAction);
- QQuickCanvasPrivate::get(canvas)->deliverDragEvent(&dragGrabber, &event);
- if (target != dragGrabber.target()) {
- target = dragGrabber.target();
- emit q->targetChanged();
- }
- }
-}
-
-QQuickDragAttached::QQuickDragAttached(QObject *parent)
- : QObject(*new QQuickDragAttachedPrivate, parent)
-{
- Q_D(QQuickDragAttached);
- d->attachedItem = qobject_cast<QQuickItem *>(parent);
- d->source = d->attachedItem;
-}
-
-QQuickDragAttached::~QQuickDragAttached()
-{
- Q_D(QQuickDragAttached);
- delete d->mimeData;
-}
-
-/*!
- \qmlattachedproperty bool QtQuick2::Drag::active
-
- This property holds whether a drag event sequence is currently active.
-
- Setting this property to true will send a QDragEnter event to the scene
- with the item's current position. Setting it to false will send a
- QDragLeave event.
-
- While a drag is active any change in an item's position will send a QDragMove
- event with item's new position to the scene.
-*/
-
-bool QQuickDragAttached::isActive() const
-{
- Q_D(const QQuickDragAttached);
- return d->active;
-}
-
-void QQuickDragAttached::setActive(bool active)
-{
- Q_D(QQuickDragAttached);
- if (d->active != active) {
- if (active)
- d->start(d->supportedActions);
- else
- cancel();
- }
-}
-
-/*!
- \qmlattachedproperty Object QtQuick2::Drag::source
-
- This property holds an object that is identified to recipients of drag events as
- the source of the events. By default this is the item Drag property is attached to.
-
- Changes to source while a Drag is active don't take effect until a new drag is started.
-*/
-
-QObject *QQuickDragAttached::source() const
-{
- Q_D(const QQuickDragAttached);
- return d->source;
-}
-
-void QQuickDragAttached::setSource(QObject *item)
-{
- Q_D(QQuickDragAttached);
- if (d->source != item) {
- d->source = item;
- emit sourceChanged();
- }
-}
-
-void QQuickDragAttached::resetSource()
-{
- Q_D(QQuickDragAttached);
- if (d->source != d->attachedItem) {
- d->source = d->attachedItem;
- emit sourceChanged();
- }
-}
-
-/*!
- \qmlattachedproperty Object QtQuick2::Drag::target
-
- While a drag is active this property holds the last object to accept an
- enter event from the dragged item, if the current drag position doesn't
- intersect any accepting targets it is null.
-
- When a drag is not active this property holds the object that accepted
- the drop event that ended the drag, if no object accepted the drop or
- the drag was canceled the target will then be null.
-*/
-
-QObject *QQuickDragAttached::target() const
-{
- Q_D(const QQuickDragAttached);
- return d->target;
-}
-
-/*!
- \qmlattachedproperty QPointF QtQuick2::Drag::hotSpot
-
- This property holds the drag position relative to the top left of the item.
-
- By default this is (0, 0).
-
- Changes to hotSpot will take effect when the next event is sent.
-*/
-
-QPointF QQuickDragAttached::hotSpot() const
-{
- Q_D(const QQuickDragAttached);
- return d->hotSpot;
-}
-
-void QQuickDragAttached::setHotSpot(const QPointF &hotSpot)
-{
- Q_D(QQuickDragAttached);
- if (d->hotSpot != hotSpot) {
- d->hotSpot = hotSpot;
- emit hotSpotChanged();
- // Send a move event if active?
- }
-}
-
-/*!
- \qmlattachedproperty stringlist QtQuick2::Drag::keys
-
- This property holds a list of keys that can be used by a DropArea to filter drag events.
-
- Changes to keys while a Drag is active don't take effect until a new drag is started.
-*/
-
-QStringList QQuickDragAttached::keys() const
-{
- Q_D(const QQuickDragAttached);
- return d->keys;
-}
-
-void QQuickDragAttached::setKeys(const QStringList &keys)
-{
- Q_D(QQuickDragAttached);
- if (d->keys != keys) {
- d->keys = keys;
- emit keysChanged();
- }
-}
-
-/*!
- \qmlattachedproperty flags QtQuick2::Drag::supportedActions
-
- This property holds return values of Drag.drop() supported by the drag source.
-
- Changes to supportedActions while a Drag is active don't take effect
- until a new drag is started.
-*/
-
-Qt::DropActions QQuickDragAttached::supportedActions() const
-{
- Q_D(const QQuickDragAttached);
- return d->supportedActions;
-}
-
-void QQuickDragAttached::setSupportedActions(Qt::DropActions actions)
-{
- Q_D(QQuickDragAttached);
- if (d->supportedActions != actions) {
- d->supportedActions = actions;
- emit supportedActionsChanged();
- }
-}
-
-/*!
- \qmlattachedproperty enumeration QtQuick2::Drag::proposedAction
-
- This property holds an action that is recommended by the drag source as a
- return value from Drag.drop().
-
- Changes to proposedAction will take effect when the next event is sent.
-*/
-
-Qt::DropAction QQuickDragAttached::proposedAction() const
-{
- Q_D(const QQuickDragAttached);
- return d->proposedAction;
-}
-
-void QQuickDragAttached::setProposedAction(Qt::DropAction action)
-{
- Q_D(QQuickDragAttached);
- if (d->proposedAction != action) {
- d->proposedAction = action;
- emit proposedActionChanged();
- // send a move event with the new default action if active?
- }
-}
-
-void QQuickDragAttachedPrivate::start(Qt::DropActions supportedActions)
-{
- Q_Q(QQuickDragAttached);
- Q_ASSERT(!active);
-
- if (QQuickCanvas *canvas = attachedItem ? attachedItem->canvas() : 0) {
- if (!mimeData)
- mimeData = new QQuickDragMimeData;
- if (!listening) {
- QQuickItemPrivate::get(attachedItem)->addItemChangeListener(this, QQuickItemPrivate::Geometry);
- listening = true;
- }
-
- mimeData->m_source = source;
- mimeData->m_supportedActions = supportedActions;
- mimeData->m_keys = keys;
- active = true;
-
- QPoint scenePos = attachedItem->mapToScene(hotSpot).toPoint();
- QDragEnterEvent event(scenePos, supportedActions, mimeData, Qt::NoButton, Qt::NoModifier);
- QQuickDropEventEx::setProposedAction(&event, proposedAction);
- QQuickCanvasPrivate::get(canvas)->deliverDragEvent(&dragGrabber, &event);
-
- emit q->activeChanged();
- if (target != dragGrabber.target()) {
- target = dragGrabber.target();
- emit q->targetChanged();
- }
- }
-}
-
-/*!
- \qmlattachedmethod void QtQuick2::Drag::start(flags supportedActions)
-
- Starts sending drag events.
-
- The optional \a supportedActions argument can be used to override the \l supportedActions
- property for the started sequence.
-*/
-
-void QQuickDragAttached::start(QDeclarativeV8Function *args)
-{
- Q_D(QQuickDragAttached);
- if (d->active)
- cancel();
-
- Qt::DropActions supportedActions = d->supportedActions;
- // check arguments for supportedActions, maybe data?
- if (args->Length() >= 1) {
- v8::Local<v8::Value> v = (*args)[0];
- if (v->IsInt32())
- supportedActions = Qt::DropActions(v->Int32Value());
- }
-
- d->start(supportedActions);
-}
-
-/*!
- \qmlattachedmethod enum QtQuick2::Drag::drop()
-
- Ends a drag sequence by sending a drop event to the target item.
-
- Returns the action accepted by the target item. If the target item or a parent doesn't accept
- the drop event then Qt.IgnoreAction will be returned.
-
- The returned drop action may be one of:
-
- \list
- \o Qt.CopyAction Copy the data to the target
- \o Qt.MoveAction Move the data from the source to the target
- \o Qt.LinkAction Create a link from the source to the target.
- \o Qt.IgnoreAction Ignore the action (do nothing with the data).
- \endlist
-
-*/
-
-int QQuickDragAttached::drop()
-{
- Q_D(QQuickDragAttached);
- Qt::DropAction acceptedAction = Qt::IgnoreAction;
-
- if (!d->active)
- return acceptedAction;
-
- QObject *target = 0;
-
- if (QQuickCanvas *canvas = d->attachedItem->canvas()) {
- QPoint scenePos = d->attachedItem->mapToScene(d->hotSpot).toPoint();
-
- QDropEvent event(
- scenePos, d->mimeData->m_supportedActions, d->mimeData, Qt::NoButton, Qt::NoModifier);
- QQuickDropEventEx::setProposedAction(&event, d->proposedAction);
- QQuickCanvasPrivate::get(canvas)->deliverDragEvent(&d->dragGrabber, &event);
-
- if (event.isAccepted()) {
- acceptedAction = event.dropAction();
- target = d->dragGrabber.target();
- }
- }
-
- d->active = false;
- if (d->target != target) {
- d->target = target;
- emit targetChanged();
- }
-
- emit activeChanged();
- return acceptedAction;
-}
-
-/*!
- \qmlattachedmethod void QtQuick2::Drag::cancel()
-
- Ends a drag sequence.
-*/
-
-void QQuickDragAttached::cancel()
-{
- Q_D(QQuickDragAttached);
- if (!d->active)
- return;
-
- if (QQuickCanvas *canvas = d->attachedItem->canvas()) {
- QDragLeaveEvent event;
- QQuickCanvasPrivate::get(canvas)->deliverDragEvent(&d->dragGrabber, &event);
- }
-
- d->active = false;
- if (d->target) {
- d->target = 0;
- emit targetChanged();
- }
- emit activeChanged();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickdrag_p.h b/src/declarative/items/qquickdrag_p.h
deleted file mode 100644
index 1d950299d7..0000000000
--- a/src/declarative/items/qquickdrag_p.h
+++ /dev/null
@@ -1,208 +0,0 @@
-// Commit: c6e6a35aeb8794d68a3ca0c4e27a3a1181c066b5
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKDRAG_P_H
-#define QQUICKDRAG_P_H
-
-#include <qquickitem.h>
-
-#include <private/qv8engine_p.h>
-
-#include <QtCore/qmimedata.h>
-#include <QtCore/qstringlist.h>
-
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickItem;
-class QQuickDrag;
-class QQuickDragPrivate;
-
-class QQuickDragGrabber
-{
- class Item : public QDeclarativeGuard<QQuickItem>
- {
- public:
- Item(QQuickItem *item) : QDeclarativeGuard<QQuickItem>(item) {}
-
- QIntrusiveListNode node;
- protected:
- void objectDestroyed(QQuickItem *) { delete this; }
- };
-
- typedef QIntrusiveList<Item, &Item::node> ItemList;
-
-public:
- QQuickDragGrabber() : m_target(0) {}
- ~QQuickDragGrabber() { while (!m_items.isEmpty()) delete m_items.first(); }
-
-
- QObject *target() const
- {
- if (m_target)
- return m_target;
- else if (!m_items.isEmpty())
- return *m_items.first();
- else
- return 0;
- }
- void setTarget(QObject *target) { m_target = target; }
- void resetTarget() { m_target = 0; }
-
- typedef ItemList::iterator iterator;
- iterator begin() { return m_items.begin(); }
- iterator end() { return m_items.end(); }
-
- void grab(QQuickItem *item) { m_items.insert(new Item(item)); }
- iterator release(iterator at) { Item *item = *at; at = at.erase(); delete item; return at; }
-
-private:
-
- ItemList m_items;
- QObject *m_target;
-};
-
-class QQuickDropEventEx : public QDropEvent
-{
-public:
- void setProposedAction(Qt::DropAction action) { default_action = action; drop_action = action; }
-
- static void setProposedAction(QDropEvent *event, Qt::DropAction action) {
- static_cast<QQuickDropEventEx *>(event)->setProposedAction(action);
- }
-
- void copyActions(const QDropEvent &from) {
- default_action = from.proposedAction(); drop_action = from.dropAction(); }
-
- static void copyActions(QDropEvent *to, const QDropEvent &from) {
- static_cast<QQuickDropEventEx *>(to)->copyActions(from);
- }
-};
-
-class QQuickDragMimeData : public QMimeData
-{
- Q_OBJECT
-public:
- QQuickDragMimeData()
- : m_source(0)
- {
- }
-
- QStringList keys() const { return m_keys; }
- QObject *source() const { return m_source; }
-
-private:
- QObject *m_source;
- Qt::DropActions m_supportedActions;
- QStringList m_keys;
-
- friend class QQuickDragAttached;
- friend class QQuickDragAttachedPrivate;
-};
-
-class QDeclarativeV8Function;
-
-class QQuickDragAttachedPrivate;
-class QQuickDragAttached : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(bool active READ isActive WRITE setActive NOTIFY activeChanged)
- Q_PROPERTY(QObject *source READ source WRITE setSource NOTIFY sourceChanged RESET resetSource)
- Q_PROPERTY(QObject *target READ target NOTIFY targetChanged)
- Q_PROPERTY(QPointF hotSpot READ hotSpot WRITE setHotSpot NOTIFY hotSpotChanged)
- Q_PROPERTY(QStringList keys READ keys WRITE setKeys NOTIFY keysChanged)
- Q_PROPERTY(Qt::DropActions supportedActions READ supportedActions WRITE setSupportedActions NOTIFY supportedActionsChanged)
- Q_PROPERTY(Qt::DropAction proposedAction READ proposedAction WRITE setProposedAction NOTIFY proposedActionChanged)
-public:
- QQuickDragAttached(QObject *parent);
- ~QQuickDragAttached();
-
- bool isActive() const;
- void setActive(bool active);
-
- QObject *source() const;
- void setSource(QObject *item);
- void resetSource();
-
- QObject *target() const;
-
- QPointF hotSpot() const;
- void setHotSpot(const QPointF &hotSpot);
-
- QStringList keys() const;
- void setKeys(const QStringList &keys);
-
- Qt::DropActions supportedActions() const;
- void setSupportedActions(Qt::DropActions actions);
-
- Qt::DropAction proposedAction() const;
- void setProposedAction(Qt::DropAction action);
-
- Q_INVOKABLE int drop();
-
-public Q_SLOTS:
- void start(QDeclarativeV8Function *);
- void cancel();
-
-Q_SIGNALS:
- void activeChanged();
- void sourceChanged();
- void targetChanged();
- void hotSpotChanged();
- void keysChanged();
- void supportedActionsChanged();
- void proposedActionChanged();
-
-private:
- Q_DECLARE_PRIVATE(QQuickDragAttached)
-};
-
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/items/qquickdroparea.cpp b/src/declarative/items/qquickdroparea.cpp
deleted file mode 100644
index 6ea1467e41..0000000000
--- a/src/declarative/items/qquickdroparea.cpp
+++ /dev/null
@@ -1,428 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickdroparea_p.h"
-#include "qquickdrag_p.h"
-#include "qquickitem_p.h"
-#include "qquickcanvas.h"
-
-#include <private/qdeclarativeengine_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QQuickDropAreaDrag::QQuickDropAreaDrag(QQuickDropAreaPrivate *d, QObject *parent)
- : QObject(parent)
- , d(d)
-{
-}
-
-QQuickDropAreaDrag::~QQuickDropAreaDrag()
-{
-}
-
-class QQuickDropAreaPrivate : public QQuickItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickDropArea)
-
-public:
- QQuickDropAreaPrivate();
- ~QQuickDropAreaPrivate();
-
- bool hasMatchingKey(const QStringList &keys) const;
-
- QStringList getKeys(const QMimeData *mimeData) const;
-
- QStringList keys;
- QRegExp keyRegExp;
- QPointF dragPosition;
- QQuickDropAreaDrag *drag;
- QDeclarativeGuard<QObject> source;
- QDeclarativeGuard<QMimeData> mimeData;
-};
-
-QQuickDropAreaPrivate::QQuickDropAreaPrivate()
- : drag(0)
-{
-}
-
-QQuickDropAreaPrivate::~QQuickDropAreaPrivate()
-{
- delete drag;
-}
-
-/*!
- \qmlclass DropArea QQuickDropArea
- \inqmlmodule QtQuick 2
- \brief The DropArea item provides drag and drop handling.
-
- A DropArea is an invisible item which receives events when other items are
- dragged over it.
-
- The Drag attached property can be used to notify the DropArea when an Item is
- dragged over it.
-
- The \l keys property can be used to filter drag events which don't include
- a matching key.
-
- The \l dropItem property is communicated to the source of a drag event as
- the recipient of a drop on the drag target.
-
- The \l delegate property provides a means to specify a component to be
- instantiated for each active drag over a drag target.
-*/
-
-QQuickDropArea::QQuickDropArea(QQuickItem *parent)
- : QQuickItem(*new QQuickDropAreaPrivate, parent)
-{
- setFlags(ItemAcceptsDrops);
-}
-
-QQuickDropArea::~QQuickDropArea()
-{
-}
-
-/*!
- \qmlproperty bool QtQuick2::DropArea::containsDrag
-
- This property identifies whether the DropArea currently contains any
- dragged items.
-*/
-
-bool QQuickDropArea::containsDrag() const
-{
- Q_D(const QQuickDropArea);
- return d->mimeData;
-}
-
-/*!
- \qmlproperty stringlist QtQuick2::DropArea::keys
-
- This property holds a list of drag keys a DropArea will accept.
-
- If no keys are listed the DropArea will accept events from any drag source,
- otherwise the drag source must have at least one compatible key.
-
- \sa QtQuick2::Drag::keys
-*/
-
-QStringList QQuickDropArea::keys() const
-{
- Q_D(const QQuickDropArea);
- return d->keys;
-}
-
-void QQuickDropArea::setKeys(const QStringList &keys)
-{
- Q_D(QQuickDropArea);
- if (d->keys != keys) {
- d->keys = keys;
-
- if (keys.isEmpty()) {
- d->keyRegExp = QRegExp();
- } else {
- QString pattern = QLatin1Char('(') + QRegExp::escape(keys.first());
- for (int i = 1; i < keys.count(); ++i)
- pattern += QLatin1Char('|') + QRegExp::escape(keys.at(i));
- pattern += QLatin1Char(')');
- d->keyRegExp = QRegExp(pattern.replace(QLatin1String("\\*"), QLatin1String(".+")));
- }
- emit keysChanged();
- }
-}
-
-QQuickDropAreaDrag *QQuickDropArea::drag()
-{
- Q_D(QQuickDropArea);
- if (!d->drag)
- d->drag = new QQuickDropAreaDrag(d);
- return d->drag;
-}
-
-/*!
- \qmlproperty Object QtQuick2::DropArea::drag.source
-
- This property holds the source of a drag.
-*/
-
-QObject *QQuickDropAreaDrag::source() const
-{
- return d->source;
-}
-
-/*!
- \qmlproperty qreal QtQuick2::DropArea::drag.x
- \qmlproperty qreal QtQuick2::DropArea::drag.y
-
- These properties hold the coordinates of the last drag event.
-*/
-
-qreal QQuickDropAreaDrag::x() const
-{
- return d->dragPosition.x();
-}
-
-qreal QQuickDropAreaDrag::y() const
-{
- return d->dragPosition.y();
-}
-
-/*!
- \qmlsignal QtQuick2::DropArea::onPositionChanged(DragEvent drag)
-
- This handler is called when the position of a drag has changed.
-*/
-
-void QQuickDropArea::dragMoveEvent(QDragMoveEvent *event)
-{
- Q_D(QQuickDropArea);
- if (!d->mimeData)
- return;
-
- d->dragPosition = event->pos();
- if (d->drag)
- emit d->drag->positionChanged();
-
- event->accept();
- QQuickDropEvent dragTargetEvent(d, event);
- emit positionChanged(&dragTargetEvent);
-}
-
-bool QQuickDropAreaPrivate::hasMatchingKey(const QStringList &keys) const
-{
- if (keyRegExp.isEmpty())
- return true;
-
- foreach (const QString &key, keys) {
- if (keyRegExp.exactMatch(key))
- return true;
- }
- return false;
-}
-
-QStringList QQuickDropAreaPrivate::getKeys(const QMimeData *mimeData) const
-{
- if (const QQuickDragMimeData *dragMime = qobject_cast<const QQuickDragMimeData *>(mimeData))
- return dragMime->keys();
- return mimeData->formats();
-}
-
-/*!
- \qmlsignal QtQuick2::DropArea::onEntered(DragEvent drag)
-
- This handler is called when a \a drag enters the bounds of a DropArea.
-*/
-
-void QQuickDropArea::dragEnterEvent(QDragEnterEvent *event)
-{
- Q_D(QQuickDropArea);
- const QMimeData *mimeData = event->mimeData();
- if (!d->effectiveEnable || d->mimeData || !mimeData || !d->hasMatchingKey(d->getKeys(mimeData)))
- return;
-
- d->dragPosition = event->pos();
-
- event->accept();
- QQuickDropEvent dragTargetEvent(d, event);
- emit entered(&dragTargetEvent);
-
- if (event->isAccepted()) {
- d->mimeData = const_cast<QMimeData *>(mimeData);
- if (QQuickDragMimeData *dragMime = qobject_cast<QQuickDragMimeData *>(d->mimeData))
- d->source = dragMime->source();
- else
- d->source = event->source();
- d->dragPosition = event->pos();
- if (d->drag) {
- emit d->drag->positionChanged();
- emit d->drag->sourceChanged();
- }
- emit containsDragChanged();
- }
-}
-
-/*!
- \qmlsignal QtQuick2::DropArea::onExited()
-
- This handler is called when a drag exits the bounds of a DropArea.
-*/
-
-void QQuickDropArea::dragLeaveEvent(QDragLeaveEvent *)
-{
- Q_D(QQuickDropArea);
- if (!d->mimeData)
- return;
-
- emit exited();
-
- d->mimeData = 0;
- d->source = 0;
- emit containsDragChanged();
- if (d->drag)
- emit d->drag->sourceChanged();
-}
-
-/*!
- \qmlsignal QtQuick2::DropArea::onDropped(DragEvent drop)
-
- This handler is called when a drop event occurs within the bounds of a
- a DropArea.
-*/
-
-void QQuickDropArea::dropEvent(QDropEvent *event)
-{
- Q_D(QQuickDropArea);
- if (!d->mimeData)
- return;
-
- QQuickDropEvent dragTargetEvent(d, event);
- emit dropped(&dragTargetEvent);
-
- d->mimeData = 0;
- d->source = 0;
- emit containsDragChanged();
- if (d->drag)
- emit d->drag->sourceChanged();
-}
-
-/*!
- \qmlclass DragEvent QQuickDragEvent
- \inqmlmodule QtQuick 2
- \brief The DragEvent object provides information about a drag event.
-
- The position of the drag event can be obtained from the \l x and \l y
- properties, and the \l keys property identifies the drag keys of the event
- \l source.
-*/
-
-/*!
- \qmlproperty real QtQuick2::DragEvent::x
-
- This property holds the x coordinate of a drag event.
-*/
-
-/*!
- \qmlproperty real QtQuick2::DragEvent::y
-
- This property holds the y coordinate of a drag event.
-*/
-
-/*!
- \qmlproperty Object QtQuick2::DragEvent::drag.source
-
- This property holds the source of a drag event.
-*/
-
-QObject *QQuickDropEvent::source()
-{
- if (const QQuickDragMimeData *dragMime = qobject_cast<const QQuickDragMimeData *>(event->mimeData()))
- return dragMime->source();
- else
- return event->source();
-}
-
-/*!
- \qmlproperty stringlist QtQuick2::DragEvent::keys
-
- This property holds a list of keys identifying the data type or source of a
- drag event.
-*/
-
-QStringList QQuickDropEvent::keys() const
-{
- return d->getKeys(event->mimeData());
-}
-
-/*!
- \qmlproperty enum QtQuick2::DragEvent::action
-
- This property holds the action that the \l source is to perform on an accepted drop.
-
- The drop action may be one of:
-
- \list
- \o Qt.CopyAction Copy the data to the target
- \o Qt.MoveAction Move the data from the source to the target
- \o Qt.LinkAction Create a link from the source to the target.
- \o Qt.IgnoreAction Ignore the action (do nothing with the data).
- \endlist
-*/
-
-/*!
- \qmlproperty flags QtQuick2::DragEvent::supportedActions
-
- This property holds the set of \l {action}{actions} supported by the
- drag source.
-*/
-
-/*!
- \qmlproperty real QtQuick2::DragEvent::accepted
-
- This property holds whether the drag event was accepted by a handler.
-
- The default value is true.
-*/
-
-/*!
- \qmlmethod void QtQuick2::DragEvent::accept()
- \qmlmethod void QtQuick2::DragEvent::accept(enum action)
-
- Accepts the drag event.
-
- If an \a action is specified it will overwrite the value of the \l action property.
-*/
-
-void QQuickDropEvent::accept(QDeclarativeV8Function *args)
-{
- Qt::DropAction action = event->dropAction();
-
- if (args->Length() >= 1) {
- v8::Local<v8::Value> v = (*args)[0];
- if (v->IsInt32())
- action = Qt::DropAction(v->Int32Value());
- }
- // get action from arguments.
- event->setDropAction(action);
- event->accept();
-}
-
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/items/qquickdroparea_p.h b/src/declarative/items/qquickdroparea_p.h
deleted file mode 100644
index 31e2bd7813..0000000000
--- a/src/declarative/items/qquickdroparea_p.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKDROPAREA_P_H
-#define QQUICKDROPAREA_P_H
-
-#include "qquickitem.h"
-
-#include <private/qdeclarativeguard_p.h>
-#include <private/qv8engine_p.h>
-
-#include <QtGui/qevent.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickDropAreaPrivate;
-class QQuickDropEvent : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(qreal x READ x)
- Q_PROPERTY(qreal y READ y)
- Q_PROPERTY(QObject *source READ source)
- Q_PROPERTY(QStringList keys READ keys)
- Q_PROPERTY(Qt::DropActions supportedActions READ supportedActions)
- Q_PROPERTY(Qt::DropAction action READ action WRITE setAction RESET resetAction)
- Q_PROPERTY(bool accepted READ accepted WRITE setAccepted)
-public:
- QQuickDropEvent(QQuickDropAreaPrivate *d, QDropEvent *event) : d(d), event(event) {}
-
- qreal x() const { return event->pos().x(); }
- qreal y() const { return event->pos().y(); }
-
- QObject *source();
-
- Qt::DropActions supportedActions() const { return event->possibleActions(); }
- Qt::DropAction action() const { return event->dropAction(); }
- void setAction(Qt::DropAction action) { event->setDropAction(action); }
- void resetAction() { event->setDropAction(event->proposedAction()); }
-
- QStringList keys() const;
-
- bool accepted() const { return event->isAccepted(); }
- void setAccepted(bool accepted) { event->setAccepted(accepted); }
-
- Q_INVOKABLE void accept(QDeclarativeV8Function *);
-
-private:
- QQuickDropAreaPrivate *d;
- QDropEvent *event;
-};
-
-class QQuickDropAreaDrag : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(qreal x READ x NOTIFY positionChanged)
- Q_PROPERTY(qreal y READ y NOTIFY positionChanged)
- Q_PROPERTY(QObject *source READ source NOTIFY sourceChanged)
-public:
- QQuickDropAreaDrag(QQuickDropAreaPrivate *d, QObject *parent = 0);
- ~QQuickDropAreaDrag();
-
- qreal x() const;
- qreal y() const;
- QObject *source() const;
-
-Q_SIGNALS:
- void positionChanged();
- void sourceChanged();
-
-private:
- QQuickDropAreaPrivate *d;
-
- friend class QQuickDropArea;
- friend class QQuickDropAreaPrivate;
-};
-
-class QQuickDropAreaPrivate;
-class Q_AUTOTEST_EXPORT QQuickDropArea : public QQuickItem
-{
- Q_OBJECT
- Q_PROPERTY(bool containsDrag READ containsDrag NOTIFY containsDragChanged)
- Q_PROPERTY(QStringList keys READ keys WRITE setKeys NOTIFY keysChanged)
- Q_PROPERTY(QQuickDropAreaDrag *drag READ drag CONSTANT)
-
-public:
- QQuickDropArea(QQuickItem *parent=0);
- ~QQuickDropArea();
-
- bool containsDrag() const;
- void setContainsDrag(bool drag);
-
- QStringList keys() const;
- void setKeys(const QStringList &keys);
-
- QQuickDropAreaDrag *drag();
-
-Q_SIGNALS:
- void containsDragChanged();
- void keysChanged();
- void sourceChanged();
-
- void entered(QQuickDropEvent *drag);
- void exited();
- void positionChanged(QQuickDropEvent *drag);
- void dropped(QQuickDropEvent *drop);
-
-protected:
- void dragMoveEvent(QDragMoveEvent *event);
- void dragEnterEvent(QDragEnterEvent *event);
- void dragLeaveEvent(QDragLeaveEvent *event);
- void dropEvent(QDropEvent *event);
-
-private:
- Q_DISABLE_COPY(QQuickDropArea)
- Q_DECLARE_PRIVATE(QQuickDropArea)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickDropEvent)
-QML_DECLARE_TYPE(QQuickDropArea)
-
-QT_END_HEADER
-
-#endif // QQUICKDROPAREA_P_H
diff --git a/src/declarative/items/qquickevents.cpp b/src/declarative/items/qquickevents.cpp
deleted file mode 100644
index c546dd305a..0000000000
--- a/src/declarative/items/qquickevents.cpp
+++ /dev/null
@@ -1,239 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickevents_p_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass KeyEvent QQuickKeyEvent
- \inqmlmodule QtQuick 2
- \ingroup qml-event-elements
-
- \brief The KeyEvent object provides information about a key event.
-
- For example, the following changes the Item's state property when the Enter
- key is pressed:
- \qml
-Item {
- focus: true
- Keys.onPressed: { if (event.key == Qt.Key_Enter) state = 'ShowDetails'; }
-}
- \endqml
-*/
-
-/*!
- \qmlproperty int QtQuick2::KeyEvent::key
-
- This property holds the code of the key that was pressed or released.
-
- See \l {Qt::Key}{Qt.Key} for the list of keyboard codes. These codes are
- independent of the underlying window system. Note that this
- function does not distinguish between capital and non-capital
- letters, use the text() function (returning the Unicode text the
- key generated) for this purpose.
-
- A value of either 0 or \l {Qt::Key_unknown}{Qt.Key_Unknown} means that the event is not
- the result of a known key; for example, it may be the result of
- a compose sequence, a keyboard macro, or due to key event
- compression.
-*/
-
-/*!
- \qmlproperty string QtQuick2::KeyEvent::text
-
- This property holds the Unicode text that the key generated.
- The text returned can be an empty string in cases where modifier keys,
- such as Shift, Control, Alt, and Meta, are being pressed or released.
- In such cases \c key will contain a valid value
-*/
-
-/*!
- \qmlproperty bool QtQuick2::KeyEvent::isAutoRepeat
-
- This property holds whether this event comes from an auto-repeating key.
-*/
-
-/*!
- \qmlproperty int QtQuick2::KeyEvent::count
-
- This property holds the number of keys involved in this event. If \l KeyEvent::text
- is not empty, this is simply the length of the string.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::KeyEvent::accepted
-
- Setting \a accepted to true prevents the key event from being
- propagated to the item's parent.
-
- Generally, if the item acts on the key event then it should be accepted
- so that ancestor items do not also respond to the same event.
-*/
-
-/*!
- \qmlproperty int QtQuick2::KeyEvent::modifiers
-
- This property holds the keyboard modifier flags that existed immediately
- before the event occurred.
-
- It contains a bitwise combination of:
- \list
- \o Qt.NoModifier - No modifier key is pressed.
- \o Qt.ShiftModifier - A Shift key on the keyboard is pressed.
- \o Qt.ControlModifier - A Ctrl key on the keyboard is pressed.
- \o Qt.AltModifier - An Alt key on the keyboard is pressed.
- \o Qt.MetaModifier - A Meta key on the keyboard is pressed.
- \o Qt.KeypadModifier - A keypad button is pressed.
- \endlist
-
- For example, to react to a Shift key + Enter key combination:
- \qml
- Item {
- focus: true
- Keys.onPressed: {
- if ((event.key == Qt.Key_Enter) && (event.modifiers & Qt.ShiftModifier))
- doSomething();
- }
- }
- \endqml
-*/
-
-
-/*!
- \qmlclass MouseEvent QQuickMouseEvent
- \inqmlmodule QtQuick 2
- \ingroup qml-event-elements
-
- \brief The MouseEvent object provides information about a mouse event.
-
- The position of the mouse can be found via the \l x and \l y properties.
- The button that caused the event is available via the \l button property.
-
- \sa MouseArea
-*/
-
-/*!
- \internal
- \class QQuickMouseEvent
-*/
-
-/*!
- \qmlproperty int QtQuick2::MouseEvent::x
- \qmlproperty int QtQuick2::MouseEvent::y
-
- These properties hold the coordinates of the position supplied by the mouse event.
-*/
-
-
-/*!
- \qmlproperty bool QtQuick2::MouseEvent::accepted
-
- Setting \a accepted to true prevents the mouse event from being
- propagated to items below this item.
-
- Generally, if the item acts on the mouse event then it should be accepted
- so that items lower in the stacking order do not also respond to the same event.
-*/
-
-/*!
- \qmlproperty enumeration QtQuick2::MouseEvent::button
-
- This property holds the button that caused the event. It can be one of:
- \list
- \o Qt.LeftButton
- \o Qt.RightButton
- \o Qt.MiddleButton
- \endlist
-*/
-
-/*!
- \qmlproperty bool QtQuick2::MouseEvent::wasHeld
-
- This property is true if the mouse button has been held pressed longer the
- threshold (800ms).
-*/
-
-/*!
- \qmlproperty int QtQuick2::MouseEvent::buttons
-
- This property holds the mouse buttons pressed when the event was generated.
- For mouse move events, this is all buttons that are pressed down. For mouse
- press and double click events this includes the button that caused the event.
- For mouse release events this excludes the button that caused the event.
-
- It contains a bitwise combination of:
- \list
- \o Qt.LeftButton
- \o Qt.RightButton
- \o Qt.MiddleButton
- \endlist
-*/
-
-/*!
- \qmlproperty int QtQuick2::MouseEvent::modifiers
-
- This property holds the keyboard modifier flags that existed immediately
- before the event occurred.
-
- It contains a bitwise combination of:
- \list
- \o Qt.NoModifier - No modifier key is pressed.
- \o Qt.ShiftModifier - A Shift key on the keyboard is pressed.
- \o Qt.ControlModifier - A Ctrl key on the keyboard is pressed.
- \o Qt.AltModifier - An Alt key on the keyboard is pressed.
- \o Qt.MetaModifier - A Meta key on the keyboard is pressed.
- \o Qt.KeypadModifier - A keypad button is pressed.
- \endlist
-
- For example, to react to a Shift key + Left mouse button click:
- \qml
- MouseArea {
- onClicked: {
- if ((mouse.button == Qt.LeftButton) && (mouse.modifiers & Qt.ShiftModifier))
- doSomething();
- }
- }
- \endqml
-*/
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickevents_p_p.h b/src/declarative/items/qquickevents_p_p.h
deleted file mode 100644
index cc5ed4f01e..0000000000
--- a/src/declarative/items/qquickevents_p_p.h
+++ /dev/null
@@ -1,144 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKEVENTS_P_P_H
-#define QQUICKEVENTS_P_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 <qdeclarative.h>
-
-#include <QtCore/qobject.h>
-#include <QtGui/qevent.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickKeyEvent : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(int key READ key)
- Q_PROPERTY(QString text READ text)
- Q_PROPERTY(int modifiers READ modifiers)
- Q_PROPERTY(bool isAutoRepeat READ isAutoRepeat)
- Q_PROPERTY(int count READ count)
- Q_PROPERTY(bool accepted READ isAccepted WRITE setAccepted)
-
-public:
- QQuickKeyEvent(QEvent::Type type, int key, Qt::KeyboardModifiers modifiers, const QString &text=QString(), bool autorep=false, ushort count=1)
- : event(type, key, modifiers, text, autorep, count) { event.setAccepted(false); }
- QQuickKeyEvent(const QKeyEvent &ke)
- : event(ke) { event.setAccepted(false); }
-
- int key() const { return event.key(); }
- QString text() const { return event.text(); }
- int modifiers() const { return event.modifiers(); }
- bool isAutoRepeat() const { return event.isAutoRepeat(); }
- int count() const { return event.count(); }
-
- bool isAccepted() { return event.isAccepted(); }
- void setAccepted(bool accepted) { event.setAccepted(accepted); }
-
-private:
- QKeyEvent event;
-};
-
-// used in QtLocation
-class Q_DECLARATIVE_EXPORT QQuickMouseEvent : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(qreal x READ x)
- Q_PROPERTY(qreal y READ y)
- Q_PROPERTY(int button READ button)
- Q_PROPERTY(int buttons READ buttons)
- Q_PROPERTY(int modifiers READ modifiers)
- Q_PROPERTY(bool wasHeld READ wasHeld)
- Q_PROPERTY(bool isClick READ isClick)
- Q_PROPERTY(bool accepted READ isAccepted WRITE setAccepted)
-
-public:
- QQuickMouseEvent(qreal x, qreal y, Qt::MouseButton button, Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers
- , bool isClick=false, bool wasHeld=false)
- : _x(x), _y(y), _button(button), _buttons(buttons), _modifiers(modifiers)
- , _wasHeld(wasHeld), _isClick(isClick), _accepted(true) {}
-
- qreal x() const { return _x; }
- qreal y() const { return _y; }
- int button() const { return _button; }
- int buttons() const { return _buttons; }
- int modifiers() const { return _modifiers; }
- bool wasHeld() const { return _wasHeld; }
- bool isClick() const { return _isClick; }
-
- // only for internal usage
- void setX(qreal x) { _x = x; }
- void setY(qreal y) { _y = y; }
- void setPosition(const QPointF &point) { _x = point.x(); _y = point.y(); }
-
- bool isAccepted() { return _accepted; }
- void setAccepted(bool accepted) { _accepted = accepted; }
-
-private:
- qreal _x;
- qreal _y;
- Qt::MouseButton _button;
- Qt::MouseButtons _buttons;
- Qt::KeyboardModifiers _modifiers;
- bool _wasHeld;
- bool _isClick;
- bool _accepted;
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickKeyEvent)
-QML_DECLARE_TYPE(QQuickMouseEvent)
-
-#endif // QQUICKEVENTS_P_P_H
diff --git a/src/declarative/items/qquickflickable.cpp b/src/declarative/items/qquickflickable.cpp
deleted file mode 100644
index aca3542a92..0000000000
--- a/src/declarative/items/qquickflickable.cpp
+++ /dev/null
@@ -1,2003 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickflickable_p.h"
-#include "qquickflickable_p_p.h"
-#include "qquickcanvas.h"
-#include "qquickcanvas_p.h"
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qguiapplication.h>
-#include <QtGui/qstylehints.h>
-#include "qplatformdefs.h"
-
-QT_BEGIN_NAMESPACE
-
-// The maximum number of pixels a flick can overshoot
-#ifndef QML_FLICK_OVERSHOOT
-#define QML_FLICK_OVERSHOOT 200
-#endif
-
-// The number of samples to use in calculating the velocity of a flick
-#ifndef QML_FLICK_SAMPLEBUFFER
-#define QML_FLICK_SAMPLEBUFFER 3
-#endif
-
-// The number of samples to discard when calculating the flick velocity.
-// Touch panels often produce inaccurate results as the finger is lifted.
-#ifndef QML_FLICK_DISCARDSAMPLES
-#define QML_FLICK_DISCARDSAMPLES 1
-#endif
-
-// The default maximum velocity of a flick.
-#ifndef QML_FLICK_DEFAULTMAXVELOCITY
-#define QML_FLICK_DEFAULTMAXVELOCITY 2500
-#endif
-
-// The default deceleration of a flick.
-#ifndef QML_FLICK_DEFAULTDECELERATION
-#define QML_FLICK_DEFAULTDECELERATION 1500
-#endif
-
-// How much faster to decelerate when overshooting
-#ifndef QML_FLICK_OVERSHOOTFRICTION
-#define QML_FLICK_OVERSHOOTFRICTION 8
-#endif
-
-// FlickThreshold determines how far the "mouse" must have moved
-// before we perform a flick.
-static const int FlickThreshold = 20;
-
-// RetainGrabVelocity is the maxmimum instantaneous velocity that
-// will ensure the Flickable retains the grab on consecutive flicks.
-static const int RetainGrabVelocity = 15;
-
-QQuickFlickableVisibleArea::QQuickFlickableVisibleArea(QQuickFlickable *parent)
- : QObject(parent), flickable(parent), m_xPosition(0.), m_widthRatio(0.)
- , m_yPosition(0.), m_heightRatio(0.)
-{
-}
-
-qreal QQuickFlickableVisibleArea::widthRatio() const
-{
- return m_widthRatio;
-}
-
-qreal QQuickFlickableVisibleArea::xPosition() const
-{
- return m_xPosition;
-}
-
-qreal QQuickFlickableVisibleArea::heightRatio() const
-{
- return m_heightRatio;
-}
-
-qreal QQuickFlickableVisibleArea::yPosition() const
-{
- return m_yPosition;
-}
-
-void QQuickFlickableVisibleArea::updateVisible()
-{
- QQuickFlickablePrivate *p = QQuickFlickablePrivate::get(flickable);
-
- bool changeX = false;
- bool changeY = false;
- bool changeWidth = false;
- bool changeHeight = false;
-
- // Vertical
- const qreal viewheight = flickable->height();
- const qreal maxyextent = -flickable->maxYExtent() + flickable->minYExtent();
- qreal pagePos = (-p->vData.move.value() + flickable->minYExtent()) / (maxyextent + viewheight);
- qreal pageSize = viewheight / (maxyextent + viewheight);
-
- if (pageSize != m_heightRatio) {
- m_heightRatio = pageSize;
- changeHeight = true;
- }
- if (pagePos != m_yPosition) {
- m_yPosition = pagePos;
- changeY = true;
- }
-
- // Horizontal
- const qreal viewwidth = flickable->width();
- const qreal maxxextent = -flickable->maxXExtent() + flickable->minXExtent();
- pagePos = (-p->hData.move.value() + flickable->minXExtent()) / (maxxextent + viewwidth);
- pageSize = viewwidth / (maxxextent + viewwidth);
-
- if (pageSize != m_widthRatio) {
- m_widthRatio = pageSize;
- changeWidth = true;
- }
- if (pagePos != m_xPosition) {
- m_xPosition = pagePos;
- changeX = true;
- }
-
- if (changeX)
- emit xPositionChanged(m_xPosition);
- if (changeY)
- emit yPositionChanged(m_yPosition);
- if (changeWidth)
- emit widthRatioChanged(m_widthRatio);
- if (changeHeight)
- emit heightRatioChanged(m_heightRatio);
-}
-
-
-QQuickFlickablePrivate::QQuickFlickablePrivate()
- : contentItem(new QQuickItem)
- , hData(this, &QQuickFlickablePrivate::setViewportX)
- , vData(this, &QQuickFlickablePrivate::setViewportY)
- , hMoved(false), vMoved(false)
- , stealMouse(false), pressed(false), interactive(true), calcVelocity(false)
- , pixelAligned(false)
- , deceleration(QML_FLICK_DEFAULTDECELERATION)
- , maxVelocity(QML_FLICK_DEFAULTMAXVELOCITY), reportedVelocitySmoothing(100)
- , delayedPressEvent(0), delayedPressTarget(0), pressDelay(0), fixupDuration(400)
- , fixupMode(Normal), vTime(0), visibleArea(0)
- , flickableDirection(QQuickFlickable::AutoFlickDirection)
- , boundsBehavior(QQuickFlickable::DragAndOvershootBounds)
-{
-}
-
-void QQuickFlickablePrivate::init()
-{
- Q_Q(QQuickFlickable);
- QDeclarative_setParent_noEvent(contentItem, q);
- contentItem->setParentItem(q);
- FAST_CONNECT(&timeline, SIGNAL(updated()), q, SLOT(ticked()))
- FAST_CONNECT(&timeline, SIGNAL(completed()), q, SLOT(movementEnding()))
- q->setAcceptedMouseButtons(Qt::LeftButton);
- q->setFiltersChildMouseEvents(true);
- QQuickItemPrivate *viewportPrivate = QQuickItemPrivate::get(contentItem);
- viewportPrivate->addItemChangeListener(this, QQuickItemPrivate::Geometry);
- lastPosTime.invalidate();
-}
-
-/*
- Returns the amount to overshoot by given a velocity.
- Will be roughly in range 0 - size/4
-*/
-qreal QQuickFlickablePrivate::overShootDistance(qreal size)
-{
- if (maxVelocity <= 0)
- return 0.0;
-
- return qMin(qreal(QML_FLICK_OVERSHOOT), size/3);
-}
-
-void QQuickFlickablePrivate::AxisData::addVelocitySample(qreal v, qreal maxVelocity)
-{
- if (v > maxVelocity)
- v = maxVelocity;
- else if (v < -maxVelocity)
- v = -maxVelocity;
- velocityBuffer.append(v);
- if (velocityBuffer.count() > QML_FLICK_SAMPLEBUFFER)
- velocityBuffer.remove(0);
-}
-
-void QQuickFlickablePrivate::AxisData::updateVelocity()
-{
- velocity = 0;
- if (velocityBuffer.count() > QML_FLICK_DISCARDSAMPLES) {
- int count = velocityBuffer.count()-QML_FLICK_DISCARDSAMPLES;
- for (int i = 0; i < count; ++i) {
- qreal v = velocityBuffer.at(i);
- velocity += v;
- }
- velocity /= count;
- }
-}
-
-void QQuickFlickablePrivate::itemGeometryChanged(QQuickItem *item, const QRectF &newGeom, const QRectF &oldGeom)
-{
- Q_Q(QQuickFlickable);
- if (item == contentItem) {
- if (newGeom.x() != oldGeom.x())
- emit q->contentXChanged();
- if (newGeom.y() != oldGeom.y())
- emit q->contentYChanged();
- }
-}
-
-void QQuickFlickablePrivate::flickX(qreal velocity)
-{
- Q_Q(QQuickFlickable);
- flick(hData, q->minXExtent(), q->maxXExtent(), q->width(), fixupX_callback, velocity);
-}
-
-void QQuickFlickablePrivate::flickY(qreal velocity)
-{
- Q_Q(QQuickFlickable);
- flick(vData, q->minYExtent(), q->maxYExtent(), q->height(), fixupY_callback, velocity);
-}
-
-void QQuickFlickablePrivate::flick(AxisData &data, qreal minExtent, qreal maxExtent, qreal,
- QDeclarativeTimeLineCallback::Callback fixupCallback, qreal velocity)
-{
- Q_Q(QQuickFlickable);
- qreal maxDistance = -1;
- data.fixingUp = false;
- // -ve velocity means list is moving up
- if (velocity > 0) {
- maxDistance = qAbs(minExtent - data.move.value());
- data.flickTarget = minExtent;
- } else {
- maxDistance = qAbs(maxExtent - data.move.value());
- data.flickTarget = maxExtent;
- }
- if (maxDistance > 0) {
- qreal v = velocity;
- if (maxVelocity != -1 && maxVelocity < qAbs(v)) {
- if (v < 0)
- v = -maxVelocity;
- else
- v = maxVelocity;
- }
- timeline.reset(data.move);
- if (boundsBehavior == QQuickFlickable::DragAndOvershootBounds)
- timeline.accel(data.move, v, deceleration);
- else
- timeline.accel(data.move, v, deceleration, maxDistance);
- timeline.callback(QDeclarativeTimeLineCallback(&data.move, fixupCallback, this));
- if (!hData.flicking && q->xflick()) {
- hData.flicking = true;
- emit q->flickingChanged();
- emit q->flickingHorizontallyChanged();
- if (!vData.flicking)
- emit q->flickStarted();
- }
- if (!vData.flicking && q->yflick()) {
- vData.flicking = true;
- emit q->flickingChanged();
- emit q->flickingVerticallyChanged();
- if (!hData.flicking)
- emit q->flickStarted();
- }
- } else {
- timeline.reset(data.move);
- fixup(data, minExtent, maxExtent);
- }
-}
-
-void QQuickFlickablePrivate::fixupY_callback(void *data)
-{
- ((QQuickFlickablePrivate *)data)->fixupY();
-}
-
-void QQuickFlickablePrivate::fixupX_callback(void *data)
-{
- ((QQuickFlickablePrivate *)data)->fixupX();
-}
-
-void QQuickFlickablePrivate::fixupX()
-{
- Q_Q(QQuickFlickable);
- fixup(hData, q->minXExtent(), q->maxXExtent());
-}
-
-void QQuickFlickablePrivate::fixupY()
-{
- Q_Q(QQuickFlickable);
- fixup(vData, q->minYExtent(), q->maxYExtent());
-}
-
-void QQuickFlickablePrivate::fixup(AxisData &data, qreal minExtent, qreal maxExtent)
-{
- if (data.move.value() > minExtent || maxExtent > minExtent) {
- timeline.reset(data.move);
- if (data.move.value() != minExtent) {
- switch (fixupMode) {
- case Immediate:
- timeline.set(data.move, minExtent);
- break;
- case ExtentChanged:
- // The target has changed. Don't start from the beginning; just complete the
- // second half of the animation using the new extent.
- timeline.move(data.move, minExtent, QEasingCurve(QEasingCurve::OutExpo), 3*fixupDuration/4);
- data.fixingUp = true;
- break;
- default: {
- qreal dist = minExtent - data.move;
- timeline.move(data.move, minExtent - dist/2, QEasingCurve(QEasingCurve::InQuad), fixupDuration/4);
- timeline.move(data.move, minExtent, QEasingCurve(QEasingCurve::OutExpo), 3*fixupDuration/4);
- data.fixingUp = true;
- }
- }
- }
- } else if (data.move.value() < maxExtent) {
- timeline.reset(data.move);
- switch (fixupMode) {
- case Immediate:
- timeline.set(data.move, maxExtent);
- break;
- case ExtentChanged:
- // The target has changed. Don't start from the beginning; just complete the
- // second half of the animation using the new extent.
- timeline.move(data.move, maxExtent, QEasingCurve(QEasingCurve::OutExpo), 3*fixupDuration/4);
- data.fixingUp = true;
- break;
- default: {
- qreal dist = maxExtent - data.move;
- timeline.move(data.move, maxExtent - dist/2, QEasingCurve(QEasingCurve::InQuad), fixupDuration/4);
- timeline.move(data.move, maxExtent, QEasingCurve(QEasingCurve::OutExpo), 3*fixupDuration/4);
- data.fixingUp = true;
- }
- }
- }
- data.inOvershoot = false;
- fixupMode = Normal;
- vTime = timeline.time();
-}
-
-void QQuickFlickablePrivate::updateBeginningEnd()
-{
- Q_Q(QQuickFlickable);
- bool atBoundaryChange = false;
-
- // Vertical
- const int maxyextent = int(-q->maxYExtent());
- const qreal ypos = -vData.move.value();
- bool atBeginning = (ypos <= -q->minYExtent());
- bool atEnd = (maxyextent <= ypos);
-
- if (atBeginning != vData.atBeginning) {
- vData.atBeginning = atBeginning;
- atBoundaryChange = true;
- }
- if (atEnd != vData.atEnd) {
- vData.atEnd = atEnd;
- atBoundaryChange = true;
- }
-
- // Horizontal
- const int maxxextent = int(-q->maxXExtent());
- const qreal xpos = -hData.move.value();
- atBeginning = (xpos <= -q->minXExtent());
- atEnd = (maxxextent <= xpos);
-
- if (atBeginning != hData.atBeginning) {
- hData.atBeginning = atBeginning;
- atBoundaryChange = true;
- }
- if (atEnd != hData.atEnd) {
- hData.atEnd = atEnd;
- atBoundaryChange = true;
- }
-
- if (vData.extentsChanged) {
- vData.extentsChanged = false;
- emit q->yOriginChanged();
- }
-
- if (hData.extentsChanged) {
- hData.extentsChanged = false;
- emit q->xOriginChanged();
- }
-
- if (atBoundaryChange)
- emit q->isAtBoundaryChanged();
-
- if (visibleArea)
- visibleArea->updateVisible();
-}
-
-/*
-XXXTODO add docs describing moving, dragging, flicking properties, e.g.
-
-When the user starts dragging the Flickable, the dragging and moving properties
-will be true.
-
-If the velocity is sufficient when the drag is ended, flicking may begin.
-
-The moving properties will remain true until all dragging and flicking
-is finished.
-*/
-
-/*!
- \qmlsignal QtQuick2::Flickable::onDragStarted()
-
- This handler is called when the view starts to be dragged due to user
- interaction.
-*/
-
-/*!
- \qmlsignal QtQuick2::Flickable::onDragEnded()
-
- This handler is called when the user stops dragging the view.
-
- If the velocity of the drag is suffient at the time the
- touch/mouse button is released then a flick will start.
-*/
-
-/*!
- \qmlclass Flickable QQuickFlickable
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-interaction-elements
-
- \brief The Flickable item provides a surface that can be "flicked".
- \inherits Item
-
- The Flickable item places its children on a surface that can be dragged
- and flicked, causing the view onto the child items to scroll. This
- behavior forms the basis of Items that are designed to show large numbers
- of child items, such as \l ListView and \l GridView.
-
- In traditional user interfaces, views can be scrolled using standard
- controls, such as scroll bars and arrow buttons. In some situations, it
- is also possible to drag the view directly by pressing and holding a
- mouse button while moving the cursor. In touch-based user interfaces,
- this dragging action is often complemented with a flicking action, where
- scrolling continues after the user has stopped touching the view.
-
- Flickable does not automatically clip its contents. If it is not used as
- a full-screen item, you should consider setting the \l{Item::}{clip} property
- to true.
-
- \section1 Example Usage
-
- \div {class="float-right"}
- \inlineimage flickable.gif
- \enddiv
-
- The following example shows a small view onto a large image in which the
- user can drag or flick the image in order to view different parts of it.
-
- \snippet doc/src/snippets/declarative/flickable.qml document
-
- \clearfloat
-
- Items declared as children of a Flickable are automatically parented to the
- Flickable's \l contentItem. This should be taken into account when
- operating on the children of the Flickable; it is usually the children of
- \c contentItem that are relevant. For example, the bound of Items added
- to the Flickable will be available by \c contentItem.childrenRect
-
- \section1 Limitations
-
- \note Due to an implementation detail, items placed inside a Flickable cannot anchor to it by
- \c id. Use \c parent instead.
-*/
-
-/*!
- \qmlsignal QtQuick2::Flickable::onMovementStarted()
-
- This handler is called when the view begins moving due to user
- interaction.
-*/
-
-/*!
- \qmlsignal QtQuick2::Flickable::onMovementEnded()
-
- This handler is called when the view stops moving due to user
- interaction. If a flick was generated, this handler will
- be triggered once the flick stops. If a flick was not
- generated, the handler will be triggered when the
- user stops dragging - i.e. a mouse or touch release.
-*/
-
-/*!
- \qmlsignal QtQuick2::Flickable::onFlickStarted()
-
- This handler is called when the view is flicked. A flick
- starts from the point that the mouse or touch is released,
- while still in motion.
-*/
-
-/*!
- \qmlsignal QtQuick2::Flickable::onFlickEnded()
-
- This handler is called when the view stops moving due to a flick.
-*/
-
-/*!
- \qmlproperty real QtQuick2::Flickable::visibleArea.xPosition
- \qmlproperty real QtQuick2::Flickable::visibleArea.widthRatio
- \qmlproperty real QtQuick2::Flickable::visibleArea.yPosition
- \qmlproperty real QtQuick2::Flickable::visibleArea.heightRatio
-
- These properties describe the position and size of the currently viewed area.
- The size is defined as the percentage of the full view currently visible,
- scaled to 0.0 - 1.0. The page position is usually in the range 0.0 (beginning) to
- 1.0 minus size ratio (end), i.e. \c yPosition is in the range 0.0 to 1.0-\c heightRatio.
- However, it is possible for the contents to be dragged outside of the normal
- range, resulting in the page positions also being outside the normal range.
-
- These properties are typically used to draw a scrollbar. For example:
-
- \snippet doc/src/snippets/declarative/flickableScrollbar.qml 0
- \dots 8
- \snippet doc/src/snippets/declarative/flickableScrollbar.qml 1
-
- \sa {declarative/ui-components/scrollbar}{scrollbar example}
-*/
-QQuickFlickable::QQuickFlickable(QQuickItem *parent)
- : QQuickItem(*(new QQuickFlickablePrivate), parent)
-{
- Q_D(QQuickFlickable);
- d->init();
-}
-
-QQuickFlickable::QQuickFlickable(QQuickFlickablePrivate &dd, QQuickItem *parent)
- : QQuickItem(dd, parent)
-{
- Q_D(QQuickFlickable);
- d->init();
-}
-
-QQuickFlickable::~QQuickFlickable()
-{
-}
-
-/*!
- \qmlproperty real QtQuick2::Flickable::contentX
- \qmlproperty real QtQuick2::Flickable::contentY
-
- These properties hold the surface coordinate currently at the top-left
- corner of the Flickable. For example, if you flick an image up 100 pixels,
- \c contentY will be 100.
-*/
-qreal QQuickFlickable::contentX() const
-{
- Q_D(const QQuickFlickable);
- return -d->contentItem->x();
-}
-
-void QQuickFlickable::setContentX(qreal pos)
-{
- Q_D(QQuickFlickable);
- d->hData.explicitValue = true;
- d->timeline.reset(d->hData.move);
- d->vTime = d->timeline.time();
- movementXEnding();
- if (-pos != d->hData.move.value()) {
- d->hData.move.setValue(-pos);
- viewportMoved();
- }
-}
-
-qreal QQuickFlickable::contentY() const
-{
- Q_D(const QQuickFlickable);
- return -d->contentItem->y();
-}
-
-void QQuickFlickable::setContentY(qreal pos)
-{
- Q_D(QQuickFlickable);
- d->vData.explicitValue = true;
- d->timeline.reset(d->vData.move);
- d->vTime = d->timeline.time();
- movementYEnding();
- if (-pos != d->vData.move.value()) {
- d->vData.move.setValue(-pos);
- viewportMoved();
- }
-}
-
-/*!
- \qmlproperty bool QtQuick2::Flickable::interactive
-
- This property describes whether the user can interact with the Flickable.
- A user cannot drag or flick a Flickable that is not interactive.
-
- By default, this property is true.
-
- This property is useful for temporarily disabling flicking. This allows
- special interaction with Flickable's children; for example, you might want
- to freeze a flickable map while scrolling through a pop-up dialog that
- is a child of the Flickable.
-*/
-bool QQuickFlickable::isInteractive() const
-{
- Q_D(const QQuickFlickable);
- return d->interactive;
-}
-
-void QQuickFlickable::setInteractive(bool interactive)
-{
- Q_D(QQuickFlickable);
- if (interactive != d->interactive) {
- d->interactive = interactive;
- if (!interactive && (d->hData.flicking || d->vData.flicking)) {
- d->timeline.clear();
- d->vTime = d->timeline.time();
- d->hData.flicking = false;
- d->vData.flicking = false;
- emit flickingChanged();
- emit flickingHorizontallyChanged();
- emit flickingVerticallyChanged();
- emit flickEnded();
- }
- emit interactiveChanged();
- }
-}
-
-/*!
- \qmlproperty real QtQuick2::Flickable::horizontalVelocity
- \qmlproperty real QtQuick2::Flickable::verticalVelocity
-
- The instantaneous velocity of movement along the x and y axes, in pixels/sec.
-
- The reported velocity is smoothed to avoid erratic output.
-*/
-qreal QQuickFlickable::horizontalVelocity() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.smoothVelocity.value();
-}
-
-qreal QQuickFlickable::verticalVelocity() const
-{
- Q_D(const QQuickFlickable);
- return d->vData.smoothVelocity.value();
-}
-
-/*!
- \qmlproperty bool QtQuick2::Flickable::atXBeginning
- \qmlproperty bool QtQuick2::Flickable::atXEnd
- \qmlproperty bool QtQuick2::Flickable::atYBeginning
- \qmlproperty bool QtQuick2::Flickable::atYEnd
-
- These properties are true if the flickable view is positioned at the beginning,
- or end respectively.
-*/
-bool QQuickFlickable::isAtXEnd() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.atEnd;
-}
-
-bool QQuickFlickable::isAtXBeginning() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.atBeginning;
-}
-
-bool QQuickFlickable::isAtYEnd() const
-{
- Q_D(const QQuickFlickable);
- return d->vData.atEnd;
-}
-
-bool QQuickFlickable::isAtYBeginning() const
-{
- Q_D(const QQuickFlickable);
- return d->vData.atBeginning;
-}
-
-void QQuickFlickable::ticked()
-{
- viewportMoved();
-}
-
-/*!
- \qmlproperty Item QtQuick2::Flickable::contentItem
-
- The internal item that contains the Items to be moved in the Flickable.
-
- Items declared as children of a Flickable are automatically parented to the Flickable's contentItem.
-
- Items created dynamically need to be explicitly parented to the \e contentItem:
- \code
- Flickable {
- id: myFlickable
- function addItem(file) {
- var component = Qt.createComponent(file)
- component.createObject(myFlickable.contentItem);
- }
- }
- \endcode
-*/
-QQuickItem *QQuickFlickable::contentItem()
-{
- Q_D(QQuickFlickable);
- return d->contentItem;
-}
-
-QQuickFlickableVisibleArea *QQuickFlickable::visibleArea()
-{
- Q_D(QQuickFlickable);
- if (!d->visibleArea)
- d->visibleArea = new QQuickFlickableVisibleArea(this);
- return d->visibleArea;
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Flickable::flickableDirection
-
- This property determines which directions the view can be flicked.
-
- \list
- \o Flickable.AutoFlickDirection (default) - allows flicking vertically if the
- \e contentHeight is not equal to the \e height of the Flickable.
- Allows flicking horizontally if the \e contentWidth is not equal
- to the \e width of the Flickable.
- \o Flickable.HorizontalFlick - allows flicking horizontally.
- \o Flickable.VerticalFlick - allows flicking vertically.
- \o Flickable.HorizontalAndVerticalFlick - allows flicking in both directions.
- \endlist
-*/
-QQuickFlickable::FlickableDirection QQuickFlickable::flickableDirection() const
-{
- Q_D(const QQuickFlickable);
- return d->flickableDirection;
-}
-
-void QQuickFlickable::setFlickableDirection(FlickableDirection direction)
-{
- Q_D(QQuickFlickable);
- if (direction != d->flickableDirection) {
- d->flickableDirection = direction;
- emit flickableDirectionChanged();
- }
-}
-
-bool QQuickFlickable::pixelAligned() const
-{
- Q_D(const QQuickFlickable);
- return d->pixelAligned;
-}
-
-void QQuickFlickable::setPixelAligned(bool align)
-{
- Q_D(QQuickFlickable);
- if (align != d->pixelAligned) {
- d->pixelAligned = align;
- emit pixelAlignedChanged();
- }
-}
-
-void QQuickFlickablePrivate::handleMousePressEvent(QMouseEvent *event)
-{
- Q_Q(QQuickFlickable);
- if (interactive && timeline.isActive()
- && (qAbs(hData.smoothVelocity.value()) > RetainGrabVelocity
- || qAbs(vData.smoothVelocity.value()) > RetainGrabVelocity)) {
- stealMouse = true; // If we've been flicked then steal the click.
- } else {
- stealMouse = false;
- }
- q->setKeepMouseGrab(stealMouse);
- pressed = true;
- timeline.clear();
- hData.reset();
- vData.reset();
- hData.dragMinBound = q->minXExtent();
- vData.dragMinBound = q->minYExtent();
- hData.dragMaxBound = q->maxXExtent();
- vData.dragMaxBound = q->maxYExtent();
- fixupMode = Normal;
- lastPos = QPointF();
- QQuickItemPrivate::start(lastPosTime);
- pressPos = event->localPos();
- hData.pressPos = hData.move.value();
- vData.pressPos = vData.move.value();
- hData.flicking = false;
- vData.flicking = false;
- QQuickItemPrivate::start(pressTime);
- QQuickItemPrivate::start(velocityTime);
-}
-
-void QQuickFlickablePrivate::handleMouseMoveEvent(QMouseEvent *event)
-{
- Q_Q(QQuickFlickable);
- if (!interactive || !lastPosTime.isValid())
- return;
- bool rejectY = false;
- bool rejectX = false;
-
- bool stealY = stealMouse;
- bool stealX = stealMouse;
-
- if (q->yflick()) {
- qreal dy = event->localPos().y() - pressPos.y();
- if (qAbs(dy) > qApp->styleHints()->startDragDistance() || QQuickItemPrivate::elapsed(pressTime) > 200) {
- if (!vMoved)
- vData.dragStartOffset = dy;
- qreal newY = dy + vData.pressPos - vData.dragStartOffset;
- const qreal minY = vData.dragMinBound;
- const qreal maxY = vData.dragMaxBound;
- if (newY > minY)
- newY = minY + (newY - minY) / 2;
- if (newY < maxY && maxY - minY <= 0)
- newY = maxY + (newY - maxY) / 2;
- if (boundsBehavior == QQuickFlickable::StopAtBounds && (newY > minY || newY < maxY)) {
- rejectY = true;
- if (newY < maxY) {
- newY = maxY;
- rejectY = false;
- }
- if (newY > minY) {
- newY = minY;
- rejectY = false;
- }
- }
- if (!rejectY && stealMouse) {
- vData.move.setValue(qRound(newY));
- vMoved = true;
- }
- if (qAbs(dy) > qApp->styleHints()->startDragDistance())
- stealY = true;
- }
- }
-
- if (q->xflick()) {
- qreal dx = event->localPos().x() - pressPos.x();
- if (qAbs(dx) > qApp->styleHints()->startDragDistance() || QQuickItemPrivate::elapsed(pressTime) > 200) {
- if (!hMoved)
- hData.dragStartOffset = dx;
- qreal newX = dx + hData.pressPos - hData.dragStartOffset;
- const qreal minX = hData.dragMinBound;
- const qreal maxX = hData.dragMaxBound;
- if (newX > minX)
- newX = minX + (newX - minX) / 2;
- if (newX < maxX && maxX - minX <= 0)
- newX = maxX + (newX - maxX) / 2;
- if (boundsBehavior == QQuickFlickable::StopAtBounds && (newX > minX || newX < maxX)) {
- rejectX = true;
- if (newX < maxX) {
- newX = maxX;
- rejectX = false;
- }
- if (newX > minX) {
- newX = minX;
- rejectX = false;
- }
- }
- if (!rejectX && stealMouse) {
- hData.move.setValue(qRound(newX));
- hMoved = true;
- }
-
- if (qAbs(dx) > qApp->styleHints()->startDragDistance())
- stealX = true;
- }
- }
-
- stealMouse = stealX || stealY;
- if (stealMouse)
- q->setKeepMouseGrab(true);
-
- if (rejectY) {
- vData.velocityBuffer.clear();
- vData.velocity = 0;
- }
- if (rejectX) {
- hData.velocityBuffer.clear();
- hData.velocity = 0;
- }
-
- if (hMoved || vMoved) {
- draggingStarting();
- q->movementStarting();
- q->viewportMoved();
- }
-
- if (!lastPos.isNull()) {
- qreal elapsed = qreal(QQuickItemPrivate::elapsed(lastPosTime)) / 1000.;
- if (elapsed <= 0)
- return;
- QQuickItemPrivate::restart(lastPosTime);
- qreal dy = event->localPos().y()-lastPos.y();
- if (q->yflick() && !rejectY)
- vData.addVelocitySample(dy/elapsed, maxVelocity);
- qreal dx = event->localPos().x()-lastPos.x();
- if (q->xflick() && !rejectX)
- hData.addVelocitySample(dx/elapsed, maxVelocity);
- }
-
- lastPos = event->localPos();
-}
-
-void QQuickFlickablePrivate::handleMouseReleaseEvent(QMouseEvent *event)
-{
- Q_Q(QQuickFlickable);
- stealMouse = false;
- q->setKeepMouseGrab(false);
- pressed = false;
-
- // if we drag then pause before release we should not cause a flick.
- qint64 elapsed = QQuickItemPrivate::elapsed(lastPosTime);
-
- vData.updateVelocity();
- hData.updateVelocity();
-
- draggingEnding();
-
- if (!lastPosTime.isValid())
- return;
-
- vTime = timeline.time();
-
- qreal velocity = elapsed < 100 ? vData.velocity : 0;
- if (vData.atBeginning || vData.atEnd)
- velocity /= 2;
- if (q->yflick() && qAbs(velocity) > MinimumFlickVelocity && qAbs(event->localPos().y() - pressPos.y()) > FlickThreshold) {
- velocityTimeline.reset(vData.smoothVelocity);
- vData.smoothVelocity.setValue(-velocity);
- flickY(velocity);
- } else {
- fixupY();
- }
-
- velocity = elapsed < 100 ? hData.velocity : 0;
- if (hData.atBeginning || hData.atEnd)
- velocity /= 2;
- if (q->xflick() && qAbs(velocity) > MinimumFlickVelocity && qAbs(event->localPos().x() - pressPos.x()) > FlickThreshold) {
- velocityTimeline.reset(hData.smoothVelocity);
- hData.smoothVelocity.setValue(-velocity);
- flickX(velocity);
- } else {
- fixupX();
- }
-
- if (!timeline.isActive())
- q->movementEnding();
-}
-
-void QQuickFlickable::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QQuickFlickable);
- if (d->interactive) {
- if (!d->pressed)
- d->handleMousePressEvent(event);
- event->accept();
- } else {
- QQuickItem::mousePressEvent(event);
- }
-}
-
-void QQuickFlickable::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QQuickFlickable);
- if (d->interactive) {
- d->handleMouseMoveEvent(event);
- event->accept();
- } else {
- QQuickItem::mouseMoveEvent(event);
- }
-}
-
-void QQuickFlickable::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QQuickFlickable);
- if (d->interactive) {
- d->clearDelayedPress();
- d->handleMouseReleaseEvent(event);
- event->accept();
- ungrabMouse();
- } else {
- QQuickItem::mouseReleaseEvent(event);
- }
-}
-
-void QQuickFlickable::wheelEvent(QWheelEvent *event)
-{
- Q_D(QQuickFlickable);
- if (!d->interactive) {
- QQuickItem::wheelEvent(event);
- } else if (yflick() && event->orientation() == Qt::Vertical) {
- bool valid = false;
- if (event->delta() > 0 && contentY() > -minYExtent()) {
- d->vData.velocity = qMax(event->delta()*2 - d->vData.smoothVelocity.value(), qreal(d->maxVelocity/4));
- valid = true;
- } else if (event->delta() < 0 && contentY() < -maxYExtent()) {
- d->vData.velocity = qMin(event->delta()*2 - d->vData.smoothVelocity.value(), qreal(-d->maxVelocity/4));
- valid = true;
- }
- if (valid) {
- d->vData.flicking = false;
- d->flickY(d->vData.velocity);
- if (d->vData.flicking) {
- d->vMoved = true;
- movementStarting();
- }
- event->accept();
- }
- } else if (xflick() && event->orientation() == Qt::Horizontal) {
- bool valid = false;
- if (event->delta() > 0 && contentX() > -minXExtent()) {
- d->hData.velocity = qMax(event->delta()*2 - d->hData.smoothVelocity.value(), qreal(d->maxVelocity/4));
- valid = true;
- } else if (event->delta() < 0 && contentX() < -maxXExtent()) {
- d->hData.velocity = qMin(event->delta()*2 - d->hData.smoothVelocity.value(), qreal(-d->maxVelocity/4));
- valid = true;
- }
- if (valid) {
- d->hData.flicking = false;
- d->flickX(d->hData.velocity);
- if (d->hData.flicking) {
- d->hMoved = true;
- movementStarting();
- }
- event->accept();
- }
- } else {
- QQuickItem::wheelEvent(event);
- }
-}
-
-bool QQuickFlickablePrivate::isOutermostPressDelay() const
-{
- Q_Q(const QQuickFlickable);
- QQuickItem *item = q->parentItem();
- while (item) {
- QQuickFlickable *flick = qobject_cast<QQuickFlickable*>(item);
- if (flick && flick->pressDelay() > 0 && flick->isInteractive())
- return false;
- item = item->parentItem();
- }
-
- return true;
-}
-
-void QQuickFlickablePrivate::captureDelayedPress(QMouseEvent *event)
-{
- Q_Q(QQuickFlickable);
- if (!q->canvas() || pressDelay <= 0)
- return;
- if (!isOutermostPressDelay())
- return;
- delayedPressTarget = q->canvas()->mouseGrabberItem();
- delayedPressEvent = new QMouseEvent(*event);
- delayedPressEvent->setAccepted(false);
- delayedPressTimer.start(pressDelay, q);
-}
-
-void QQuickFlickablePrivate::clearDelayedPress()
-{
- if (delayedPressEvent) {
- delayedPressTimer.stop();
- delete delayedPressEvent;
- delayedPressEvent = 0;
- }
-}
-
-//XXX pixelAligned ignores the global position of the Flickable, i.e. assumes Flickable itself is pixel aligned.
-void QQuickFlickablePrivate::setViewportX(qreal x)
-{
- contentItem->setX(pixelAligned ? qRound(x) : x);
-}
-
-void QQuickFlickablePrivate::setViewportY(qreal y)
-{
- contentItem->setY(pixelAligned ? qRound(y) : y);
-}
-
-void QQuickFlickable::timerEvent(QTimerEvent *event)
-{
- Q_D(QQuickFlickable);
- if (event->timerId() == d->delayedPressTimer.timerId()) {
- d->delayedPressTimer.stop();
- if (d->delayedPressEvent) {
- QQuickItem *grabber = canvas() ? canvas()->mouseGrabberItem() : 0;
- if (!grabber || grabber != this) {
- // We replay the mouse press but the grabber we had might not be interessted by the event (e.g. overlay)
- // so we reset the grabber
- if (canvas()->mouseGrabberItem() == d->delayedPressTarget)
- d->delayedPressTarget->ungrabMouse();
- // Use the event handler that will take care of finding the proper item to propagate the event
- QQuickCanvasPrivate::get(canvas())->deliverMouseEvent(d->delayedPressEvent);
- }
- delete d->delayedPressEvent;
- d->delayedPressEvent = 0;
- }
- }
-}
-
-qreal QQuickFlickable::minYExtent() const
-{
- Q_D(const QQuickFlickable);
- return d->vData.startMargin;
-}
-
-qreal QQuickFlickable::minXExtent() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.startMargin;
-}
-
-/* returns -ve */
-qreal QQuickFlickable::maxXExtent() const
-{
- Q_D(const QQuickFlickable);
- return width() - vWidth() - d->hData.endMargin;
-}
-/* returns -ve */
-qreal QQuickFlickable::maxYExtent() const
-{
- Q_D(const QQuickFlickable);
- return height() - vHeight() - d->vData.endMargin;
-}
-
-void QQuickFlickable::componentComplete()
-{
- Q_D(QQuickFlickable);
- QQuickItem::componentComplete();
- if (!d->hData.explicitValue && d->hData.startMargin != 0.)
- setContentX(-minXExtent());
- if (!d->vData.explicitValue && d->vData.startMargin != 0.)
- setContentY(-minYExtent());
-}
-
-void QQuickFlickable::viewportMoved()
-{
- Q_D(QQuickFlickable);
-
- qreal prevX = d->lastFlickablePosition.x();
- qreal prevY = d->lastFlickablePosition.y();
- if (d->pressed || d->calcVelocity) {
- int elapsed = QQuickItemPrivate::restart(d->velocityTime);
- if (elapsed > 0) {
- qreal horizontalVelocity = (prevX - d->hData.move.value()) * 1000 / elapsed;
- if (qAbs(horizontalVelocity) > 0) {
- d->velocityTimeline.reset(d->hData.smoothVelocity);
- if (d->calcVelocity)
- d->velocityTimeline.set(d->hData.smoothVelocity, horizontalVelocity);
- else
- d->velocityTimeline.move(d->hData.smoothVelocity, horizontalVelocity, d->reportedVelocitySmoothing);
- d->velocityTimeline.move(d->hData.smoothVelocity, 0, d->reportedVelocitySmoothing);
- }
- qreal verticalVelocity = (prevY - d->vData.move.value()) * 1000 / elapsed;
- if (qAbs(verticalVelocity) > 0) {
- d->velocityTimeline.reset(d->vData.smoothVelocity);
- if (d->calcVelocity)
- d->velocityTimeline.set(d->vData.smoothVelocity, verticalVelocity);
- else
- d->velocityTimeline.move(d->vData.smoothVelocity, verticalVelocity, d->reportedVelocitySmoothing);
- d->velocityTimeline.move(d->vData.smoothVelocity, 0, d->reportedVelocitySmoothing);
- }
- }
- } else {
- if (d->timeline.time() > d->vTime) {
- d->velocityTimeline.clear();
- qreal horizontalVelocity = (prevX - d->hData.move.value()) * 1000 / (d->timeline.time() - d->vTime);
- qreal verticalVelocity = (prevY - d->vData.move.value()) * 1000 / (d->timeline.time() - d->vTime);
- d->hData.smoothVelocity.setValue(horizontalVelocity);
- d->vData.smoothVelocity.setValue(verticalVelocity);
- }
- }
-
- if (!d->vData.inOvershoot && !d->vData.fixingUp && d->vData.flicking
- && (d->vData.move.value() > minYExtent() || d->vData.move.value() < maxYExtent())
- && qAbs(d->vData.smoothVelocity.value()) > 100) {
- // Increase deceleration if we've passed a bound
- d->vData.inOvershoot = true;
- qreal maxDistance = d->overShootDistance(height());
- d->timeline.reset(d->vData.move);
- d->timeline.accel(d->vData.move, -d->vData.smoothVelocity.value(), d->deceleration*QML_FLICK_OVERSHOOTFRICTION, maxDistance);
- d->timeline.callback(QDeclarativeTimeLineCallback(&d->vData.move, d->fixupY_callback, d));
- }
- if (!d->hData.inOvershoot && !d->hData.fixingUp && d->hData.flicking
- && (d->hData.move.value() > minXExtent() || d->hData.move.value() < maxXExtent())
- && qAbs(d->hData.smoothVelocity.value()) > 100) {
- // Increase deceleration if we've passed a bound
- d->hData.inOvershoot = true;
- qreal maxDistance = d->overShootDistance(width());
- d->timeline.reset(d->hData.move);
- d->timeline.accel(d->hData.move, -d->hData.smoothVelocity.value(), d->deceleration*QML_FLICK_OVERSHOOTFRICTION, maxDistance);
- d->timeline.callback(QDeclarativeTimeLineCallback(&d->hData.move, d->fixupX_callback, d));
- }
-
- d->lastFlickablePosition = QPointF(d->hData.move.value(), d->vData.move.value());
-
- d->vTime = d->timeline.time();
- d->updateBeginningEnd();
-}
-
-void QQuickFlickable::geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry)
-{
- Q_D(QQuickFlickable);
- QQuickItem::geometryChanged(newGeometry, oldGeometry);
-
- bool changed = false;
- if (newGeometry.width() != oldGeometry.width()) {
- if (xflick())
- changed = true;
- if (d->hData.viewSize < 0) {
- d->contentItem->setWidth(width());
- emit contentWidthChanged();
- }
- // Make sure that we're entirely in view.
- if (!d->pressed && !d->hData.moving && !d->vData.moving) {
- d->fixupMode = QQuickFlickablePrivate::Immediate;
- d->fixupX();
- }
- }
- if (newGeometry.height() != oldGeometry.height()) {
- if (yflick())
- changed = true;
- if (d->vData.viewSize < 0) {
- d->contentItem->setHeight(height());
- emit contentHeightChanged();
- }
- // Make sure that we're entirely in view.
- if (!d->pressed && !d->hData.moving && !d->vData.moving) {
- d->fixupMode = QQuickFlickablePrivate::Immediate;
- d->fixupY();
- }
- }
-
- if (changed)
- d->updateBeginningEnd();
-}
-
-void QQuickFlickable::cancelFlick()
-{
- Q_D(QQuickFlickable);
- d->timeline.reset(d->hData.move);
- d->timeline.reset(d->vData.move);
- movementEnding();
-}
-
-void QQuickFlickablePrivate::data_append(QDeclarativeListProperty<QObject> *prop, QObject *o)
-{
- QQuickItem *i = qobject_cast<QQuickItem *>(o);
- if (i) {
- i->setParentItem(static_cast<QQuickFlickablePrivate*>(prop->data)->contentItem);
- } else {
- o->setParent(prop->object); // XXX todo - do we want this?
- }
-}
-
-int QQuickFlickablePrivate::data_count(QDeclarativeListProperty<QObject> *)
-{
- // XXX todo
- return 0;
-}
-
-QObject *QQuickFlickablePrivate::data_at(QDeclarativeListProperty<QObject> *, int)
-{
- // XXX todo
- return 0;
-}
-
-void QQuickFlickablePrivate::data_clear(QDeclarativeListProperty<QObject> *)
-{
- // XXX todo
-}
-
-QDeclarativeListProperty<QObject> QQuickFlickable::flickableData()
-{
- Q_D(QQuickFlickable);
- return QDeclarativeListProperty<QObject>(this, (void *)d, QQuickFlickablePrivate::data_append,
- QQuickFlickablePrivate::data_count,
- QQuickFlickablePrivate::data_at,
- QQuickFlickablePrivate::data_clear);
-}
-
-QDeclarativeListProperty<QQuickItem> QQuickFlickable::flickableChildren()
-{
- Q_D(QQuickFlickable);
- return QQuickItemPrivate::get(d->contentItem)->children();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Flickable::boundsBehavior
- This property holds whether the surface may be dragged
- beyond the Flickable's boundaries, or overshoot the
- Flickable's boundaries when flicked.
-
- This enables the feeling that the edges of the view are soft,
- rather than a hard physical boundary.
-
- The \c boundsBehavior can be one of:
-
- \list
- \o Flickable.StopAtBounds - the contents can not be dragged beyond the boundary
- of the flickable, and flicks will not overshoot.
- \o Flickable.DragOverBounds - the contents can be dragged beyond the boundary
- of the Flickable, but flicks will not overshoot.
- \o Flickable.DragAndOvershootBounds (default) - the contents can be dragged
- beyond the boundary of the Flickable, and can overshoot the
- boundary when flicked.
- \endlist
-*/
-QQuickFlickable::BoundsBehavior QQuickFlickable::boundsBehavior() const
-{
- Q_D(const QQuickFlickable);
- return d->boundsBehavior;
-}
-
-void QQuickFlickable::setBoundsBehavior(BoundsBehavior b)
-{
- Q_D(QQuickFlickable);
- if (b == d->boundsBehavior)
- return;
- d->boundsBehavior = b;
- emit boundsBehaviorChanged();
-}
-
-/*!
- \qmlproperty real QtQuick2::Flickable::contentWidth
- \qmlproperty real QtQuick2::Flickable::contentHeight
-
- The dimensions of the content (the surface controlled by Flickable).
- This should typically be set to the combined size of the items placed in the
- Flickable.
-
- The following snippet shows how these properties are used to display
- an image that is larger than the Flickable item itself:
-
- \snippet doc/src/snippets/declarative/flickable.qml document
-
- In some cases, the the content dimensions can be automatically set
- using the \l {Item::childrenRect.width}{childrenRect.width}
- and \l {Item::childrenRect.height}{childrenRect.height} properties.
-*/
-qreal QQuickFlickable::contentWidth() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.viewSize;
-}
-
-void QQuickFlickable::setContentWidth(qreal w)
-{
- Q_D(QQuickFlickable);
- if (d->hData.viewSize == w)
- return;
- d->hData.viewSize = w;
- if (w < 0)
- d->contentItem->setWidth(width());
- else
- d->contentItem->setWidth(w);
- d->hData.markExtentsDirty();
- // Make sure that we're entirely in view.
- if (!d->pressed && !d->hData.moving && !d->vData.moving) {
- d->fixupMode = QQuickFlickablePrivate::Immediate;
- d->fixupX();
- } else if (!d->pressed && d->hData.fixingUp) {
- d->fixupMode = QQuickFlickablePrivate::ExtentChanged;
- d->fixupX();
- }
- emit contentWidthChanged();
- d->updateBeginningEnd();
-}
-
-qreal QQuickFlickable::contentHeight() const
-{
- Q_D(const QQuickFlickable);
- return d->vData.viewSize;
-}
-
-void QQuickFlickable::setContentHeight(qreal h)
-{
- Q_D(QQuickFlickable);
- if (d->vData.viewSize == h)
- return;
- d->vData.viewSize = h;
- if (h < 0)
- d->contentItem->setHeight(height());
- else
- d->contentItem->setHeight(h);
- d->vData.markExtentsDirty();
- // Make sure that we're entirely in view.
- if (!d->pressed && !d->hData.moving && !d->vData.moving) {
- d->fixupMode = QQuickFlickablePrivate::Immediate;
- d->fixupY();
- } else if (!d->pressed && d->vData.fixingUp) {
- d->fixupMode = QQuickFlickablePrivate::ExtentChanged;
- d->fixupY();
- }
- emit contentHeightChanged();
- d->updateBeginningEnd();
-}
-
-/*!
- \qmlproperty real QtQuick2::Flickable::topMargin
- \qmlproperty real QtQuick2::Flickable::leftMargin
- \qmlproperty real QtQuick2::Flickable::bottomMargin
- \qmlproperty real QtQuick2::Flickable::rightMargin
-
- These properties hold the margins around the content. This space is reserved
- in addition to the contentWidth and contentHeight.
-*/
-
-
-qreal QQuickFlickable::topMargin() const
-{
- Q_D(const QQuickFlickable);
- return d->vData.startMargin;
-}
-
-void QQuickFlickable::setTopMargin(qreal m)
-{
- Q_D(QQuickFlickable);
- if (d->vData.startMargin == m)
- return;
- d->vData.startMargin = m;
- d->vData.markExtentsDirty();
- if (!d->pressed && !d->hData.moving && !d->vData.moving) {
- d->fixupMode = QQuickFlickablePrivate::Immediate;
- d->fixupY();
- }
- emit topMarginChanged();
- d->updateBeginningEnd();
-}
-
-qreal QQuickFlickable::bottomMargin() const
-{
- Q_D(const QQuickFlickable);
- return d->vData.endMargin;
-}
-
-void QQuickFlickable::setBottomMargin(qreal m)
-{
- Q_D(QQuickFlickable);
- if (d->vData.endMargin == m)
- return;
- d->vData.endMargin = m;
- d->vData.markExtentsDirty();
- if (!d->pressed && !d->hData.moving && !d->vData.moving) {
- d->fixupMode = QQuickFlickablePrivate::Immediate;
- d->fixupY();
- }
- emit bottomMarginChanged();
- d->updateBeginningEnd();
-}
-
-qreal QQuickFlickable::leftMargin() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.startMargin;
-}
-
-void QQuickFlickable::setLeftMargin(qreal m)
-{
- Q_D(QQuickFlickable);
- if (d->hData.startMargin == m)
- return;
- d->hData.startMargin = m;
- d->hData.markExtentsDirty();
- if (!d->pressed && !d->hData.moving && !d->vData.moving) {
- d->fixupMode = QQuickFlickablePrivate::Immediate;
- d->fixupX();
- }
- emit leftMarginChanged();
- d->updateBeginningEnd();
-}
-
-qreal QQuickFlickable::rightMargin() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.endMargin;
-}
-
-void QQuickFlickable::setRightMargin(qreal m)
-{
- Q_D(QQuickFlickable);
- if (d->hData.endMargin == m)
- return;
- d->hData.endMargin = m;
- d->hData.markExtentsDirty();
- if (!d->pressed && !d->hData.moving && !d->vData.moving) {
- d->fixupMode = QQuickFlickablePrivate::Immediate;
- d->fixupX();
- }
- emit rightMarginChanged();
- d->updateBeginningEnd();
-}
-
-/*!
- \qmlproperty real QtQuick2::Flickable::xOrigin
- \qmlproperty real QtQuick2::Flickable::yOrigin
-
- These properties hold the origin of the content. This is usually (0,0), however
- ListView and GridView may have an arbitrary origin due to delegate size variation,
- or item insertion/removal outside the visible region.
-*/
-
-qreal QQuickFlickable::yOrigin() const
-{
- Q_D(const QQuickFlickable);
- return -minYExtent() + d->vData.startMargin;
-}
-
-qreal QQuickFlickable::xOrigin() const
-{
- Q_D(const QQuickFlickable);
- return -minXExtent() + d->hData.startMargin;
-}
-
-
-/*!
- \qmlmethod QtQuick2::Flickable::resizeContent(real width, real height, QPointF center)
-
- Resizes the content to \a width x \a height about \a center.
-
- This does not scale the contents of the Flickable - it only resizes the \l contentWidth
- and \l contentHeight.
-
- Resizing the content may result in the content being positioned outside
- the bounds of the Flickable. Calling \l returnToBounds() will
- move the content back within legal bounds.
-*/
-void QQuickFlickable::resizeContent(qreal w, qreal h, QPointF center)
-{
- Q_D(QQuickFlickable);
- if (w != d->hData.viewSize) {
- qreal oldSize = d->hData.viewSize;
- d->hData.viewSize = w;
- d->contentItem->setWidth(w);
- emit contentWidthChanged();
- if (center.x() != 0) {
- qreal pos = center.x() * w / oldSize;
- setContentX(contentX() + pos - center.x());
- }
- }
- if (h != d->vData.viewSize) {
- qreal oldSize = d->vData.viewSize;
- d->vData.viewSize = h;
- d->contentItem->setHeight(h);
- emit contentHeightChanged();
- if (center.y() != 0) {
- qreal pos = center.y() * h / oldSize;
- setContentY(contentY() + pos - center.y());
- }
- }
- d->updateBeginningEnd();
-}
-
-/*!
- \qmlmethod QtQuick2::Flickable::returnToBounds()
-
- Ensures the content is within legal bounds.
-
- This may be called to ensure that the content is within legal bounds
- after manually positioning the content.
-*/
-void QQuickFlickable::returnToBounds()
-{
- Q_D(QQuickFlickable);
- d->fixupX();
- d->fixupY();
-}
-
-qreal QQuickFlickable::vWidth() const
-{
- Q_D(const QQuickFlickable);
- if (d->hData.viewSize < 0)
- return width();
- else
- return d->hData.viewSize;
-}
-
-qreal QQuickFlickable::vHeight() const
-{
- Q_D(const QQuickFlickable);
- if (d->vData.viewSize < 0)
- return height();
- else
- return d->vData.viewSize;
-}
-
-bool QQuickFlickable::xflick() const
-{
- Q_D(const QQuickFlickable);
- if (d->flickableDirection == QQuickFlickable::AutoFlickDirection)
- return vWidth() != width();
- return d->flickableDirection & QQuickFlickable::HorizontalFlick;
-}
-
-bool QQuickFlickable::yflick() const
-{
- Q_D(const QQuickFlickable);
- if (d->flickableDirection == QQuickFlickable::AutoFlickDirection)
- return vHeight() != height();
- return d->flickableDirection & QQuickFlickable::VerticalFlick;
-}
-
-void QQuickFlickable::mouseUngrabEvent()
-{
- Q_D(QQuickFlickable);
- if (d->pressed) {
- // if our mouse grab has been removed (probably by another Flickable),
- // fix our state
- d->pressed = false;
- d->draggingEnding();
- d->stealMouse = false;
- setKeepMouseGrab(false);
- }
-}
-
-bool QQuickFlickable::sendMouseEvent(QMouseEvent *event)
-{
- Q_D(QQuickFlickable);
- QRectF myRect = mapRectToScene(QRectF(0, 0, width(), height()));
-
- QQuickCanvas *c = canvas();
- QQuickItem *grabber = c ? c->mouseGrabberItem() : 0;
- bool disabledItem = grabber && !grabber->isEnabled();
- bool stealThisEvent = d->stealMouse;
- if ((stealThisEvent || myRect.contains(event->windowPos())) && (!grabber || !grabber->keepMouseGrab() || disabledItem)) {
- QMouseEvent mouseEvent(event->type(), mapFromScene(event->windowPos()), event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers());
-
- mouseEvent.setAccepted(false);
-
- switch (mouseEvent.type()) {
- case QEvent::MouseMove:
- d->handleMouseMoveEvent(&mouseEvent);
- break;
- case QEvent::MouseButtonPress:
- if (d->pressed) // we are already pressed - this is a delayed replay
- return false;
-
- d->handleMousePressEvent(&mouseEvent);
- d->captureDelayedPress(event);
- stealThisEvent = d->stealMouse; // Update stealThisEvent in case changed by function call above
- break;
- case QEvent::MouseButtonRelease:
- if (d->delayedPressEvent) {
- // We replay the mouse press but the grabber we had might not be interessted by the event (e.g. overlay)
- // so we reset the grabber
- if (c->mouseGrabberItem() == d->delayedPressTarget)
- d->delayedPressTarget->ungrabMouse();
- //Use the event handler that will take care of finding the proper item to propagate the event
- QQuickCanvasPrivate::get(canvas())->deliverMouseEvent(d->delayedPressEvent);
- d->clearDelayedPress();
- // We send the release
- canvas()->sendEvent(c->mouseGrabberItem(), event);
- // And the event has been consumed
- d->stealMouse = false;
- d->pressed = false;
- return true;
- }
- d->handleMouseReleaseEvent(&mouseEvent);
- break;
- default:
- break;
- }
- grabber = qobject_cast<QQuickItem*>(c->mouseGrabberItem());
- if ((grabber && stealThisEvent && !grabber->keepMouseGrab() && grabber != this) || disabledItem) {
- d->clearDelayedPress();
- grabMouse();
- }
-
- return stealThisEvent || d->delayedPressEvent || disabledItem;
- } else if (d->lastPosTime.isValid()) {
- d->lastPosTime.invalidate();
- returnToBounds();
- }
- if (event->type() == QEvent::MouseButtonRelease) {
- d->lastPosTime.invalidate();
- d->clearDelayedPress();
- d->stealMouse = false;
- d->pressed = false;
- }
- return false;
-}
-
-
-bool QQuickFlickable::childMouseEventFilter(QQuickItem *i, QEvent *e)
-{
- Q_D(QQuickFlickable);
- if (!isVisible() || !d->interactive || !isEnabled())
- return QQuickItem::childMouseEventFilter(i, e);
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease:
- return sendMouseEvent(static_cast<QMouseEvent *>(e));
- default:
- break;
- }
-
- return QQuickItem::childMouseEventFilter(i, e);
-}
-
-/*!
- \qmlproperty real QtQuick2::Flickable::maximumFlickVelocity
- This property holds the maximum velocity that the user can flick the view in pixels/second.
-
- The default value is platform dependent.
-*/
-qreal QQuickFlickable::maximumFlickVelocity() const
-{
- Q_D(const QQuickFlickable);
- return d->maxVelocity;
-}
-
-void QQuickFlickable::setMaximumFlickVelocity(qreal v)
-{
- Q_D(QQuickFlickable);
- if (v == d->maxVelocity)
- return;
- d->maxVelocity = v;
- emit maximumFlickVelocityChanged();
-}
-
-/*!
- \qmlproperty real QtQuick2::Flickable::flickDeceleration
- This property holds the rate at which a flick will decelerate.
-
- The default value is platform dependent.
-*/
-qreal QQuickFlickable::flickDeceleration() const
-{
- Q_D(const QQuickFlickable);
- return d->deceleration;
-}
-
-void QQuickFlickable::setFlickDeceleration(qreal deceleration)
-{
- Q_D(QQuickFlickable);
- if (deceleration == d->deceleration)
- return;
- d->deceleration = deceleration;
- emit flickDecelerationChanged();
-}
-
-bool QQuickFlickable::isFlicking() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.flicking || d->vData.flicking;
-}
-
-/*!
- \qmlproperty bool QtQuick2::Flickable::flicking
- \qmlproperty bool QtQuick2::Flickable::flickingHorizontally
- \qmlproperty bool QtQuick2::Flickable::flickingVertically
-
- These properties describe whether the view is currently moving horizontally,
- vertically or in either direction, due to the user flicking the view.
-*/
-bool QQuickFlickable::isFlickingHorizontally() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.flicking;
-}
-
-bool QQuickFlickable::isFlickingVertically() const
-{
- Q_D(const QQuickFlickable);
- return d->vData.flicking;
-}
-
-/*!
- \qmlproperty bool QtQuick2::Flickable::dragging
- \qmlproperty bool QtQuick2::Flickable::draggingHorizontally
- \qmlproperty bool QtQuick2::Flickable::draggingVertically
-
- These properties describe whether the view is currently moving horizontally,
- vertically or in either direction, due to the user dragging the view.
-*/
-bool QQuickFlickable::isDragging() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.dragging || d->vData.dragging;
-}
-
-bool QQuickFlickable::isDraggingHorizontally() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.dragging;
-}
-
-bool QQuickFlickable::isDraggingVertically() const
-{
- Q_D(const QQuickFlickable);
- return d->vData.dragging;
-}
-
-void QQuickFlickablePrivate::draggingStarting()
-{
- Q_Q(QQuickFlickable);
- bool wasDragging = hData.dragging || vData.dragging;
- if (hMoved && !hData.dragging) {
- hData.dragging = true;
- emit q->draggingHorizontallyChanged();
- }
- if (vMoved && !vData.dragging) {
- vData.dragging = true;
- emit q->draggingVerticallyChanged();
- }
- if (!wasDragging && (hData.dragging || vData.dragging)) {
- emit q->draggingChanged();
- emit q->dragStarted();
- }
-}
-
-void QQuickFlickablePrivate::draggingEnding()
-{
- Q_Q(QQuickFlickable);
- bool wasDragging = hData.dragging || vData.dragging;
- if (hData.dragging) {
- hData.dragging = false;
- emit q->draggingHorizontallyChanged();
- }
- if (vData.dragging) {
- vData.dragging = false;
- emit q->draggingVerticallyChanged();
- }
- if (wasDragging && !hData.dragging && !vData.dragging) {
- emit q->draggingChanged();
- emit q->dragEnded();
- }
-}
-
-/*!
- \qmlproperty int QtQuick2::Flickable::pressDelay
-
- This property holds the time to delay (ms) delivering a press to
- children of the Flickable. This can be useful where reacting
- to a press before a flicking action has undesirable effects.
-
- If the flickable is dragged/flicked before the delay times out
- the press event will not be delivered. If the button is released
- within the timeout, both the press and release will be delivered.
-
- Note that for nested Flickables with pressDelay set, the pressDelay of
- inner Flickables is overridden by the outermost Flickable.
-*/
-int QQuickFlickable::pressDelay() const
-{
- Q_D(const QQuickFlickable);
- return d->pressDelay;
-}
-
-void QQuickFlickable::setPressDelay(int delay)
-{
- Q_D(QQuickFlickable);
- if (d->pressDelay == delay)
- return;
- d->pressDelay = delay;
- emit pressDelayChanged();
-}
-
-/*!
- \qmlproperty bool QtQuick2::Flickable::moving
- \qmlproperty bool QtQuick2::Flickable::movingHorizontally
- \qmlproperty bool QtQuick2::Flickable::movingVertically
-
- These properties describe whether the view is currently moving horizontally,
- vertically or in either direction, due to the user either dragging or
- flicking the view.
-*/
-
-bool QQuickFlickable::isMoving() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.moving || d->vData.moving;
-}
-
-bool QQuickFlickable::isMovingHorizontally() const
-{
- Q_D(const QQuickFlickable);
- return d->hData.moving;
-}
-
-bool QQuickFlickable::isMovingVertically() const
-{
- Q_D(const QQuickFlickable);
- return d->vData.moving;
-}
-
-void QQuickFlickable::movementStarting()
-{
- Q_D(QQuickFlickable);
- if (d->hMoved && !d->hData.moving) {
- d->hData.moving = true;
- emit movingChanged();
- emit movingHorizontallyChanged();
- if (!d->vData.moving)
- emit movementStarted();
- }
- else if (d->vMoved && !d->vData.moving) {
- d->vData.moving = true;
- emit movingChanged();
- emit movingVerticallyChanged();
- if (!d->hData.moving)
- emit movementStarted();
- }
-}
-
-void QQuickFlickable::movementEnding()
-{
- Q_D(QQuickFlickable);
- movementXEnding();
- movementYEnding();
- d->hData.smoothVelocity.setValue(0);
- d->vData.smoothVelocity.setValue(0);
-}
-
-void QQuickFlickable::movementXEnding()
-{
- Q_D(QQuickFlickable);
- if (d->hData.flicking) {
- d->hData.flicking = false;
- emit flickingChanged();
- emit flickingHorizontallyChanged();
- if (!d->vData.flicking)
- emit flickEnded();
- }
- if (!d->pressed && !d->stealMouse) {
- if (d->hData.moving) {
- d->hData.moving = false;
- d->hMoved = false;
- emit movingChanged();
- emit movingHorizontallyChanged();
- if (!d->vData.moving)
- emit movementEnded();
- }
- }
- d->hData.fixingUp = false;
-}
-
-void QQuickFlickable::movementYEnding()
-{
- Q_D(QQuickFlickable);
- if (d->vData.flicking) {
- d->vData.flicking = false;
- emit flickingChanged();
- emit flickingVerticallyChanged();
- if (!d->hData.flicking)
- emit flickEnded();
- }
- if (!d->pressed && !d->stealMouse) {
- if (d->vData.moving) {
- d->vData.moving = false;
- d->vMoved = false;
- emit movingChanged();
- emit movingVerticallyChanged();
- if (!d->hData.moving)
- emit movementEnded();
- }
- }
- d->vData.fixingUp = false;
-}
-
-void QQuickFlickablePrivate::updateVelocity()
-{
- Q_Q(QQuickFlickable);
- emit q->horizontalVelocityChanged();
- emit q->verticalVelocityChanged();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickflickable_p.h b/src/declarative/items/qquickflickable_p.h
deleted file mode 100644
index 658db94846..0000000000
--- a/src/declarative/items/qquickflickable_p.h
+++ /dev/null
@@ -1,277 +0,0 @@
-// Commit: 1bcddaaf318fc37c71c5191913f3487c49444ec6
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKFLICKABLE_P_H
-#define QQUICKFLICKABLE_P_H
-
-#include "qquickitem.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickFlickablePrivate;
-class QQuickFlickableVisibleArea;
-class Q_DECLARATIVE_EXPORT QQuickFlickable : public QQuickItem
-{
- Q_OBJECT
-
- Q_PROPERTY(qreal contentWidth READ contentWidth WRITE setContentWidth NOTIFY contentWidthChanged)
- Q_PROPERTY(qreal contentHeight READ contentHeight WRITE setContentHeight NOTIFY contentHeightChanged)
- Q_PROPERTY(qreal contentX READ contentX WRITE setContentX NOTIFY contentXChanged)
- Q_PROPERTY(qreal contentY READ contentY WRITE setContentY NOTIFY contentYChanged)
- Q_PROPERTY(QQuickItem *contentItem READ contentItem CONSTANT)
-
- Q_PROPERTY(qreal topMargin READ topMargin WRITE setTopMargin NOTIFY topMarginChanged)
- Q_PROPERTY(qreal bottomMargin READ bottomMargin WRITE setBottomMargin NOTIFY bottomMarginChanged)
- Q_PROPERTY(qreal yOrigin READ yOrigin NOTIFY yOriginChanged)
-
- Q_PROPERTY(qreal leftMargin READ leftMargin WRITE setLeftMargin NOTIFY leftMarginChanged)
- Q_PROPERTY(qreal rightMargin READ rightMargin WRITE setRightMargin NOTIFY rightMarginChanged)
- Q_PROPERTY(qreal xOrigin READ xOrigin NOTIFY xOriginChanged)
-
- Q_PROPERTY(qreal horizontalVelocity READ horizontalVelocity NOTIFY horizontalVelocityChanged)
- Q_PROPERTY(qreal verticalVelocity READ verticalVelocity NOTIFY verticalVelocityChanged)
-
- Q_PROPERTY(BoundsBehavior boundsBehavior READ boundsBehavior WRITE setBoundsBehavior NOTIFY boundsBehaviorChanged)
- Q_PROPERTY(qreal maximumFlickVelocity READ maximumFlickVelocity WRITE setMaximumFlickVelocity NOTIFY maximumFlickVelocityChanged)
- Q_PROPERTY(qreal flickDeceleration READ flickDeceleration WRITE setFlickDeceleration NOTIFY flickDecelerationChanged)
- Q_PROPERTY(bool moving READ isMoving NOTIFY movingChanged)
- Q_PROPERTY(bool movingHorizontally READ isMovingHorizontally NOTIFY movingHorizontallyChanged)
- Q_PROPERTY(bool movingVertically READ isMovingVertically NOTIFY movingVerticallyChanged)
- Q_PROPERTY(bool flicking READ isFlicking NOTIFY flickingChanged)
- Q_PROPERTY(bool flickingHorizontally READ isFlickingHorizontally NOTIFY flickingHorizontallyChanged)
- Q_PROPERTY(bool flickingVertically READ isFlickingVertically NOTIFY flickingVerticallyChanged)
- Q_PROPERTY(bool dragging READ isDragging NOTIFY draggingChanged)
- Q_PROPERTY(bool draggingHorizontally READ isDraggingHorizontally NOTIFY draggingHorizontallyChanged)
- Q_PROPERTY(bool draggingVertically READ isDraggingVertically NOTIFY draggingVerticallyChanged)
- Q_PROPERTY(FlickableDirection flickableDirection READ flickableDirection WRITE setFlickableDirection NOTIFY flickableDirectionChanged)
-
- Q_PROPERTY(bool interactive READ isInteractive WRITE setInteractive NOTIFY interactiveChanged)
- Q_PROPERTY(int pressDelay READ pressDelay WRITE setPressDelay NOTIFY pressDelayChanged)
-
- 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(QQuickFlickableVisibleArea *visibleArea READ visibleArea CONSTANT)
-
- Q_PROPERTY(bool pixelAligned READ pixelAligned WRITE setPixelAligned NOTIFY pixelAlignedChanged)
-
- Q_PROPERTY(QDeclarativeListProperty<QObject> flickableData READ flickableData)
- Q_PROPERTY(QDeclarativeListProperty<QQuickItem> flickableChildren READ flickableChildren)
- Q_CLASSINFO("DefaultProperty", "flickableData")
-
- Q_ENUMS(FlickableDirection)
- Q_ENUMS(BoundsBehavior)
-
-public:
- QQuickFlickable(QQuickItem *parent=0);
- ~QQuickFlickable();
-
- QDeclarativeListProperty<QObject> flickableData();
- QDeclarativeListProperty<QQuickItem> flickableChildren();
-
- enum BoundsBehavior { StopAtBounds, DragOverBounds, DragAndOvershootBounds };
- BoundsBehavior boundsBehavior() const;
- void setBoundsBehavior(BoundsBehavior);
-
- qreal contentWidth() const;
- void setContentWidth(qreal);
-
- qreal contentHeight() const;
- void setContentHeight(qreal);
-
- qreal contentX() const;
- virtual void setContentX(qreal pos);
-
- qreal contentY() const;
- virtual void setContentY(qreal pos);
-
- qreal topMargin() const;
- void setTopMargin(qreal m);
-
- qreal bottomMargin() const;
- void setBottomMargin(qreal m);
-
- qreal leftMargin() const;
- void setLeftMargin(qreal m);
-
- qreal rightMargin() const;
- void setRightMargin(qreal m);
-
- virtual qreal yOrigin() const;
- virtual qreal xOrigin() const;
-
- bool isMoving() const;
- bool isMovingHorizontally() const;
- bool isMovingVertically() const;
- bool isFlicking() const;
- bool isFlickingHorizontally() const;
- bool isFlickingVertically() const;
- bool isDragging() const;
- bool isDraggingHorizontally() const;
- bool isDraggingVertically() const;
-
- int pressDelay() const;
- void setPressDelay(int delay);
-
- qreal maximumFlickVelocity() const;
- void setMaximumFlickVelocity(qreal);
-
- qreal flickDeceleration() const;
- void setFlickDeceleration(qreal);
-
- bool isInteractive() const;
- void setInteractive(bool);
-
- qreal horizontalVelocity() const;
- qreal verticalVelocity() const;
-
- bool isAtXEnd() const;
- bool isAtXBeginning() const;
- bool isAtYEnd() const;
- bool isAtYBeginning() const;
-
- QQuickItem *contentItem();
-
- enum FlickableDirection { AutoFlickDirection=0x00, HorizontalFlick=0x01, VerticalFlick=0x02, HorizontalAndVerticalFlick=0x03 };
- FlickableDirection flickableDirection() const;
- void setFlickableDirection(FlickableDirection);
-
- bool pixelAligned() const;
- void setPixelAligned(bool align);
-
- Q_INVOKABLE void resizeContent(qreal w, qreal h, QPointF center);
- Q_INVOKABLE void returnToBounds();
-
-Q_SIGNALS:
- void contentWidthChanged();
- void contentHeightChanged();
- void contentXChanged();
- void contentYChanged();
- void topMarginChanged();
- void bottomMarginChanged();
- void leftMarginChanged();
- void rightMarginChanged();
- void yOriginChanged();
- void xOriginChanged();
- void movingChanged();
- void movingHorizontallyChanged();
- void movingVerticallyChanged();
- void flickingChanged();
- void flickingHorizontallyChanged();
- void flickingVerticallyChanged();
- void draggingChanged();
- void draggingHorizontallyChanged();
- void draggingVerticallyChanged();
- void horizontalVelocityChanged();
- void verticalVelocityChanged();
- void isAtBoundaryChanged();
- void flickableDirectionChanged();
- void interactiveChanged();
- void boundsBehaviorChanged();
- void maximumFlickVelocityChanged();
- void flickDecelerationChanged();
- void pressDelayChanged();
- void movementStarted();
- void movementEnded();
- void flickStarted();
- void flickEnded();
- void dragStarted();
- void dragEnded();
- void pixelAlignedChanged();
-
-protected:
- virtual bool childMouseEventFilter(QQuickItem *, QEvent *);
- virtual void mousePressEvent(QMouseEvent *event);
- virtual void mouseMoveEvent(QMouseEvent *event);
- virtual void mouseReleaseEvent(QMouseEvent *event);
- virtual void wheelEvent(QWheelEvent *event);
- virtual void timerEvent(QTimerEvent *event);
-
- QQuickFlickableVisibleArea *visibleArea();
-
-protected Q_SLOTS:
- virtual void ticked();
- void movementStarting();
- void movementEnding();
-
-protected:
- void movementXEnding();
- void movementYEnding();
- virtual qreal minXExtent() const;
- virtual qreal minYExtent() const;
- virtual qreal maxXExtent() const;
- virtual qreal maxYExtent() const;
- qreal vWidth() const;
- qreal vHeight() const;
- virtual void componentComplete();
- virtual void viewportMoved();
- virtual void geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry);
- void mouseUngrabEvent();
- bool sendMouseEvent(QMouseEvent *event);
-
- bool xflick() const;
- bool yflick() const;
- void cancelFlick();
-
-protected:
- QQuickFlickable(QQuickFlickablePrivate &dd, QQuickItem *parent);
-
-private:
- Q_DISABLE_COPY(QQuickFlickable)
- Q_DECLARE_PRIVATE(QQuickFlickable)
- friend class QQuickFlickableVisibleArea;
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickFlickable)
-
-QT_END_HEADER
-
-#endif // QQUICKFLICKABLE_P_H
diff --git a/src/declarative/items/qquickflickable_p_p.h b/src/declarative/items/qquickflickable_p_p.h
deleted file mode 100644
index 8ceea6162f..0000000000
--- a/src/declarative/items/qquickflickable_p_p.h
+++ /dev/null
@@ -1,262 +0,0 @@
-// Commit: 160f1867868cdea916923652b00484ed11f90aaa
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKFLICKABLE_P_P_H
-#define QQUICKFLICKABLE_P_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 "qquickflickable_p.h"
-#include "qquickitem_p.h"
-#include "qquickitemchangelistener_p.h"
-
-#include <QtDeclarative/qdeclarative.h>
-#include <QtCore/qdatetime.h>
-#include "qplatformdefs.h"
-
-#include <private/qdeclarativetimeline_p_p.h>
-#include <private/qdeclarativeanimation_p_p.h>
-
-QT_BEGIN_NAMESPACE
-
-// Really slow flicks can be annoying.
-const qreal MinimumFlickVelocity = 75.0;
-
-class QQuickFlickableVisibleArea;
-class QQuickFlickablePrivate : public QQuickItemPrivate, public QQuickItemChangeListener
-{
- Q_DECLARE_PUBLIC(QQuickFlickable)
-
-public:
- static inline QQuickFlickablePrivate *get(QQuickFlickable *o) { return o->d_func(); }
-
- QQuickFlickablePrivate();
- void init();
-
- struct Velocity : public QDeclarativeTimeLineValue
- {
- Velocity(QQuickFlickablePrivate *p)
- : parent(p) {}
- virtual void setValue(qreal v) {
- if (v != value()) {
- QDeclarativeTimeLineValue::setValue(v);
- parent->updateVelocity();
- }
- }
- QQuickFlickablePrivate *parent;
- };
-
- struct AxisData {
- AxisData(QQuickFlickablePrivate *fp, void (QQuickFlickablePrivate::*func)(qreal))
- : move(fp, func), viewSize(-1), startMargin(0), endMargin(0)
- , smoothVelocity(fp), atEnd(false), atBeginning(true)
- , fixingUp(false), inOvershoot(false), moving(false), flicking(false)
- , dragging(false), extentsChanged(false)
- , explicitValue(false), minExtentDirty(true), maxExtentDirty(true)
- {}
-
- void reset() {
- velocityBuffer.clear();
- dragStartOffset = 0;
- fixingUp = false;
- inOvershoot = false;
- }
-
- void markExtentsDirty() {
- minExtentDirty = true;
- maxExtentDirty = true;
- extentsChanged = true;
- }
-
- void addVelocitySample(qreal v, qreal maxVelocity);
- void updateVelocity();
-
- QDeclarativeTimeLineValueProxy<QQuickFlickablePrivate> move;
- qreal viewSize;
- qreal pressPos;
- qreal dragStartOffset;
- qreal dragMinBound;
- qreal dragMaxBound;
- qreal velocity;
- qreal flickTarget;
- qreal startMargin;
- qreal endMargin;
- QQuickFlickablePrivate::Velocity smoothVelocity;
- QPODVector<qreal,10> velocityBuffer;
- bool atEnd : 1;
- bool atBeginning : 1;
- bool fixingUp : 1;
- bool inOvershoot : 1;
- bool moving : 1;
- bool flicking : 1;
- bool dragging : 1;
- bool extentsChanged : 1;
- bool explicitValue : 1;
- mutable bool minExtentDirty : 1;
- mutable bool maxExtentDirty : 1;
- };
-
- void flickX(qreal velocity);
- void flickY(qreal velocity);
- virtual void flick(AxisData &data, qreal minExtent, qreal maxExtent, qreal vSize,
- QDeclarativeTimeLineCallback::Callback fixupCallback, qreal velocity);
-
- void fixupX();
- void fixupY();
- virtual void fixup(AxisData &data, qreal minExtent, qreal maxExtent);
-
- void updateBeginningEnd();
-
- bool isOutermostPressDelay() const;
- void captureDelayedPress(QMouseEvent *event);
- void clearDelayedPress();
-
- void setViewportX(qreal x);
- void setViewportY(qreal y);
-
- qreal overShootDistance(qreal size);
-
- void itemGeometryChanged(QQuickItem *, const QRectF &, const QRectF &);
-
- void draggingStarting();
- void draggingEnding();
-
-public:
- QQuickItem *contentItem;
-
- AxisData hData;
- AxisData vData;
-
- QDeclarativeTimeLine timeline;
- bool hMoved : 1;
- bool vMoved : 1;
- bool stealMouse : 1;
- bool pressed : 1;
- bool interactive : 1;
- bool calcVelocity : 1;
- bool pixelAligned : 1;
- QElapsedTimer lastPosTime;
- QPointF lastPos;
- QPointF pressPos;
- QElapsedTimer pressTime;
- qreal deceleration;
- qreal maxVelocity;
- QElapsedTimer velocityTime;
- QPointF lastFlickablePosition;
- qreal reportedVelocitySmoothing;
- QMouseEvent *delayedPressEvent;
- QQuickItem *delayedPressTarget;
- QBasicTimer delayedPressTimer;
- int pressDelay;
- int fixupDuration;
-
- enum FixupMode { Normal, Immediate, ExtentChanged };
- FixupMode fixupMode;
-
- static void fixupY_callback(void *);
- static void fixupX_callback(void *);
-
- void updateVelocity();
- int vTime;
- QDeclarativeTimeLine velocityTimeline;
- QQuickFlickableVisibleArea *visibleArea;
- QQuickFlickable::FlickableDirection flickableDirection;
- QQuickFlickable::BoundsBehavior boundsBehavior;
-
- void handleMousePressEvent(QMouseEvent *);
- void handleMouseMoveEvent(QMouseEvent *);
- void handleMouseReleaseEvent(QMouseEvent *);
-
- // flickableData property
- static void data_append(QDeclarativeListProperty<QObject> *, QObject *);
- static int data_count(QDeclarativeListProperty<QObject> *);
- static QObject *data_at(QDeclarativeListProperty<QObject> *, int);
- static void data_clear(QDeclarativeListProperty<QObject> *);
-};
-
-class QQuickFlickableVisibleArea : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(qreal xPosition READ xPosition NOTIFY xPositionChanged)
- Q_PROPERTY(qreal yPosition READ yPosition NOTIFY yPositionChanged)
- Q_PROPERTY(qreal widthRatio READ widthRatio NOTIFY widthRatioChanged)
- Q_PROPERTY(qreal heightRatio READ heightRatio NOTIFY heightRatioChanged)
-
-public:
- QQuickFlickableVisibleArea(QQuickFlickable *parent=0);
-
- qreal xPosition() const;
- qreal widthRatio() const;
- qreal yPosition() const;
- qreal heightRatio() const;
-
- void updateVisible();
-
-signals:
- void xPositionChanged(qreal xPosition);
- void yPositionChanged(qreal yPosition);
- void widthRatioChanged(qreal widthRatio);
- void heightRatioChanged(qreal heightRatio);
-
-private:
- QQuickFlickable *flickable;
- qreal m_xPosition;
- qreal m_widthRatio;
- qreal m_yPosition;
- qreal m_heightRatio;
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickFlickableVisibleArea)
-
-#endif // QQUICKFLICKABLE_P_P_H
diff --git a/src/declarative/items/qquickflipable.cpp b/src/declarative/items/qquickflipable.cpp
deleted file mode 100644
index ed89f2aaf5..0000000000
--- a/src/declarative/items/qquickflipable.cpp
+++ /dev/null
@@ -1,308 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickflipable_p.h"
-#include "qquickitem_p.h"
-
-#include <private/qdeclarativeguard_p.h>
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-
-QT_BEGIN_NAMESPACE
-
-// XXX todo - i think this needs work and a bit of a re-think
-
-class QQuickLocalTransform : public QQuickTransform
-{
- Q_OBJECT
-public:
- QQuickLocalTransform(QObject *parent) : QQuickTransform(parent) {}
-
- void setTransform(const QTransform &t) {
- transform = t;
- update();
- }
- virtual void applyTo(QMatrix4x4 *matrix) const {
- *matrix *= transform;
- }
-private:
- QTransform transform;
-};
-
-class QQuickFlipablePrivate : public QQuickItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickFlipable)
-public:
- QQuickFlipablePrivate() : current(QQuickFlipable::Front), front(0), back(0), sideDirty(false) {}
-
- virtual void transformChanged();
- void updateSide();
- void setBackTransform();
-
- QQuickFlipable::Side current;
- QDeclarativeGuard<QQuickLocalTransform> backTransform;
- QDeclarativeGuard<QQuickItem> front;
- QDeclarativeGuard<QQuickItem> back;
-
- bool sideDirty;
- bool wantBackXFlipped;
- bool wantBackYFlipped;
-};
-
-/*!
- \qmlclass Flipable QQuickFlipable
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-interaction-elements
- \brief The Flipable item provides a surface that can be flipped.
- \inherits Item
-
- Flipable is an item that can be visibly "flipped" between its front and
- back sides, like a card. It is used together with \l Rotation, \l State
- and \l Transition elements to produce a flipping effect.
-
- The \l front and \l back properties are used to hold the items that are
- shown respectively on the front and back sides of the flipable item.
-
- \section1 Example Usage
-
- The following example shows a Flipable item that flips whenever it is
- clicked, rotating about the y-axis.
-
- This flipable item has a \c flipped boolean property that is toggled
- whenever the MouseArea within the flipable is clicked. When
- \c flipped is true, the item changes to the "back" state; in this
- state, the \c angle of the \l Rotation item is changed to 180
- degrees to produce the flipping effect. When \c flipped is false, the
- item reverts to the default state, in which the \c angle value is 0.
-
- \snippet doc/src/snippets/declarative/flipable/flipable.qml 0
-
- \image flipable.gif
-
- The \l Transition creates the animation that changes the angle over
- four seconds. When the item changes between its "back" and
- default states, the NumberAnimation animates the angle between
- its old and new values.
-
- See \l {QML States} for details on state changes and the default
- state, and \l {QML Animation and Transitions} for more information on how
- animations work within transitions.
-
- \sa {declarative/ui-components/flipable}{Flipable example}
-*/
-QQuickFlipable::QQuickFlipable(QQuickItem *parent)
-: QQuickItem(*(new QQuickFlipablePrivate), parent)
-{
-}
-
-QQuickFlipable::~QQuickFlipable()
-{
-}
-
-/*!
- \qmlproperty Item QtQuick2::Flipable::front
- \qmlproperty Item QtQuick2::Flipable::back
-
- The front and back sides of the flipable.
-*/
-
-QQuickItem *QQuickFlipable::front()
-{
- Q_D(const QQuickFlipable);
- return d->front;
-}
-
-void QQuickFlipable::setFront(QQuickItem *front)
-{
- Q_D(QQuickFlipable);
- if (d->front) {
- qmlInfo(this) << tr("front is a write-once property");
- return;
- }
- d->front = front;
- d->front->setParentItem(this);
- if (Back == d->current)
- d->front->setOpacity(0.);
- emit frontChanged();
-}
-
-QQuickItem *QQuickFlipable::back()
-{
- Q_D(const QQuickFlipable);
- return d->back;
-}
-
-void QQuickFlipable::setBack(QQuickItem *back)
-{
- Q_D(QQuickFlipable);
- if (d->back) {
- qmlInfo(this) << tr("back is a write-once property");
- return;
- }
- if (back == 0)
- return;
- d->back = back;
- d->back->setParentItem(this);
-
- d->backTransform = new QQuickLocalTransform(d->back);
- d->backTransform->prependToItem(d->back);
-
- if (Front == d->current)
- d->back->setOpacity(0.);
- connect(back, SIGNAL(widthChanged()),
- this, SLOT(retransformBack()));
- connect(back, SIGNAL(heightChanged()),
- this, SLOT(retransformBack()));
- emit backChanged();
-}
-
-void QQuickFlipable::retransformBack()
-{
- Q_D(QQuickFlipable);
- if (d->current == QQuickFlipable::Back && d->back)
- d->setBackTransform();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Flipable::side
-
- The side of the Flipable currently visible. Possible values are \c
- Flipable.Front and \c Flipable.Back.
-*/
-QQuickFlipable::Side QQuickFlipable::side() const
-{
- Q_D(const QQuickFlipable);
-
- const_cast<QQuickFlipablePrivate *>(d)->updateSide();
- return d->current;
-}
-
-void QQuickFlipablePrivate::transformChanged()
-{
- Q_Q(QQuickFlipable);
-
- if (!sideDirty) {
- sideDirty = true;
- q->polish();
- }
-
- QQuickItemPrivate::transformChanged();
-}
-
-void QQuickFlipable::updatePolish()
-{
- Q_D(QQuickFlipable);
- d->updateSide();
-}
-
-// determination on the currently visible side of the flipable
-// has to be done on the complete scene transform to give
-// correct results.
-void QQuickFlipablePrivate::updateSide()
-{
- Q_Q(QQuickFlipable);
-
- if (!sideDirty)
- return;
-
- sideDirty = false;
-
- QTransform sceneTransform;
- itemToParentTransform(sceneTransform);
-
- QPointF p1(0, 0);
- QPointF p2(1, 0);
- QPointF p3(1, 1);
-
- QPointF scenep1 = sceneTransform.map(p1);
- QPointF scenep2 = sceneTransform.map(p2);
- QPointF scenep3 = sceneTransform.map(p3);
-#if 0
- p1 = q->mapToParent(p1);
- p2 = q->mapToParent(p2);
- p3 = q->mapToParent(p3);
-#endif
-
- qreal cross = (scenep1.x() - scenep2.x()) * (scenep3.y() - scenep2.y()) -
- (scenep1.y() - scenep2.y()) * (scenep3.x() - scenep2.x());
-
- wantBackYFlipped = scenep1.x() >= scenep2.x();
- wantBackXFlipped = scenep2.y() >= scenep3.y();
-
- QQuickFlipable::Side newSide;
- if (cross > 0) {
- newSide = QQuickFlipable::Back;
- } else {
- newSide = QQuickFlipable::Front;
- }
-
- if (newSide != current) {
- current = newSide;
- if (current == QQuickFlipable::Back && back)
- setBackTransform();
- if (front)
- front->setOpacity((current==QQuickFlipable::Front)?1.:0.);
- if (back)
- back->setOpacity((current==QQuickFlipable::Back)?1.:0.);
- emit q->sideChanged();
- }
-}
-
-/* Depends on the width/height of the back item, and so needs reevaulating
- if those change.
-*/
-void QQuickFlipablePrivate::setBackTransform()
-{
- QTransform mat;
- mat.translate(back->width()/2,back->height()/2);
- if (back->width() && wantBackYFlipped)
- mat.rotate(180, Qt::YAxis);
- if (back->height() && wantBackXFlipped)
- mat.rotate(180, Qt::XAxis);
- mat.translate(-back->width()/2,-back->height()/2);
-
- if (backTransform)
- backTransform->setTransform(mat);
-}
-
-QT_END_NAMESPACE
-
-#include "qquickflipable.moc"
diff --git a/src/declarative/items/qquickflipable_p.h b/src/declarative/items/qquickflipable_p.h
deleted file mode 100644
index 698ec0fcb2..0000000000
--- a/src/declarative/items/qquickflipable_p.h
+++ /dev/null
@@ -1,104 +0,0 @@
-// Commit: ebd4bc73c46c2962742a682b6a391fb68c482aec
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKFLIPABLE_P_H
-#define QQUICKFLIPABLE_P_H
-
-#include "qquickitem.h"
-
-#include <QtGui/qtransform.h>
-#include <QtGui/qvector3d.h>
-#include <QtCore/qobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickFlipablePrivate;
-class Q_AUTOTEST_EXPORT QQuickFlipable : public QQuickItem
-{
- Q_OBJECT
-
- Q_ENUMS(Side)
- Q_PROPERTY(QQuickItem *front READ front WRITE setFront NOTIFY frontChanged)
- Q_PROPERTY(QQuickItem *back READ back WRITE setBack NOTIFY backChanged)
- Q_PROPERTY(Side side READ side NOTIFY sideChanged)
- //### flipAxis
- //### flipRotation
-public:
- QQuickFlipable(QQuickItem *parent=0);
- ~QQuickFlipable();
-
- QQuickItem *front();
- void setFront(QQuickItem *);
-
- QQuickItem *back();
- void setBack(QQuickItem *);
-
- enum Side { Front, Back };
- Side side() const;
-
-Q_SIGNALS:
- void frontChanged();
- void backChanged();
- void sideChanged();
-
-protected:
- virtual void updatePolish();
-
-private Q_SLOTS:
- void retransformBack();
-
-private:
- Q_DISABLE_COPY(QQuickFlipable)
- Q_DECLARE_PRIVATE(QQuickFlipable)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickFlipable)
-
-QT_END_HEADER
-
-#endif // QQUICKFLIPABLE_P_H
diff --git a/src/declarative/items/qquickfocusscope.cpp b/src/declarative/items/qquickfocusscope.cpp
deleted file mode 100644
index b807fe58f6..0000000000
--- a/src/declarative/items/qquickfocusscope.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickfocusscope_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass FocusScope QQuickFocusScope
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-interaction-elements
-
- \brief The FocusScope object explicitly creates a focus scope.
- \inherits Item
-
- Focus scopes assist in keyboard focus handling when building reusable QML
- components. All the details are covered in the
- \l {qmlfocus}{keyboard focus documentation}.
-
- \sa {declarative/keyinteraction/focus}{Keyboard focus example}
-*/
-QQuickFocusScope::QQuickFocusScope(QQuickItem *parent)
-: QQuickItem(parent)
-{
- setFlag(ItemIsFocusScope);
-}
-
-QQuickFocusScope::~QQuickFocusScope()
-{
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickfocusscope_p.h b/src/declarative/items/qquickfocusscope_p.h
deleted file mode 100644
index ff1a389f62..0000000000
--- a/src/declarative/items/qquickfocusscope_p.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKFOCUSSCOPE_P_H
-#define QQUICKFOCUSSCOPE_P_H
-
-#include "qquickitem.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class Q_AUTOTEST_EXPORT QQuickFocusScope : public QQuickItem
-{
- Q_OBJECT
-public:
- QQuickFocusScope(QQuickItem *parent=0);
- virtual ~QQuickFocusScope();
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickFocusScope)
-
-QT_END_HEADER
-
-#endif // QQUICKFOCUSSCOPE_P_H
diff --git a/src/declarative/items/qquickgridview.cpp b/src/declarative/items/qquickgridview.cpp
deleted file mode 100644
index 44e1f14c6f..0000000000
--- a/src/declarative/items/qquickgridview.cpp
+++ /dev/null
@@ -1,1958 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickgridview_p.h"
-#include "qquickvisualitemmodel_p.h"
-#include "qquickflickable_p_p.h"
-#include "qquickitemview_p_p.h"
-
-#include <private/qdeclarativesmoothedanimation_p_p.h>
-#include <private/qlistmodelinterface_p.h>
-
-#include <QtGui/qevent.h>
-#include <QtCore/qmath.h>
-#include <QtCore/qcoreapplication.h>
-#include <math.h>
-#include "qplatformdefs.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QML_FLICK_SNAPONETHRESHOLD
-#define QML_FLICK_SNAPONETHRESHOLD 30
-#endif
-
-//----------------------------------------------------------------------------
-
-class FxGridItemSG : public FxViewItem
-{
-public:
- FxGridItemSG(QQuickItem *i, QQuickGridView *v, bool own) : FxViewItem(i, own), view(v) {
- attached = static_cast<QQuickGridViewAttached*>(qmlAttachedPropertiesObject<QQuickGridView>(item));
- if (attached)
- static_cast<QQuickGridViewAttached*>(attached)->setView(view);
- }
-
- ~FxGridItemSG() {}
-
- qreal position() const {
- return rowPos();
- }
-
- qreal endPosition() const {
- return endRowPos();
- }
-
- qreal size() const {
- return view->flow() == QQuickGridView::LeftToRight ? view->cellHeight() : view->cellWidth();
- }
-
- qreal sectionSize() const {
- return 0.0;
- }
-
- qreal rowPos() const {
- if (view->flow() == QQuickGridView::LeftToRight)
- return item->y();
- else
- return (view->effectiveLayoutDirection() == Qt::RightToLeft ? -view->cellWidth()-item->x() : item->x());
- }
-
- qreal colPos() const {
- if (view->flow() == QQuickGridView::LeftToRight) {
- if (view->effectiveLayoutDirection() == Qt::RightToLeft) {
- qreal colSize = view->cellWidth();
- int columns = view->width()/colSize;
- return colSize * (columns-1) - item->x();
- } else {
- return item->x();
- }
- } else {
- return item->y();
- }
- }
- qreal endRowPos() const {
- if (view->flow() == QQuickGridView::LeftToRight) {
- return item->y() + view->cellHeight();
- } else {
- if (view->effectiveLayoutDirection() == Qt::RightToLeft)
- return -item->x();
- else
- return item->x() + view->cellWidth();
- }
- }
- void setPosition(qreal col, qreal row) {
- if (view->effectiveLayoutDirection() == Qt::RightToLeft) {
- if (view->flow() == QQuickGridView::LeftToRight) {
- int columns = view->width()/view->cellWidth();
- item->setPos(QPointF((view->cellWidth() * (columns-1) - col), row));
- } else {
- item->setPos(QPointF(-view->cellWidth()-row, col));
- }
- } else {
- if (view->flow() == QQuickGridView::LeftToRight)
- item->setPos(QPointF(col, row));
- else
- item->setPos(QPointF(row, col));
- }
- }
- bool contains(qreal x, qreal y) const {
- return (x >= item->x() && x < item->x() + view->cellWidth() &&
- y >= item->y() && y < item->y() + view->cellHeight());
- }
-
- QQuickGridView *view;
-};
-
-//----------------------------------------------------------------------------
-
-class QQuickGridViewPrivate : public QQuickItemViewPrivate
-{
- Q_DECLARE_PUBLIC(QQuickGridView)
-
-public:
- virtual Qt::Orientation layoutOrientation() const;
- virtual bool isContentFlowReversed() const;
- bool isRightToLeftTopToBottom() const;
-
- virtual qreal positionAt(int index) const;
- virtual qreal endPositionAt(int index) const;
- virtual qreal originPosition() const;
- virtual qreal lastPosition() const;
-
- qreal rowSize() const;
- qreal colSize() const;
- qreal colPosAt(int modelIndex) const;
- qreal rowPosAt(int modelIndex) const;
- qreal snapPosAt(qreal pos) const;
- FxViewItem *snapItemAt(qreal pos) const;
- int snapIndex() const;
-
- virtual bool addVisibleItems(qreal fillFrom, qreal fillTo, bool doBuffer);
- virtual bool removeNonVisibleItems(qreal bufferFrom, qreal bufferTo);
- virtual void visibleItemsChanged();
-
- virtual FxViewItem *newViewItem(int index, QQuickItem *item);
- virtual void repositionPackageItemAt(QQuickItem *item, int index);
- virtual void resetItemPosition(FxViewItem *item, FxViewItem *toItem);
- virtual void resetFirstItemPosition();
- virtual void moveItemBy(FxViewItem *item, qreal forwards, qreal backwards);
-
- virtual void createHighlight();
- virtual void updateHighlight();
- virtual void resetHighlightPosition();
-
- virtual void setPosition(qreal pos);
- virtual void layoutVisibleItems();
- bool applyInsertionChange(const QDeclarativeChangeSet::Insert &, FxViewItem *, InsertionsResult *);
- virtual bool needsRefillForAddedOrRemovedIndex(int index) const;
-
- virtual qreal headerSize() const;
- virtual qreal footerSize() const;
- virtual bool showHeaderForIndex(int index) const;
- virtual bool showFooterForIndex(int index) const;
- virtual void updateHeader();
- virtual void updateFooter();
-
- virtual void changedVisibleIndex(int newIndex);
- virtual void initializeCurrentItem();
-
- virtual void updateViewport();
- virtual void itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry);
- virtual void fixupPosition();
- virtual void fixup(AxisData &data, qreal minExtent, qreal maxExtent);
- virtual void flick(QQuickItemViewPrivate::AxisData &data, qreal minExtent, qreal maxExtent, qreal vSize,
- QDeclarativeTimeLineCallback::Callback fixupCallback, qreal velocity);
-
- QQuickGridView::Flow flow;
- qreal cellWidth;
- qreal cellHeight;
- int columns;
- QQuickGridView::SnapMode snapMode;
-
- QSmoothedAnimation *highlightXAnimator;
- QSmoothedAnimation *highlightYAnimator;
-
- QQuickGridViewPrivate()
- : flow(QQuickGridView::LeftToRight)
- , cellWidth(100), cellHeight(100), columns(1)
- , snapMode(QQuickGridView::NoSnap)
- , highlightXAnimator(0), highlightYAnimator(0)
- {}
-};
-
-Qt::Orientation QQuickGridViewPrivate::layoutOrientation() const
-{
- return flow == QQuickGridView::LeftToRight ? Qt::Vertical : Qt::Horizontal;
-}
-
-bool QQuickGridViewPrivate::isContentFlowReversed() const
-{
- return isRightToLeftTopToBottom();
-}
-
-bool QQuickGridViewPrivate::isRightToLeftTopToBottom() const
-{
- Q_Q(const QQuickGridView);
- return flow == QQuickGridView::TopToBottom && q->effectiveLayoutDirection() == Qt::RightToLeft;
-}
-
-void QQuickGridViewPrivate::changedVisibleIndex(int newIndex)
-{
- visibleIndex = newIndex / columns * columns;
-}
-
-void QQuickGridViewPrivate::setPosition(qreal pos)
-{
- Q_Q(QQuickGridView);
- if (flow == QQuickGridView::LeftToRight) {
- q->QQuickFlickable::setContentY(pos);
- q->QQuickFlickable::setContentX(0);
- } else {
- if (q->effectiveLayoutDirection() == Qt::LeftToRight)
- q->QQuickFlickable::setContentX(pos);
- else
- q->QQuickFlickable::setContentX(-pos-size());
- q->QQuickFlickable::setContentY(0);
- }
-}
-
-qreal QQuickGridViewPrivate::originPosition() const
-{
- qreal pos = 0;
- if (!visibleItems.isEmpty())
- pos = static_cast<FxGridItemSG*>(visibleItems.first())->rowPos() - visibleIndex / columns * rowSize();
- return pos;
-}
-
-qreal QQuickGridViewPrivate::lastPosition() const
-{
- qreal pos = 0;
- if (model && model->count()) {
- // get end position of last item
- pos = (rowPosAt(model->count() - 1) + rowSize());
- }
- return pos;
-}
-
-qreal QQuickGridViewPrivate::positionAt(int index) const
-{
- return rowPosAt(index);
-}
-
-qreal QQuickGridViewPrivate::endPositionAt(int index) const
-{
- return rowPosAt(index) + rowSize();
-}
-
-qreal QQuickGridViewPrivate::rowSize() const {
- return flow == QQuickGridView::LeftToRight ? cellHeight : cellWidth;
-}
-qreal QQuickGridViewPrivate::colSize() const {
- return flow == QQuickGridView::LeftToRight ? cellWidth : cellHeight;
-}
-
-qreal QQuickGridViewPrivate::colPosAt(int modelIndex) const
-{
- if (FxViewItem *item = visibleItem(modelIndex))
- return static_cast<FxGridItemSG*>(item)->colPos();
- if (!visibleItems.isEmpty()) {
- if (modelIndex == visibleIndex) {
- FxGridItemSG *firstItem = static_cast<FxGridItemSG*>(visibleItems.first());
- return firstItem->colPos();
- } else if (modelIndex < visibleIndex) {
- int count = (visibleIndex - modelIndex) % columns;
- int col = static_cast<FxGridItemSG*>(visibleItems.first())->colPos() / colSize();
- col = (columns - count + col) % columns;
- return col * colSize();
- } else {
- int count = columns - 1 - (modelIndex - visibleItems.last()->index - 1) % columns;
- return static_cast<FxGridItemSG*>(visibleItems.last())->colPos() - count * colSize();
- }
- }
- return (modelIndex % columns) * colSize();
-}
-
-qreal QQuickGridViewPrivate::rowPosAt(int modelIndex) const
-{
- if (FxViewItem *item = visibleItem(modelIndex))
- return static_cast<FxGridItemSG*>(item)->rowPos();
- if (!visibleItems.isEmpty()) {
- if (modelIndex == visibleIndex) {
- FxGridItemSG *firstItem = static_cast<FxGridItemSG*>(visibleItems.first());
- return firstItem->rowPos();
- } else if (modelIndex < visibleIndex) {
- FxGridItemSG *firstItem = static_cast<FxGridItemSG*>(visibleItems.first());
- int firstCol = firstItem->colPos() / colSize();
- int col = visibleIndex - modelIndex + (columns - firstCol - 1);
- int rows = col / columns;
- return firstItem->rowPos() - rows * rowSize();
- } else {
- FxGridItemSG *lastItem = static_cast<FxGridItemSG*>(visibleItems.last());
- int count = modelIndex - lastItem->index;
- int col = lastItem->colPos() + count * colSize();
- int rows = col / (columns * colSize());
- return lastItem->rowPos() + rows * rowSize();
- }
- }
- return (modelIndex / columns) * rowSize();
-}
-
-
-qreal QQuickGridViewPrivate::snapPosAt(qreal pos) const
-{
- Q_Q(const QQuickGridView);
- qreal snapPos = 0;
- if (!visibleItems.isEmpty()) {
- qreal highlightStart = highlightRangeStart;
- pos += highlightStart;
- pos += rowSize()/2;
- snapPos = static_cast<FxGridItemSG*>(visibleItems.first())->rowPos() - visibleIndex / columns * rowSize();
- snapPos = pos - fmodf(pos - snapPos, qreal(rowSize()));
- snapPos -= highlightStart;
- qreal maxExtent;
- qreal minExtent;
- if (isRightToLeftTopToBottom()) {
- maxExtent = q->minXExtent()-size();
- minExtent = q->maxXExtent()-size();
- } else {
- maxExtent = flow == QQuickGridView::LeftToRight ? -q->maxYExtent() : -q->maxXExtent();
- minExtent = flow == QQuickGridView::LeftToRight ? -q->minYExtent() : -q->minXExtent();
- }
- if (snapPos > maxExtent)
- snapPos = maxExtent;
- if (snapPos < minExtent)
- snapPos = minExtent;
- }
- return snapPos;
-}
-
-FxViewItem *QQuickGridViewPrivate::snapItemAt(qreal pos) const
-{
- for (int i = 0; i < visibleItems.count(); ++i) {
- FxViewItem *item = visibleItems.at(i);
- if (item->index == -1)
- continue;
- qreal itemTop = item->position();
- if (itemTop+rowSize()/2 >= pos && itemTop - rowSize()/2 <= pos)
- return item;
- }
- return 0;
-}
-
-int QQuickGridViewPrivate::snapIndex() const
-{
- int index = currentIndex;
- for (int i = 0; i < visibleItems.count(); ++i) {
- FxGridItemSG *item = static_cast<FxGridItemSG*>(visibleItems.at(i));
- if (item->index == -1)
- continue;
- qreal itemTop = item->position();
- FxGridItemSG *hItem = static_cast<FxGridItemSG*>(highlight);
- if (itemTop >= hItem->rowPos()-rowSize()/2 && itemTop < hItem->rowPos()+rowSize()/2) {
- index = item->index;
- if (item->colPos() >= hItem->colPos()-colSize()/2 && item->colPos() < hItem->colPos()+colSize()/2)
- return item->index;
- }
- }
- return index;
-}
-
-FxViewItem *QQuickGridViewPrivate::newViewItem(int modelIndex, QQuickItem *item)
-{
- Q_Q(QQuickGridView);
- Q_UNUSED(modelIndex);
- return new FxGridItemSG(item, q, false);
-}
-
-bool QQuickGridViewPrivate::addVisibleItems(qreal fillFrom, qreal fillTo, bool doBuffer)
-{
- qreal colPos = colPosAt(visibleIndex);
- qreal rowPos = rowPosAt(visibleIndex);
- if (visibleItems.count()) {
- FxGridItemSG *lastItem = static_cast<FxGridItemSG*>(visibleItems.last());
- rowPos = lastItem->rowPos();
- int colNum = qFloor((lastItem->colPos()+colSize()/2) / colSize());
- if (++colNum >= columns) {
- colNum = 0;
- rowPos += rowSize();
- }
- colPos = colNum * colSize();
- }
-
- int modelIndex = findLastVisibleIndex();
- modelIndex = modelIndex < 0 ? visibleIndex : modelIndex + 1;
-
- if (visibleItems.count() && (fillFrom > rowPos + rowSize()*2
- || fillTo < rowPosAt(visibleIndex) - rowSize())) {
- // We've jumped more than a page. Estimate which items are now
- // visible and fill from there.
- int count = (fillFrom - (rowPos + rowSize())) / (rowSize()) * columns;
- for (int i = 0; i < visibleItems.count(); ++i)
- releaseItem(visibleItems.at(i));
- visibleItems.clear();
- modelIndex += count;
- if (modelIndex >= model->count())
- modelIndex = model->count() - 1;
- else if (modelIndex < 0)
- modelIndex = 0;
- modelIndex = modelIndex / columns * columns;
- visibleIndex = modelIndex;
- colPos = colPosAt(visibleIndex);
- rowPos = rowPosAt(visibleIndex);
- }
-
- int colNum = qFloor((colPos+colSize()/2) / colSize());
- FxGridItemSG *item = 0;
- bool changed = false;
-
- while (modelIndex < model->count() && rowPos <= fillTo + rowSize()*(columns - colNum)/(columns+1)) {
-// qDebug() << "refill: append item" << modelIndex << colPos << rowPos;
- if (!(item = static_cast<FxGridItemSG*>(createItem(modelIndex, doBuffer))))
- break;
- item->setPosition(colPos, rowPos);
- item->item->setVisible(!doBuffer);
- visibleItems.append(item);
- if (++colNum >= columns) {
- colNum = 0;
- rowPos += rowSize();
- }
- colPos = colNum * colSize();
- ++modelIndex;
- changed = true;
- }
-
- // Find first column
- if (visibleItems.count()) {
- FxGridItemSG *firstItem = static_cast<FxGridItemSG*>(visibleItems.first());
- rowPos = firstItem->rowPos();
- colNum = qFloor((firstItem->colPos()+colSize()/2) / colSize());
- if (--colNum < 0) {
- colNum = columns - 1;
- rowPos -= rowSize();
- }
- } else {
- colNum = qFloor((colPos+colSize()/2) / colSize());
- }
-
- // Prepend
- colPos = colNum * colSize();
- while (visibleIndex > 0 && rowPos + rowSize() - 1 >= fillFrom - rowSize()*(colNum+1)/(columns+1)){
-// qDebug() << "refill: prepend item" << visibleIndex-1 << "top pos" << rowPos << colPos;
- if (!(item = static_cast<FxGridItemSG*>(createItem(visibleIndex-1, doBuffer))))
- break;
- --visibleIndex;
- item->setPosition(colPos, rowPos);
- item->item->setVisible(!doBuffer);
- visibleItems.prepend(item);
- if (--colNum < 0) {
- colNum = columns-1;
- rowPos -= rowSize();
- }
- colPos = colNum * colSize();
- changed = true;
- }
-
- return changed;
-}
-
-bool QQuickGridViewPrivate::removeNonVisibleItems(qreal bufferFrom, qreal bufferTo)
-{
- Q_Q(QQuickGridView);
- FxGridItemSG *item = 0;
- bool changed = false;
-
- while (visibleItems.count() > 1
- && (item = static_cast<FxGridItemSG*>(visibleItems.first()))
- && item->rowPos()+rowSize()-1 < bufferFrom - rowSize()*(item->colPos()/colSize()+1)/(columns+1)) {
- if (item->attached->delayRemove())
- break;
-// qDebug() << "refill: remove first" << visibleIndex << "top end pos" << item->endRowPos();
- if (item->index != -1)
- visibleIndex++;
- visibleItems.removeFirst();
- releaseItem(item);
- changed = true;
- }
- while (visibleItems.count() > 1
- && (item = static_cast<FxGridItemSG*>(visibleItems.last()))
- && item->rowPos() > bufferTo + rowSize()*(columns - item->colPos()/colSize())/(columns+1)) {
- if (item->attached->delayRemove())
- break;
-// qDebug() << "refill: remove last" << visibleIndex+visibleItems.count()-1;
- visibleItems.removeLast();
- releaseItem(item);
- changed = true;
- }
-
- return changed;
-}
-
-void QQuickGridViewPrivate::visibleItemsChanged()
-{
- updateHeader();
- updateFooter();
- updateViewport();
-}
-
-void QQuickGridViewPrivate::updateViewport()
-{
- Q_Q(QQuickGridView);
- qreal length = flow == QQuickGridView::LeftToRight ? q->width() : q->height();
- columns = (int)qMax((length + colSize()/2) / colSize(), qreal(1.));
- QQuickItemViewPrivate::updateViewport();
-}
-
-void QQuickGridViewPrivate::layoutVisibleItems()
-{
- if (visibleItems.count()) {
- FxGridItemSG *firstItem = static_cast<FxGridItemSG*>(visibleItems.first());
- qreal rowPos = firstItem->rowPos();
- qreal colPos = firstItem->colPos();
- int col = visibleIndex % columns;
- if (colPos != col * colSize()) {
- colPos = col * colSize();
- firstItem->setPosition(colPos, rowPos);
- }
- for (int i = 1; i < visibleItems.count(); ++i) {
- FxGridItemSG *item = static_cast<FxGridItemSG*>(visibleItems.at(i));
- if (++col >= columns) {
- col = 0;
- rowPos += rowSize();
- }
- colPos = col * colSize();
- item->setPosition(colPos, rowPos);
- }
- }
-}
-
-void QQuickGridViewPrivate::repositionPackageItemAt(QQuickItem *item, int index)
-{
- Q_Q(QQuickGridView);
- qreal pos = position();
- if (flow == QQuickGridView::LeftToRight) {
- if (item->y() + item->height() > pos && item->y() < pos + q->height())
- item->setPos(QPointF(colPosAt(index), rowPosAt(index)));
- } else {
- if (item->x() + item->width() > pos && item->x() < pos + q->width()) {
- if (isRightToLeftTopToBottom())
- item->setPos(QPointF(-rowPosAt(index)-item->width(), colPosAt(index)));
- else
- item->setPos(QPointF(rowPosAt(index), colPosAt(index)));
- }
- }
-}
-
-void QQuickGridViewPrivate::resetItemPosition(FxViewItem *item, FxViewItem *toItem)
-{
- if (item == toItem)
- return;
- FxGridItemSG *toGridItem = static_cast<FxGridItemSG*>(toItem);
- static_cast<FxGridItemSG*>(item)->setPosition(toGridItem->colPos(), toGridItem->rowPos());
-}
-
-void QQuickGridViewPrivate::resetFirstItemPosition()
-{
- FxGridItemSG *item = static_cast<FxGridItemSG*>(visibleItems.first());
- item->setPosition(0, 0);
-}
-
-void QQuickGridViewPrivate::moveItemBy(FxViewItem *item, qreal forwards, qreal backwards)
-{
- int moveCount = (forwards / rowSize()) - (backwards / rowSize());
-
- FxGridItemSG *gridItem = static_cast<FxGridItemSG*>(item);
- gridItem->setPosition(gridItem->colPos(), gridItem->rowPos() + ((moveCount / columns) * rowSize()));
-}
-
-void QQuickGridViewPrivate::createHighlight()
-{
- Q_Q(QQuickGridView);
- bool changed = false;
- if (highlight) {
- if (trackedItem == highlight)
- trackedItem = 0;
- delete highlight;
- highlight = 0;
-
- delete highlightXAnimator;
- delete highlightYAnimator;
- highlightXAnimator = 0;
- highlightYAnimator = 0;
-
- changed = true;
- }
-
- if (currentItem) {
- QQuickItem *item = createHighlightItem();
- if (item) {
- FxGridItemSG *newHighlight = new FxGridItemSG(item, q, true);
- if (autoHighlight)
- resetHighlightPosition();
- highlightXAnimator = new QSmoothedAnimation(q);
- highlightXAnimator->target = QDeclarativeProperty(item, QLatin1String("x"));
- highlightXAnimator->userDuration = highlightMoveDuration;
- highlightYAnimator = new QSmoothedAnimation(q);
- highlightYAnimator->target = QDeclarativeProperty(item, QLatin1String("y"));
- highlightYAnimator->userDuration = highlightMoveDuration;
-
- highlight = newHighlight;
- changed = true;
- }
- }
- if (changed)
- emit q->highlightItemChanged();
-}
-
-void QQuickGridViewPrivate::updateHighlight()
-{
- applyPendingChanges();
-
- if ((!currentItem && highlight) || (currentItem && !highlight))
- createHighlight();
- bool strictHighlight = haveHighlightRange && highlightRange == QQuickGridView::StrictlyEnforceRange;
- if (currentItem && autoHighlight && highlight && (!strictHighlight || !pressed)) {
- // auto-update highlight
- highlightXAnimator->to = currentItem->item->x();
- highlightYAnimator->to = currentItem->item->y();
- highlight->item->setWidth(currentItem->item->width());
- highlight->item->setHeight(currentItem->item->height());
-
- highlightXAnimator->restart();
- highlightYAnimator->restart();
- }
- updateTrackedItem();
-}
-
-void QQuickGridViewPrivate::resetHighlightPosition()
-{
- if (highlight && currentItem) {
- FxGridItemSG *cItem = static_cast<FxGridItemSG*>(currentItem);
- static_cast<FxGridItemSG*>(highlight)->setPosition(cItem->colPos(), cItem->rowPos());
- }
-}
-
-qreal QQuickGridViewPrivate::headerSize() const
-{
- if (!header)
- return 0.0;
- return flow == QQuickGridView::LeftToRight ? header->item->height() : header->item->width();
-}
-
-qreal QQuickGridViewPrivate::footerSize() const
-{
- if (!footer)
- return 0.0;
- return flow == QQuickGridView::LeftToRight? footer->item->height() : footer->item->width();
-}
-
-bool QQuickGridViewPrivate::showHeaderForIndex(int index) const
-{
- return index / columns == 0;
-}
-
-bool QQuickGridViewPrivate::showFooterForIndex(int index) const
-{
- return index / columns == (model->count()-1) / columns;
-}
-
-void QQuickGridViewPrivate::updateFooter()
-{
- Q_Q(QQuickGridView);
- bool created = false;
- if (!footer) {
- QQuickItem *item = createComponentItem(footerComponent, true);
- if (!item)
- return;
- item->setZ(1);
- footer = new FxGridItemSG(item, q, true);
- created = true;
- }
-
- FxGridItemSG *gridItem = static_cast<FxGridItemSG*>(footer);
- qreal colOffset = 0;
- qreal rowOffset = 0;
- if (q->effectiveLayoutDirection() == Qt::RightToLeft) {
- if (flow == QQuickGridView::TopToBottom)
- rowOffset = gridItem->item->width() - cellWidth;
- else
- colOffset = gridItem->item->width() - cellWidth;
- }
- if (visibleItems.count()) {
- qreal endPos = lastPosition();
- if (findLastVisibleIndex() == model->count()-1) {
- gridItem->setPosition(colOffset, endPos + rowOffset);
- } else {
- qreal visiblePos = isRightToLeftTopToBottom() ? -position() : position() + size();
- if (endPos <= visiblePos || gridItem->endPosition() <= endPos + rowOffset)
- gridItem->setPosition(colOffset, endPos + rowOffset);
- }
- } else {
- gridItem->setPosition(colOffset, rowOffset);
- }
-
- if (created)
- emit q->footerItemChanged();
-}
-
-void QQuickGridViewPrivate::updateHeader()
-{
- Q_Q(QQuickGridView);
- bool created = false;
- if (!header) {
- QQuickItem *item = createComponentItem(headerComponent, true);
- if (!item)
- return;
- item->setZ(1);
- header = new FxGridItemSG(item, q, true);
- created = true;
- }
-
- FxGridItemSG *gridItem = static_cast<FxGridItemSG*>(header);
- qreal colOffset = 0;
- qreal rowOffset = -headerSize();
- if (q->effectiveLayoutDirection() == Qt::RightToLeft) {
- if (flow == QQuickGridView::TopToBottom)
- rowOffset += gridItem->item->width()-cellWidth;
- else
- colOffset = gridItem->item->width()-cellWidth;
- }
- if (visibleItems.count()) {
- qreal startPos = originPosition();
- if (visibleIndex == 0) {
- gridItem->setPosition(colOffset, startPos + rowOffset);
- } else {
- qreal tempPos = isRightToLeftTopToBottom() ? -position()-size() : position();
- qreal headerPos = isRightToLeftTopToBottom() ? gridItem->rowPos() + cellWidth - headerSize() : gridItem->rowPos();
- if (tempPos <= startPos || headerPos > startPos + rowOffset)
- gridItem->setPosition(colOffset, startPos + rowOffset);
- }
- } else {
- if (isRightToLeftTopToBottom())
- gridItem->setPosition(colOffset, rowOffset);
- else
- gridItem->setPosition(colOffset, -headerSize());
- }
-
- if (created)
- emit q->headerItemChanged();
-}
-
-void QQuickGridViewPrivate::initializeCurrentItem()
-{
- if (currentItem && currentIndex >= 0) {
- FxGridItemSG *gridItem = static_cast<FxGridItemSG*>(currentItem);
- if (gridItem)
- gridItem->setPosition(colPosAt(currentIndex), rowPosAt(currentIndex));
- }
-}
-
-void QQuickGridViewPrivate::itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_Q(QQuickGridView);
- QQuickItemViewPrivate::itemGeometryChanged(item, newGeometry, oldGeometry);
- if (!q->isComponentComplete())
- return;
- if (item == q) {
- if (newGeometry.height() != oldGeometry.height() || newGeometry.width() != oldGeometry.width()) {
- updateViewport();
- forceLayout = true;
- q->polish();
- }
- }
-}
-
-void QQuickGridViewPrivate::fixupPosition()
-{
- moveReason = Other;
- if (flow == QQuickGridView::LeftToRight)
- fixupY();
- else
- fixupX();
-}
-
-void QQuickGridViewPrivate::fixup(AxisData &data, qreal minExtent, qreal maxExtent)
-{
- if ((flow == QQuickGridView::TopToBottom && &data == &vData)
- || (flow == QQuickGridView::LeftToRight && &data == &hData))
- return;
-
- fixupMode = moveReason == Mouse ? fixupMode : Immediate;
-
- qreal viewPos = isRightToLeftTopToBottom() ? -position()-size() : position();
-
- bool strictHighlightRange = haveHighlightRange && highlightRange == QQuickGridView::StrictlyEnforceRange;
- if (snapMode != QQuickGridView::NoSnap) {
- qreal tempPosition = isRightToLeftTopToBottom() ? -position()-size() : position();
- if (snapMode == QQuickGridView::SnapOneRow && moveReason == Mouse) {
- // if we've been dragged < rowSize()/2 then bias towards the next row
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
- qreal bias = 0;
- if (data.velocity > 0 && dist > QML_FLICK_SNAPONETHRESHOLD && dist < rowSize()/2)
- bias = rowSize()/2;
- else if (data.velocity < 0 && dist < -QML_FLICK_SNAPONETHRESHOLD && dist > -rowSize()/2)
- bias = -rowSize()/2;
- if (isRightToLeftTopToBottom())
- bias = -bias;
- tempPosition -= bias;
- }
- FxViewItem *topItem = snapItemAt(tempPosition+highlightRangeStart);
- if (!topItem && strictHighlightRange && currentItem) {
- // StrictlyEnforceRange always keeps an item in range
- updateHighlight();
- topItem = currentItem;
- }
- FxViewItem *bottomItem = snapItemAt(tempPosition+highlightRangeEnd);
- if (!bottomItem && strictHighlightRange && currentItem) {
- // StrictlyEnforceRange always keeps an item in range
- updateHighlight();
- bottomItem = currentItem;
- }
- qreal pos;
- bool isInBounds = -position() > maxExtent && -position() <= minExtent;
- if (topItem && (isInBounds || strictHighlightRange)) {
- qreal headerPos = header ? static_cast<FxGridItemSG*>(header)->rowPos() : 0;
- if (topItem->index == 0 && header && tempPosition+highlightRangeStart < headerPos+headerSize()/2 && !strictHighlightRange) {
- pos = isRightToLeftTopToBottom() ? - headerPos + highlightRangeStart - size() : headerPos - highlightRangeStart;
- } else {
- if (isRightToLeftTopToBottom())
- pos = qMax(qMin(-topItem->position() + highlightRangeStart - size(), -maxExtent), -minExtent);
- else
- pos = qMax(qMin(topItem->position() - highlightRangeStart, -maxExtent), -minExtent);
- }
- } else if (bottomItem && isInBounds) {
- if (isRightToLeftTopToBottom())
- pos = qMax(qMin(-bottomItem->position() + highlightRangeEnd - size(), -maxExtent), -minExtent);
- else
- pos = qMax(qMin(bottomItem->position() - highlightRangeEnd, -maxExtent), -minExtent);
- } else {
- QQuickItemViewPrivate::fixup(data, minExtent, maxExtent);
- return;
- }
-
- qreal dist = qAbs(data.move + pos);
- if (dist > 0) {
- timeline.reset(data.move);
- if (fixupMode != Immediate) {
- timeline.move(data.move, -pos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2);
- data.fixingUp = true;
- } else {
- timeline.set(data.move, -pos);
- }
- vTime = timeline.time();
- }
- } else if (haveHighlightRange && highlightRange == QQuickGridView::StrictlyEnforceRange) {
- if (currentItem) {
- updateHighlight();
- qreal pos = static_cast<FxGridItemSG*>(currentItem)->rowPos();
- if (viewPos < pos + rowSize() - highlightRangeEnd)
- viewPos = pos + rowSize() - highlightRangeEnd;
- if (viewPos > pos - highlightRangeStart)
- viewPos = pos - highlightRangeStart;
- if (isRightToLeftTopToBottom())
- viewPos = -viewPos-size();
- timeline.reset(data.move);
- if (viewPos != position()) {
- if (fixupMode != Immediate) {
- timeline.move(data.move, -viewPos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2);
- data.fixingUp = true;
- } else {
- timeline.set(data.move, -viewPos);
- }
- }
- vTime = timeline.time();
- }
- } else {
- QQuickItemViewPrivate::fixup(data, minExtent, maxExtent);
- }
- data.inOvershoot = false;
- fixupMode = Normal;
-}
-
-void QQuickGridViewPrivate::flick(AxisData &data, qreal minExtent, qreal maxExtent, qreal vSize,
- QDeclarativeTimeLineCallback::Callback fixupCallback, qreal velocity)
-{
- Q_Q(QQuickGridView);
- data.fixingUp = false;
- moveReason = Mouse;
- if ((!haveHighlightRange || highlightRange != QQuickGridView::StrictlyEnforceRange)
- && snapMode == QQuickGridView::NoSnap) {
- QQuickItemViewPrivate::flick(data, minExtent, maxExtent, vSize, fixupCallback, velocity);
- return;
- }
- qreal maxDistance = 0;
- qreal dataValue = isRightToLeftTopToBottom() ? -data.move.value()+size() : data.move.value();
- // -ve velocity means list is moving up/left
- if (velocity > 0) {
- if (data.move.value() < minExtent) {
- if (snapMode == QQuickGridView::SnapOneRow) {
- // if we've been dragged < averageSize/2 then bias towards the next item
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
- qreal bias = dist < rowSize()/2 ? rowSize()/2 : 0;
- if (isRightToLeftTopToBottom())
- bias = -bias;
- data.flickTarget = -snapPosAt(-dataValue - bias);
- maxDistance = qAbs(data.flickTarget - data.move.value());
- velocity = maxVelocity;
- } else {
- maxDistance = qAbs(minExtent - data.move.value());
- }
- }
- if (snapMode == QQuickGridView::NoSnap && highlightRange != QQuickGridView::StrictlyEnforceRange)
- data.flickTarget = minExtent;
- } else {
- if (data.move.value() > maxExtent) {
- if (snapMode == QQuickGridView::SnapOneRow) {
- // if we've been dragged < averageSize/2 then bias towards the next item
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
- qreal bias = -dist < rowSize()/2 ? rowSize()/2 : 0;
- if (isRightToLeftTopToBottom())
- bias = -bias;
- data.flickTarget = -snapPosAt(-dataValue + bias);
- maxDistance = qAbs(data.flickTarget - data.move.value());
- velocity = -maxVelocity;
- } else {
- maxDistance = qAbs(maxExtent - data.move.value());
- }
- }
- if (snapMode == QQuickGridView::NoSnap && highlightRange != QQuickGridView::StrictlyEnforceRange)
- data.flickTarget = maxExtent;
- }
- bool overShoot = boundsBehavior == QQuickFlickable::DragAndOvershootBounds;
- if (maxDistance > 0 || overShoot) {
- // This mode requires the grid to stop exactly on a row boundary.
- qreal v = velocity;
- if (maxVelocity != -1 && maxVelocity < qAbs(v)) {
- if (v < 0)
- v = -maxVelocity;
- else
- v = maxVelocity;
- }
- qreal accel = deceleration;
- qreal v2 = v * v;
- qreal overshootDist = 0.0;
- if ((maxDistance > 0.0 && v2 / (2.0f * maxDistance) < accel) || snapMode == QQuickGridView::SnapOneRow) {
- // + rowSize()/4 to encourage moving at least one item in the flick direction
- qreal dist = v2 / (accel * 2.0) + rowSize()/4;
- dist = qMin(dist, maxDistance);
- if (v > 0)
- dist = -dist;
- if (snapMode != QQuickGridView::SnapOneRow) {
- qreal distTemp = isRightToLeftTopToBottom() ? -dist : dist;
- data.flickTarget = -snapPosAt(-dataValue + distTemp);
- }
- data.flickTarget = isRightToLeftTopToBottom() ? -data.flickTarget+size() : data.flickTarget;
- if (overShoot) {
- if (data.flickTarget >= minExtent) {
- overshootDist = overShootDistance(vSize);
- data.flickTarget += overshootDist;
- } else if (data.flickTarget <= maxExtent) {
- overshootDist = overShootDistance(vSize);
- data.flickTarget -= overshootDist;
- }
- }
- qreal adjDist = -data.flickTarget + data.move.value();
- if (qAbs(adjDist) > qAbs(dist)) {
- // Prevent painfully slow flicking - adjust velocity to suit flickDeceleration
- qreal adjv2 = accel * 2.0f * qAbs(adjDist);
- if (adjv2 > v2) {
- v2 = adjv2;
- v = qSqrt(v2);
- if (dist > 0)
- v = -v;
- }
- }
- dist = adjDist;
- accel = v2 / (2.0f * qAbs(dist));
- } else {
- data.flickTarget = velocity > 0 ? minExtent : maxExtent;
- overshootDist = overShoot ? overShootDistance(vSize) : 0;
- }
- timeline.reset(data.move);
- timeline.accel(data.move, v, accel, maxDistance + overshootDist);
- timeline.callback(QDeclarativeTimeLineCallback(&data.move, fixupCallback, this));
- if (!hData.flicking && q->xflick()) {
- hData.flicking = true;
- emit q->flickingChanged();
- emit q->flickingHorizontallyChanged();
- emit q->flickStarted();
- }
- if (!vData.flicking && q->yflick()) {
- vData.flicking = true;
- emit q->flickingChanged();
- emit q->flickingVerticallyChanged();
- emit q->flickStarted();
- }
- } else {
- timeline.reset(data.move);
- fixup(data, minExtent, maxExtent);
- }
-}
-
-
-//----------------------------------------------------------------------------
-/*!
- \qmlclass GridView QQuickGridView
- \inqmlmodule QtQuick 2
- \ingroup qml-view-elements
-
- \inherits Flickable
- \brief The GridView item provides a grid view of items provided by a model.
-
- A GridView displays data from models created from built-in QML elements like ListModel
- and XmlListModel, or custom model classes defined in C++ that inherit from
- QAbstractListModel.
-
- A GridView has a \l model, which defines the data to be displayed, and
- a \l delegate, which defines how the data should be displayed. Items in a
- GridView are laid out horizontally or vertically. Grid views are inherently flickable
- as GridView inherits from \l Flickable.
-
- \section1 Example Usage
-
- The following example shows the definition of a simple list model defined
- in a file called \c ContactModel.qml:
-
- \snippet doc/src/snippets/declarative/gridview/ContactModel.qml 0
-
- \div {class="float-right"}
- \inlineimage gridview-simple.png
- \enddiv
-
- This model can be referenced as \c ContactModel in other QML files. See \l{QML Modules}
- for more information about creating reusable components like this.
-
- Another component can display this model data in a GridView, as in the following
- example, which creates a \c ContactModel component for its model, and a \l Column element
- (containing \l Image and \l Text elements) for its delegate.
-
- \clearfloat
- \snippet doc/src/snippets/declarative/gridview/gridview.qml import
- \codeline
- \snippet doc/src/snippets/declarative/gridview/gridview.qml classdocs simple
-
- \div {class="float-right"}
- \inlineimage gridview-highlight.png
- \enddiv
-
- The view will create a new delegate for each item in the model. Note that the delegate
- is able to access the model's \c name and \c portrait data directly.
-
- An improved grid view is shown below. The delegate is visually improved and is moved
- into a separate \c contactDelegate component.
-
- \clearfloat
- \snippet doc/src/snippets/declarative/gridview/gridview.qml classdocs advanced
-
- The currently selected item is highlighted with a blue \l Rectangle using the \l highlight property,
- and \c focus is set to \c true to enable keyboard navigation for the grid view.
- The grid view itself is a focus scope (see \l{qmlfocus#Acquiring Focus and Focus Scopes}{the focus documentation page} for more details).
-
- Delegates are instantiated as needed and may be destroyed at any time.
- State should \e never be stored in a delegate.
-
- GridView attaches a number of properties to the root item of the delegate, for example
- \c {GridView.isCurrentItem}. In the following example, the root delegate item can access
- this attached property directly as \c GridView.isCurrentItem, while the child
- \c contactInfo object must refer to this property as \c wrapper.GridView.isCurrentItem.
-
- \snippet doc/src/snippets/declarative/gridview/gridview.qml isCurrentItem
-
- \note Views do not set the \l{Item::}{clip} property automatically.
- If the view is not clipped by another item or the screen, it will be necessary
- to set this property to true in order to clip the items that are partially or
- fully outside the view.
-
- \sa {declarative/modelviews/gridview}{GridView example}
-*/
-
-QQuickGridView::QQuickGridView(QQuickItem *parent)
- : QQuickItemView(*(new QQuickGridViewPrivate), parent)
-{
-}
-
-QQuickGridView::~QQuickGridView()
-{
-}
-
-void QQuickGridView::setHighlightFollowsCurrentItem(bool autoHighlight)
-{
- Q_D(QQuickGridView);
- if (d->autoHighlight != autoHighlight) {
- if (!autoHighlight && d->highlightXAnimator) {
- d->highlightXAnimator->stop();
- d->highlightYAnimator->stop();
- }
- QQuickItemView::setHighlightFollowsCurrentItem(autoHighlight);
- }
-}
-
-/*!
- \qmlattachedproperty bool QtQuick2::GridView::isCurrentItem
- This attached property is true if this delegate is the current item; otherwise false.
-
- It is attached to each instance of the delegate.
-*/
-
-/*!
- \qmlattachedproperty GridView QtQuick2::GridView::view
- This attached property holds the view that manages this delegate instance.
-
- It is attached to each instance of the delegate.
-
- \snippet doc/src/snippets/declarative/gridview/gridview.qml isCurrentItem
-*/
-
-/*!
- \qmlattachedproperty bool QtQuick2::GridView::delayRemove
- This attached property holds whether the delegate may be destroyed.
-
- It is attached to each instance of the delegate.
-
- It is sometimes necessary to delay the destruction of an item
- until an animation completes.
-
- The example below ensures that the animation completes before
- the item is removed from the grid.
-
- \snippet doc/src/snippets/declarative/gridview/gridview.qml delayRemove
-*/
-
-/*!
- \qmlattachedsignal QtQuick2::GridView::onAdd()
- This attached handler is called immediately after an item is added to the view.
-*/
-
-/*!
- \qmlattachedsignal QtQuick2::GridView::onRemove()
- This attached handler is called immediately before an item is removed from the view.
-*/
-
-
-/*!
- \qmlproperty model QtQuick2::GridView::model
- This property holds the model providing data for the grid.
-
- The model provides the set of data that is used to create the items
- in the view. Models can be created directly in QML using \l ListModel, \l XmlListModel
- or \l VisualItemModel, or provided by C++ model classes. If a C++ model class is
- used, it must be a subclass of \l QAbstractItemModel or a simple list.
-
- \sa {qmlmodels}{Data Models}
-*/
-
-/*!
- \qmlproperty Component QtQuick2::GridView::delegate
-
- The delegate provides a template defining each item instantiated by the view.
- The index is exposed as an accessible \c index property. Properties of the
- model are also available depending upon the type of \l {qmlmodels}{Data Model}.
-
- The number of elements in the delegate has a direct effect on the
- flicking performance of the view. If at all possible, place functionality
- that is not needed for the normal display of the delegate in a \l Loader which
- can load additional elements when needed.
-
- The GridView will layout the items based on the size of the root item
- in the delegate.
-
- \note Delegates are instantiated as needed and may be destroyed at any time.
- State should \e never be stored in a delegate.
-*/
-
-/*!
- \qmlproperty int QtQuick2::GridView::currentIndex
- \qmlproperty Item QtQuick2::GridView::currentItem
-
- The \c currentIndex property holds the index of the current item, and
- \c currentItem holds the current item. Setting the currentIndex to -1
- will clear the highlight and set currentItem to null.
-
- If highlightFollowsCurrentItem is \c true, setting either of these
- properties will smoothly scroll the GridView so that the current
- item becomes visible.
-
- Note that the position of the current item
- may only be approximate until it becomes visible in the view.
-*/
-
-
-/*!
- \qmlproperty Item QtQuick2::GridView::highlightItem
-
- This holds the highlight item created from the \l highlight component.
-
- The highlightItem is managed by the view unless
- \l highlightFollowsCurrentItem is set to false.
-
- \sa highlight, highlightFollowsCurrentItem
-*/
-
-
-/*!
- \qmlproperty int QtQuick2::GridView::count
- This property holds the number of items in the view.
-*/
-
-
-/*!
- \qmlproperty Component QtQuick2::GridView::highlight
- This property holds the component to use as the highlight.
-
- An instance of the highlight component is created for each view.
- The geometry of the resulting component instance will be managed by the view
- so as to stay with the current item, unless the highlightFollowsCurrentItem property is false.
-
- \sa highlightItem, highlightFollowsCurrentItem
-*/
-
-/*!
- \qmlproperty bool QtQuick2::GridView::highlightFollowsCurrentItem
- This property sets whether the highlight is managed by the view.
-
- If this property is true (the default value), the highlight is moved smoothly
- to follow the current item. Otherwise, the
- highlight is not moved by the view, and any movement must be implemented
- by the highlight.
-
- Here is a highlight with its motion defined by a \l {SpringAnimation} item:
-
- \snippet doc/src/snippets/declarative/gridview/gridview.qml highlightFollowsCurrentItem
-*/
-
-
-/*!
- \qmlproperty int QtQuick2::GridView::highlightMoveDuration
- This property holds the move animation duration of the highlight delegate.
-
- highlightFollowsCurrentItem must be true for this property
- to have effect.
-
- The default value for the duration is 150ms.
-
- \sa highlightFollowsCurrentItem
-*/
-
-/*!
- \qmlproperty real QtQuick2::GridView::preferredHighlightBegin
- \qmlproperty real QtQuick2::GridView::preferredHighlightEnd
- \qmlproperty enumeration QtQuick2::GridView::highlightRangeMode
-
- These properties define the preferred range of the highlight (for the current item)
- within the view. The \c preferredHighlightBegin value must be less than the
- \c preferredHighlightEnd value.
-
- These properties affect the position of the current item when the view is scrolled.
- For example, if the currently selected item should stay in the middle of the
- view when it is scrolled, set the \c preferredHighlightBegin and
- \c preferredHighlightEnd values to the top and bottom coordinates of where the middle
- item would be. If the \c currentItem is changed programmatically, the view will
- automatically scroll so that the current item is in the middle of the view.
- Furthermore, the behavior of the current item index will occur whether or not a
- highlight exists.
-
- Valid values for \c highlightRangeMode are:
-
- \list
- \o GridView.ApplyRange - the view attempts to maintain the highlight within the range.
- However, the highlight can move outside of the range at the ends of the view or due
- to mouse interaction.
- \o GridView.StrictlyEnforceRange - the highlight never moves outside of the range.
- The current item changes if a keyboard or mouse action would cause the highlight to move
- outside of the range.
- \o GridView.NoHighlightRange - this is the default value.
- \endlist
-*/
-
-
-/*!
- \qmlproperty enumeration QtQuick2::GridView::layoutDirection
- This property holds the layout direction of the grid.
-
- Possible values:
-
- \list
- \o Qt.LeftToRight (default) - Items will be laid out starting in the top, left corner. The flow is
- dependent on the \l GridView::flow property.
- \o Qt.RightToLeft - Items will be laid out starting in the top, right corner. The flow is dependent
- on the \l GridView::flow property.
- \endlist
-
- \bold Note: If GridView::flow is set to GridView.LeftToRight, this is not to be confused if
- GridView::layoutDirection is set to Qt.RightToLeft. The GridView.LeftToRight flow value simply
- indicates that the flow is horizontal.
-*/
-
-
-/*!
- \qmlproperty enumeration QtQuick2::GridView::effectiveLayoutDirection
- This property holds the effective layout direction of the grid.
-
- When using the attached property \l {LayoutMirroring::enabled}{LayoutMirroring::enabled} for locale layouts,
- the visual layout direction of the grid will be mirrored. However, the
- property \l {GridView::layoutDirection}{layoutDirection} will remain unchanged.
-
- \sa GridView::layoutDirection, {LayoutMirroring}{LayoutMirroring}
-*/
-/*!
- \qmlproperty bool QtQuick2::GridView::keyNavigationWraps
- This property holds whether the grid wraps key navigation
-
- If this is true, key navigation that would move the current item selection
- past one end of the view instead wraps around and moves the selection to
- the other end of the view.
-
- By default, key navigation is not wrapped.
-*/
-/*!
- \qmlproperty int QtQuick2::GridView::cacheBuffer
- This property determines whether delegates are retained outside the
- visible area of the view.
-
- If non-zero the view may keep as many delegates
- instantiated as will fit within the buffer specified. For example,
- if in a vertical view the delegate is 20 pixels high, there are 3
- columns and \c cacheBuffer is
- set to 40, then up to 6 delegates above and 6 delegates below the visible
- area may be created/retained. The buffered delegates are created asynchronously,
- allowing creation to occur across multiple frames and reducing the
- likelihood of skipping frames. In order to improve painting performance
- delegates outside the visible area have their \l visible property set to
- false until they are moved into the visible area.
-
- Note that cacheBuffer is not a pixel buffer - it only maintains additional
- instantiated delegates.
-
- Setting this value can make scrolling the list smoother at the expense
- of additional memory usage. It is not a substitute for creating efficient
- delegates; the fewer elements in a delegate, the faster a view may be
- scrolled.
-*/
-void QQuickGridView::setHighlightMoveDuration(int duration)
-{
- Q_D(QQuickGridView);
- if (d->highlightMoveDuration != duration) {
- if (d->highlightYAnimator) {
- d->highlightXAnimator->userDuration = duration;
- d->highlightYAnimator->userDuration = duration;
- }
- QQuickItemView::setHighlightMoveDuration(duration);
- }
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::GridView::flow
- This property holds the flow of the grid.
-
- Possible values:
-
- \list
- \o GridView.LeftToRight (default) - Items are laid out from left to right, and the view scrolls vertically
- \o GridView.TopToBottom - Items are laid out from top to bottom, and the view scrolls horizontally
- \endlist
-*/
-QQuickGridView::Flow QQuickGridView::flow() const
-{
- Q_D(const QQuickGridView);
- return d->flow;
-}
-
-void QQuickGridView::setFlow(Flow flow)
-{
- Q_D(QQuickGridView);
- if (d->flow != flow) {
- d->flow = flow;
- if (d->flow == LeftToRight) {
- setContentWidth(-1);
- setFlickableDirection(VerticalFlick);
- } else {
- setContentHeight(-1);
- setFlickableDirection(HorizontalFlick);
- }
- setContentX(0);
- setContentY(0);
- d->regenerate();
- emit flowChanged();
- }
-}
-
-
-/*!
- \qmlproperty real QtQuick2::GridView::cellWidth
- \qmlproperty real QtQuick2::GridView::cellHeight
-
- These properties holds the width and height of each cell in the grid.
-
- The default cell size is 100x100.
-*/
-qreal QQuickGridView::cellWidth() const
-{
- Q_D(const QQuickGridView);
- return d->cellWidth;
-}
-
-void QQuickGridView::setCellWidth(qreal cellWidth)
-{
- Q_D(QQuickGridView);
- if (cellWidth != d->cellWidth && cellWidth > 0) {
- d->cellWidth = qMax(qreal(1), cellWidth);
- d->updateViewport();
- emit cellWidthChanged();
- d->forceLayout = true;
- d->layout();
- }
-}
-
-qreal QQuickGridView::cellHeight() const
-{
- Q_D(const QQuickGridView);
- return d->cellHeight;
-}
-
-void QQuickGridView::setCellHeight(qreal cellHeight)
-{
- Q_D(QQuickGridView);
- if (cellHeight != d->cellHeight && cellHeight > 0) {
- d->cellHeight = qMax(qreal(1), cellHeight);
- d->updateViewport();
- emit cellHeightChanged();
- d->forceLayout = true;
- d->layout();
- }
-}
-/*!
- \qmlproperty enumeration QtQuick2::GridView::snapMode
-
- This property determines how the view scrolling will settle following a drag or flick.
- The possible values are:
-
- \list
- \o GridView.NoSnap (default) - the view stops anywhere within the visible area.
- \o GridView.SnapToRow - the view settles with a row (or column for \c GridView.TopToBottom flow)
- aligned with the start of the view.
- \o GridView.SnapOneRow - the view will settle no more than one row (or column for \c GridView.TopToBottom flow)
- away from the first visible row at the time the mouse button is released.
- This mode is particularly useful for moving one page at a time.
- \endlist
-
-*/
-QQuickGridView::SnapMode QQuickGridView::snapMode() const
-{
- Q_D(const QQuickGridView);
- return d->snapMode;
-}
-
-void QQuickGridView::setSnapMode(SnapMode mode)
-{
- Q_D(QQuickGridView);
- if (d->snapMode != mode) {
- d->snapMode = mode;
- emit snapModeChanged();
- }
-}
-
-
-/*!
- \qmlproperty Component QtQuick2::GridView::footer
- This property holds the component to use as the footer.
-
- An instance of the footer component is created for each view. The
- footer is positioned at the end of the view, after any items.
-
- \sa header
-*/
-/*!
- \qmlproperty Component QtQuick2::GridView::header
- This property holds the component to use as the header.
-
- An instance of the header component is created for each view. The
- header is positioned at the beginning of the view, before any items.
-
- \sa footer
-*/
-void QQuickGridView::viewportMoved()
-{
- Q_D(QQuickGridView);
- QQuickItemView::viewportMoved();
- if (!d->itemCount)
- return;
- if (d->inViewportMoved)
- return;
- d->inViewportMoved = true;
-
- // Set visibility of items to eliminate cost of items outside the visible area.
- qreal from = d->isContentFlowReversed() ? -d->position()-d->size() : d->position();
- qreal to = d->isContentFlowReversed() ? -d->position() : d->position()+d->size();
- for (int i = 0; i < d->visibleItems.count(); ++i) {
- FxGridItemSG *item = static_cast<FxGridItemSG*>(d->visibleItems.at(i));
- item->item->setVisible(item->rowPos() + d->rowSize() >= from && item->rowPos() <= to);
- }
-
- if (yflick())
- d->bufferMode = d->vData.smoothVelocity < 0 ? QQuickItemViewPrivate::BufferBefore : QQuickItemViewPrivate::BufferAfter;
- else if (d->isRightToLeftTopToBottom())
- d->bufferMode = d->hData.smoothVelocity < 0 ? QQuickItemViewPrivate::BufferAfter : QQuickItemViewPrivate::BufferBefore;
- else
- d->bufferMode = d->hData.smoothVelocity < 0 ? QQuickItemViewPrivate::BufferBefore : QQuickItemViewPrivate::BufferAfter;
-
- d->refill();
- if (d->hData.flicking || d->vData.flicking || d->hData.moving || d->vData.moving)
- d->moveReason = QQuickGridViewPrivate::Mouse;
- if (d->moveReason != QQuickGridViewPrivate::SetIndex) {
- if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange && d->highlight) {
- // reposition highlight
- qreal pos = d->highlight->position();
- qreal viewPos = d->isRightToLeftTopToBottom() ? -d->position()-d->size() : d->position();
- if (pos > viewPos + d->highlightRangeEnd - d->highlight->size())
- pos = viewPos + d->highlightRangeEnd - d->highlight->size();
- if (pos < viewPos + d->highlightRangeStart)
- pos = viewPos + d->highlightRangeStart;
-
- if (pos != d->highlight->position()) {
- d->highlightXAnimator->stop();
- d->highlightYAnimator->stop();
- static_cast<FxGridItemSG*>(d->highlight)->setPosition(static_cast<FxGridItemSG*>(d->highlight)->colPos(), pos);
- } else {
- d->updateHighlight();
- }
-
- // update current index
- int idx = d->snapIndex();
- if (idx >= 0 && idx != d->currentIndex) {
- d->updateCurrent(idx);
- if (d->currentItem && static_cast<FxGridItemSG*>(d->currentItem)->colPos() != static_cast<FxGridItemSG*>(d->highlight)->colPos() && d->autoHighlight) {
- if (d->flow == LeftToRight)
- d->highlightXAnimator->to = d->currentItem->item->x();
- else
- d->highlightYAnimator->to = d->currentItem->item->y();
- }
- }
- }
- }
-
- d->inViewportMoved = false;
-}
-
-void QQuickGridView::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QQuickGridView);
- if (d->model && d->model->count() && d->interactive) {
- d->moveReason = QQuickGridViewPrivate::SetIndex;
- int oldCurrent = currentIndex();
- switch (event->key()) {
- case Qt::Key_Up:
- moveCurrentIndexUp();
- break;
- case Qt::Key_Down:
- moveCurrentIndexDown();
- break;
- case Qt::Key_Left:
- moveCurrentIndexLeft();
- break;
- case Qt::Key_Right:
- moveCurrentIndexRight();
- break;
- default:
- break;
- }
- if (oldCurrent != currentIndex()) {
- event->accept();
- return;
- }
- }
- event->ignore();
- QQuickItemView::keyPressEvent(event);
-}
-/*!
- \qmlmethod QtQuick2::GridView::moveCurrentIndexUp()
-
- Move the currentIndex up one item in the view.
- The current index will wrap if keyNavigationWraps is true and it
- is currently at the end. This method has no effect if the \l count is zero.
-
- \bold Note: methods should only be called after the Component has completed.
-*/
-
-
-void QQuickGridView::moveCurrentIndexUp()
-{
- Q_D(QQuickGridView);
- const int count = d->model ? d->model->count() : 0;
- if (!count)
- return;
- if (d->flow == QQuickGridView::LeftToRight) {
- if (currentIndex() >= d->columns || d->wrap) {
- int index = currentIndex() - d->columns;
- setCurrentIndex((index >= 0 && index < count) ? index : count-1);
- }
- } else {
- if (currentIndex() > 0 || d->wrap) {
- int index = currentIndex() - 1;
- setCurrentIndex((index >= 0 && index < count) ? index : count-1);
- }
- }
-}
-
-/*!
- \qmlmethod QtQuick2::GridView::moveCurrentIndexDown()
-
- Move the currentIndex down one item in the view.
- The current index will wrap if keyNavigationWraps is true and it
- is currently at the end. This method has no effect if the \l count is zero.
-
- \bold Note: methods should only be called after the Component has completed.
-*/
-void QQuickGridView::moveCurrentIndexDown()
-{
- Q_D(QQuickGridView);
- const int count = d->model ? d->model->count() : 0;
- if (!count)
- return;
- if (d->flow == QQuickGridView::LeftToRight) {
- if (currentIndex() < count - d->columns || d->wrap) {
- int index = currentIndex()+d->columns;
- setCurrentIndex((index >= 0 && index < count) ? index : 0);
- }
- } else {
- if (currentIndex() < count - 1 || d->wrap) {
- int index = currentIndex() + 1;
- setCurrentIndex((index >= 0 && index < count) ? index : 0);
- }
- }
-}
-
-/*!
- \qmlmethod QtQuick2::GridView::moveCurrentIndexLeft()
-
- Move the currentIndex left one item in the view.
- The current index will wrap if keyNavigationWraps is true and it
- is currently at the end. This method has no effect if the \l count is zero.
-
- \bold Note: methods should only be called after the Component has completed.
-*/
-void QQuickGridView::moveCurrentIndexLeft()
-{
- Q_D(QQuickGridView);
- const int count = d->model ? d->model->count() : 0;
- if (!count)
- return;
- if (effectiveLayoutDirection() == Qt::LeftToRight) {
- if (d->flow == QQuickGridView::LeftToRight) {
- if (currentIndex() > 0 || d->wrap) {
- int index = currentIndex() - 1;
- setCurrentIndex((index >= 0 && index < count) ? index : count-1);
- }
- } else {
- if (currentIndex() >= d->columns || d->wrap) {
- int index = currentIndex() - d->columns;
- setCurrentIndex((index >= 0 && index < count) ? index : count-1);
- }
- }
- } else {
- if (d->flow == QQuickGridView::LeftToRight) {
- if (currentIndex() < count - 1 || d->wrap) {
- int index = currentIndex() + 1;
- setCurrentIndex((index >= 0 && index < count) ? index : 0);
- }
- } else {
- if (currentIndex() < count - d->columns || d->wrap) {
- int index = currentIndex() + d->columns;
- setCurrentIndex((index >= 0 && index < count) ? index : 0);
- }
- }
- }
-}
-
-
-/*!
- \qmlmethod QtQuick2::GridView::moveCurrentIndexRight()
-
- Move the currentIndex right one item in the view.
- The current index will wrap if keyNavigationWraps is true and it
- is currently at the end. This method has no effect if the \l count is zero.
-
- \bold Note: methods should only be called after the Component has completed.
-*/
-void QQuickGridView::moveCurrentIndexRight()
-{
- Q_D(QQuickGridView);
- const int count = d->model ? d->model->count() : 0;
- if (!count)
- return;
- if (effectiveLayoutDirection() == Qt::LeftToRight) {
- if (d->flow == QQuickGridView::LeftToRight) {
- if (currentIndex() < count - 1 || d->wrap) {
- int index = currentIndex() + 1;
- setCurrentIndex((index >= 0 && index < count) ? index : 0);
- }
- } else {
- if (currentIndex() < count - d->columns || d->wrap) {
- int index = currentIndex()+d->columns;
- setCurrentIndex((index >= 0 && index < count) ? index : 0);
- }
- }
- } else {
- if (d->flow == QQuickGridView::LeftToRight) {
- if (currentIndex() > 0 || d->wrap) {
- int index = currentIndex() - 1;
- setCurrentIndex((index >= 0 && index < count) ? index : count-1);
- }
- } else {
- if (currentIndex() >= d->columns || d->wrap) {
- int index = currentIndex() - d->columns;
- setCurrentIndex((index >= 0 && index < count) ? index : count-1);
- }
- }
- }
-}
-
-bool QQuickGridViewPrivate::applyInsertionChange(const QDeclarativeChangeSet::Insert &change, FxViewItem *firstVisible, InsertionsResult *insertResult)
-{
- Q_Q(QQuickGridView);
-
- int modelIndex = change.index;
- int count = change.count;
-
- int index = visibleItems.count() ? mapFromModel(modelIndex) : 0;
-
- if (index < 0) {
- int i = visibleItems.count() - 1;
- while (i > 0 && visibleItems.at(i)->index == -1)
- --i;
- if (visibleItems.at(i)->index + 1 == modelIndex) {
- // Special case of appending an item to the model.
- index = visibleItems.count();
- } else {
- if (modelIndex <= visibleIndex) {
- // Insert before visible items
- visibleIndex += count;
- for (int i = 0; i < visibleItems.count(); ++i) {
- FxViewItem *item = visibleItems.at(i);
- if (item->index != -1 && item->index >= modelIndex)
- item->index += count;
- }
- }
- return true;
- }
- }
-
- qreal tempPos = isRightToLeftTopToBottom() ? -position()-size()+q->width()+1 : position();
- qreal colPos = 0;
- qreal rowPos = 0;
- int colNum = 0;
- if (visibleItems.count()) {
- if (index < visibleItems.count()) {
- FxGridItemSG *gridItem = static_cast<FxGridItemSG*>(visibleItems.at(index));
- colPos = gridItem->colPos();
- rowPos = gridItem->rowPos();
- colNum = qFloor((colPos+colSize()/2) / colSize());
- } else {
- // appending items to visible list
- FxGridItemSG *gridItem = static_cast<FxGridItemSG*>(visibleItems.at(index-1));
- rowPos = gridItem->rowPos();
- colNum = qFloor((gridItem->colPos()+colSize()/2) / colSize());
- if (++colNum >= columns) {
- colNum = 0;
- rowPos += rowSize();
- }
- colPos = colNum * colSize();
- }
- }
-
- // Update the indexes of the following visible items.
- for (int i = 0; i < visibleItems.count(); ++i) {
- FxViewItem *item = visibleItems.at(i);
- if (item->index != -1 && item->index >= modelIndex)
- item->index += count;
- }
-
- int prevAddedCount = insertResult->addedItems.count();
- if (firstVisible && rowPos < firstVisible->position()) {
- // Insert items before the visible item.
- int insertionIdx = index;
- int i = count - 1;
- int from = tempPos - buffer;
-
- while (i >= 0) {
- if (rowPos > from && insertionIdx < visibleIndex) {
- // item won't be visible, just note the size for repositioning
- insertResult->sizeAddedBeforeVisible += rowSize();
- } else {
- // item is before first visible e.g. in cache buffer
- FxViewItem *item = 0;
- if (change.isMove() && (item = currentChanges.removedItems.take(change.moveKey(modelIndex + i)))) {
- if (item->index > modelIndex + i)
- insertResult->movedBackwards.append(item);
- item->index = modelIndex + i;
- }
- if (!item)
- item = createItem(modelIndex + i);
- if (!item)
- return false;
-
- item->item->setVisible(true);
- visibleItems.insert(insertionIdx, item);
- if (!change.isMove()) {
- insertResult->addedItems.append(item);
- insertResult->sizeAddedBeforeVisible += rowSize();
- }
- }
-
- if (--colNum < 0 ) {
- colNum = columns - 1;
- rowPos -= rowSize();
- }
- colPos = colNum * colSize();
- index++;
- i--;
- }
- } else {
- int i = 0;
- int to = buffer+tempPos+size()-1;
- while (i < count && rowPos <= to + rowSize()*(columns - (colPos/colSize()))/qreal(columns)) {
- FxViewItem *item = 0;
- if (change.isMove() && (item = currentChanges.removedItems.take(change.moveKey(modelIndex + i)))) {
- if (item->index > modelIndex + i)
- insertResult->movedBackwards.append(item);
- item->index = modelIndex + i;
- }
- if (!item)
- item = createItem(modelIndex + i);
- if (!item)
- return false;
-
- item->item->setVisible(true);
- visibleItems.insert(index, item);
- if (!change.isMove())
- insertResult->addedItems.append(item);
- if (++colNum >= columns) {
- colNum = 0;
- rowPos += rowSize();
- }
- colPos = colNum * colSize();
- ++index;
- ++i;
- }
- }
-
- updateVisibleIndex();
-
- return insertResult->addedItems.count() > prevAddedCount;
-}
-
-bool QQuickGridViewPrivate::needsRefillForAddedOrRemovedIndex(int modelIndex) const
-{
- // If we add or remove items before visible items, a layout may be
- // required to ensure item 0 is in the first column.
- return modelIndex < visibleIndex;
-}
-
-/*!
- \qmlmethod QtQuick2::GridView::positionViewAtIndex(int index, PositionMode mode)
-
- Positions the view such that the \a index is at the position specified by
- \a mode:
-
- \list
- \o GridView.Beginning - position item at the top (or left for \c GridView.TopToBottom flow) of the view.
- \o GridView.Center - position item in the center of the view.
- \o GridView.End - position item at bottom (or right for horizontal orientation) of the view.
- \o GridView.Visible - if any part of the item is visible then take no action, otherwise
- bring the item into view.
- \o GridView.Contain - ensure the entire item is visible. If the item is larger than
- the view the item is positioned at the top (or left for \c GridView.TopToBottom flow) of the view.
- \endlist
-
- If positioning the view at the index would cause empty space to be displayed at
- the beginning or end of the view, the view will be positioned at the boundary.
-
- It is not recommended to use \l {Flickable::}{contentX} or \l {Flickable::}{contentY} to position the view
- at a particular index. This is unreliable since removing items from the start
- of the view does not cause all other items to be repositioned.
- The correct way to bring an item into view is with \c positionViewAtIndex.
-
- \bold Note: methods should only be called after the Component has completed. To position
- the view at startup, this method should be called by Component.onCompleted. For
- example, to position the view at the end:
-
- \code
- Component.onCompleted: positionViewAtIndex(count - 1, GridView.Beginning)
- \endcode
-*/
-
-/*!
- \qmlmethod QtQuick2::GridView::positionViewAtBeginning()
- \qmlmethod QtQuick2::GridView::positionViewAtEnd()
-
- Positions the view at the beginning or end, taking into account any header or footer.
-
- It is not recommended to use \l {Flickable::}{contentX} or \l {Flickable::}{contentY} to position the view
- at a particular index. This is unreliable since removing items from the start
- of the list does not cause all other items to be repositioned, and because
- the actual start of the view can vary based on the size of the delegates.
-
- \bold Note: methods should only be called after the Component has completed. To position
- the view at startup, this method should be called by Component.onCompleted. For
- example, to position the view at the end on startup:
-
- \code
- Component.onCompleted: positionViewAtEnd()
- \endcode
-*/
-
-/*!
- \qmlmethod int QtQuick2::GridView::indexAt(int x, int y)
-
- Returns the index of the visible item containing the point \a x, \a y in content
- coordinates. If there is no item at the point specified, or the item is
- not visible -1 is returned.
-
- If the item is outside the visible area, -1 is returned, regardless of
- whether an item will exist at that point when scrolled into view.
-
- \bold Note: methods should only be called after the Component has completed.
-*/
-
-QQuickGridViewAttached *QQuickGridView::qmlAttachedProperties(QObject *obj)
-{
- return new QQuickGridViewAttached(obj);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickgridview_p.h b/src/declarative/items/qquickgridview_p.h
deleted file mode 100644
index b02c0a8350..0000000000
--- a/src/declarative/items/qquickgridview_p.h
+++ /dev/null
@@ -1,146 +0,0 @@
-// Commit: 95814418f9d6adeba365c795462e8afb00138211
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKGRIDVIEW_P_H
-#define QQUICKGRIDVIEW_P_H
-
-#include "qquickitemview_p.h"
-
-#include <private/qdeclarativeguard_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-class QQuickVisualModel;
-class QQuickGridViewAttached;
-class QQuickGridViewPrivate;
-class Q_AUTOTEST_EXPORT QQuickGridView : public QQuickItemView
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickGridView)
-
- Q_PROPERTY(Flow flow READ flow WRITE setFlow NOTIFY flowChanged)
- Q_PROPERTY(qreal cellWidth READ cellWidth WRITE setCellWidth NOTIFY cellWidthChanged)
- Q_PROPERTY(qreal cellHeight READ cellHeight WRITE setCellHeight NOTIFY cellHeightChanged)
-
- Q_PROPERTY(SnapMode snapMode READ snapMode WRITE setSnapMode NOTIFY snapModeChanged)
-
- Q_ENUMS(SnapMode)
- Q_ENUMS(Flow)
- Q_CLASSINFO("DefaultProperty", "data")
-
-public:
- QQuickGridView(QQuickItem *parent=0);
- ~QQuickGridView();
-
- virtual void setHighlightFollowsCurrentItem(bool);
- virtual void setHighlightMoveDuration(int);
-
- enum Flow { LeftToRight, TopToBottom };
- Flow flow() const;
- void setFlow(Flow);
-
- qreal cellWidth() const;
- void setCellWidth(qreal);
-
- qreal cellHeight() const;
- void setCellHeight(qreal);
-
- enum SnapMode { NoSnap, SnapToRow, SnapOneRow };
- SnapMode snapMode() const;
- void setSnapMode(SnapMode mode);
-
- static QQuickGridViewAttached *qmlAttachedProperties(QObject *);
-
-public Q_SLOTS:
- void moveCurrentIndexUp();
- void moveCurrentIndexDown();
- void moveCurrentIndexLeft();
- void moveCurrentIndexRight();
-
-Q_SIGNALS:
- void cellWidthChanged();
- void cellHeightChanged();
- void highlightMoveDurationChanged();
- void flowChanged();
- void snapModeChanged();
-
-protected:
- virtual void viewportMoved();
- virtual void keyPressEvent(QKeyEvent *);
-};
-
-class QQuickGridViewAttached : public QQuickItemViewAttached
-{
- Q_OBJECT
-public:
- QQuickGridViewAttached(QObject *parent)
- : QQuickItemViewAttached(parent), m_view(0) {}
- ~QQuickGridViewAttached() {}
-
- Q_PROPERTY(QQuickGridView *view READ view NOTIFY viewChanged)
- QQuickGridView *view() { return m_view; }
- void setView(QQuickGridView *view) {
- if (view != m_view) {
- m_view = view;
- emit viewChanged();
- }
- }
-
-Q_SIGNALS:
- void viewChanged();
-
-public:
- QDeclarativeGuard<QQuickGridView> m_view;
-};
-
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickGridView)
-QML_DECLARE_TYPEINFO(QQuickGridView, QML_HAS_ATTACHED_PROPERTIES)
-
-QT_END_HEADER
-
-#endif // QQUICKGRIDVIEW_P_H
diff --git a/src/declarative/items/qquickimage.cpp b/src/declarative/items/qquickimage.cpp
deleted file mode 100644
index 46b8ea0915..0000000000
--- a/src/declarative/items/qquickimage.cpp
+++ /dev/null
@@ -1,746 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickimage_p.h"
-#include "qquickimage_p_p.h"
-
-#include <private/qsgtextureprovider_p.h>
-
-#include <private/qsgcontext_p.h>
-#include <private/qsgadaptationlayer_p.h>
-
-#include <QtGui/qpainter.h>
-#include <qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickImageTextureProvider : public QSGTextureProvider
-{
- Q_OBJECT
-public:
- QQuickImageTextureProvider()
- : m_texture(0)
- , m_smooth(false)
- {
- }
-
- QSGTexture *texture() const {
-
- if (m_texture && m_texture->isAtlasTexture())
- const_cast<QQuickImageTextureProvider *>(this)->m_texture = m_texture->removedFromAtlas();
-
- if (m_texture) {
- m_texture->setFiltering(m_smooth ? QSGTexture::Linear : QSGTexture::Nearest);
- m_texture->setMipmapFiltering(QSGTexture::Nearest);
- m_texture->setHorizontalWrapMode(QSGTexture::ClampToEdge);
- m_texture->setVerticalWrapMode(QSGTexture::ClampToEdge);
- }
- return m_texture;
- }
-
- friend class QQuickImage;
-
- QSGTexture *m_texture;
- bool m_smooth;
-};
-
-#include "qquickimage.moc"
-
-QQuickImagePrivate::QQuickImagePrivate()
- : fillMode(QQuickImage::Stretch)
- , paintedWidth(0)
- , paintedHeight(0)
- , pixmapChanged(false)
- , hAlign(QQuickImage::AlignHCenter)
- , vAlign(QQuickImage::AlignVCenter)
- , provider(0)
-{
-}
-
-/*!
- \qmlclass Image QQuickImage
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
- \brief The Image element displays an image in a declarative user interface
- \inherits Item
-
- The Image element is used to display images in a declarative user interface.
-
- The source of the image is specified as a URL using the \l source property.
- Images can be supplied in any of the standard image formats supported by Qt,
- including bitmap formats such as PNG and JPEG, and vector graphics formats
- such as SVG. If you need to display animated images, use the \l AnimatedImage
- element.
-
- If the \l{Item::width}{width} and \l{Item::height}{height} properties are not
- specified, the Image element automatically uses the size of the loaded image.
- By default, specifying the width and height of the element causes the image
- to be scaled to that size. This behavior can be changed by setting the
- \l fillMode property, allowing the image to be stretched and tiled instead.
-
- \section1 Example Usage
-
- The following example shows the simplest usage of the Image element.
-
- \snippet doc/src/snippets/declarative/image.qml document
-
- \beginfloatleft
- \image declarative-qtlogo.png
- \endfloat
-
- \clearfloat
-
- \section1 Performance
-
- By default, locally available images are loaded immediately, and the user interface
- is blocked until loading is complete. If a large image is to be loaded, it may be
- preferable to load the image in a low priority thread, by enabling the \l asynchronous
- property.
-
- If the image is obtained from a network rather than a local resource, it is
- automatically loaded asynchronously, and the \l progress and \l status properties
- are updated as appropriate.
-
- Images are cached and shared internally, so if several Image elements have the same \l source,
- only one copy of the image will be loaded.
-
- \bold Note: Images are often the greatest user of memory in QML user interfaces. It is recommended
- that images which do not form part of the user interface have their
- size bounded via the \l sourceSize property. This is especially important for content
- that is loaded from external sources or provided by the user.
-
- \sa {declarative/imageelements/image}{Image example}, QDeclarativeImageProvider
-*/
-
-QQuickImage::QQuickImage(QQuickItem *parent)
- : QQuickImageBase(*(new QQuickImagePrivate), parent)
-{
-}
-
-QQuickImage::QQuickImage(QQuickImagePrivate &dd, QQuickItem *parent)
- : QQuickImageBase(dd, parent)
-{
-}
-
-QQuickImage::~QQuickImage()
-{
- Q_D(QQuickImage);
- if (d->provider)
- d->provider->deleteLater();
-}
-
-void QQuickImagePrivate::setImage(const QImage &image)
-{
- Q_Q(QQuickImage);
- pix.setImage(image);
-
- q->pixmapChange();
- status = pix.isNull() ? QQuickImageBase::Null : QQuickImageBase::Ready;
-
- q->update();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Image::fillMode
-
- Set this property to define what happens when the source image has a different size
- than the item.
-
- \list
- \o Image.Stretch - the image is scaled to fit
- \o Image.PreserveAspectFit - the image is scaled uniformly to fit without cropping
- \o Image.PreserveAspectCrop - the image is scaled uniformly to fill, cropping if necessary
- \o Image.Tile - the image is duplicated horizontally and vertically
- \o Image.TileVertically - the image is stretched horizontally and tiled vertically
- \o Image.TileHorizontally - the image is stretched vertically and tiled horizontally
- \o Image.Pad - the image is not transformed
- \endlist
-
- \table
-
- \row
- \o \image declarative-qtlogo-stretch.png
- \o Stretch (default)
- \qml
- Image {
- width: 130; height: 100
- smooth: true
- source: "qtlogo.png"
- }
- \endqml
-
- \row
- \o \image declarative-qtlogo-preserveaspectfit.png
- \o PreserveAspectFit
- \qml
- Image {
- width: 130; height: 100
- fillMode: Image.PreserveAspectFit
- smooth: true
- source: "qtlogo.png"
- }
- \endqml
-
- \row
- \o \image declarative-qtlogo-preserveaspectcrop.png
- \o PreserveAspectCrop
- \qml
- Image {
- width: 130; height: 100
- fillMode: Image.PreserveAspectCrop
- smooth: true
- source: "qtlogo.png"
- clip: true
- }
- \endqml
-
- \row
- \o \image declarative-qtlogo-tile.png
- \o Tile
- \qml
- Image {
- width: 120; height: 120
- fillMode: Image.Tile
- source: "qtlogo.png"
- }
- \endqml
-
- \row
- \o \image declarative-qtlogo-tilevertically.png
- \o TileVertically
- \qml
- Image {
- width: 120; height: 120
- fillMode: Image.TileVertically
- smooth: true
- source: "qtlogo.png"
- }
- \endqml
-
- \row
- \o \image declarative-qtlogo-tilehorizontally.png
- \o TileHorizontally
- \qml
- Image {
- width: 120; height: 120
- fillMode: Image.TileHorizontally
- smooth: true
- source: "qtlogo.png"
- }
- \endqml
-
- \endtable
-
- Note that \c clip is \c false by default which means that the element might
- paint outside its bounding rectangle even if the fillMode is set to \c PreserveAspectCrop.
-
- \sa {declarative/imageelements/image}{Image example}
-*/
-QQuickImage::FillMode QQuickImage::fillMode() const
-{
- Q_D(const QQuickImage);
- return d->fillMode;
-}
-
-void QQuickImage::setFillMode(FillMode mode)
-{
- Q_D(QQuickImage);
- if (d->fillMode == mode)
- return;
- d->fillMode = mode;
- update();
- updatePaintedGeometry();
- emit fillModeChanged();
-}
-
-/*!
-
- \qmlproperty real QtQuick2::Image::paintedWidth
- \qmlproperty real QtQuick2::Image::paintedHeight
-
- These properties hold the size of the image that is actually painted.
- In most cases it is the same as \c width and \c height, but when using a
- \c fillMode \c PreserveAspectFit or \c fillMode \c PreserveAspectCrop
- \c paintedWidth or \c paintedHeight can be smaller or larger than
- \c width and \c height of the Image element.
-*/
-qreal QQuickImage::paintedWidth() const
-{
- Q_D(const QQuickImage);
- return d->paintedWidth;
-}
-
-qreal QQuickImage::paintedHeight() const
-{
- Q_D(const QQuickImage);
- return d->paintedHeight;
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Image::status
-
- This property holds the status of image loading. It can be one of:
- \list
- \o Image.Null - no image has been set
- \o Image.Ready - the image has been loaded
- \o Image.Loading - the image is currently being loaded
- \o Image.Error - an error occurred while loading the image
- \endlist
-
- Use this status to provide an update or respond to the status change in some way.
- For example, you could:
-
- \list
- \o Trigger a state change:
- \qml
- State { name: 'loaded'; when: image.status == Image.Ready }
- \endqml
-
- \o Implement an \c onStatusChanged signal handler:
- \qml
- Image {
- id: image
- onStatusChanged: if (image.status == Image.Ready) console.log('Loaded')
- }
- \endqml
-
- \o Bind to the status value:
- \qml
- Text { text: image.status == Image.Ready ? 'Loaded' : 'Not loaded' }
- \endqml
- \endlist
-
- \sa progress
-*/
-
-/*!
- \qmlproperty real QtQuick2::Image::progress
-
- This property holds the progress of image loading, from 0.0 (nothing loaded)
- to 1.0 (finished).
-
- \sa status
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Image::smooth
-
- Set this property if you want the image to be smoothly filtered when scaled or
- transformed. Smooth filtering gives better visual quality, but is slower. If
- the image is displayed at its natural size, this property has no visual or
- performance effect.
-
- \note Generally scaling artifacts are only visible if the image is stationary on
- the screen. A common pattern when animating an image is to disable smooth
- filtering at the beginning of the animation and reenable it at the conclusion.
-*/
-
-/*!
- \qmlproperty QSize QtQuick2::Image::sourceSize
-
- This property holds the actual width and height of the loaded image.
-
- Unlike the \l {Item::}{width} and \l {Item::}{height} properties, which scale
- the painting of the image, this property sets the actual number of pixels
- stored for the loaded image so that large images do not use more
- memory than necessary. For example, this ensures the image in memory is no
- larger than 1024x1024 pixels, regardless of the Image's \l {Item::}{width} and
- \l {Item::}{height} values:
-
- \code
- Rectangle {
- width: ...
- height: ...
-
- Image {
- anchors.fill: parent
- source: "reallyBigImage.jpg"
- sourceSize.width: 1024
- sourceSize.height: 1024
- }
- }
- \endcode
-
- If the image's actual size is larger than the sourceSize, the image is scaled down.
- If only one dimension of the size is set to greater than 0, the
- other dimension is set in proportion to preserve the source image's aspect ratio.
- (The \l fillMode is independent of this.)
-
- If the source is an intrinsically scalable image (eg. SVG), this property
- determines the size of the loaded image regardless of intrinsic size.
- Avoid changing this property dynamically; rendering an SVG is \e slow compared
- to an image.
-
- If the source is a non-scalable image (eg. JPEG), the loaded image will
- be no greater than this property specifies. For some formats (currently only JPEG),
- the whole image will never actually be loaded into memory.
-
- Since QtQuick 1.1 the sourceSize can be cleared to the natural size of the image
- by setting sourceSize to \c undefined.
-
- \note \e {Changing this property dynamically causes the image source to be reloaded,
- potentially even from the network, if it is not in the disk cache.}
-*/
-
-/*!
- \qmlproperty url QtQuick2::Image::source
-
- Image can handle any image format supported by Qt, loaded from any URL scheme supported by Qt.
-
- The URL may be absolute, or relative to the URL of the component.
-
- \sa QDeclarativeImageProvider
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Image::asynchronous
-
- Specifies that images on the local filesystem should be loaded
- asynchronously in a separate thread. The default value is
- false, causing the user interface thread to block while the
- image is loaded. Setting \a asynchronous to true is useful where
- maintaining a responsive user interface is more desirable
- than having images immediately visible.
-
- Note that this property is only valid for images read from the
- local filesystem. Images loaded via a network resource (e.g. HTTP)
- are always loaded asynchronously.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Image::cache
-
- Specifies whether the image should be cached. The default value is
- true. Setting \a cache to false is useful when dealing with large images,
- to make sure that they aren't cached at the expense of small 'ui element' images.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Image::mirror
-
- This property holds whether the image should be horizontally inverted
- (effectively displaying a mirrored image).
-
- The default value is false.
-*/
-
-/*!
- \qmlproperty enumeration QtQuick2::Image::horizontalAlignment
- \qmlproperty enumeration QtQuick2::Image::verticalAlignment
-
- Sets the horizontal and vertical alignment of the image. By default, the image is top-left aligned.
-
- The valid values for \c horizontalAlignment are \c Image.AlignLeft, \c Image.AlignRight and \c Image.AlignHCenter.
- The valid values for \c verticalAlignment are \c Image.AlignTop, \c Image.AlignBottom
- and \c Image.AlignVCenter.
-*/
-void QQuickImage::updatePaintedGeometry()
-{
- Q_D(QQuickImage);
-
- if (d->fillMode == PreserveAspectFit) {
- if (!d->pix.width() || !d->pix.height()) {
- setImplicitSize(0, 0);
- return;
- }
- qreal w = widthValid() ? width() : d->pix.width();
- qreal widthScale = w / qreal(d->pix.width());
- qreal h = heightValid() ? height() : d->pix.height();
- qreal heightScale = h / qreal(d->pix.height());
- if (widthScale <= heightScale) {
- d->paintedWidth = w;
- d->paintedHeight = widthScale * qreal(d->pix.height());
- } else if (heightScale < widthScale) {
- d->paintedWidth = heightScale * qreal(d->pix.width());
- d->paintedHeight = h;
- }
- qreal iHeight = (widthValid() && !heightValid()) ? d->paintedHeight : d->pix.height();
- qreal iWidth = (heightValid() && !widthValid()) ? d->paintedWidth : d->pix.width();
- setImplicitSize(iWidth, iHeight);
-
- } else if (d->fillMode == PreserveAspectCrop) {
- if (!d->pix.width() || !d->pix.height())
- return;
- qreal widthScale = width() / qreal(d->pix.width());
- qreal heightScale = height() / qreal(d->pix.height());
- if (widthScale < heightScale) {
- widthScale = heightScale;
- } else if (heightScale < widthScale) {
- heightScale = widthScale;
- }
-
- d->paintedHeight = heightScale * qreal(d->pix.height());
- d->paintedWidth = widthScale * qreal(d->pix.width());
- } else if (d->fillMode == Pad) {
- d->paintedWidth = d->pix.width();
- d->paintedHeight = d->pix.height();
- } else {
- d->paintedWidth = width();
- d->paintedHeight = height();
- }
- emit paintedGeometryChanged();
-}
-
-void QQuickImage::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- QQuickImageBase::geometryChanged(newGeometry, oldGeometry);
- updatePaintedGeometry();
-}
-
-QRectF QQuickImage::boundingRect() const
-{
- Q_D(const QQuickImage);
- return QRectF(0, 0, qMax(width(), d->paintedWidth), qMax(height(), d->paintedHeight));
-}
-
-QSGTextureProvider *QQuickImage::textureProvider() const
-{
- Q_D(const QQuickImage);
- if (!d->provider) {
- // Make sure it gets thread affinity on the rendering thread so deletion works properly..
- Q_ASSERT_X(d->canvas
- && d->sceneGraphContext()
- && QThread::currentThread() == d->sceneGraphContext()->thread(),
- "QQuickImage::textureProvider",
- "Cannot be used outside the GUI thread");
- QQuickImagePrivate *dd = const_cast<QQuickImagePrivate *>(d);
- dd->provider = new QQuickImageTextureProvider;
- dd->provider->m_smooth = d->smooth;
- dd->provider->m_texture = d->sceneGraphContext()->textureForFactory(d->pix.textureFactory());
- }
-
- return d->provider;
-}
-
-QSGNode *QQuickImage::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
-{
- Q_D(QQuickImage);
-
- QSGTexture *texture = d->sceneGraphContext()->textureForFactory(d->pix.textureFactory());
-
- // Copy over the current texture state into the texture provider...
- if (d->provider) {
- d->provider->m_smooth = d->smooth;
- d->provider->m_texture = texture;
- }
-
- if (!texture || width() <= 0 || height() <= 0) {
- delete oldNode;
- return 0;
- }
-
- QSGImageNode *node = static_cast<QSGImageNode *>(oldNode);
- if (!node) {
- d->pixmapChanged = true;
- node = d->sceneGraphContext()->createImageNode();
- node->setTexture(texture);
- }
-
- if (d->pixmapChanged) {
- // force update the texture in the node to trigger reconstruction of
- // geometry and the likes when a atlas segment has changed.
- node->setTexture(0);
- node->setTexture(texture);
- d->pixmapChanged = false;
- }
-
- QRectF targetRect;
- QRectF sourceRect;
- QSGTexture::WrapMode hWrap = QSGTexture::ClampToEdge;
- QSGTexture::WrapMode vWrap = QSGTexture::ClampToEdge;
-
- qreal pixWidth = (d->fillMode == PreserveAspectFit) ? d->paintedWidth : d->pix.width();
- qreal pixHeight = (d->fillMode == PreserveAspectFit) ? d->paintedHeight : d->pix.height();
-
- int xOffset = 0;
- if (d->hAlign == QQuickImage::AlignHCenter)
- xOffset = qCeil((width() - pixWidth) / 2.);
- else if (d->hAlign == QQuickImage::AlignRight)
- xOffset = qCeil(width() - pixWidth);
-
- int yOffset = 0;
- if (d->vAlign == QQuickImage::AlignVCenter)
- yOffset = qCeil((height() - pixHeight) / 2.);
- else if (d->vAlign == QQuickImage::AlignBottom)
- yOffset = qCeil(height() - pixHeight);
-
- switch (d->fillMode) {
- default:
- case Stretch:
- targetRect = QRectF(0, 0, width(), height());
- sourceRect = d->pix.rect();
- break;
-
- case PreserveAspectFit:
- targetRect = QRectF(xOffset, yOffset, d->paintedWidth, d->paintedHeight);
- sourceRect = d->pix.rect();
- break;
-
- case PreserveAspectCrop: {
- targetRect = QRect(0, 0, width(), height());
- qreal wscale = width() / qreal(d->pix.width());
- qreal hscale = height() / qreal(d->pix.height());
-
- if (wscale > hscale) {
- int src = (hscale / wscale) * qreal(d->pix.height());
- int y = 0;
- if (d->vAlign == QQuickImage::AlignVCenter)
- y = qCeil((d->pix.height() - src) / 2.);
- else if (d->vAlign == QQuickImage::AlignBottom)
- y = qCeil(d->pix.height() - src);
- sourceRect = QRectF(0, y, d->pix.width(), src);
-
- } else {
- int src = (wscale / hscale) * qreal(d->pix.width());
- int x = 0;
- if (d->hAlign == QQuickImage::AlignHCenter)
- x = qCeil((d->pix.width() - src) / 2.);
- else if (d->hAlign == QQuickImage::AlignRight)
- x = qCeil(d->pix.width() - src);
- sourceRect = QRectF(x, 0, src, d->pix.height());
- }
- }
- break;
-
- case Tile:
- targetRect = QRectF(0, 0, width(), height());
- sourceRect = QRectF(-xOffset, -yOffset, width(), height());
- hWrap = QSGTexture::Repeat;
- vWrap = QSGTexture::Repeat;
- break;
-
- case TileHorizontally:
- targetRect = QRectF(0, 0, width(), height());
- sourceRect = QRectF(-xOffset, 0, width(), d->pix.height());
- hWrap = QSGTexture::Repeat;
- break;
-
- case TileVertically:
- targetRect = QRectF(0, 0, width(), height());
- sourceRect = QRectF(0, -yOffset, d->pix.width(), height());
- vWrap = QSGTexture::Repeat;
- break;
-
- case Pad:
- qreal w = qMin(qreal(d->pix.width()), width());
- qreal h = qMin(qreal(d->pix.height()), height());
- qreal x = (d->pix.width() > width()) ? -xOffset : 0;
- qreal y = (d->pix.height() > height()) ? -yOffset : 0;
- targetRect = QRectF(x + xOffset, y + yOffset, w, h);
- sourceRect = QRectF(x, y, w, h);
- break;
- };
-
- QRectF nsrect(sourceRect.x() / d->pix.width(),
- sourceRect.y() / d->pix.height(),
- sourceRect.width() / d->pix.width(),
- sourceRect.height() / d->pix.height());
-
- if (d->mirror) {
- qreal oldLeft = nsrect.left();
- nsrect.setLeft(nsrect.right());
- nsrect.setRight(oldLeft);
- }
-
- node->setHorizontalWrapMode(hWrap);
- node->setVerticalWrapMode(vWrap);
- node->setFiltering(d->smooth ? QSGTexture::Linear : QSGTexture::Nearest);
-
- node->setTargetRect(targetRect);
- node->setSourceRect(nsrect);
- node->update();
-
- return node;
-}
-
-void QQuickImage::pixmapChange()
-{
- Q_D(QQuickImage);
- // PreserveAspectFit calculates the implicit size differently so we
- // don't call our superclass pixmapChange(), since that would
- // result in the implicit size being set incorrectly, then updated
- // in updatePaintedGeometry()
- if (d->fillMode != PreserveAspectFit)
- QQuickImageBase::pixmapChange();
- updatePaintedGeometry();
- d->pixmapChanged = true;
-
- // When the pixmap changes, such as being deleted, we need to update the textures
- update();
-}
-
-QQuickImage::VAlignment QQuickImage::verticalAlignment() const
-{
- Q_D(const QQuickImage);
- return d->vAlign;
-}
-
-void QQuickImage::setVerticalAlignment(VAlignment align)
-{
- Q_D(QQuickImage);
- if (d->vAlign == align)
- return;
-
- d->vAlign = align;
- update();
- updatePaintedGeometry();
- emit verticalAlignmentChanged(align);
-}
-
-QQuickImage::HAlignment QQuickImage::horizontalAlignment() const
-{
- Q_D(const QQuickImage);
- return d->hAlign;
-}
-
-void QQuickImage::setHorizontalAlignment(HAlignment align)
-{
- Q_D(QQuickImage);
- if (d->hAlign == align)
- return;
-
- d->hAlign = align;
- update();
- updatePaintedGeometry();
- emit horizontalAlignmentChanged(align);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickimage_p.h b/src/declarative/items/qquickimage_p.h
deleted file mode 100644
index 0d1c8dcba3..0000000000
--- a/src/declarative/items/qquickimage_p.h
+++ /dev/null
@@ -1,122 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKIMAGE_P_H
-#define QQUICKIMAGE_P_H
-
-#include "qquickimagebase_p.h"
-#include <private/qsgtextureprovider_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickImagePrivate;
-class Q_AUTOTEST_EXPORT QQuickImage : public QQuickImageBase
-{
- Q_OBJECT
- Q_ENUMS(FillMode)
- Q_ENUMS(HAlignment)
- Q_ENUMS(VAlignment)
-
- Q_PROPERTY(FillMode fillMode READ fillMode WRITE setFillMode NOTIFY fillModeChanged)
- Q_PROPERTY(qreal paintedWidth READ paintedWidth NOTIFY paintedGeometryChanged)
- Q_PROPERTY(qreal paintedHeight READ paintedHeight NOTIFY paintedGeometryChanged)
- Q_PROPERTY(HAlignment horizontalAlignment READ horizontalAlignment WRITE setHorizontalAlignment NOTIFY horizontalAlignmentChanged)
- Q_PROPERTY(VAlignment verticalAlignment READ verticalAlignment WRITE setVerticalAlignment NOTIFY verticalAlignmentChanged)
-
-public:
- QQuickImage(QQuickItem *parent=0);
- ~QQuickImage();
-
- enum HAlignment { AlignLeft = Qt::AlignLeft,
- AlignRight = Qt::AlignRight,
- AlignHCenter = Qt::AlignHCenter };
- enum VAlignment { AlignTop = Qt::AlignTop,
- AlignBottom = Qt::AlignBottom,
- AlignVCenter = Qt::AlignVCenter };
-
- enum FillMode { Stretch, PreserveAspectFit, PreserveAspectCrop, Tile, TileVertically, TileHorizontally, Pad };
-
- FillMode fillMode() const;
- void setFillMode(FillMode);
-
- qreal paintedWidth() const;
- qreal paintedHeight() const;
-
- QRectF boundingRect() const;
-
- HAlignment horizontalAlignment() const;
- void setHorizontalAlignment(HAlignment align);
-
- VAlignment verticalAlignment() const;
- void setVerticalAlignment(VAlignment align);
-
- bool isTextureProvider() const { return true; }
- QSGTextureProvider *textureProvider() const;
-
-Q_SIGNALS:
- void fillModeChanged();
- void paintedGeometryChanged();
- void horizontalAlignmentChanged(HAlignment alignment);
- void verticalAlignmentChanged(VAlignment alignment);
-
-protected:
- QQuickImage(QQuickImagePrivate &dd, QQuickItem *parent);
- void pixmapChange();
- void updatePaintedGeometry();
-
- virtual void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry);
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
-
-private:
- Q_DISABLE_COPY(QQuickImage)
- Q_DECLARE_PRIVATE(QQuickImage)
-};
-
-QT_END_NAMESPACE
-QML_DECLARE_TYPE(QQuickImage)
-QT_END_HEADER
-
-#endif // QQUICKIMAGE_P_H
diff --git a/src/declarative/items/qquickimage_p_p.h b/src/declarative/items/qquickimage_p_p.h
deleted file mode 100644
index 2077dfb0b3..0000000000
--- a/src/declarative/items/qquickimage_p_p.h
+++ /dev/null
@@ -1,85 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKIMAGE_P_P_H
-#define QQUICKIMAGE_P_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 "qquickimagebase_p_p.h"
-#include "qquickimage_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QQuickImageTextureProvider;
-
-class QQuickImagePrivate : public QQuickImageBasePrivate
-{
- Q_DECLARE_PUBLIC(QQuickImage)
-
-public:
- QQuickImagePrivate();
-
- QQuickImage::FillMode fillMode;
- qreal paintedWidth;
- qreal paintedHeight;
- void setImage(const QImage &img);
-
- bool pixmapChanged : 1;
- QQuickImage::HAlignment hAlign;
- QQuickImage::VAlignment vAlign;
-
- QQuickImageTextureProvider *provider;
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKIMAGE_P_P_H
diff --git a/src/declarative/items/qquickimagebase.cpp b/src/declarative/items/qquickimagebase.cpp
deleted file mode 100644
index d0e495eff5..0000000000
--- a/src/declarative/items/qquickimagebase.cpp
+++ /dev/null
@@ -1,290 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickimagebase_p.h"
-#include "qquickimagebase_p_p.h"
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-
-QT_BEGIN_NAMESPACE
-
-QQuickImageBase::QQuickImageBase(QQuickItem *parent)
-: QQuickImplicitSizeItem(*(new QQuickImageBasePrivate), parent)
-{
- setFlag(ItemHasContents);
-}
-
-QQuickImageBase::QQuickImageBase(QQuickImageBasePrivate &dd, QQuickItem *parent)
-: QQuickImplicitSizeItem(dd, parent)
-{
- setFlag(ItemHasContents);
-}
-
-QQuickImageBase::~QQuickImageBase()
-{
-}
-
-QQuickImageBase::Status QQuickImageBase::status() const
-{
- Q_D(const QQuickImageBase);
- return d->status;
-}
-
-
-qreal QQuickImageBase::progress() const
-{
- Q_D(const QQuickImageBase);
- return d->progress;
-}
-
-
-bool QQuickImageBase::asynchronous() const
-{
- Q_D(const QQuickImageBase);
- return d->async;
-}
-
-void QQuickImageBase::setAsynchronous(bool async)
-{
- Q_D(QQuickImageBase);
- if (d->async != async) {
- d->async = async;
- emit asynchronousChanged();
- }
-}
-
-QUrl QQuickImageBase::source() const
-{
- Q_D(const QQuickImageBase);
- return d->url;
-}
-
-void QQuickImageBase::setSource(const QUrl &url)
-{
- Q_D(QQuickImageBase);
- //equality is fairly expensive, so we bypass for simple, common case
- if ((d->url.isEmpty() == url.isEmpty()) && url == d->url)
- return;
-
- d->url = url;
- emit sourceChanged(d->url);
-
- if (isComponentComplete())
- load();
-}
-
-void QQuickImageBase::setSourceSize(const QSize& size)
-{
- Q_D(QQuickImageBase);
- if (d->sourcesize == size)
- return;
-
- d->sourcesize = size;
- d->explicitSourceSize = true;
- emit sourceSizeChanged();
- if (isComponentComplete())
- load();
-}
-
-QSize QQuickImageBase::sourceSize() const
-{
- Q_D(const QQuickImageBase);
-
- int width = d->sourcesize.width();
- int height = d->sourcesize.height();
- return QSize(width != -1 ? width : d->pix.width(), height != -1 ? height : d->pix.height());
-}
-
-void QQuickImageBase::resetSourceSize()
-{
- Q_D(QQuickImageBase);
- if (!d->explicitSourceSize)
- return;
- d->explicitSourceSize = false;
- d->sourcesize = QSize();
- emit sourceSizeChanged();
- if (isComponentComplete())
- load();
-}
-
-bool QQuickImageBase::cache() const
-{
- Q_D(const QQuickImageBase);
- return d->cache;
-}
-
-void QQuickImageBase::setCache(bool cache)
-{
- Q_D(QQuickImageBase);
- if (d->cache == cache)
- return;
-
- d->cache = cache;
- emit cacheChanged();
- if (isComponentComplete())
- load();
-}
-
-QImage QQuickImageBase::image() const
-{
- Q_D(const QQuickImageBase);
- return d->pix.image();
-}
-
-void QQuickImageBase::setMirror(bool mirror)
-{
- Q_D(QQuickImageBase);
- if (mirror == d->mirror)
- return;
-
- d->mirror = mirror;
-
- if (isComponentComplete())
- update();
-
- emit mirrorChanged();
-}
-
-bool QQuickImageBase::mirror() const
-{
- Q_D(const QQuickImageBase);
- return d->mirror;
-}
-
-void QQuickImageBase::load()
-{
- Q_D(QQuickImageBase);
-
- if (d->url.isEmpty()) {
- d->pix.clear(this);
- d->status = Null;
- d->progress = 0.0;
- pixmapChange();
- emit progressChanged(d->progress);
- emit statusChanged(d->status);
- update();
- } else {
- QDeclarativePixmap::Options options;
- if (d->async)
- options |= QDeclarativePixmap::Asynchronous;
- if (d->cache)
- options |= QDeclarativePixmap::Cache;
- d->pix.clear(this);
- pixmapChange();
- d->pix.load(qmlEngine(this), d->url, d->explicitSourceSize ? sourceSize() : QSize(), options);
-
- if (d->pix.isLoading()) {
- d->progress = 0.0;
- d->status = Loading;
- emit progressChanged(d->progress);
- emit statusChanged(d->status);
-
- static int thisRequestProgress = -1;
- static int thisRequestFinished = -1;
- if (thisRequestProgress == -1) {
- thisRequestProgress =
- QQuickImageBase::staticMetaObject.indexOfSlot("requestProgress(qint64,qint64)");
- thisRequestFinished =
- QQuickImageBase::staticMetaObject.indexOfSlot("requestFinished()");
- }
-
- d->pix.connectFinished(this, thisRequestFinished);
- d->pix.connectDownloadProgress(this, thisRequestProgress);
-
- } else {
- requestFinished();
- }
- }
-}
-
-void QQuickImageBase::requestFinished()
-{
- Q_D(QQuickImageBase);
-
- QQuickImageBase::Status oldStatus = d->status;
- qreal oldProgress = d->progress;
-
- if (d->pix.isError()) {
- d->status = Error;
- qmlInfo(this) << d->pix.error();
- } else {
- d->status = Ready;
- }
-
- d->progress = 1.0;
-
- pixmapChange();
-
- if (d->sourcesize.width() != d->pix.width() || d->sourcesize.height() != d->pix.height())
- emit sourceSizeChanged();
-
- if (d->status != oldStatus)
- emit statusChanged(d->status);
- if (d->progress != oldProgress)
- emit progressChanged(d->progress);
-
- update();
-}
-
-void QQuickImageBase::requestProgress(qint64 received, qint64 total)
-{
- Q_D(QQuickImageBase);
- if (d->status == Loading && total > 0) {
- d->progress = qreal(received)/total;
- emit progressChanged(d->progress);
- }
-}
-
-void QQuickImageBase::componentComplete()
-{
- Q_D(QQuickImageBase);
- QQuickItem::componentComplete();
- if (d->url.isValid())
- load();
-}
-
-void QQuickImageBase::pixmapChange()
-{
- Q_D(QQuickImageBase);
- setImplicitSize(d->pix.width(), d->pix.height());
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickimagebase_p.h b/src/declarative/items/qquickimagebase_p.h
deleted file mode 100644
index 51b5f088d4..0000000000
--- a/src/declarative/items/qquickimagebase_p.h
+++ /dev/null
@@ -1,119 +0,0 @@
-// Commit: af05f64d3edc860c3cf79c7f0bdf2377faae5f40
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKIMAGEBASE_P_H
-#define QQUICKIMAGEBASE_P_H
-
-#include "qquickimplicitsizeitem_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-class QQuickImageBasePrivate;
-class Q_AUTOTEST_EXPORT QQuickImageBase : public QQuickImplicitSizeItem
-{
- Q_OBJECT
- Q_ENUMS(Status)
-
- Q_PROPERTY(Status status READ status NOTIFY statusChanged)
- Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
- Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged)
- Q_PROPERTY(bool asynchronous READ asynchronous WRITE setAsynchronous NOTIFY asynchronousChanged)
- Q_PROPERTY(bool cache READ cache WRITE setCache NOTIFY cacheChanged)
- Q_PROPERTY(QSize sourceSize READ sourceSize WRITE setSourceSize RESET resetSourceSize NOTIFY sourceSizeChanged)
- Q_PROPERTY(bool mirror READ mirror WRITE setMirror NOTIFY mirrorChanged)
-
-public:
- QQuickImageBase(QQuickItem *parent=0);
- ~QQuickImageBase();
- enum Status { Null, Ready, Loading, Error };
- Status status() const;
- qreal progress() const;
-
- QUrl source() const;
- virtual void setSource(const QUrl &url);
-
- bool asynchronous() const;
- void setAsynchronous(bool);
-
- bool cache() const;
- void setCache(bool);
-
- QImage image() const;
-
- virtual void setSourceSize(const QSize&);
- QSize sourceSize() const;
- void resetSourceSize();
-
- virtual void setMirror(bool mirror);
- bool mirror() const;
-
-Q_SIGNALS:
- void sourceChanged(const QUrl &);
- void sourceSizeChanged();
- void statusChanged(QQuickImageBase::Status);
- void progressChanged(qreal progress);
- void asynchronousChanged();
- void cacheChanged();
- void mirrorChanged();
-
-protected:
- virtual void load();
- virtual void componentComplete();
- virtual void pixmapChange();
- QQuickImageBase(QQuickImageBasePrivate &dd, QQuickItem *parent);
-
-private Q_SLOTS:
- virtual void requestFinished();
- void requestProgress(qint64,qint64);
-
-private:
- Q_DISABLE_COPY(QQuickImageBase)
- Q_DECLARE_PRIVATE(QQuickImageBase)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKIMAGEBASE_P_H
diff --git a/src/declarative/items/qquickimagebase_p_p.h b/src/declarative/items/qquickimagebase_p_p.h
deleted file mode 100644
index 2347a82e92..0000000000
--- a/src/declarative/items/qquickimagebase_p_p.h
+++ /dev/null
@@ -1,93 +0,0 @@
-// Commit: 6f78a6080b84cc3ef96b73a4ff58d1b5a72f08f4
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKIMAGEBASE_P_P_H
-#define QQUICKIMAGEBASE_P_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 "qquickimplicitsizeitem_p_p.h"
-#include "qquickimagebase_p.h"
-
-#include <private/qdeclarativepixmapcache_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QNetworkReply;
-class QQuickImageBasePrivate : public QQuickImplicitSizeItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickImageBase)
-
-public:
- QQuickImageBasePrivate()
- : status(QQuickImageBase::Null),
- progress(0.0),
- explicitSourceSize(false),
- async(false),
- cache(true),
- mirror(false)
- {
- }
-
- QDeclarativePixmap pix;
- QQuickImageBase::Status status;
- QUrl url;
- qreal progress;
- QSize sourcesize;
- bool explicitSourceSize : 1;
- bool async : 1;
- bool cache : 1;
- bool mirror: 1;
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKIMAGEBASE_P_P_H
diff --git a/src/declarative/items/qquickimplicitsizeitem.cpp b/src/declarative/items/qquickimplicitsizeitem.cpp
deleted file mode 100644
index b0c5826349..0000000000
--- a/src/declarative/items/qquickimplicitsizeitem.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickimplicitsizeitem_p.h"
-#include "qquickimplicitsizeitem_p_p.h"
-
-QT_BEGIN_NAMESPACE
-
-void QQuickImplicitSizeItemPrivate::implicitWidthChanged()
-{
- Q_Q(QQuickImplicitSizeItem);
- emit q->implicitWidthChanged();
-}
-
-void QQuickImplicitSizeItemPrivate::implicitHeightChanged()
-{
- Q_Q(QQuickImplicitSizeItem);
- emit q->implicitHeightChanged();
-}
-
-QQuickImplicitSizeItem::QQuickImplicitSizeItem(QQuickImplicitSizeItemPrivate &dd, QQuickItem *parent)
- : QQuickItem(dd, parent)
-{
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickimplicitsizeitem_p.h b/src/declarative/items/qquickimplicitsizeitem_p.h
deleted file mode 100644
index 9ca98e1d60..0000000000
--- a/src/declarative/items/qquickimplicitsizeitem_p.h
+++ /dev/null
@@ -1,75 +0,0 @@
-// Commit: 6f78a6080b84cc3ef96b73a4ff58d1b5a72f08f4
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKIMPLICITSIZEITEM_H
-#define QQUICKIMPLICITSIZEITEM_H
-
-#include "qquickpainteditem.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-class QQuickImplicitSizeItemPrivate;
-class Q_AUTOTEST_EXPORT QQuickImplicitSizeItem : public QQuickItem
-{
- Q_OBJECT
- Q_PROPERTY(qreal implicitWidth READ implicitWidth NOTIFY implicitWidthChanged)
- Q_PROPERTY(qreal implicitHeight READ implicitHeight NOTIFY implicitHeightChanged)
-
-protected:
- QQuickImplicitSizeItem(QQuickImplicitSizeItemPrivate &dd, QQuickItem *parent);
-
-Q_SIGNALS:
- void implicitWidthChanged();
- void implicitHeightChanged();
-
-private:
- Q_DISABLE_COPY(QQuickImplicitSizeItem)
- Q_DECLARE_PRIVATE(QQuickImplicitSizeItem)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKIMPLICITSIZEITEM_H
diff --git a/src/declarative/items/qquickimplicitsizeitem_p_p.h b/src/declarative/items/qquickimplicitsizeitem_p_p.h
deleted file mode 100644
index 17c204d7c3..0000000000
--- a/src/declarative/items/qquickimplicitsizeitem_p_p.h
+++ /dev/null
@@ -1,78 +0,0 @@
-// Commit: 6f78a6080b84cc3ef96b73a4ff58d1b5a72f08f4
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKIMPLICITSIZEITEM_P_H
-#define QQUICKIMPLICITSIZEITEM_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 "qquickitem_p.h"
-#include "qquickpainteditem_p.h"
-#include "qquickimplicitsizeitem_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QQuickImplicitSizeItemPrivate : public QQuickItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickImplicitSizeItem)
-
-public:
- QQuickImplicitSizeItemPrivate()
- {
- }
-
- virtual void implicitWidthChanged();
- virtual void implicitHeightChanged();
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKIMPLICITSIZEITEM_P_H
diff --git a/src/declarative/items/qquickitem.cpp b/src/declarative/items/qquickitem.cpp
deleted file mode 100644
index 9c11196944..0000000000
--- a/src/declarative/items/qquickitem.cpp
+++ /dev/null
@@ -1,5236 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickitem.h"
-
-#include "qquickcanvas.h"
-#include <QtDeclarative/qjsengine.h>
-#include "qquickcanvas_p.h"
-
-#include "qquickevents_p_p.h"
-
-#include <QtDeclarative/qdeclarativeengine.h>
-#include <QtDeclarative/qdeclarativecomponent.h>
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtGui/qpen.h>
-#include <QtGui/qcursor.h>
-#include <QtGui/qguiapplication.h>
-#include <QtGui/qinputpanel.h>
-#include <QtCore/qdebug.h>
-#include <QtCore/qcoreevent.h>
-#include <QtCore/qnumeric.h>
-
-#include <private/qdeclarativeengine_p.h>
-#include <private/qdeclarativestategroup_p.h>
-#include <private/qdeclarativeopenmetaobject_p.h>
-#include <private/qdeclarativestate_p.h>
-#include <private/qlistmodelinterface_p.h>
-#include <private/qquickitem_p.h>
-
-#include <float.h>
-
-// XXX todo Readd parentNotifier for faster parent bindings
-// XXX todo Check that elements that create items handle memory correctly after visual ownership change
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass Transform QQuickTransform
- \inqmlmodule QtQuick 2
- \ingroup qml-transform-elements
- \brief The Transform elements provide a way of building advanced transformations on Items.
-
- The Transform element is a base type which cannot be instantiated directly.
- The following concrete Transform types are available:
-
- \list
- \o \l Rotation
- \o \l Scale
- \o \l Translate
- \endlist
-
- The Transform elements let you create and control advanced transformations that can be configured
- independently using specialized properties.
-
- You can assign any number of Transform elements to an \l Item. Each Transform is applied in order,
- one at a time.
-*/
-
-/*!
- \qmlclass Translate QQuickTranslate
- \inqmlmodule QtQuick 2
- \ingroup qml-transform-elements
- \brief The Translate object provides a way to move an Item without changing its x or y properties.
-
- The Translate object provides independent control over position in addition to the Item's x and y properties.
-
- The following example moves the Y axis of the \l Rectangle elements while still allowing the \l Row element
- to lay the items out as if they had not been transformed:
- \qml
- import QtQuick 1.0
-
- Row {
- Rectangle {
- width: 100; height: 100
- color: "blue"
- transform: Translate { y: 20 }
- }
- Rectangle {
- width: 100; height: 100
- color: "red"
- transform: Translate { y: -20 }
- }
- }
- \endqml
-
- \image translate.png
-*/
-
-/*!
- \qmlproperty real QtQuick2::Translate::x
-
- The translation along the X axis.
-*/
-
-/*!
- \qmlproperty real QtQuick2::Translate::y
-
- The translation along the Y axis.
-*/
-
-/*!
- \qmlclass Scale QQuickScale
- \inqmlmodule QtQuick 2
- \ingroup qml-transform-elements
- \brief The Scale element provides a way to scale an Item.
-
- The Scale element gives more control over scaling than using \l Item's \l{Item::scale}{scale} property. Specifically,
- it allows a different scale for the x and y axes, and allows the scale to be relative to an
- arbitrary point.
-
- The following example scales the X axis of the Rectangle, relative to its interior point 25, 25:
- \qml
- Rectangle {
- width: 100; height: 100
- color: "blue"
- transform: Scale { origin.x: 25; origin.y: 25; xScale: 3}
- }
- \endqml
-
- \sa Rotation, Translate
-*/
-
-/*!
- \qmlproperty real QtQuick2::Scale::origin.x
- \qmlproperty real QtQuick2::Scale::origin.y
-
- The point that the item is scaled from (i.e., the point that stays fixed relative to the parent as
- the rest of the item grows). By default the origin is 0, 0.
-*/
-
-/*!
- \qmlproperty real QtQuick2::Scale::xScale
-
- The scaling factor for the X axis.
-*/
-
-/*!
- \qmlproperty real QtQuick2::Scale::yScale
-
- The scaling factor for the Y axis.
-*/
-
-/*!
- \qmlclass Rotation QQuickRotation
- \inqmlmodule QtQuick 2
- \ingroup qml-transform-elements
- \brief The Rotation object provides a way to rotate an Item.
-
- The Rotation object gives more control over rotation than using \l Item's \l{Item::rotation}{rotation} property.
- Specifically, it allows (z axis) rotation to be relative to an arbitrary point.
-
- The following example rotates a Rectangle around its interior point 25, 25:
- \qml
- Rectangle {
- width: 100; height: 100
- color: "blue"
- transform: Rotation { origin.x: 25; origin.y: 25; angle: 45}
- }
- \endqml
-
- Rotation also provides a way to specify 3D-like rotations for Items. For these types of
- rotations you must specify the axis to rotate around in addition to the origin point.
-
- The following example shows various 3D-like rotations applied to an \l Image.
- \snippet doc/src/snippets/declarative/rotation.qml 0
-
- \image axisrotation.png
-
- \sa {declarative/ui-components/dialcontrol}{Dial Control example}, {declarative/toys/clocks}{Clocks example}
-*/
-
-/*!
- \qmlproperty real QtQuick2::Rotation::origin.x
- \qmlproperty real QtQuick2::Rotation::origin.y
-
- The origin point of the rotation (i.e., the point that stays fixed relative to the parent as
- the rest of the item rotates). By default the origin is 0, 0.
-*/
-
-/*!
- \qmlproperty real QtQuick2::Rotation::axis.x
- \qmlproperty real QtQuick2::Rotation::axis.y
- \qmlproperty real QtQuick2::Rotation::axis.z
-
- The axis to rotate around. For simple (2D) rotation around a point, you do not need to specify an axis,
- as the default axis is the z axis (\c{ axis { x: 0; y: 0; z: 1 } }).
-
- For a typical 3D-like rotation you will usually specify both the origin and the axis.
-
- \image 3d-rotation-axis.png
-*/
-
-/*!
- \qmlproperty real QtQuick2::Rotation::angle
-
- The angle to rotate, in degrees clockwise.
-*/
-
-QQuickTransformPrivate::QQuickTransformPrivate()
-{
-}
-
-QQuickTransform::QQuickTransform(QObject *parent)
-: QObject(*(new QQuickTransformPrivate), parent)
-{
-}
-
-QQuickTransform::QQuickTransform(QQuickTransformPrivate &dd, QObject *parent)
-: QObject(dd, parent)
-{
-}
-
-QQuickTransform::~QQuickTransform()
-{
- Q_D(QQuickTransform);
- for (int ii = 0; ii < d->items.count(); ++ii) {
- QQuickItemPrivate *p = QQuickItemPrivate::get(d->items.at(ii));
- p->transforms.removeOne(this);
- p->dirty(QQuickItemPrivate::Transform);
- }
-}
-
-void QQuickTransform::update()
-{
- Q_D(QQuickTransform);
- for (int ii = 0; ii < d->items.count(); ++ii) {
- QQuickItemPrivate *p = QQuickItemPrivate::get(d->items.at(ii));
- p->dirty(QQuickItemPrivate::Transform);
- }
-}
-
-QQuickContents::QQuickContents(QQuickItem *item)
-: m_item(item), m_x(0), m_y(0), m_width(0), m_height(0)
-{
-}
-
-QQuickContents::~QQuickContents()
-{
- QList<QQuickItem *> children = m_item->childItems();
- for (int i = 0; i < children.count(); ++i) {
- QQuickItem *child = children.at(i);
- QQuickItemPrivate::get(child)->removeItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
- }
-}
-
-bool QQuickContents::calcHeight(QQuickItem *changed)
-{
- qreal oldy = m_y;
- qreal oldheight = m_height;
-
- if (changed) {
- qreal top = oldy;
- qreal bottom = oldy + oldheight;
- qreal y = changed->y();
- if (y + changed->height() > bottom)
- bottom = y + changed->height();
- if (y < top)
- top = y;
- m_y = top;
- m_height = bottom - top;
- } else {
- qreal top = FLT_MAX;
- qreal bottom = 0;
- QList<QQuickItem *> children = m_item->childItems();
- for (int i = 0; i < children.count(); ++i) {
- QQuickItem *child = children.at(i);
- qreal y = child->y();
- if (y + child->height() > bottom)
- bottom = y + child->height();
- if (y < top)
- top = y;
- }
- if (!children.isEmpty())
- m_y = top;
- m_height = qMax(bottom - top, qreal(0.0));
- }
-
- return (m_height != oldheight || m_y != oldy);
-}
-
-bool QQuickContents::calcWidth(QQuickItem *changed)
-{
- qreal oldx = m_x;
- qreal oldwidth = m_width;
-
- if (changed) {
- qreal left = oldx;
- qreal right = oldx + oldwidth;
- qreal x = changed->x();
- if (x + changed->width() > right)
- right = x + changed->width();
- if (x < left)
- left = x;
- m_x = left;
- m_width = right - left;
- } else {
- qreal left = FLT_MAX;
- qreal right = 0;
- QList<QQuickItem *> children = m_item->childItems();
- for (int i = 0; i < children.count(); ++i) {
- QQuickItem *child = children.at(i);
- qreal x = child->x();
- if (x + child->width() > right)
- right = x + child->width();
- if (x < left)
- left = x;
- }
- if (!children.isEmpty())
- m_x = left;
- m_width = qMax(right - left, qreal(0.0));
- }
-
- return (m_width != oldwidth || m_x != oldx);
-}
-
-void QQuickContents::complete()
-{
- QQuickItemPrivate::get(m_item)->addItemChangeListener(this, QQuickItemPrivate::Children);
-
- QList<QQuickItem *> children = m_item->childItems();
- for (int i = 0; i < children.count(); ++i) {
- QQuickItem *child = children.at(i);
- QQuickItemPrivate::get(child)->addItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
- //###what about changes to visibility?
- }
- calcGeometry();
-}
-
-void QQuickContents::updateRect()
-{
- QQuickItemPrivate::get(m_item)->emitChildrenRectChanged(rectF());
-}
-
-void QQuickContents::itemGeometryChanged(QQuickItem *changed, const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_UNUSED(changed)
- bool wChanged = false;
- bool hChanged = false;
- //### we can only pass changed if the left edge has moved left, or the right edge has moved right
- if (newGeometry.width() != oldGeometry.width() || newGeometry.x() != oldGeometry.x())
- wChanged = calcWidth(/*changed*/);
- if (newGeometry.height() != oldGeometry.height() || newGeometry.y() != oldGeometry.y())
- hChanged = calcHeight(/*changed*/);
- if (wChanged || hChanged)
- updateRect();
-}
-
-void QQuickContents::itemDestroyed(QQuickItem *item)
-{
- if (item)
- QQuickItemPrivate::get(item)->removeItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
- calcGeometry();
-}
-
-void QQuickContents::itemChildRemoved(QQuickItem *, QQuickItem *item)
-{
- if (item)
- QQuickItemPrivate::get(item)->removeItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
- calcGeometry();
-}
-
-void QQuickContents::itemChildAdded(QQuickItem *, QQuickItem *item)
-{
- if (item)
- QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
- calcGeometry(item);
-}
-
-QQuickItemKeyFilter::QQuickItemKeyFilter(QQuickItem *item)
-: m_processPost(false), m_next(0)
-{
- QQuickItemPrivate *p = item?QQuickItemPrivate::get(item):0;
- if (p) {
- m_next = p->keyHandler;
- p->keyHandler = this;
- }
-}
-
-QQuickItemKeyFilter::~QQuickItemKeyFilter()
-{
-}
-
-void QQuickItemKeyFilter::keyPressed(QKeyEvent *event, bool post)
-{
- if (m_next) m_next->keyPressed(event, post);
-}
-
-void QQuickItemKeyFilter::keyReleased(QKeyEvent *event, bool post)
-{
- if (m_next) m_next->keyReleased(event, post);
-}
-
-void QQuickItemKeyFilter::inputMethodEvent(QInputMethodEvent *event, bool post)
-{
- if (m_next)
- m_next->inputMethodEvent(event, post);
- else
- event->ignore();
-}
-
-QVariant QQuickItemKeyFilter::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- if (m_next) return m_next->inputMethodQuery(query);
- return QVariant();
-}
-
-void QQuickItemKeyFilter::componentComplete()
-{
- if (m_next) m_next->componentComplete();
-}
-/*!
- \qmlclass KeyNavigation QQuickKeyNavigationAttached
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-interaction-elements
- \brief The KeyNavigation attached property supports key navigation by arrow keys.
-
- Key-based user interfaces commonly allow the use of arrow keys to navigate between
- focusable items. The KeyNavigation attached property enables this behavior by providing a
- convenient way to specify the item that should gain focus when an arrow or tab key is pressed.
-
- The following example provides key navigation for a 2x2 grid of items:
-
- \snippet doc/src/snippets/declarative/keynavigation.qml 0
-
- The top-left item initially receives focus by setting \l {Item::}{focus} to
- \c true. When an arrow key is pressed, the focus will move to the
- appropriate item, as defined by the value that has been set for
- the KeyNavigation \l left, \l right, \l up or \l down properties.
-
- Note that if a KeyNavigation attached property receives the key press and release
- events for a requested arrow or tab key, the event is accepted and does not
- propagate any further.
-
- By default, KeyNavigation receives key events after the item to which it is attached.
- If the item accepts the key event, the KeyNavigation attached property will not
- receive an event for that key. Setting the \l priority property to
- \c KeyNavigation.BeforeItem allows the event to be used for key navigation
- before the item, rather than after.
-
- If item to which the focus is switching is not enabled or visible, an attempt will
- be made to skip this item and focus on the next. This is possible if there are
- a chain of items with the same KeyNavigation handler. If multiple items in a row are not enabled
- or visible, they will also be skipped.
-
- KeyNavigation will implicitly set the other direction to return focus to this item. So if you set
- \l left to another item, \l right will be set on that item's KeyNavigation to set focus back to this
- item. However, if that item's KeyNavigation has had right explicitly set then no change will occur.
- This means that the above example could have been written, with the same behaviour, without specifing
- KeyNavigation.right or KeyNavigation.down for any of the items.
-
- \sa {Keys}{Keys attached property}
-*/
-
-/*!
- \qmlproperty Item QtQuick2::KeyNavigation::left
- \qmlproperty Item QtQuick2::KeyNavigation::right
- \qmlproperty Item QtQuick2::KeyNavigation::up
- \qmlproperty Item QtQuick2::KeyNavigation::down
- \qmlproperty Item QtQuick2::KeyNavigation::tab
- \qmlproperty Item QtQuick2::KeyNavigation::backtab
-
- These properties hold the item to assign focus to
- when the left, right, up or down cursor keys, or the
- tab key are pressed.
-*/
-
-/*!
- \qmlproperty Item QtQuick2::KeyNavigation::tab
- \qmlproperty Item QtQuick2::KeyNavigation::backtab
-
- These properties hold the item to assign focus to
- when the Tab key or Shift+Tab key combination (Backtab) are pressed.
-*/
-
-QQuickKeyNavigationAttached::QQuickKeyNavigationAttached(QObject *parent)
-: QObject(*(new QQuickKeyNavigationAttachedPrivate), parent),
- QQuickItemKeyFilter(qobject_cast<QQuickItem*>(parent))
-{
- m_processPost = true;
-}
-
-QQuickKeyNavigationAttached *
-QQuickKeyNavigationAttached::qmlAttachedProperties(QObject *obj)
-{
- return new QQuickKeyNavigationAttached(obj);
-}
-
-QQuickItem *QQuickKeyNavigationAttached::left() const
-{
- Q_D(const QQuickKeyNavigationAttached);
- return d->left;
-}
-
-void QQuickKeyNavigationAttached::setLeft(QQuickItem *i)
-{
- Q_D(QQuickKeyNavigationAttached);
- if (d->left == i)
- return;
- d->left = i;
- d->leftSet = true;
- QQuickKeyNavigationAttached* other =
- qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
- if (other && !other->d_func()->rightSet){
- other->d_func()->right = qobject_cast<QQuickItem*>(parent());
- emit other->rightChanged();
- }
- emit leftChanged();
-}
-
-QQuickItem *QQuickKeyNavigationAttached::right() const
-{
- Q_D(const QQuickKeyNavigationAttached);
- return d->right;
-}
-
-void QQuickKeyNavigationAttached::setRight(QQuickItem *i)
-{
- Q_D(QQuickKeyNavigationAttached);
- if (d->right == i)
- return;
- d->right = i;
- d->rightSet = true;
- QQuickKeyNavigationAttached* other =
- qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
- if (other && !other->d_func()->leftSet){
- other->d_func()->left = qobject_cast<QQuickItem*>(parent());
- emit other->leftChanged();
- }
- emit rightChanged();
-}
-
-QQuickItem *QQuickKeyNavigationAttached::up() const
-{
- Q_D(const QQuickKeyNavigationAttached);
- return d->up;
-}
-
-void QQuickKeyNavigationAttached::setUp(QQuickItem *i)
-{
- Q_D(QQuickKeyNavigationAttached);
- if (d->up == i)
- return;
- d->up = i;
- d->upSet = true;
- QQuickKeyNavigationAttached* other =
- qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
- if (other && !other->d_func()->downSet){
- other->d_func()->down = qobject_cast<QQuickItem*>(parent());
- emit other->downChanged();
- }
- emit upChanged();
-}
-
-QQuickItem *QQuickKeyNavigationAttached::down() const
-{
- Q_D(const QQuickKeyNavigationAttached);
- return d->down;
-}
-
-void QQuickKeyNavigationAttached::setDown(QQuickItem *i)
-{
- Q_D(QQuickKeyNavigationAttached);
- if (d->down == i)
- return;
- d->down = i;
- d->downSet = true;
- QQuickKeyNavigationAttached* other =
- qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
- if (other && !other->d_func()->upSet) {
- other->d_func()->up = qobject_cast<QQuickItem*>(parent());
- emit other->upChanged();
- }
- emit downChanged();
-}
-
-QQuickItem *QQuickKeyNavigationAttached::tab() const
-{
- Q_D(const QQuickKeyNavigationAttached);
- return d->tab;
-}
-
-void QQuickKeyNavigationAttached::setTab(QQuickItem *i)
-{
- Q_D(QQuickKeyNavigationAttached);
- if (d->tab == i)
- return;
- d->tab = i;
- d->tabSet = true;
- QQuickKeyNavigationAttached* other =
- qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
- if (other && !other->d_func()->backtabSet) {
- other->d_func()->backtab = qobject_cast<QQuickItem*>(parent());
- emit other->backtabChanged();
- }
- emit tabChanged();
-}
-
-QQuickItem *QQuickKeyNavigationAttached::backtab() const
-{
- Q_D(const QQuickKeyNavigationAttached);
- return d->backtab;
-}
-
-void QQuickKeyNavigationAttached::setBacktab(QQuickItem *i)
-{
- Q_D(QQuickKeyNavigationAttached);
- if (d->backtab == i)
- return;
- d->backtab = i;
- d->backtabSet = true;
- QQuickKeyNavigationAttached* other =
- qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
- if (other && !other->d_func()->tabSet) {
- other->d_func()->tab = qobject_cast<QQuickItem*>(parent());
- emit other->tabChanged();
- }
- emit backtabChanged();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::KeyNavigation::priority
-
- This property determines whether the keys are processed before
- or after the attached item's own key handling.
-
- \list
- \o KeyNavigation.BeforeItem - process the key events before normal
- item key processing. If the event is used for key navigation, it will be accepted and will not
- be passed on to the item.
- \o KeyNavigation.AfterItem (default) - process the key events after normal item key
- handling. If the item accepts the key event it will not be
- handled by the KeyNavigation attached property handler.
- \endlist
-*/
-QQuickKeyNavigationAttached::Priority QQuickKeyNavigationAttached::priority() const
-{
- return m_processPost ? AfterItem : BeforeItem;
-}
-
-void QQuickKeyNavigationAttached::setPriority(Priority order)
-{
- bool processPost = order == AfterItem;
- if (processPost != m_processPost) {
- m_processPost = processPost;
- emit priorityChanged();
- }
-}
-
-void QQuickKeyNavigationAttached::keyPressed(QKeyEvent *event, bool post)
-{
- Q_D(QQuickKeyNavigationAttached);
- event->ignore();
-
- if (post != m_processPost) {
- QQuickItemKeyFilter::keyPressed(event, post);
- return;
- }
-
- bool mirror = false;
- switch (event->key()) {
- case Qt::Key_Left: {
- if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
- mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
- QQuickItem* leftItem = mirror ? d->right : d->left;
- if (leftItem) {
- setFocusNavigation(leftItem, mirror ? "right" : "left");
- event->accept();
- }
- break;
- }
- case Qt::Key_Right: {
- if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
- mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
- QQuickItem* rightItem = mirror ? d->left : d->right;
- if (rightItem) {
- setFocusNavigation(rightItem, mirror ? "left" : "right");
- event->accept();
- }
- break;
- }
- case Qt::Key_Up:
- if (d->up) {
- setFocusNavigation(d->up, "up");
- event->accept();
- }
- break;
- case Qt::Key_Down:
- if (d->down) {
- setFocusNavigation(d->down, "down");
- event->accept();
- }
- break;
- case Qt::Key_Tab:
- if (d->tab) {
- setFocusNavigation(d->tab, "tab");
- event->accept();
- }
- break;
- case Qt::Key_Backtab:
- if (d->backtab) {
- setFocusNavigation(d->backtab, "backtab");
- event->accept();
- }
- break;
- default:
- break;
- }
-
- if (!event->isAccepted()) QQuickItemKeyFilter::keyPressed(event, post);
-}
-
-void QQuickKeyNavigationAttached::keyReleased(QKeyEvent *event, bool post)
-{
- Q_D(QQuickKeyNavigationAttached);
- event->ignore();
-
- if (post != m_processPost) {
- QQuickItemKeyFilter::keyReleased(event, post);
- return;
- }
-
- bool mirror = false;
- switch (event->key()) {
- case Qt::Key_Left:
- if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
- mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
- if (mirror ? d->right : d->left)
- event->accept();
- break;
- case Qt::Key_Right:
- if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
- mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
- if (mirror ? d->left : d->right)
- event->accept();
- break;
- case Qt::Key_Up:
- if (d->up) {
- event->accept();
- }
- break;
- case Qt::Key_Down:
- if (d->down) {
- event->accept();
- }
- break;
- case Qt::Key_Tab:
- if (d->tab) {
- event->accept();
- }
- break;
- case Qt::Key_Backtab:
- if (d->backtab) {
- event->accept();
- }
- break;
- default:
- break;
- }
-
- if (!event->isAccepted()) QQuickItemKeyFilter::keyReleased(event, post);
-}
-
-void QQuickKeyNavigationAttached::setFocusNavigation(QQuickItem *currentItem, const char *dir)
-{
- QQuickItem *initialItem = currentItem;
- bool isNextItem = false;
- do {
- isNextItem = false;
- if (currentItem->isVisible() && currentItem->isEnabled()) {
- currentItem->setFocus(true);
- } else {
- QObject *attached =
- qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(currentItem, false);
- if (attached) {
- QQuickItem *tempItem = qvariant_cast<QQuickItem*>(attached->property(dir));
- if (tempItem) {
- currentItem = tempItem;
- isNextItem = true;
- }
- }
- }
- }
- while (currentItem != initialItem && isNextItem);
-}
-
-const QQuickKeysAttached::SigMap QQuickKeysAttached::sigMap[] = {
- { Qt::Key_Left, "leftPressed" },
- { Qt::Key_Right, "rightPressed" },
- { Qt::Key_Up, "upPressed" },
- { Qt::Key_Down, "downPressed" },
- { Qt::Key_Tab, "tabPressed" },
- { Qt::Key_Backtab, "backtabPressed" },
- { Qt::Key_Asterisk, "asteriskPressed" },
- { Qt::Key_NumberSign, "numberSignPressed" },
- { Qt::Key_Escape, "escapePressed" },
- { Qt::Key_Return, "returnPressed" },
- { Qt::Key_Enter, "enterPressed" },
- { Qt::Key_Delete, "deletePressed" },
- { Qt::Key_Space, "spacePressed" },
- { Qt::Key_Back, "backPressed" },
- { Qt::Key_Cancel, "cancelPressed" },
- { Qt::Key_Select, "selectPressed" },
- { Qt::Key_Yes, "yesPressed" },
- { Qt::Key_No, "noPressed" },
- { Qt::Key_Context1, "context1Pressed" },
- { Qt::Key_Context2, "context2Pressed" },
- { Qt::Key_Context3, "context3Pressed" },
- { Qt::Key_Context4, "context4Pressed" },
- { Qt::Key_Call, "callPressed" },
- { Qt::Key_Hangup, "hangupPressed" },
- { Qt::Key_Flip, "flipPressed" },
- { Qt::Key_Menu, "menuPressed" },
- { Qt::Key_VolumeUp, "volumeUpPressed" },
- { Qt::Key_VolumeDown, "volumeDownPressed" },
- { 0, 0 }
-};
-
-bool QQuickKeysAttachedPrivate::isConnected(const char *signalName)
-{
- return isSignalConnected(signalIndex(signalName));
-}
-
-/*!
- \qmlclass Keys QQuickKeysAttached
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-interaction-elements
- \brief The Keys attached property provides key handling to Items.
-
- All visual primitives support key handling via the Keys
- attached property. Keys can be handled via the onPressed
- and onReleased signal properties.
-
- The signal properties have a \l KeyEvent parameter, named
- \e event which contains details of the event. If a key is
- handled \e event.accepted should be set to true to prevent the
- event from propagating up the item hierarchy.
-
- \section1 Example Usage
-
- The following example shows how the general onPressed handler can
- be used to test for a certain key; in this case, the left cursor
- key:
-
- \snippet doc/src/snippets/declarative/keys/keys-pressed.qml key item
-
- Some keys may alternatively be handled via specific signal properties,
- for example \e onSelectPressed. These handlers automatically set
- \e event.accepted to true.
-
- \snippet doc/src/snippets/declarative/keys/keys-handler.qml key item
-
- See \l{Qt::Key}{Qt.Key} for the list of keyboard codes.
-
- \section1 Key Handling Priorities
-
- The Keys attached property can be configured to handle key events
- before or after the item it is attached to. This makes it possible
- to intercept events in order to override an item's default behavior,
- or act as a fallback for keys not handled by the item.
-
- If \l priority is Keys.BeforeItem (default) the order of key event processing is:
-
- \list 1
- \o Items specified in \c forwardTo
- \o specific key handlers, e.g. onReturnPressed
- \o onKeyPress, onKeyRelease handlers
- \o Item specific key handling, e.g. TextInput key handling
- \o parent item
- \endlist
-
- If priority is Keys.AfterItem the order of key event processing is:
-
- \list 1
- \o Item specific key handling, e.g. TextInput key handling
- \o Items specified in \c forwardTo
- \o specific key handlers, e.g. onReturnPressed
- \o onKeyPress, onKeyRelease handlers
- \o parent item
- \endlist
-
- If the event is accepted during any of the above steps, key
- propagation stops.
-
- \sa KeyEvent, {KeyNavigation}{KeyNavigation attached property}
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Keys::enabled
-
- This flags enables key handling if true (default); otherwise
- no key handlers will be called.
-*/
-
-/*!
- \qmlproperty enumeration QtQuick2::Keys::priority
-
- This property determines whether the keys are processed before
- or after the attached item's own key handling.
-
- \list
- \o Keys.BeforeItem (default) - process the key events before normal
- item key processing. If the event is accepted it will not
- be passed on to the item.
- \o Keys.AfterItem - process the key events after normal item key
- handling. If the item accepts the key event it will not be
- handled by the Keys attached property handler.
- \endlist
-*/
-
-/*!
- \qmlproperty list<Object> QtQuick2::Keys::forwardTo
-
- This property provides a way to forward key presses, key releases, and keyboard input
- coming from input methods to other items. This can be useful when you want
- one item to handle some keys (e.g. the up and down arrow keys), and another item to
- handle other keys (e.g. the left and right arrow keys). Once an item that has been
- forwarded keys accepts the event it is no longer forwarded to items later in the
- list.
-
- This example forwards key events to two lists:
- \qml
- Item {
- ListView {
- id: list1
- // ...
- }
- ListView {
- id: list2
- // ...
- }
- Keys.forwardTo: [list1, list2]
- focus: true
- }
- \endqml
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onPressed(KeyEvent event)
-
- This handler is called when a key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onReleased(KeyEvent event)
-
- This handler is called when a key has been released. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDigit0Pressed(KeyEvent event)
-
- This handler is called when the digit '0' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDigit1Pressed(KeyEvent event)
-
- This handler is called when the digit '1' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDigit2Pressed(KeyEvent event)
-
- This handler is called when the digit '2' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDigit3Pressed(KeyEvent event)
-
- This handler is called when the digit '3' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDigit4Pressed(KeyEvent event)
-
- This handler is called when the digit '4' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDigit5Pressed(KeyEvent event)
-
- This handler is called when the digit '5' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDigit6Pressed(KeyEvent event)
-
- This handler is called when the digit '6' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDigit7Pressed(KeyEvent event)
-
- This handler is called when the digit '7' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDigit8Pressed(KeyEvent event)
-
- This handler is called when the digit '8' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDigit9Pressed(KeyEvent event)
-
- This handler is called when the digit '9' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onLeftPressed(KeyEvent event)
-
- This handler is called when the Left arrow has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onRightPressed(KeyEvent event)
-
- This handler is called when the Right arrow has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onUpPressed(KeyEvent event)
-
- This handler is called when the Up arrow has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDownPressed(KeyEvent event)
-
- This handler is called when the Down arrow has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onTabPressed(KeyEvent event)
-
- This handler is called when the Tab key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onBacktabPressed(KeyEvent event)
-
- This handler is called when the Shift+Tab key combination (Backtab) has
- been pressed. The \a event parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onAsteriskPressed(KeyEvent event)
-
- This handler is called when the Asterisk '*' has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onEscapePressed(KeyEvent event)
-
- This handler is called when the Escape key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onReturnPressed(KeyEvent event)
-
- This handler is called when the Return key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onEnterPressed(KeyEvent event)
-
- This handler is called when the Enter key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onDeletePressed(KeyEvent event)
-
- This handler is called when the Delete key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onSpacePressed(KeyEvent event)
-
- This handler is called when the Space key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onBackPressed(KeyEvent event)
-
- This handler is called when the Back key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onCancelPressed(KeyEvent event)
-
- This handler is called when the Cancel key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onSelectPressed(KeyEvent event)
-
- This handler is called when the Select key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onYesPressed(KeyEvent event)
-
- This handler is called when the Yes key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onNoPressed(KeyEvent event)
-
- This handler is called when the No key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onContext1Pressed(KeyEvent event)
-
- This handler is called when the Context1 key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onContext2Pressed(KeyEvent event)
-
- This handler is called when the Context2 key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onContext3Pressed(KeyEvent event)
-
- This handler is called when the Context3 key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onContext4Pressed(KeyEvent event)
-
- This handler is called when the Context4 key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onCallPressed(KeyEvent event)
-
- This handler is called when the Call key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onHangupPressed(KeyEvent event)
-
- This handler is called when the Hangup key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onFlipPressed(KeyEvent event)
-
- This handler is called when the Flip key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onMenuPressed(KeyEvent event)
-
- This handler is called when the Menu key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onVolumeUpPressed(KeyEvent event)
-
- This handler is called when the VolumeUp key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-/*!
- \qmlsignal QtQuick2::Keys::onVolumeDownPressed(KeyEvent event)
-
- This handler is called when the VolumeDown key has been pressed. The \a event
- parameter provides information about the event.
-*/
-
-QQuickKeysAttached::QQuickKeysAttached(QObject *parent)
-: QObject(*(new QQuickKeysAttachedPrivate), parent),
- QQuickItemKeyFilter(qobject_cast<QQuickItem*>(parent))
-{
- Q_D(QQuickKeysAttached);
- m_processPost = false;
- d->item = qobject_cast<QQuickItem*>(parent);
-}
-
-QQuickKeysAttached::~QQuickKeysAttached()
-{
-}
-
-QQuickKeysAttached::Priority QQuickKeysAttached::priority() const
-{
- return m_processPost ? AfterItem : BeforeItem;
-}
-
-void QQuickKeysAttached::setPriority(Priority order)
-{
- bool processPost = order == AfterItem;
- if (processPost != m_processPost) {
- m_processPost = processPost;
- emit priorityChanged();
- }
-}
-
-void QQuickKeysAttached::componentComplete()
-{
- Q_D(QQuickKeysAttached);
- if (d->item) {
- for (int ii = 0; ii < d->targets.count(); ++ii) {
- QQuickItem *targetItem = d->targets.at(ii);
- if (targetItem && (targetItem->flags() & QQuickItem::ItemAcceptsInputMethod)) {
- d->item->setFlag(QQuickItem::ItemAcceptsInputMethod);
- break;
- }
- }
- }
-}
-
-void QQuickKeysAttached::keyPressed(QKeyEvent *event, bool post)
-{
- Q_D(QQuickKeysAttached);
- if (post != m_processPost || !d->enabled || d->inPress) {
- event->ignore();
- QQuickItemKeyFilter::keyPressed(event, post);
- return;
- }
-
- // first process forwards
- if (d->item && d->item->canvas()) {
- d->inPress = true;
- for (int ii = 0; ii < d->targets.count(); ++ii) {
- QQuickItem *i = d->targets.at(ii);
- if (i && i->isVisible()) {
- d->item->canvas()->sendEvent(i, event);
- if (event->isAccepted()) {
- d->inPress = false;
- return;
- }
- }
- }
- d->inPress = false;
- }
-
- QQuickKeyEvent ke(*event);
- QByteArray keySignal = keyToSignal(event->key());
- if (!keySignal.isEmpty()) {
- keySignal += "(QQuickKeyEvent*)";
- if (d->isConnected(keySignal)) {
- // If we specifically handle a key then default to accepted
- ke.setAccepted(true);
- int idx = QQuickKeysAttached::staticMetaObject.indexOfSignal(keySignal);
- metaObject()->method(idx).invoke(this, Qt::DirectConnection, Q_ARG(QQuickKeyEvent*, &ke));
- }
- }
- if (!ke.isAccepted())
- emit pressed(&ke);
- event->setAccepted(ke.isAccepted());
-
- if (!event->isAccepted()) QQuickItemKeyFilter::keyPressed(event, post);
-}
-
-void QQuickKeysAttached::keyReleased(QKeyEvent *event, bool post)
-{
- Q_D(QQuickKeysAttached);
- if (post != m_processPost || !d->enabled || d->inRelease) {
- event->ignore();
- QQuickItemKeyFilter::keyReleased(event, post);
- return;
- }
-
- if (d->item && d->item->canvas()) {
- d->inRelease = true;
- for (int ii = 0; ii < d->targets.count(); ++ii) {
- QQuickItem *i = d->targets.at(ii);
- if (i && i->isVisible()) {
- d->item->canvas()->sendEvent(i, event);
- if (event->isAccepted()) {
- d->inRelease = false;
- return;
- }
- }
- }
- d->inRelease = false;
- }
-
- QQuickKeyEvent ke(*event);
- emit released(&ke);
- event->setAccepted(ke.isAccepted());
-
- if (!event->isAccepted()) QQuickItemKeyFilter::keyReleased(event, post);
-}
-
-void QQuickKeysAttached::inputMethodEvent(QInputMethodEvent *event, bool post)
-{
- Q_D(QQuickKeysAttached);
- if (post == m_processPost && d->item && !d->inIM && d->item->canvas()) {
- d->inIM = true;
- for (int ii = 0; ii < d->targets.count(); ++ii) {
- QQuickItem *i = d->targets.at(ii);
- if (i && i->isVisible() && (i->flags() & QQuickItem::ItemAcceptsInputMethod)) {
- d->item->canvas()->sendEvent(i, event);
- if (event->isAccepted()) {
- d->imeItem = i;
- d->inIM = false;
- return;
- }
- }
- }
- d->inIM = false;
- }
- QQuickItemKeyFilter::inputMethodEvent(event, post);
-}
-
-QVariant QQuickKeysAttached::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- Q_D(const QQuickKeysAttached);
- if (d->item) {
- for (int ii = 0; ii < d->targets.count(); ++ii) {
- QQuickItem *i = d->targets.at(ii);
- if (i && i->isVisible() && (i->flags() & QQuickItem::ItemAcceptsInputMethod) && i == d->imeItem) {
- //### how robust is i == d->imeItem check?
- QVariant v = i->inputMethodQuery(query);
- if (v.userType() == QVariant::RectF)
- v = d->item->mapRectFromItem(i, v.toRectF()); //### cost?
- return v;
- }
- }
- }
- return QQuickItemKeyFilter::inputMethodQuery(query);
-}
-
-QQuickKeysAttached *QQuickKeysAttached::qmlAttachedProperties(QObject *obj)
-{
- return new QQuickKeysAttached(obj);
-}
-
-/*!
- \qmlclass LayoutMirroring QQuickLayoutMirroringAttached
- \inqmlmodule QtQuick 2
- \ingroup qml-utility-elements
- \brief The LayoutMirroring attached property is used to mirror layout behavior.
-
- The LayoutMirroring attached property is used to horizontally mirror \l {anchor-layout}{Item anchors},
- \l{Using QML Positioner and Repeater Items}{positioner} elements (such as \l Row and \l Grid)
- and views (such as \l GridView and horizontal \l ListView). Mirroring is a visual change: left
- anchors become right anchors, and positioner elements like \l Grid and \l Row reverse the
- horizontal layout of child items.
-
- Mirroring is enabled for an item by setting the \l enabled property to true. By default, this
- only affects the item itself; setting the \l childrenInherit property to true propagates the mirroring
- behavior to all child elements as well. If the \c LayoutMirroring attached property has not been defined
- for an item, mirroring is not enabled.
-
- The following example shows mirroring in action. The \l Row below is specified as being anchored
- to the left of its parent. However, since mirroring has been enabled, the anchor is horizontally
- reversed and it is now anchored to the right. Also, since items in a \l Row are positioned
- from left to right by default, they are now positioned from right to left instead, as demonstrated
- by the numbering and opacity of the items:
-
- \snippet doc/src/snippets/declarative/layoutmirroring.qml 0
-
- \image layoutmirroring.png
-
- Layout mirroring is useful when it is necessary to support both left-to-right and right-to-left
- layout versions of an application to target different language areas. The \l childrenInherit
- property allows layout mirroring to be applied without manually setting layout configurations
- for every item in an application. Keep in mind, however, that mirroring does not affect any
- positioning that is defined by the \l Item \l {Item::}{x} coordinate value, so even with
- mirroring enabled, it will often be necessary to apply some layout fixes to support the
- desired layout direction. Also, it may be necessary to disable the mirroring of individual
- child items (by setting \l {enabled}{LayoutMirroring.enabled} to false for such items) if
- mirroring is not the desired behavior, or if the child item already implements mirroring in
- some custom way.
-
- See \l {QML Right-to-left User Interfaces} for further details on using \c LayoutMirroring and
- other related features to implement right-to-left support for an application.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::LayoutMirroring::enabled
-
- This property holds whether the item's layout is mirrored horizontally. Setting this to true
- horizontally reverses \l {anchor-layout}{anchor} settings such that left anchors become right,
- and right anchors become left. For \l{Using QML Positioner and Repeater Items}{positioner} elements
- (such as \l Row and \l Grid) and view elements (such as \l {GridView}{GridView} and \l {ListView}{ListView})
- this also mirrors the horizontal layout direction of the item.
-
- The default value is false.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::LayoutMirroring::childrenInherit
-
- This property holds whether the \l {enabled}{LayoutMirroring.enabled} value for this item
- is inherited by its children.
-
- The default value is false.
-*/
-
-
-QQuickLayoutMirroringAttached::QQuickLayoutMirroringAttached(QObject *parent) : QObject(parent), itemPrivate(0)
-{
- if (QQuickItem *item = qobject_cast<QQuickItem*>(parent)) {
- itemPrivate = QQuickItemPrivate::get(item);
- itemPrivate->attachedLayoutDirection = this;
- } else
- qmlInfo(parent) << tr("LayoutDirection attached property only works with Items");
-}
-
-QQuickLayoutMirroringAttached * QQuickLayoutMirroringAttached::qmlAttachedProperties(QObject *object)
-{
- return new QQuickLayoutMirroringAttached(object);
-}
-
-bool QQuickLayoutMirroringAttached::enabled() const
-{
- return itemPrivate ? itemPrivate->effectiveLayoutMirror : false;
-}
-
-void QQuickLayoutMirroringAttached::setEnabled(bool enabled)
-{
- if (!itemPrivate)
- return;
-
- itemPrivate->isMirrorImplicit = false;
- if (enabled != itemPrivate->effectiveLayoutMirror) {
- itemPrivate->setLayoutMirror(enabled);
- if (itemPrivate->inheritMirrorFromItem)
- itemPrivate->resolveLayoutMirror();
- }
-}
-
-void QQuickLayoutMirroringAttached::resetEnabled()
-{
- if (itemPrivate && !itemPrivate->isMirrorImplicit) {
- itemPrivate->isMirrorImplicit = true;
- itemPrivate->resolveLayoutMirror();
- }
-}
-
-bool QQuickLayoutMirroringAttached::childrenInherit() const
-{
- return itemPrivate ? itemPrivate->inheritMirrorFromItem : false;
-}
-
-void QQuickLayoutMirroringAttached::setChildrenInherit(bool childrenInherit) {
- if (itemPrivate && childrenInherit != itemPrivate->inheritMirrorFromItem) {
- itemPrivate->inheritMirrorFromItem = childrenInherit;
- itemPrivate->resolveLayoutMirror();
- childrenInheritChanged();
- }
-}
-
-void QQuickItemPrivate::resolveLayoutMirror()
-{
- Q_Q(QQuickItem);
- if (QQuickItem *parentItem = q->parentItem()) {
- QQuickItemPrivate *parentPrivate = QQuickItemPrivate::get(parentItem);
- setImplicitLayoutMirror(parentPrivate->inheritedLayoutMirror, parentPrivate->inheritMirrorFromParent);
- } else {
- setImplicitLayoutMirror(isMirrorImplicit ? false : effectiveLayoutMirror, inheritMirrorFromItem);
- }
-}
-
-void QQuickItemPrivate::setImplicitLayoutMirror(bool mirror, bool inherit)
-{
- inherit = inherit || inheritMirrorFromItem;
- if (!isMirrorImplicit && inheritMirrorFromItem)
- mirror = effectiveLayoutMirror;
- if (mirror == inheritedLayoutMirror && inherit == inheritMirrorFromParent)
- return;
-
- inheritMirrorFromParent = inherit;
- inheritedLayoutMirror = inheritMirrorFromParent ? mirror : false;
-
- if (isMirrorImplicit)
- setLayoutMirror(inherit ? inheritedLayoutMirror : false);
- for (int i = 0; i < childItems.count(); ++i) {
- if (QQuickItem *child = qobject_cast<QQuickItem *>(childItems.at(i))) {
- QQuickItemPrivate *childPrivate = QQuickItemPrivate::get(child);
- childPrivate->setImplicitLayoutMirror(inheritedLayoutMirror, inheritMirrorFromParent);
- }
- }
-}
-
-void QQuickItemPrivate::setLayoutMirror(bool mirror)
-{
- if (mirror != effectiveLayoutMirror) {
- effectiveLayoutMirror = mirror;
- if (_anchors) {
- QQuickAnchorsPrivate *anchor_d = QQuickAnchorsPrivate::get(_anchors);
- anchor_d->fillChanged();
- anchor_d->centerInChanged();
- anchor_d->updateHorizontalAnchors();
- emit _anchors->mirroredChanged();
- }
- mirrorChange();
- if (attachedLayoutDirection) {
- emit attachedLayoutDirection->enabledChanged();
- }
- }
-}
-
-/*!
- \class QQuickItem
- \brief The QQuickItem class provides the most basic of all visual items in QML.
-
- All visual items in Qt Declarative inherit from QQuickItem. Although QQuickItem
- has no visual appearance, it defines all the properties that are
- common across visual items - such as the x and y position, the
- width and height, \l {anchor-layout}{anchoring} and key handling.
-
- You can subclass QQuickItem to provide your own custom visual item that inherits
- these features. Note that, because it does not draw anything, QQuickItem sets the
- QGraphicsItem::ItemHasNoContents flag. If you subclass QQuickItem to create a visual
- item, you will need to unset this flag.
-
-*/
-
-/*!
- \qmlclass Item QQuickItem
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
- \brief The Item is the most basic of all visual items in QML.
-
- All visual items in Qt Declarative inherit from Item. Although Item
- has no visual appearance, it defines all the properties that are
- common across visual items - such as the x and y position, the
- width and height, \l {anchor-layout}{anchoring} and key handling.
-
- Item is also useful for grouping items together.
-
- \qml
- Item {
- Image {
- source: "tile.png"
- }
- Image {
- x: 80
- width: 100
- height: 100
- source: "tile.png"
- }
- Image {
- x: 190
- width: 100
- height: 100
- fillMode: Image.Tile
- source: "tile.png"
- }
- }
- \endqml
-
-
- \section1 Key Handling
-
- Key handling is available to all Item-based visual elements via the \l {Keys}{Keys}
- attached property. The \e Keys attached property provides basic handlers such
- as \l {Keys::onPressed}{onPressed} and \l {Keys::onReleased}{onReleased},
- as well as handlers for specific keys, such as
- \l {Keys::onCancelPressed}{onCancelPressed}. The example below
- assigns \l {qmlfocus}{focus} to the item and handles
- the Left key via the general \e onPressed handler and the Select key via the
- onSelectPressed handler:
-
- \qml
- Item {
- focus: true
- Keys.onPressed: {
- if (event.key == Qt.Key_Left) {
- console.log("move left");
- event.accepted = true;
- }
- }
- Keys.onSelectPressed: console.log("Selected");
- }
- \endqml
-
- See the \l {Keys}{Keys} attached property for detailed documentation.
-
- \section1 Layout Mirroring
-
- Item layouts can be mirrored using the \l {LayoutMirroring}{LayoutMirroring} attached property.
-
-*/
-
-/*!
- \fn void QQuickItem::childrenRectChanged(const QRectF &)
- \internal
-*/
-
-/*!
- \fn void QQuickItem::baselineOffsetChanged(qreal)
- \internal
-*/
-
-/*!
- \fn void QQuickItem::stateChanged(const QString &state)
- \internal
-*/
-
-/*!
- \fn void QQuickItem::parentChanged(QQuickItem *)
- \internal
-*/
-
-/*!
- \fn void QQuickItem::smoothChanged(bool)
- \internal
-*/
-
-/*!
- \fn void QQuickItem::clipChanged(bool)
- \internal
-*/
-
-/*! \fn void QQuickItem::transformOriginChanged(TransformOrigin)
- \internal
-*/
-
-/*!
- \fn void QQuickItem::focusChanged(bool)
- \internal
-*/
-
-/*!
- \fn void QQuickItem::activeFocusChanged(bool)
- \internal
-*/
-/*!
- \fn QQuickItem::QQuickItem(QQuickItem *parent)
-
- Constructs a QQuickItem with the given \a parent.
-*/
-QQuickItem::QQuickItem(QQuickItem* parent)
-: QObject(*(new QQuickItemPrivate), parent)
-{
- Q_D(QQuickItem);
- d->init(parent);
-}
-
-/*! \internal
-*/
-QQuickItem::QQuickItem(QQuickItemPrivate &dd, QQuickItem *parent)
-: QObject(dd, parent)
-{
- Q_D(QQuickItem);
- d->init(parent);
-}
-
-#ifndef QT_NO_DEBUG
-static int qt_item_count = 0;
-
-static void qt_print_item_count()
-{
- qDebug("Number of leaked items: %i", qt_item_count);
- qt_item_count = -1;
-}
-#endif
-
-/*!
- Destroys the QQuickItem.
-*/
-QQuickItem::~QQuickItem()
-{
-#ifndef QT_NO_DEBUG
- --qt_item_count;
- if (qt_item_count < 0)
- qDebug("Item destroyed after qt_print_item_count() was called.");
-#endif
-
- Q_D(QQuickItem);
-
- if (d->parentItem)
- setParentItem(0);
- else if (d->canvas && d->itemNodeInstance)
- QQuickCanvasPrivate::get(d->canvas)->cleanup(d->itemNodeInstance); // cleanup root
- // XXX todo - optimize
- while (!d->childItems.isEmpty())
- d->childItems.first()->setParentItem(0);
-
- for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
- QQuickAnchorsPrivate *anchor = d->changeListeners.at(ii).listener->anchorPrivate();
- if (anchor)
- anchor->clearItem(this);
- }
-
- /*
- update item anchors that depended on us unless they are our child (and will also be destroyed),
- or our sibling, and our parent is also being destroyed.
- */
- for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
- QQuickAnchorsPrivate *anchor = d->changeListeners.at(ii).listener->anchorPrivate();
- if (anchor && anchor->item && anchor->item->parentItem() && anchor->item->parentItem() != this)
- anchor->update();
- }
-
- for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::Destroyed)
- change.listener->itemDestroyed(this);
- }
- d->changeListeners.clear();
- delete d->_anchorLines; d->_anchorLines = 0;
- delete d->_anchors; d->_anchors = 0;
- delete d->_stateGroup; d->_stateGroup = 0;
- delete d->_contents; d->_contents = 0;
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Item::transformOrigin
- This property holds the origin point around which scale and rotation transform.
-
- Nine transform origins are available, as shown in the image below.
-
- \image declarative-transformorigin.png
-
- This example rotates an image around its bottom-right corner.
- \qml
- Image {
- source: "myimage.png"
- transformOrigin: Item.BottomRight
- rotation: 45
- }
- \endqml
-
- The default transform origin is \c Item.Center.
-
- To set an arbitrary transform origin point use the \l Scale or \l Rotation
- transform elements.
-*/
-
-/*!
- \qmlproperty Item QtQuick2::Item::parent
- This property holds the parent of the item.
-*/
-
-/*!
- \property QQuickItem::parent
- This property holds the parent of the item.
-*/
-void QQuickItem::setParentItem(QQuickItem *parentItem)
-{
- Q_D(QQuickItem);
- if (parentItem == d->parentItem)
- return;
-
- d->removeFromDirtyList();
-
- QQuickItem *oldParentItem = d->parentItem;
- QQuickItem *scopeFocusedItem = 0;
-
- if (oldParentItem) {
- QQuickItemPrivate *op = QQuickItemPrivate::get(oldParentItem);
-
- QQuickItem *scopeItem = 0;
-
- if (d->canvas && hasFocus()) {
- scopeItem = oldParentItem;
- while (!scopeItem->isFocusScope()) scopeItem = scopeItem->parentItem();
- scopeFocusedItem = this;
- } else if (d->canvas && !isFocusScope() && d->subFocusItem) {
- scopeItem = oldParentItem;
- while (!scopeItem->isFocusScope()) scopeItem = scopeItem->parentItem();
- scopeFocusedItem = d->subFocusItem;
- }
-
- if (scopeFocusedItem)
- QQuickCanvasPrivate::get(d->canvas)->clearFocusInScope(scopeItem, scopeFocusedItem,
- QQuickCanvasPrivate::DontChangeFocusProperty);
-
- op->removeChild(this);
- }
-
- d->parentItem = parentItem;
-
- QQuickCanvas *parentCanvas = parentItem?QQuickItemPrivate::get(parentItem)->canvas:0;
- if (d->canvas != parentCanvas) {
- QQuickItemPrivate::InitializationState initState;
- initState.clear();
- d->initCanvas(&initState, parentCanvas);
- }
-
- d->dirty(QQuickItemPrivate::ParentChanged);
-
- if (d->parentItem)
- QQuickItemPrivate::get(d->parentItem)->addChild(this);
-
- d->setEffectiveVisibleRecur(d->calcEffectiveVisible());
- d->setEffectiveEnableRecur(d->calcEffectiveEnable());
-
- if (scopeFocusedItem && d->parentItem && d->canvas) {
- // We need to test whether this item becomes scope focused
- QQuickItem *scopeItem = 0;
- scopeItem = d->parentItem;
- while (!scopeItem->isFocusScope()) scopeItem = scopeItem->parentItem();
-
- if (scopeItem->scopedFocusItem()) {
- QQuickItemPrivate::get(scopeFocusedItem)->focus = false;
- emit scopeFocusedItem->focusChanged(false);
- } else {
- QQuickCanvasPrivate::get(d->canvas)->setFocusInScope(scopeItem, scopeFocusedItem,
- QQuickCanvasPrivate::DontChangeFocusProperty);
- }
- }
-
- d->resolveLayoutMirror();
-
- d->itemChange(ItemParentHasChanged, d->parentItem);
-
- emit parentChanged(d->parentItem);
-}
-
-void QQuickItem::stackBefore(const QQuickItem *sibling)
-{
- Q_D(QQuickItem);
- if (!sibling || sibling == this || !d->parentItem || d->parentItem != QQuickItemPrivate::get(sibling)->parentItem) {
- qWarning("QQuickItem::stackBefore: Cannot stack before %p, which must be a sibling", sibling);
- return;
- }
-
- QQuickItemPrivate *parentPrivate = QQuickItemPrivate::get(d->parentItem);
-
- int myIndex = parentPrivate->childItems.indexOf(this);
- int siblingIndex = parentPrivate->childItems.indexOf(const_cast<QQuickItem *>(sibling));
-
- Q_ASSERT(myIndex != -1 && siblingIndex != -1);
-
- if (myIndex == siblingIndex - 1)
- return;
-
- parentPrivate->childItems.removeAt(myIndex);
-
- if (myIndex < siblingIndex) --siblingIndex;
-
- parentPrivate->childItems.insert(siblingIndex, this);
-
- parentPrivate->dirty(QQuickItemPrivate::ChildrenStackingChanged);
- parentPrivate->markSortedChildrenDirty(this);
-
- for (int ii = qMin(siblingIndex, myIndex); ii < parentPrivate->childItems.count(); ++ii)
- QQuickItemPrivate::get(parentPrivate->childItems.at(ii))->siblingOrderChanged();
-}
-
-void QQuickItem::stackAfter(const QQuickItem *sibling)
-{
- Q_D(QQuickItem);
- if (!sibling || sibling == this || !d->parentItem || d->parentItem != QQuickItemPrivate::get(sibling)->parentItem) {
- qWarning("QQuickItem::stackAfter: Cannot stack after %p, which must be a sibling", sibling);
- return;
- }
-
- QQuickItemPrivate *parentPrivate = QQuickItemPrivate::get(d->parentItem);
-
- int myIndex = parentPrivate->childItems.indexOf(this);
- int siblingIndex = parentPrivate->childItems.indexOf(const_cast<QQuickItem *>(sibling));
-
- Q_ASSERT(myIndex != -1 && siblingIndex != -1);
-
- if (myIndex == siblingIndex + 1)
- return;
-
- parentPrivate->childItems.removeAt(myIndex);
-
- if (myIndex < siblingIndex) --siblingIndex;
-
- parentPrivate->childItems.insert(siblingIndex + 1, this);
-
- parentPrivate->dirty(QQuickItemPrivate::ChildrenStackingChanged);
- parentPrivate->markSortedChildrenDirty(this);
-
- for (int ii = qMin(myIndex, siblingIndex + 1); ii < parentPrivate->childItems.count(); ++ii)
- QQuickItemPrivate::get(parentPrivate->childItems.at(ii))->siblingOrderChanged();
-}
-
-/*!
- Returns the QQuickItem parent of this item.
-*/
-QQuickItem *QQuickItem::parentItem() const
-{
- Q_D(const QQuickItem);
- return d->parentItem;
-}
-
-QSGEngine *QQuickItem::sceneGraphEngine() const
-{
- return canvas()->sceneGraphEngine();
-}
-
-QQuickCanvas *QQuickItem::canvas() const
-{
- Q_D(const QQuickItem);
- return d->canvas;
-}
-
-static bool itemZOrder_sort(QQuickItem *lhs, QQuickItem *rhs)
-{
- return lhs->z() < rhs->z();
-}
-
-QList<QQuickItem *> QQuickItemPrivate::paintOrderChildItems() const
-{
- if (sortedChildItems)
- return *sortedChildItems;
-
- // If none of the items have set Z then the paint order list is the same as
- // the childItems list. This is by far the most common case.
- bool haveZ = false;
- for (int i = 0; i < childItems.count(); ++i) {
- if (QQuickItemPrivate::get(childItems.at(i))->z != 0.) {
- haveZ = true;
- break;
- }
- }
- if (haveZ) {
- sortedChildItems = new QList<QQuickItem*>(childItems);
- qStableSort(sortedChildItems->begin(), sortedChildItems->end(), itemZOrder_sort);
- return *sortedChildItems;
- }
-
- sortedChildItems = const_cast<QList<QQuickItem*>*>(&childItems);
-
- return childItems;
-}
-
-void QQuickItemPrivate::addChild(QQuickItem *child)
-{
- Q_Q(QQuickItem);
-
- Q_ASSERT(!childItems.contains(child));
-
- childItems.append(child);
-
- markSortedChildrenDirty(child);
- dirty(QQuickItemPrivate::ChildrenChanged);
-
- itemChange(QQuickItem::ItemChildAddedChange, child);
-
- emit q->childrenChanged();
-}
-
-void QQuickItemPrivate::removeChild(QQuickItem *child)
-{
- Q_Q(QQuickItem);
-
- Q_ASSERT(child);
- Q_ASSERT(childItems.contains(child));
- childItems.removeOne(child);
- Q_ASSERT(!childItems.contains(child));
-
- markSortedChildrenDirty(child);
- dirty(QQuickItemPrivate::ChildrenChanged);
-
- itemChange(QQuickItem::ItemChildRemovedChange, child);
-
- emit q->childrenChanged();
-}
-
-void QQuickItemPrivate::InitializationState::clear()
-{
- focusScope = 0;
-}
-
-void QQuickItemPrivate::InitializationState::clear(QQuickItem *fs)
-{
- focusScope = fs;
-}
-
-QQuickItem *QQuickItemPrivate::InitializationState::getFocusScope(QQuickItem *item)
-{
- if (!focusScope) {
- QQuickItem *fs = item->parentItem();
- while (!fs->isFocusScope())
- fs = fs->parentItem();
- focusScope = fs;
- }
- return focusScope;
-}
-
-void QQuickItemPrivate::initCanvas(InitializationState *state, QQuickCanvas *c)
-{
- Q_Q(QQuickItem);
-
- if (canvas) {
- removeFromDirtyList();
- QQuickCanvasPrivate *c = QQuickCanvasPrivate::get(canvas);
- if (polishScheduled)
- c->itemsToPolish.remove(q);
- if (c->mouseGrabberItem == q)
- c->mouseGrabberItem = 0;
- if ( hoverEnabled )
- c->hoverItems.removeAll(q);
- if (itemNodeInstance)
- c->cleanup(itemNodeInstance);
- }
-
- canvas = c;
-
- if (canvas && polishScheduled)
- QQuickCanvasPrivate::get(canvas)->itemsToPolish.insert(q);
-
- itemNodeInstance = 0;
- opacityNode = 0;
- clipNode = 0;
- rootNode = 0;
- groupNode = 0;
- paintNode = 0;
- beforePaintNode = 0;
-
- InitializationState _dummy;
- InitializationState *childState = state;
-
- if (c && q->isFocusScope()) {
- _dummy.clear(q);
- childState = &_dummy;
- }
-
- for (int ii = 0; ii < childItems.count(); ++ii) {
- QQuickItem *child = childItems.at(ii);
- QQuickItemPrivate::get(child)->initCanvas(childState, c);
- }
-
- if (c && focus) {
- // Fixup
- if (state->getFocusScope(q)->scopedFocusItem()) {
- focus = false;
- emit q->focusChanged(false);
- } else {
- QQuickCanvasPrivate::get(canvas)->setFocusInScope(state->getFocusScope(q), q);
- }
- }
-
- dirty(Canvas);
-
- itemChange(QQuickItem::ItemSceneChange, c);
-}
-
-/*!
-Returns a transform that maps points from canvas space into item space.
-*/
-QTransform QQuickItemPrivate::canvasToItemTransform() const
-{
- // XXX todo - optimize
- return itemToCanvasTransform().inverted();
-}
-
-/*!
-Returns a transform that maps points from item space into canvas space.
-*/
-QTransform QQuickItemPrivate::itemToCanvasTransform() const
-{
- // XXX todo
- QTransform rv = parentItem?QQuickItemPrivate::get(parentItem)->itemToCanvasTransform():QTransform();
- itemToParentTransform(rv);
- return rv;
-}
-
-/*!
-Motifies \a t with this items local transform relative to its parent.
-*/
-void QQuickItemPrivate::itemToParentTransform(QTransform &t) const
-{
- if (x || y)
- t.translate(x, y);
-
- if (!transforms.isEmpty()) {
- QMatrix4x4 m(t);
- for (int ii = transforms.count() - 1; ii >= 0; --ii)
- transforms.at(ii)->applyTo(&m);
- t = m.toTransform();
- }
-
- if (scale != 1. || rotation != 0.) {
- QPointF tp = computeTransformOrigin();
- t.translate(tp.x(), tp.y());
- t.scale(scale, scale);
- t.rotate(rotation);
- t.translate(-tp.x(), -tp.y());
- }
-}
-
-
-/*!
- \qmlproperty real QtQuick2::Item::childrenRect.x
- \qmlproperty real QtQuick2::Item::childrenRect.y
- \qmlproperty real QtQuick2::Item::childrenRect.width
- \qmlproperty real QtQuick2::Item::childrenRect.height
-
- The childrenRect properties allow an item access to the geometry of its
- children. This property is useful if you have an item that needs to be
- sized to fit its children.
-*/
-
-
-/*!
- \qmlproperty list<Item> QtQuick2::Item::children
- \qmlproperty list<Object> QtQuick2::Item::resources
-
- The children property contains the list of visual children of this item.
- The resources property contains non-visual resources that you want to
- reference by name.
-
- Generally you can rely on Item's default property to handle all this for
- you, but it can come in handy in some cases.
-
- \qml
- Item {
- children: [
- Text {},
- Rectangle {}
- ]
- resources: [
- Component {
- id: myComponent
- Text {}
- }
- ]
- }
- \endqml
-*/
-
-/*!
- Returns true if construction of the QML component is complete; otherwise
- returns false.
-
- It is often desirable to delay some processing until the component is
- completed.
-
- \sa componentComplete()
-*/
-bool QQuickItem::isComponentComplete() const
-{
- Q_D(const QQuickItem);
- return d->componentComplete;
-}
-
-QQuickItemPrivate::QQuickItemPrivate()
-: _anchors(0), _contents(0), baselineOffset(0), _anchorLines(0), _stateGroup(0), origin(QQuickItem::Center),
-
- flags(0), widthValid(false), heightValid(false), componentComplete(true),
- keepMouse(false), keepTouch(false), hoverEnabled(false), smooth(false), focus(false), activeFocus(false), notifiedFocus(false),
- notifiedActiveFocus(false), filtersChildMouseEvents(false), explicitVisible(true),
- effectiveVisible(true), explicitEnable(true), effectiveEnable(true), polishScheduled(false),
- inheritedLayoutMirror(false), effectiveLayoutMirror(false), isMirrorImplicit(true),
- inheritMirrorFromParent(false), inheritMirrorFromItem(false), childrenDoNotOverlap(false),
-
- canvas(0), parentItem(0), sortedChildItems(&childItems),
-
- subFocusItem(0),
-
- x(0), y(0), width(0), height(0), implicitWidth(0), implicitHeight(0),
- z(0), scale(1), rotation(0), opacity(1),
-
- attachedLayoutDirection(0), acceptedMouseButtons(0),
- imHints(Qt::ImhMultiLine),
-
- keyHandler(0),
-
- dirtyAttributes(0), nextDirtyItem(0), prevDirtyItem(0),
-
- itemNodeInstance(0), opacityNode(0), clipNode(0), rootNode(0), groupNode(0), paintNode(0)
- , beforePaintNode(0), effectRefCount(0), hideRefCount(0)
-{
-}
-
-QQuickItemPrivate::~QQuickItemPrivate()
-{
- if (sortedChildItems != &childItems)
- delete sortedChildItems;
-}
-
-void QQuickItemPrivate::init(QQuickItem *parent)
-{
-#ifndef QT_NO_DEBUG
- ++qt_item_count;
- static bool atexit_registered = false;
- if (!atexit_registered) {
- atexit(qt_print_item_count);
- atexit_registered = true;
- }
-#endif
-
- Q_Q(QQuickItem);
- baselineOffset.invalidate();
-
- if (parent) {
- q->setParentItem(parent);
- QQuickItemPrivate *parentPrivate = QQuickItemPrivate::get(parent);
- setImplicitLayoutMirror(parentPrivate->inheritedLayoutMirror, parentPrivate->inheritMirrorFromParent);
- }
-}
-
-void QQuickItemPrivate::data_append(QDeclarativeListProperty<QObject> *prop, QObject *o)
-{
- if (!o)
- return;
-
- QQuickItem *that = static_cast<QQuickItem *>(prop->object);
-
- // This test is measurably (albeit only slightly) faster than qobject_cast<>()
- const QMetaObject *mo = o->metaObject();
- while (mo && mo != &QQuickItem::staticMetaObject) {
- mo = mo->d.superdata;
- }
-
- if (mo) {
- QQuickItem *item = static_cast<QQuickItem *>(o);
- item->setParentItem(that);
- } else {
- if (o->inherits("QGraphicsItem"))
- qWarning("Cannot add a QtQuick 1.0 item (%s) into a QtQuick 2.0 scene!", o->metaObject()->className());
-
- // XXX todo - do we really want this behavior?
- o->setParent(that);
- }
-}
-
-/*!
- \qmlproperty list<Object> QtQuick2::Item::data
- \default
-
- The data property allows you to freely mix visual children and resources
- in an item. If you assign a visual item to the data list it becomes
- a child and if you assign any other object type, it is added as a resource.
-
- So you can write:
- \qml
- Item {
- Text {}
- Rectangle {}
- Timer {}
- }
- \endqml
-
- instead of:
- \qml
- Item {
- children: [
- Text {},
- Rectangle {}
- ]
- resources: [
- Timer {}
- ]
- }
- \endqml
-
- data is a behind-the-scenes property: you should never need to explicitly
- specify it.
- */
-
-int QQuickItemPrivate::data_count(QDeclarativeListProperty<QObject> *prop)
-{
- Q_UNUSED(prop);
- // XXX todo
- return 0;
-}
-
-QObject *QQuickItemPrivate::data_at(QDeclarativeListProperty<QObject> *prop, int i)
-{
- Q_UNUSED(prop);
- Q_UNUSED(i);
- // XXX todo
- return 0;
-}
-
-void QQuickItemPrivate::data_clear(QDeclarativeListProperty<QObject> *prop)
-{
- Q_UNUSED(prop);
- // XXX todo
-}
-
-QObject *QQuickItemPrivate::resources_at(QDeclarativeListProperty<QObject> *prop, int index)
-{
- const QObjectList children = prop->object->children();
- if (index < children.count())
- return children.at(index);
- else
- return 0;
-}
-
-void QQuickItemPrivate::resources_append(QDeclarativeListProperty<QObject> *prop, QObject *o)
-{
- // XXX todo - do we really want this behavior?
- o->setParent(prop->object);
-}
-
-int QQuickItemPrivate::resources_count(QDeclarativeListProperty<QObject> *prop)
-{
- return prop->object->children().count();
-}
-
-void QQuickItemPrivate::resources_clear(QDeclarativeListProperty<QObject> *prop)
-{
- // XXX todo - do we really want this behavior?
- const QObjectList children = prop->object->children();
- for (int index = 0; index < children.count(); index++)
- children.at(index)->setParent(0);
-}
-
-QQuickItem *QQuickItemPrivate::children_at(QDeclarativeListProperty<QQuickItem> *prop, int index)
-{
- QQuickItemPrivate *p = QQuickItemPrivate::get(static_cast<QQuickItem *>(prop->object));
- if (index >= p->childItems.count() || index < 0)
- return 0;
- else
- return p->childItems.at(index);
-}
-
-void QQuickItemPrivate::children_append(QDeclarativeListProperty<QQuickItem> *prop, QQuickItem *o)
-{
- if (!o)
- return;
-
- QQuickItem *that = static_cast<QQuickItem *>(prop->object);
- if (o->parentItem() == that)
- o->setParentItem(0);
-
- o->setParentItem(that);
-}
-
-int QQuickItemPrivate::children_count(QDeclarativeListProperty<QQuickItem> *prop)
-{
- QQuickItemPrivate *p = QQuickItemPrivate::get(static_cast<QQuickItem *>(prop->object));
- return p->childItems.count();
-}
-
-void QQuickItemPrivate::children_clear(QDeclarativeListProperty<QQuickItem> *prop)
-{
- QQuickItem *that = static_cast<QQuickItem *>(prop->object);
- QQuickItemPrivate *p = QQuickItemPrivate::get(that);
- while (!p->childItems.isEmpty())
- p->childItems.at(0)->setParentItem(0);
-}
-
-int QQuickItemPrivate::transform_count(QDeclarativeListProperty<QQuickTransform> *prop)
-{
- QQuickItem *that = static_cast<QQuickItem *>(prop->object);
- return QQuickItemPrivate::get(that)->transforms.count();
-}
-
-void QQuickTransform::appendToItem(QQuickItem *item)
-{
- Q_D(QQuickTransform);
- if (!item)
- return;
-
- QQuickItemPrivate *p = QQuickItemPrivate::get(item);
-
- if (!d->items.isEmpty() && !p->transforms.isEmpty() && p->transforms.contains(this)) {
- p->transforms.removeOne(this);
- p->transforms.append(this);
- } else {
- p->transforms.append(this);
- d->items.append(item);
- }
-
- p->dirty(QQuickItemPrivate::Transform);
-}
-
-void QQuickTransform::prependToItem(QQuickItem *item)
-{
- Q_D(QQuickTransform);
- if (!item)
- return;
-
- QQuickItemPrivate *p = QQuickItemPrivate::get(item);
-
- if (!d->items.isEmpty() && !p->transforms.isEmpty() && p->transforms.contains(this)) {
- p->transforms.removeOne(this);
- p->transforms.prepend(this);
- } else {
- p->transforms.prepend(this);
- d->items.append(item);
- }
-
- p->dirty(QQuickItemPrivate::Transform);
-}
-
-void QQuickItemPrivate::transform_append(QDeclarativeListProperty<QQuickTransform> *prop, QQuickTransform *transform)
-{
- if (!transform)
- return;
-
- QQuickItem *that = static_cast<QQuickItem *>(prop->object);
- transform->appendToItem(that);
-}
-
-QQuickTransform *QQuickItemPrivate::transform_at(QDeclarativeListProperty<QQuickTransform> *prop, int idx)
-{
- QQuickItem *that = static_cast<QQuickItem *>(prop->object);
- QQuickItemPrivate *p = QQuickItemPrivate::get(that);
-
- if (idx < 0 || idx >= p->transforms.count())
- return 0;
- else
- return p->transforms.at(idx);
-}
-
-void QQuickItemPrivate::transform_clear(QDeclarativeListProperty<QQuickTransform> *prop)
-{
- QQuickItem *that = static_cast<QQuickItem *>(prop->object);
- QQuickItemPrivate *p = QQuickItemPrivate::get(that);
-
- for (int ii = 0; ii < p->transforms.count(); ++ii) {
- QQuickTransform *t = p->transforms.at(ii);
- QQuickTransformPrivate *tp = QQuickTransformPrivate::get(t);
- tp->items.removeOne(that);
- }
-
- p->transforms.clear();
-
- p->dirty(QQuickItemPrivate::Transform);
-}
-
-/*!
- \property QQuickItem::childrenRect
- \brief The geometry of an item's children.
-
- This property holds the (collective) position and size of the item's children.
-*/
-
-/*!
- \qmlproperty real QtQuick2::Item::x
- \qmlproperty real QtQuick2::Item::y
- \qmlproperty real QtQuick2::Item::width
- \qmlproperty real QtQuick2::Item::height
-
- Defines the item's position and size relative to its parent.
-
- \qml
- Item { x: 100; y: 100; width: 100; height: 100 }
- \endqml
- */
-
-/*!
- \qmlproperty real QtQuick2::Item::z
-
- Sets the stacking order of sibling items. By default the stacking order is 0.
-
- Items with a higher stacking value are drawn on top of siblings with a
- lower stacking order. Items with the same stacking value are drawn
- bottom up in the order they appear. Items with a negative stacking
- value are drawn under their parent's content.
-
- The following example shows the various effects of stacking order.
-
- \table
- \row
- \o \image declarative-item_stacking1.png
- \o Same \c z - later children above earlier children:
- \qml
- Item {
- Rectangle {
- color: "red"
- width: 100; height: 100
- }
- Rectangle {
- color: "blue"
- x: 50; y: 50; width: 100; height: 100
- }
- }
- \endqml
- \row
- \o \image declarative-item_stacking2.png
- \o Higher \c z on top:
- \qml
- Item {
- Rectangle {
- z: 1
- color: "red"
- width: 100; height: 100
- }
- Rectangle {
- color: "blue"
- x: 50; y: 50; width: 100; height: 100
- }
- }
- \endqml
- \row
- \o \image declarative-item_stacking3.png
- \o Same \c z - children above parents:
- \qml
- Item {
- Rectangle {
- color: "red"
- width: 100; height: 100
- Rectangle {
- color: "blue"
- x: 50; y: 50; width: 100; height: 100
- }
- }
- }
- \endqml
- \row
- \o \image declarative-item_stacking4.png
- \o Lower \c z below:
- \qml
- Item {
- Rectangle {
- color: "red"
- width: 100; height: 100
- Rectangle {
- z: -1
- color: "blue"
- x: 50; y: 50; width: 100; height: 100
- }
- }
- }
- \endqml
- \endtable
- */
-
-/*!
- \qmlproperty bool QtQuick2::Item::visible
-
- This property holds whether the item is visible. By default this is true.
-
- Setting this property directly affects the \c visible value of child
- items. When set to \c false, the \c visible values of all child items also
- become \c false. When set to \c true, the \c visible values of child items
- are returned to \c true, unless they have explicitly been set to \c false.
-
- (Because of this flow-on behavior, using the \c visible property may not
- have the intended effect if a property binding should only respond to
- explicit property changes. In such cases it may be better to use the
- \l opacity property instead.)
-
- Setting this property to \c false automatically causes \l focus to be set
- to \c false, and this item will longer receive mouse and keyboard events.
- (In contrast, setting the \l opacity to 0 does not affect the \l focus
- property and the receiving of key events.)
-
- \note This property's value is only affected by changes to this property or
- the parent's \c visible property. It does not change, for example, if this
- item moves off-screen, or if the \l opacity changes to 0.
-*/
-
-
-/*!
- \qmlproperty AnchorLine QtQuick2::Item::anchors.top
- \qmlproperty AnchorLine QtQuick2::Item::anchors.bottom
- \qmlproperty AnchorLine QtQuick2::Item::anchors.left
- \qmlproperty AnchorLine QtQuick2::Item::anchors.right
- \qmlproperty AnchorLine QtQuick2::Item::anchors.horizontalCenter
- \qmlproperty AnchorLine QtQuick2::Item::anchors.verticalCenter
- \qmlproperty AnchorLine QtQuick2::Item::anchors.baseline
-
- \qmlproperty Item QtQuick2::Item::anchors.fill
- \qmlproperty Item QtQuick2::Item::anchors.centerIn
-
- \qmlproperty real QtQuick2::Item::anchors.margins
- \qmlproperty real QtQuick2::Item::anchors.topMargin
- \qmlproperty real QtQuick2::Item::anchors.bottomMargin
- \qmlproperty real QtQuick2::Item::anchors.leftMargin
- \qmlproperty real QtQuick2::Item::anchors.rightMargin
- \qmlproperty real QtQuick2::Item::anchors.horizontalCenterOffset
- \qmlproperty real QtQuick2::Item::anchors.verticalCenterOffset
- \qmlproperty real QtQuick2::Item::anchors.baselineOffset
-
- \qmlproperty bool QtQuick2::Item::anchors.mirrored
-
- Anchors provide a way to position an item by specifying its
- relationship with other items.
-
- Margins apply to top, bottom, left, right, and fill anchors.
- The \c anchors.margins property can be used to set all of the various margins at once, to the same value.
- Note that margins are anchor-specific and are not applied if an item does not
- use anchors.
-
- Offsets apply for horizontal center, vertical center, and baseline anchors.
-
- \table
- \row
- \o \image declarative-anchors_example.png
- \o Text anchored to Image, horizontally centered and vertically below, with a margin.
- \qml
- Item {
- Image {
- id: pic
- // ...
- }
- Text {
- id: label
- anchors.horizontalCenter: pic.horizontalCenter
- anchors.top: pic.bottom
- anchors.topMargin: 5
- // ...
- }
- }
- \endqml
- \row
- \o \image declarative-anchors_example2.png
- \o
- Left of Text anchored to right of Image, with a margin. The y
- property of both defaults to 0.
-
- \qml
- Item {
- Image {
- id: pic
- // ...
- }
- Text {
- id: label
- anchors.left: pic.right
- anchors.leftMargin: 5
- // ...
- }
- }
- \endqml
- \endtable
-
- \c anchors.fill provides a convenient way for one item to have the
- same geometry as another item, and is equivalent to connecting all
- four directional anchors.
-
- To clear an anchor value, set it to \c undefined.
-
- \c anchors.mirrored returns true it the layout has been \l {LayoutMirroring}{mirrored}.
-
- \note You can only anchor an item to siblings or a parent.
-
- For more information see \l {anchor-layout}{Anchor Layouts}.
-*/
-
-/*!
- \property QQuickItem::baselineOffset
- \brief The position of the item's baseline in local coordinates.
-
- The baseline of a \l Text item is the imaginary line on which the text
- sits. Controls containing text usually set their baseline to the
- baseline of their text.
-
- For non-text items, a default baseline offset of 0 is used.
-*/
-QQuickAnchors *QQuickItemPrivate::anchors() const
-{
- if (!_anchors) {
- Q_Q(const QQuickItem);
- _anchors = new QQuickAnchors(const_cast<QQuickItem *>(q));
- if (!componentComplete)
- _anchors->classBegin();
- }
- return _anchors;
-}
-
-QQuickItemPrivate::AnchorLines *QQuickItemPrivate::anchorLines() const
-{
- Q_Q(const QQuickItem);
- if (!_anchorLines) _anchorLines =
- new AnchorLines(const_cast<QQuickItem *>(q));
- return _anchorLines;
-}
-
-void QQuickItemPrivate::siblingOrderChanged()
-{
- Q_Q(QQuickItem);
- for (int ii = 0; ii < changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::SiblingOrder) {
- change.listener->itemSiblingOrderChanged(q);
- }
- }
-}
-
-QDeclarativeListProperty<QObject> QQuickItemPrivate::data()
-{
- return QDeclarativeListProperty<QObject>(q_func(), 0, QQuickItemPrivate::data_append,
- QQuickItemPrivate::data_count,
- QQuickItemPrivate::data_at,
- QQuickItemPrivate::data_clear);
-}
-
-QRectF QQuickItem::childrenRect()
-{
- Q_D(QQuickItem);
- if (!d->_contents) {
- d->_contents = new QQuickContents(this);
- if (d->componentComplete)
- d->_contents->complete();
- }
- return d->_contents->rectF();
-}
-
-QList<QQuickItem *> QQuickItem::childItems() const
-{
- Q_D(const QQuickItem);
- return d->childItems;
-}
-
-bool QQuickItem::clip() const
-{
- return flags() & ItemClipsChildrenToShape;
-}
-
-void QQuickItem::setClip(bool c)
-{
- if (clip() == c)
- return;
-
- setFlag(ItemClipsChildrenToShape, c);
-
- emit clipChanged(c);
-}
-
-
-/*!
- This function is called to handle this item's changes in
- geometry from \a oldGeometry to \a newGeometry. If the two
- geometries are the same, it doesn't do anything.
- */
-void QQuickItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_D(QQuickItem);
-
- if (d->_anchors)
- QQuickAnchorsPrivate::get(d->_anchors)->updateMe();
-
- bool xChange = (newGeometry.x() != oldGeometry.x());
- bool yChange = (newGeometry.y() != oldGeometry.y());
- bool widthChange = (newGeometry.width() != oldGeometry.width());
- bool heightChange = (newGeometry.height() != oldGeometry.height());
-
- for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::Geometry) {
- if (change.gTypes == QQuickItemPrivate::GeometryChange) {
- change.listener->itemGeometryChanged(this, newGeometry, oldGeometry);
- } else if ((xChange && (change.gTypes & QQuickItemPrivate::XChange)) ||
- (yChange && (change.gTypes & QQuickItemPrivate::YChange)) ||
- (widthChange && (change.gTypes & QQuickItemPrivate::WidthChange)) ||
- (heightChange && (change.gTypes & QQuickItemPrivate::HeightChange))) {
- change.listener->itemGeometryChanged(this, newGeometry, oldGeometry);
- }
- }
- }
-
- if (xChange)
- emit xChanged();
- if (yChange)
- emit yChanged();
- if (widthChange)
- emit widthChanged();
- if (heightChange)
- emit heightChanged();
-}
-
-/*!
- Called by the rendering thread when it is time to sync the state of the QML objects with the
- scene graph objects. The function should return the root of the scene graph subtree for
- this item. \a oldNode is the node that was returned the last time the function was called.
-
- The main thread is blocked while this function is executed so it is safe to read
- values from the QQuickItem instance and other objects in the main thread.
-
- \warning This is the only function in which it is allowed to make use of scene graph
- objects from the main thread. Use of scene graph objects outside this function will
- result in race conditions and potential crashes.
- */
-
-QSGNode *QQuickItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
-{
- delete oldNode;
- return 0;
-}
-
-QSGTransformNode *QQuickItemPrivate::createTransformNode()
-{
- return new QSGTransformNode;
-}
-
-void QQuickItem::updatePolish()
-{
-}
-
-void QQuickItemPrivate::removeItemChangeListener(QQuickItemChangeListener *listener, ChangeTypes types)
-{
- ChangeListener change(listener, types);
- changeListeners.removeOne(change);
-}
-
-void QQuickItemPrivate::updateOrAddGeometryChangeListener(QQuickItemChangeListener *listener, GeometryChangeTypes types)
-{
- ChangeListener change(listener, types);
- int index = changeListeners.find(change);
- if (index > -1)
- changeListeners[index].gTypes = change.gTypes; //we may have different GeometryChangeTypes
- else
- changeListeners.append(change);
-}
-
-void QQuickItemPrivate::updateOrRemoveGeometryChangeListener(QQuickItemChangeListener *listener, GeometryChangeTypes types)
-{
- ChangeListener change(listener, types);
- if (types == NoChange) {
- changeListeners.removeOne(change);
- } else {
- int index = changeListeners.find(change);
- if (index > -1)
- changeListeners[index].gTypes = change.gTypes; //we may have different GeometryChangeTypes
- }
-}
-
-void QQuickItem::keyPressEvent(QKeyEvent *event)
-{
- event->ignore();
-}
-
-void QQuickItem::keyReleaseEvent(QKeyEvent *event)
-{
- event->ignore();
-}
-
-void QQuickItem::inputMethodEvent(QInputMethodEvent *event)
-{
- event->ignore();
-}
-
-void QQuickItem::focusInEvent(QFocusEvent *)
-{
-}
-
-void QQuickItem::focusOutEvent(QFocusEvent *)
-{
-}
-
-void QQuickItem::mousePressEvent(QMouseEvent *event)
-{
- event->ignore();
-}
-
-void QQuickItem::mouseMoveEvent(QMouseEvent *event)
-{
- event->ignore();
-}
-
-void QQuickItem::mouseReleaseEvent(QMouseEvent *event)
-{
- event->ignore();
-}
-
-void QQuickItem::mouseDoubleClickEvent(QMouseEvent *event)
-{
- mousePressEvent(event);
-}
-
-void QQuickItem::mouseUngrabEvent()
-{
- // XXX todo
-}
-
-void QQuickItem::touchUngrabEvent()
-{
- // XXX todo
-}
-
-void QQuickItem::wheelEvent(QWheelEvent *event)
-{
- event->ignore();
-}
-
-void QQuickItem::touchEvent(QTouchEvent *event)
-{
- event->ignore();
-}
-
-void QQuickItem::hoverEnterEvent(QHoverEvent *event)
-{
- Q_UNUSED(event);
-}
-
-void QQuickItem::hoverMoveEvent(QHoverEvent *event)
-{
- Q_UNUSED(event);
-}
-
-void QQuickItem::hoverLeaveEvent(QHoverEvent *event)
-{
- Q_UNUSED(event);
-}
-
-void QQuickItem::dragEnterEvent(QDragEnterEvent *event)
-{
- Q_UNUSED(event);
-}
-
-void QQuickItem::dragMoveEvent(QDragMoveEvent *event)
-{
-
- Q_UNUSED(event);
-}
-
-void QQuickItem::dragLeaveEvent(QDragLeaveEvent *event)
-{
-
- Q_UNUSED(event);
-}
-
-void QQuickItem::dropEvent(QDropEvent *event)
-{
- Q_UNUSED(event);
-}
-
-bool QQuickItem::childMouseEventFilter(QQuickItem *, QEvent *)
-{
- return false;
-}
-
-void QQuickItem::windowDeactivateEvent()
-{
- foreach (QQuickItem* item, childItems()) {
- item->windowDeactivateEvent();
- }
-}
-
-Qt::InputMethodHints QQuickItem::inputMethodHints() const
-{
- Q_D(const QQuickItem);
- return d->imHints;
-}
-
-void QQuickItem::setInputMethodHints(Qt::InputMethodHints hints)
-{
- Q_D(QQuickItem);
- d->imHints = hints;
-
- if (!d->canvas || d->canvas->activeFocusItem() != this)
- return;
-
- QInputPanel *p = qApp->inputPanel();
- if (p->inputItem() == this)
- qApp->inputPanel()->update(Qt::ImHints);
-}
-
-void QQuickItem::updateMicroFocus()
-{
- QInputPanel *p = qApp->inputPanel();
- if (p->inputItem() == this)
- qApp->inputPanel()->update(Qt::ImQueryInput);
-}
-
-QVariant QQuickItem::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- Q_D(const QQuickItem);
- QVariant v;
-
- switch (query) {
- case Qt::ImEnabled:
- v = (bool)(flags() & ItemAcceptsInputMethod);
- break;
- case Qt::ImHints:
- v = (int)inputMethodHints();
- break;
- case Qt::ImCursorRectangle:
- case Qt::ImFont:
- case Qt::ImCursorPosition:
- case Qt::ImSurroundingText:
- case Qt::ImCurrentSelection:
- case Qt::ImMaximumTextLength:
- case Qt::ImAnchorPosition:
- case Qt::ImPreferredLanguage:
- if (d->keyHandler)
- v = d->keyHandler->inputMethodQuery(query);
- default:
- break;
- }
-
- return v;
-}
-
-QQuickAnchorLine QQuickItemPrivate::left() const
-{
- return anchorLines()->left;
-}
-
-QQuickAnchorLine QQuickItemPrivate::right() const
-{
- return anchorLines()->right;
-}
-
-QQuickAnchorLine QQuickItemPrivate::horizontalCenter() const
-{
- return anchorLines()->hCenter;
-}
-
-QQuickAnchorLine QQuickItemPrivate::top() const
-{
- return anchorLines()->top;
-}
-
-QQuickAnchorLine QQuickItemPrivate::bottom() const
-{
- return anchorLines()->bottom;
-}
-
-QQuickAnchorLine QQuickItemPrivate::verticalCenter() const
-{
- return anchorLines()->vCenter;
-}
-
-QQuickAnchorLine QQuickItemPrivate::baseline() const
-{
- return anchorLines()->baseline;
-}
-
-qreal QQuickItem::baselineOffset() const
-{
- Q_D(const QQuickItem);
- if (!d->baselineOffset.isValid()) {
- return 0.0;
- } else
- return d->baselineOffset;
-}
-
-void QQuickItem::setBaselineOffset(qreal offset)
-{
- Q_D(QQuickItem);
- if (offset == d->baselineOffset)
- return;
-
- d->baselineOffset = offset;
-
- for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::Geometry) {
- QQuickAnchorsPrivate *anchor = change.listener->anchorPrivate();
- if (anchor)
- anchor->updateVerticalAnchors();
- }
- }
- emit baselineOffsetChanged(offset);
-}
-
-void QQuickItem::update()
-{
- Q_D(QQuickItem);
- Q_ASSERT(flags() & ItemHasContents);
- d->dirty(QQuickItemPrivate::Content);
-}
-
-void QQuickItem::polish()
-{
- Q_D(QQuickItem);
- if (!d->polishScheduled) {
- d->polishScheduled = true;
- if (d->canvas) {
- QQuickCanvasPrivate *p = QQuickCanvasPrivate::get(d->canvas);
- bool maybeupdate = p->itemsToPolish.isEmpty();
- p->itemsToPolish.insert(this);
- if (maybeupdate) d->canvas->maybeUpdate();
- }
- }
-}
-
-void QQuickItem::mapFromItem(QDeclarativeV8Function *args) const
-{
- if (args->Length() != 0) {
- v8::Local<v8::Value> item = (*args)[0];
- QV8Engine *engine = args->engine();
-
- QQuickItem *itemObj = 0;
- if (!item->IsNull())
- itemObj = qobject_cast<QQuickItem*>(engine->toQObject(item));
-
- if (!itemObj && !item->IsNull()) {
- qmlInfo(this) << "mapFromItem() given argument \"" << engine->toString(item->ToString())
- << "\" which is neither null nor an Item";
- return;
- }
-
- v8::Local<v8::Object> rv = v8::Object::New();
- args->returnValue(rv);
-
- qreal x = (args->Length() > 1)?(*args)[1]->NumberValue():0;
- qreal y = (args->Length() > 2)?(*args)[2]->NumberValue():0;
-
- QPointF p = mapFromItem(itemObj, QPointF(x, y));
-
- rv->Set(v8::String::New("x"), v8::Number::New(p.x()));
- rv->Set(v8::String::New("y"), v8::Number::New(p.y()));
- }
-}
-
-QTransform QQuickItem::itemTransform(QQuickItem *other, bool *ok) const
-{
- Q_D(const QQuickItem);
-
- // XXX todo - we need to be able to handle common parents better and detect
- // invalid cases
- if (ok) *ok = true;
-
- QTransform t = d->itemToCanvasTransform();
- if (other) t *= QQuickItemPrivate::get(other)->canvasToItemTransform();
-
- return t;
-}
-
-void QQuickItem::mapToItem(QDeclarativeV8Function *args) const
-{
- if (args->Length() != 0) {
- v8::Local<v8::Value> item = (*args)[0];
- QV8Engine *engine = args->engine();
-
- QQuickItem *itemObj = 0;
- if (!item->IsNull())
- itemObj = qobject_cast<QQuickItem*>(engine->toQObject(item));
-
- if (!itemObj && !item->IsNull()) {
- qmlInfo(this) << "mapToItem() given argument \"" << engine->toString(item->ToString())
- << "\" which is neither null nor an Item";
- return;
- }
-
- v8::Local<v8::Object> rv = v8::Object::New();
- args->returnValue(rv);
-
- qreal x = (args->Length() > 1)?(*args)[1]->NumberValue():0;
- qreal y = (args->Length() > 2)?(*args)[2]->NumberValue():0;
-
- QPointF p = mapToItem(itemObj, QPointF(x, y));
-
- rv->Set(v8::String::New("x"), v8::Number::New(p.x()));
- rv->Set(v8::String::New("y"), v8::Number::New(p.y()));
- }
-}
-
-void QQuickItem::forceActiveFocus()
-{
- setFocus(true);
- QQuickItem *parent = parentItem();
- while (parent) {
- if (parent->flags() & QQuickItem::ItemIsFocusScope) {
- parent->setFocus(true);
- }
- parent = parent->parentItem();
- }
-}
-
-QQuickItem *QQuickItem::childAt(qreal x, qreal y) const
-{
- // XXX todo - should this include transform etc.?
- const QList<QQuickItem *> children = childItems();
- for (int i = children.count()-1; i >= 0; --i) {
- QQuickItem *child = children.at(i);
- if (child->isVisible() && child->x() <= x
- && child->x() + child->width() >= x
- && child->y() <= y
- && child->y() + child->height() >= y)
- return child;
- }
- return 0;
-}
-
-QDeclarativeListProperty<QObject> QQuickItemPrivate::resources()
-{
- return QDeclarativeListProperty<QObject>(q_func(), 0, QQuickItemPrivate::resources_append,
- QQuickItemPrivate::resources_count,
- QQuickItemPrivate::resources_at,
- QQuickItemPrivate::resources_clear);
-}
-
-QDeclarativeListProperty<QQuickItem> QQuickItemPrivate::children()
-{
- return QDeclarativeListProperty<QQuickItem>(q_func(), 0, QQuickItemPrivate::children_append,
- QQuickItemPrivate::children_count,
- QQuickItemPrivate::children_at,
- QQuickItemPrivate::children_clear);
-
-}
-
-QDeclarativeListProperty<QDeclarativeState> QQuickItemPrivate::states()
-{
- return _states()->statesProperty();
-}
-
-QDeclarativeListProperty<QDeclarativeTransition> QQuickItemPrivate::transitions()
-{
- return _states()->transitionsProperty();
-}
-
-QString QQuickItemPrivate::state() const
-{
- if (!_stateGroup)
- return QString();
- else
- return _stateGroup->state();
-}
-
-void QQuickItemPrivate::setState(const QString &state)
-{
- _states()->setState(state);
-}
-
-QString QQuickItem::state() const
-{
- Q_D(const QQuickItem);
- return d->state();
-}
-
-void QQuickItem::setState(const QString &state)
-{
- Q_D(QQuickItem);
- d->setState(state);
-}
-
-QDeclarativeListProperty<QQuickTransform> QQuickItem::transform()
-{
- return QDeclarativeListProperty<QQuickTransform>(this, 0, QQuickItemPrivate::transform_append,
- QQuickItemPrivate::transform_count,
- QQuickItemPrivate::transform_at,
- QQuickItemPrivate::transform_clear);
-}
-
-void QQuickItem::classBegin()
-{
- Q_D(QQuickItem);
- d->componentComplete = false;
- if (d->_stateGroup)
- d->_stateGroup->classBegin();
- if (d->_anchors)
- d->_anchors->classBegin();
-}
-
-void QQuickItem::componentComplete()
-{
- Q_D(QQuickItem);
- d->componentComplete = true;
- if (d->_stateGroup)
- d->_stateGroup->componentComplete();
- if (d->_anchors) {
- d->_anchors->componentComplete();
- QQuickAnchorsPrivate::get(d->_anchors)->updateOnComplete();
- }
- if (d->keyHandler)
- d->keyHandler->componentComplete();
- if (d->_contents)
- d->_contents->complete();
-}
-
-QDeclarativeStateGroup *QQuickItemPrivate::_states()
-{
- Q_Q(QQuickItem);
- if (!_stateGroup) {
- _stateGroup = new QDeclarativeStateGroup;
- if (!componentComplete)
- _stateGroup->classBegin();
- FAST_CONNECT(_stateGroup, SIGNAL(stateChanged(QString)),
- q, SIGNAL(stateChanged(QString)))
- }
-
- return _stateGroup;
-}
-
-QQuickItemPrivate::AnchorLines::AnchorLines(QQuickItem *q)
-{
- left.item = q;
- left.anchorLine = QQuickAnchorLine::Left;
- right.item = q;
- right.anchorLine = QQuickAnchorLine::Right;
- hCenter.item = q;
- hCenter.anchorLine = QQuickAnchorLine::HCenter;
- top.item = q;
- top.anchorLine = QQuickAnchorLine::Top;
- bottom.item = q;
- bottom.anchorLine = QQuickAnchorLine::Bottom;
- vCenter.item = q;
- vCenter.anchorLine = QQuickAnchorLine::VCenter;
- baseline.item = q;
- baseline.anchorLine = QQuickAnchorLine::Baseline;
-}
-
-QPointF QQuickItemPrivate::computeTransformOrigin() const
-{
- switch (origin) {
- default:
- case QQuickItem::TopLeft:
- return QPointF(0, 0);
- case QQuickItem::Top:
- return QPointF(width / 2., 0);
- case QQuickItem::TopRight:
- return QPointF(width, 0);
- case QQuickItem::Left:
- return QPointF(0, height / 2.);
- case QQuickItem::Center:
- return QPointF(width / 2., height / 2.);
- case QQuickItem::Right:
- return QPointF(width, height / 2.);
- case QQuickItem::BottomLeft:
- return QPointF(0, height);
- case QQuickItem::Bottom:
- return QPointF(width / 2., height);
- case QQuickItem::BottomRight:
- return QPointF(width, height);
- }
-}
-
-void QQuickItemPrivate::transformChanged()
-{
-}
-
-void QQuickItemPrivate::deliverKeyEvent(QKeyEvent *e)
-{
- Q_Q(QQuickItem);
-
- Q_ASSERT(e->isAccepted());
- if (keyHandler) {
- if (e->type() == QEvent::KeyPress)
- keyHandler->keyPressed(e, false);
- else
- keyHandler->keyReleased(e, false);
-
- if (e->isAccepted())
- return;
- else
- e->accept();
- }
-
- if (e->type() == QEvent::KeyPress)
- q->keyPressEvent(e);
- else
- q->keyReleaseEvent(e);
-
- if (e->isAccepted())
- return;
-
- if (keyHandler) {
- e->accept();
-
- if (e->type() == QEvent::KeyPress)
- keyHandler->keyPressed(e, true);
- else
- keyHandler->keyReleased(e, true);
- }
-}
-
-void QQuickItemPrivate::deliverInputMethodEvent(QInputMethodEvent *e)
-{
- Q_Q(QQuickItem);
-
- Q_ASSERT(e->isAccepted());
- if (keyHandler) {
- keyHandler->inputMethodEvent(e, false);
-
- if (e->isAccepted())
- return;
- else
- e->accept();
- }
-
- q->inputMethodEvent(e);
-
- if (e->isAccepted())
- return;
-
- if (keyHandler) {
- e->accept();
-
- keyHandler->inputMethodEvent(e, true);
- }
-}
-
-void QQuickItemPrivate::deliverFocusEvent(QFocusEvent *e)
-{
- Q_Q(QQuickItem);
-
- if (e->type() == QEvent::FocusIn) {
- q->focusInEvent(e);
- } else {
- q->focusOutEvent(e);
- }
-}
-
-void QQuickItemPrivate::deliverMouseEvent(QMouseEvent *e)
-{
- Q_Q(QQuickItem);
-
- Q_ASSERT(e->isAccepted());
-
- switch (e->type()) {
- default:
- Q_ASSERT(!"Unknown event type");
- case QEvent::MouseMove:
- q->mouseMoveEvent(e);
- break;
- case QEvent::MouseButtonPress:
- q->mousePressEvent(e);
- break;
- case QEvent::MouseButtonRelease:
- q->mouseReleaseEvent(e);
- break;
- case QEvent::MouseButtonDblClick:
- q->mouseDoubleClickEvent(e);
- break;
- }
-}
-
-void QQuickItemPrivate::deliverWheelEvent(QWheelEvent *e)
-{
- Q_Q(QQuickItem);
- q->wheelEvent(e);
-}
-
-void QQuickItemPrivate::deliverTouchEvent(QTouchEvent *e)
-{
- Q_Q(QQuickItem);
- q->touchEvent(e);
-}
-
-void QQuickItemPrivate::deliverHoverEvent(QHoverEvent *e)
-{
- Q_Q(QQuickItem);
- switch (e->type()) {
- default:
- Q_ASSERT(!"Unknown event type");
- case QEvent::HoverEnter:
- q->hoverEnterEvent(e);
- break;
- case QEvent::HoverLeave:
- q->hoverLeaveEvent(e);
- break;
- case QEvent::HoverMove:
- q->hoverMoveEvent(e);
- break;
- }
-}
-
-void QQuickItemPrivate::deliverDragEvent(QEvent *e)
-{
- Q_Q(QQuickItem);
- switch (e->type()) {
- default:
- Q_ASSERT(!"Unknown event type");
- case QEvent::DragEnter:
- q->dragEnterEvent(static_cast<QDragEnterEvent *>(e));
- break;
- case QEvent::DragLeave:
- q->dragLeaveEvent(static_cast<QDragLeaveEvent *>(e));
- break;
- case QEvent::DragMove:
- q->dragMoveEvent(static_cast<QDragMoveEvent *>(e));
- break;
- case QEvent::Drop:
- q->dropEvent(static_cast<QDropEvent *>(e));
- break;
- }
-}
-
-void QQuickItem::itemChange(ItemChange change, const ItemChangeData &value)
-{
- Q_UNUSED(change);
- Q_UNUSED(value);
-}
-
-/*! \internal */
-// XXX todo - do we want/need this anymore?
-// Note that it's now used for varying clip rect
-QRectF QQuickItem::boundingRect() const
-{
- Q_D(const QQuickItem);
- return QRectF(0, 0, d->width, d->height);
-}
-
-QQuickItem::TransformOrigin QQuickItem::transformOrigin() const
-{
- Q_D(const QQuickItem);
- return d->origin;
-}
-
-void QQuickItem::setTransformOrigin(TransformOrigin origin)
-{
- Q_D(QQuickItem);
- if (origin == d->origin)
- return;
-
- d->origin = origin;
- d->dirty(QQuickItemPrivate::TransformOrigin);
-
- emit transformOriginChanged(d->origin);
-}
-
-QPointF QQuickItem::transformOriginPoint() const
-{
- Q_D(const QQuickItem);
- if (!d->transformOriginPoint.isNull())
- return d->transformOriginPoint;
- return d->computeTransformOrigin();
-}
-
-void QQuickItem::setTransformOriginPoint(const QPointF &point)
-{
- Q_D(QQuickItem);
- if (d->transformOriginPoint == point)
- return;
-
- d->transformOriginPoint = point;
- d->dirty(QQuickItemPrivate::TransformOrigin);
-}
-
-qreal QQuickItem::z() const
-{
- Q_D(const QQuickItem);
- return d->z;
-}
-
-void QQuickItem::setZ(qreal v)
-{
- Q_D(QQuickItem);
- if (d->z == v)
- return;
-
- d->z = v;
-
- d->dirty(QQuickItemPrivate::ZValue);
- if (d->parentItem) {
- QQuickItemPrivate::get(d->parentItem)->dirty(QQuickItemPrivate::ChildrenStackingChanged);
- QQuickItemPrivate::get(d->parentItem)->markSortedChildrenDirty(this);
- }
-
- emit zChanged();
-}
-
-
-/*!
- \qmlproperty real QtQuick2::Item::rotation
- This property holds the rotation of the item in degrees clockwise.
-
- This specifies how many degrees to rotate the item around its transformOrigin.
- The default rotation is 0 degrees (i.e. not rotated at all).
-
- \table
- \row
- \o \image declarative-rotation.png
- \o
- \qml
- Rectangle {
- color: "blue"
- width: 100; height: 100
- Rectangle {
- color: "red"
- x: 25; y: 25; width: 50; height: 50
- rotation: 30
- }
- }
- \endqml
- \endtable
-
- \sa transform, Rotation
-*/
-
-/*!
- \qmlproperty real QtQuick2::Item::scale
- This property holds the scale of the item.
-
- A scale of less than 1 means the item will be displayed smaller than
- normal, and a scale of greater than 1 means the item will be
- displayed larger than normal. A negative scale means the item will
- be mirrored.
-
- By default, items are displayed at a scale of 1 (i.e. at their
- normal size).
-
- Scaling is from the item's transformOrigin.
-
- \table
- \row
- \o \image declarative-scale.png
- \o
- \qml
- Rectangle {
- color: "blue"
- width: 100; height: 100
- Rectangle {
- color: "green"
- width: 25; height: 25
- }
- Rectangle {
- color: "red"
- x: 25; y: 25; width: 50; height: 50
- scale: 1.4
- }
- }
- \endqml
- \endtable
-
- \sa transform, Scale
-*/
-
-/*!
- \qmlproperty real QtQuick2::Item::opacity
-
- This property holds the opacity of the item. Opacity is specified as a
- number between 0 (fully transparent) and 1 (fully opaque). The default is 1.
-
- When this property is set, the specified opacity is also applied
- individually to child items. In almost all cases this is what you want,
- but in some cases it may produce undesired results. For example in the
- second set of rectangles below, the red rectangle has specified an opacity
- of 0.5, which affects the opacity of its blue child rectangle even though
- the child has not specified an opacity.
-
- \table
- \row
- \o \image declarative-item_opacity1.png
- \o
- \qml
- Item {
- Rectangle {
- color: "red"
- width: 100; height: 100
- Rectangle {
- color: "blue"
- x: 50; y: 50; width: 100; height: 100
- }
- }
- }
- \endqml
- \row
- \o \image declarative-item_opacity2.png
- \o
- \qml
- Item {
- Rectangle {
- opacity: 0.5
- color: "red"
- width: 100; height: 100
- Rectangle {
- color: "blue"
- x: 50; y: 50; width: 100; height: 100
- }
- }
- }
- \endqml
- \endtable
-
- If an item's opacity is set to 0, the item will no longer receive mouse
- events, but will continue to receive key events and will retain the keyboard
- \l focus if it has been set. (In contrast, setting the \l visible property
- to \c false stops both mouse and keyboard events, and also removes focus
- from the item.)
-*/
-
-/*!
- Returns a value indicating whether mouse input should
- remain with this item exclusively.
-
- \sa setKeepMouseGrab()
- */
-
-qreal QQuickItem::rotation() const
-{
- Q_D(const QQuickItem);
- return d->rotation;
-}
-
-void QQuickItem::setRotation(qreal r)
-{
- Q_D(QQuickItem);
- if (d->rotation == r)
- return;
-
- d->rotation = r;
-
- d->dirty(QQuickItemPrivate::BasicTransform);
-
- d->itemChange(ItemRotationHasChanged, r);
-
- emit rotationChanged();
-}
-
-qreal QQuickItem::scale() const
-{
- Q_D(const QQuickItem);
- return d->scale;
-}
-
-void QQuickItem::setScale(qreal s)
-{
- Q_D(QQuickItem);
- if (d->scale == s)
- return;
-
- d->scale = s;
-
- d->dirty(QQuickItemPrivate::BasicTransform);
-
- emit scaleChanged();
-}
-
-qreal QQuickItem::opacity() const
-{
- Q_D(const QQuickItem);
- return d->opacity;
-}
-
-void QQuickItem::setOpacity(qreal o)
-{
- Q_D(QQuickItem);
- if (d->opacity == o)
- return;
-
- d->opacity = o;
-
- d->dirty(QQuickItemPrivate::OpacityValue);
-
- d->itemChange(ItemOpacityHasChanged, o);
-
- emit opacityChanged();
-}
-
-bool QQuickItem::isVisible() const
-{
- Q_D(const QQuickItem);
- return d->effectiveVisible;
-}
-
-void QQuickItem::setVisible(bool v)
-{
- Q_D(QQuickItem);
- if (v == d->explicitVisible)
- return;
-
- d->explicitVisible = v;
-
- d->setEffectiveVisibleRecur(d->calcEffectiveVisible());
-}
-
-bool QQuickItem::isEnabled() const
-{
- Q_D(const QQuickItem);
- return d->effectiveEnable;
-}
-
-void QQuickItem::setEnabled(bool e)
-{
- Q_D(QQuickItem);
- if (e == d->explicitEnable)
- return;
-
- d->explicitEnable = e;
-
- d->setEffectiveEnableRecur(d->calcEffectiveEnable());
-}
-
-bool QQuickItemPrivate::calcEffectiveVisible() const
-{
- // XXX todo - Should the effective visible of an element with no parent just be the current
- // effective visible? This would prevent pointless re-processing in the case of an element
- // moving to/from a no-parent situation, but it is different from what graphics view does.
- return explicitVisible && (!parentItem || QQuickItemPrivate::get(parentItem)->effectiveVisible);
-}
-
-void QQuickItemPrivate::setEffectiveVisibleRecur(bool newEffectiveVisible)
-{
- Q_Q(QQuickItem);
-
- if (newEffectiveVisible && !explicitVisible) {
- // This item locally overrides visibility
- return;
- }
-
- if (newEffectiveVisible == effectiveVisible) {
- // No change necessary
- return;
- }
-
- effectiveVisible = newEffectiveVisible;
- dirty(Visible);
- if (parentItem) QQuickItemPrivate::get(parentItem)->dirty(ChildrenStackingChanged);
-
- if (canvas) {
- QQuickCanvasPrivate *canvasPriv = QQuickCanvasPrivate::get(canvas);
- if (canvasPriv->mouseGrabberItem == q)
- q->ungrabMouse();
- }
-
- for (int ii = 0; ii < childItems.count(); ++ii)
- QQuickItemPrivate::get(childItems.at(ii))->setEffectiveVisibleRecur(newEffectiveVisible);
-
- for (int ii = 0; ii < changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::Visibility)
- change.listener->itemVisibilityChanged(q);
- }
-
- emit q->visibleChanged();
-}
-
-bool QQuickItemPrivate::calcEffectiveEnable() const
-{
- // XXX todo - Should the effective enable of an element with no parent just be the current
- // effective enable? This would prevent pointless re-processing in the case of an element
- // moving to/from a no-parent situation, but it is different from what graphics view does.
- return explicitEnable && (!parentItem || QQuickItemPrivate::get(parentItem)->effectiveEnable);
-}
-
-void QQuickItemPrivate::setEffectiveEnableRecur(bool newEffectiveEnable)
-{
- Q_Q(QQuickItem);
-
- // XXX todo - need to fixup focus
-
- if (newEffectiveEnable && !explicitEnable) {
- // This item locally overrides enable
- return;
- }
-
- if (newEffectiveEnable == effectiveEnable) {
- // No change necessary
- return;
- }
-
- effectiveEnable = newEffectiveEnable;
-
- if (canvas) {
- QQuickCanvasPrivate *canvasPriv = QQuickCanvasPrivate::get(canvas);
- if (canvasPriv->mouseGrabberItem == q)
- q->ungrabMouse();
- }
-
- for (int ii = 0; ii < childItems.count(); ++ii)
- QQuickItemPrivate::get(childItems.at(ii))->setEffectiveEnableRecur(newEffectiveEnable);
-
- emit q->enabledChanged();
-}
-
-QString QQuickItemPrivate::dirtyToString() const
-{
-#define DIRTY_TO_STRING(value) if (dirtyAttributes & value) { \
- if (!rv.isEmpty()) \
- rv.append(QLatin1String("|")); \
- rv.append(QLatin1String(#value)); \
-}
-
-// QString rv = QLatin1String("0x") + QString::number(dirtyAttributes, 16);
- QString rv;
-
- DIRTY_TO_STRING(TransformOrigin);
- DIRTY_TO_STRING(Transform);
- DIRTY_TO_STRING(BasicTransform);
- DIRTY_TO_STRING(Position);
- DIRTY_TO_STRING(Size);
- DIRTY_TO_STRING(ZValue);
- DIRTY_TO_STRING(Content);
- DIRTY_TO_STRING(Smooth);
- DIRTY_TO_STRING(OpacityValue);
- DIRTY_TO_STRING(ChildrenChanged);
- DIRTY_TO_STRING(ChildrenStackingChanged);
- DIRTY_TO_STRING(ParentChanged);
- DIRTY_TO_STRING(Clip);
- DIRTY_TO_STRING(Canvas);
- DIRTY_TO_STRING(EffectReference);
- DIRTY_TO_STRING(Visible);
- DIRTY_TO_STRING(HideReference);
-
- return rv;
-}
-
-void QQuickItemPrivate::dirty(DirtyType type)
-{
- Q_Q(QQuickItem);
- if (type & (TransformOrigin | Transform | BasicTransform | Position | Size))
- transformChanged();
-
- if (!(dirtyAttributes & type) || (canvas && !prevDirtyItem)) {
- dirtyAttributes |= type;
- if (canvas) {
- addToDirtyList();
- QQuickCanvasPrivate::get(canvas)->dirtyItem(q);
- }
- }
-}
-
-void QQuickItemPrivate::addToDirtyList()
-{
- Q_Q(QQuickItem);
-
- Q_ASSERT(canvas);
- if (!prevDirtyItem) {
- Q_ASSERT(!nextDirtyItem);
-
- QQuickCanvasPrivate *p = QQuickCanvasPrivate::get(canvas);
- nextDirtyItem = p->dirtyItemList;
- if (nextDirtyItem) QQuickItemPrivate::get(nextDirtyItem)->prevDirtyItem = &nextDirtyItem;
- prevDirtyItem = &p->dirtyItemList;
- p->dirtyItemList = q;
- p->dirtyItem(q);
- }
- Q_ASSERT(prevDirtyItem);
-}
-
-void QQuickItemPrivate::removeFromDirtyList()
-{
- if (prevDirtyItem) {
- if (nextDirtyItem) QQuickItemPrivate::get(nextDirtyItem)->prevDirtyItem = prevDirtyItem;
- *prevDirtyItem = nextDirtyItem;
- prevDirtyItem = 0;
- nextDirtyItem = 0;
- }
- Q_ASSERT(!prevDirtyItem);
- Q_ASSERT(!nextDirtyItem);
-}
-
-void QQuickItemPrivate::refFromEffectItem(bool hide)
-{
- ++effectRefCount;
- if (1 == effectRefCount) {
- dirty(EffectReference);
- if (parentItem) QQuickItemPrivate::get(parentItem)->dirty(ChildrenStackingChanged);
- }
- if (hide) {
- if (++hideRefCount == 1)
- dirty(HideReference);
- }
-}
-
-void QQuickItemPrivate::derefFromEffectItem(bool unhide)
-{
- Q_ASSERT(effectRefCount);
- --effectRefCount;
- if (0 == effectRefCount) {
- dirty(EffectReference);
- if (parentItem) QQuickItemPrivate::get(parentItem)->dirty(ChildrenStackingChanged);
- }
- if (unhide) {
- if (--hideRefCount == 0)
- dirty(HideReference);
- }
-}
-
-void QQuickItemPrivate::itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData &data)
-{
- Q_Q(QQuickItem);
- switch (change) {
- case QQuickItem::ItemChildAddedChange:
- q->itemChange(change, data);
- for (int ii = 0; ii < changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::Children) {
- change.listener->itemChildAdded(q, data.item);
- }
- }
- break;
- case QQuickItem::ItemChildRemovedChange:
- q->itemChange(change, data);
- for (int ii = 0; ii < changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::Children) {
- change.listener->itemChildRemoved(q, data.item);
- }
- }
- break;
- case QQuickItem::ItemSceneChange:
- q->itemChange(change, data);
- break;
- case QQuickItem::ItemVisibleHasChanged:
- q->itemChange(change, data);
- for (int ii = 0; ii < changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::Visibility) {
- change.listener->itemVisibilityChanged(q);
- }
- }
- break;
- case QQuickItem::ItemParentHasChanged:
- q->itemChange(change, data);
- for (int ii = 0; ii < changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::Parent) {
- change.listener->itemParentChanged(q, data.item);
- }
- }
- break;
- case QQuickItem::ItemOpacityHasChanged:
- q->itemChange(change, data);
- for (int ii = 0; ii < changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::Opacity) {
- change.listener->itemOpacityChanged(q);
- }
- }
- break;
- case QQuickItem::ItemActiveFocusHasChanged:
- q->itemChange(change, data);
- break;
- case QQuickItem::ItemRotationHasChanged:
- q->itemChange(change, data);
- for (int ii = 0; ii < changeListeners.count(); ++ii) {
- const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
- if (change.types & QQuickItemPrivate::Rotation) {
- change.listener->itemRotationChanged(q);
- }
- }
- break;
- }
-}
-
-/*!
- \property QQuickItem::smooth
- \brief whether the item is smoothly transformed.
-
- This property is provided purely for the purpose of optimization. Turning
- smooth transforms off is faster, but looks worse; turning smooth
- transformations on is slower, but looks better.
-
- By default smooth transformations are off.
-*/
-
-/*!
- Returns true if the item should be drawn with antialiasing and
- smooth pixmap filtering, false otherwise.
-
- The default is false.
-
- \sa setSmooth()
-*/
-bool QQuickItem::smooth() const
-{
- Q_D(const QQuickItem);
- return d->smooth;
-}
-
-/*!
- Sets whether the item should be drawn with antialiasing and
- smooth pixmap filtering to \a smooth.
-
- \sa smooth()
-*/
-void QQuickItem::setSmooth(bool smooth)
-{
- Q_D(QQuickItem);
- if (d->smooth == smooth)
- return;
-
- d->smooth = smooth;
- d->dirty(QQuickItemPrivate::Smooth);
-
- emit smoothChanged(smooth);
-}
-
-QQuickItem::Flags QQuickItem::flags() const
-{
- Q_D(const QQuickItem);
- return (QQuickItem::Flags)d->flags;
-}
-
-void QQuickItem::setFlag(Flag flag, bool enabled)
-{
- Q_D(QQuickItem);
- if (enabled)
- setFlags((Flags)(d->flags | (quint32)flag));
- else
- setFlags((Flags)(d->flags & ~(quint32)flag));
-}
-
-void QQuickItem::setFlags(Flags flags)
-{
- Q_D(QQuickItem);
-
- if ((flags & ItemIsFocusScope) != (d->flags & ItemIsFocusScope)) {
- if (flags & ItemIsFocusScope && !d->childItems.isEmpty() && d->canvas) {
- qWarning("QQuickItem: Cannot set FocusScope once item has children and is in a canvas.");
- flags &= ~ItemIsFocusScope;
- } else if (d->flags & ItemIsFocusScope) {
- qWarning("QQuickItem: Cannot unset FocusScope flag.");
- flags |= ItemIsFocusScope;
- }
- }
-
- if ((flags & ItemClipsChildrenToShape ) != (d->flags & ItemClipsChildrenToShape))
- d->dirty(QQuickItemPrivate::Clip);
-
- d->flags = flags;
-}
-
-qreal QQuickItem::x() const
-{
- Q_D(const QQuickItem);
- return d->x;
-}
-
-qreal QQuickItem::y() const
-{
- Q_D(const QQuickItem);
- return d->y;
-}
-
-QPointF QQuickItem::pos() const
-{
- Q_D(const QQuickItem);
- return QPointF(d->x, d->y);
-}
-
-void QQuickItem::setX(qreal v)
-{
- Q_D(QQuickItem);
- if (d->x == v)
- return;
-
- qreal oldx = d->x;
- d->x = v;
-
- d->dirty(QQuickItemPrivate::Position);
-
- geometryChanged(QRectF(x(), y(), width(), height()),
- QRectF(oldx, y(), width(), height()));
-}
-
-void QQuickItem::setY(qreal v)
-{
- Q_D(QQuickItem);
- if (d->y == v)
- return;
-
- qreal oldy = d->y;
- d->y = v;
-
- d->dirty(QQuickItemPrivate::Position);
-
- geometryChanged(QRectF(x(), y(), width(), height()),
- QRectF(x(), oldy, width(), height()));
-}
-
-void QQuickItem::setPos(const QPointF &pos)
-{
- Q_D(QQuickItem);
- if (QPointF(d->x, d->y) == pos)
- return;
-
- qreal oldx = d->x;
- qreal oldy = d->y;
-
- d->x = pos.x();
- d->y = pos.y();
-
- d->dirty(QQuickItemPrivate::Position);
-
- geometryChanged(QRectF(x(), y(), width(), height()),
- QRectF(oldx, oldy, width(), height()));
-}
-
-qreal QQuickItem::width() const
-{
- Q_D(const QQuickItem);
- return d->width;
-}
-
-void QQuickItem::setWidth(qreal w)
-{
- Q_D(QQuickItem);
- if (qIsNaN(w))
- return;
-
- d->widthValid = true;
- if (d->width == w)
- return;
-
- qreal oldWidth = d->width;
- d->width = w;
-
- d->dirty(QQuickItemPrivate::Size);
-
- geometryChanged(QRectF(x(), y(), width(), height()),
- QRectF(x(), y(), oldWidth, height()));
-}
-
-void QQuickItem::resetWidth()
-{
- Q_D(QQuickItem);
- d->widthValid = false;
- setImplicitWidth(implicitWidth());
-}
-
-void QQuickItemPrivate::implicitWidthChanged()
-{
- Q_Q(QQuickItem);
- emit q->implicitWidthChanged();
-}
-
-qreal QQuickItemPrivate::getImplicitWidth() const
-{
- return implicitWidth;
-}
-/*!
- Returns the width of the item that is implied by other properties that determine the content.
-*/
-qreal QQuickItem::implicitWidth() const
-{
- Q_D(const QQuickItem);
- return d->getImplicitWidth();
-}
-
-/*!
- \qmlproperty real QtQuick2::Item::implicitWidth
- \qmlproperty real QtQuick2::Item::implicitHeight
-
- Defines the natural width or height of the Item if no \l width or \l height is specified.
-
- The default implicit size for most items is 0x0, however some elements have an inherent
- implicit size which cannot be overridden, e.g. Image, Text.
-
- Setting the implicit size is useful for defining components that have a preferred size
- based on their content, for example:
-
- \qml
- // Label.qml
- import QtQuick 1.1
-
- Item {
- property alias icon: image.source
- property alias label: text.text
- implicitWidth: text.implicitWidth + image.implicitWidth
- implicitHeight: Math.max(text.implicitHeight, image.implicitHeight)
- Image { id: image }
- Text {
- id: text
- wrapMode: Text.Wrap
- anchors.left: image.right; anchors.right: parent.right
- anchors.verticalCenter: parent.verticalCenter
- }
- }
- \endqml
-
- \bold Note: using implicitWidth of Text or TextEdit and setting the width explicitly
- incurs a performance penalty as the text must be laid out twice.
-*/
-
-/*!
- Sets the implied width of the item to \a w.
- This is the width implied by other properties that determine the content.
-*/
-void QQuickItem::setImplicitWidth(qreal w)
-{
- Q_D(QQuickItem);
- bool changed = w != d->implicitWidth;
- d->implicitWidth = w;
- if (d->width == w || widthValid()) {
- if (changed)
- d->implicitWidthChanged();
- return;
- }
-
- qreal oldWidth = d->width;
- d->width = w;
-
- d->dirty(QQuickItemPrivate::Size);
-
- geometryChanged(QRectF(x(), y(), width(), height()),
- QRectF(x(), y(), oldWidth, height()));
-
- if (changed)
- d->implicitWidthChanged();
-}
-
-/*!
- Returns whether the width property has been set explicitly.
-*/
-bool QQuickItem::widthValid() const
-{
- Q_D(const QQuickItem);
- return d->widthValid;
-}
-
-qreal QQuickItem::height() const
-{
- Q_D(const QQuickItem);
- return d->height;
-}
-
-void QQuickItem::setHeight(qreal h)
-{
- Q_D(QQuickItem);
- if (qIsNaN(h))
- return;
-
- d->heightValid = true;
- if (d->height == h)
- return;
-
- qreal oldHeight = d->height;
- d->height = h;
-
- d->dirty(QQuickItemPrivate::Size);
-
- geometryChanged(QRectF(x(), y(), width(), height()),
- QRectF(x(), y(), width(), oldHeight));
-}
-
-void QQuickItem::resetHeight()
-{
- Q_D(QQuickItem);
- d->heightValid = false;
- setImplicitHeight(implicitHeight());
-}
-
-void QQuickItemPrivate::implicitHeightChanged()
-{
- Q_Q(QQuickItem);
- emit q->implicitHeightChanged();
-}
-
-qreal QQuickItemPrivate::getImplicitHeight() const
-{
- return implicitHeight;
-}
-
-/*!
- Returns the height of the item that is implied by other properties that determine the content.
-*/
-qreal QQuickItem::implicitHeight() const
-{
- Q_D(const QQuickItem);
- return d->getImplicitHeight();
-}
-
-
-/*!
- Sets the implied height of the item to \a h.
- This is the height implied by other properties that determine the content.
-*/
-void QQuickItem::setImplicitHeight(qreal h)
-{
- Q_D(QQuickItem);
- bool changed = h != d->implicitHeight;
- d->implicitHeight = h;
- if (d->height == h || heightValid()) {
- if (changed)
- d->implicitHeightChanged();
- return;
- }
-
- qreal oldHeight = d->height;
- d->height = h;
-
- d->dirty(QQuickItemPrivate::Size);
-
- geometryChanged(QRectF(x(), y(), width(), height()),
- QRectF(x(), y(), width(), oldHeight));
-
- if (changed)
- d->implicitHeightChanged();
-}
-
-void QQuickItem::setImplicitSize(qreal w, qreal h)
-{
- Q_D(QQuickItem);
- bool wChanged = w != d->implicitWidth;
- bool hChanged = h != d->implicitHeight;
-
- d->implicitWidth = w;
- d->implicitHeight = h;
-
- bool wDone = false;
- bool hDone = false;
- if (d->width == w || widthValid()) {
- if (wChanged)
- d->implicitWidthChanged();
- wDone = true;
- }
- if (d->height == h || heightValid()) {
- if (hChanged)
- d->implicitHeightChanged();
- hDone = true;
- }
- if (wDone && hDone)
- return;
-
- qreal oldWidth = d->width;
- qreal oldHeight = d->height;
- if (!wDone)
- d->width = w;
- if (!hDone)
- d->height = h;
-
- d->dirty(QQuickItemPrivate::Size);
-
- geometryChanged(QRectF(x(), y(), width(), height()),
- QRectF(x(), y(), oldWidth, oldHeight));
-
- if (!wDone && wChanged)
- d->implicitWidthChanged();
- if (!hDone && hChanged)
- d->implicitHeightChanged();
-}
-
-/*!
- Returns whether the height property has been set explicitly.
-*/
-bool QQuickItem::heightValid() const
-{
- Q_D(const QQuickItem);
- return d->heightValid;
-}
-
-void QQuickItem::setSize(const QSizeF &size)
-{
- Q_D(QQuickItem);
- d->heightValid = true;
- d->widthValid = true;
-
- if (QSizeF(d->width, d->height) == size)
- return;
-
- qreal oldHeight = d->height;
- qreal oldWidth = d->width;
- d->height = size.height();
- d->width = size.width();
-
- d->dirty(QQuickItemPrivate::Size);
-
- geometryChanged(QRectF(x(), y(), width(), height()),
- QRectF(x(), y(), oldWidth, oldHeight));
-}
-
-bool QQuickItem::hasActiveFocus() const
-{
- Q_D(const QQuickItem);
- return d->activeFocus;
-}
-
-bool QQuickItem::hasFocus() const
-{
- Q_D(const QQuickItem);
- return d->focus;
-}
-
-void QQuickItem::setFocus(bool focus)
-{
- Q_D(QQuickItem);
- if (d->focus == focus)
- return;
-
- if (d->canvas) {
- // Need to find our nearest focus scope
- QQuickItem *scope = parentItem();
- while (scope && !scope->isFocusScope())
- scope = scope->parentItem();
- if (focus)
- QQuickCanvasPrivate::get(d->canvas)->setFocusInScope(scope, this);
- else
- QQuickCanvasPrivate::get(d->canvas)->clearFocusInScope(scope, this);
- } else {
- d->focus = focus;
- emit focusChanged(focus);
- }
-}
-
-bool QQuickItem::isFocusScope() const
-{
- return flags() & ItemIsFocusScope;
-}
-
-QQuickItem *QQuickItem::scopedFocusItem() const
-{
- Q_D(const QQuickItem);
- if (!isFocusScope())
- return 0;
- else
- return d->subFocusItem;
-}
-
-
-Qt::MouseButtons QQuickItem::acceptedMouseButtons() const
-{
- Q_D(const QQuickItem);
- return d->acceptedMouseButtons;
-}
-
-void QQuickItem::setAcceptedMouseButtons(Qt::MouseButtons buttons)
-{
- Q_D(QQuickItem);
- d->acceptedMouseButtons = buttons;
-}
-
-bool QQuickItem::filtersChildMouseEvents() const
-{
- Q_D(const QQuickItem);
- return d->filtersChildMouseEvents;
-}
-
-void QQuickItem::setFiltersChildMouseEvents(bool filter)
-{
- Q_D(QQuickItem);
- d->filtersChildMouseEvents = filter;
-}
-
-bool QQuickItem::isUnderMouse() const
-{
- Q_D(const QQuickItem);
- if (!d->canvas)
- return false;
-
- QPoint cursorPos = QCursor::pos();
- if (QRectF(0, 0, width(), height()).contains(mapFromScene(cursorPos))) // ### refactor: d->canvas->mapFromGlobal(cursorPos))))
- return true;
- return false;
-}
-
-bool QQuickItem::acceptHoverEvents() const
-{
- Q_D(const QQuickItem);
- return d->hoverEnabled;
-}
-
-void QQuickItem::setAcceptHoverEvents(bool enabled)
-{
- Q_D(QQuickItem);
- d->hoverEnabled = enabled;
-}
-
-void QQuickItem::grabMouse()
-{
- Q_D(QQuickItem);
- if (!d->canvas)
- return;
- QQuickCanvasPrivate *canvasPriv = QQuickCanvasPrivate::get(d->canvas);
- if (canvasPriv->mouseGrabberItem == this)
- return;
-
- QQuickItem *oldGrabber = canvasPriv->mouseGrabberItem;
- canvasPriv->mouseGrabberItem = this;
- if (oldGrabber)
- oldGrabber->mouseUngrabEvent();
-}
-
-void QQuickItem::ungrabMouse()
-{
- Q_D(QQuickItem);
- if (!d->canvas)
- return;
- QQuickCanvasPrivate *canvasPriv = QQuickCanvasPrivate::get(d->canvas);
- if (canvasPriv->mouseGrabberItem != this) {
- qWarning("QQuickItem::ungrabMouse(): Item is not the mouse grabber.");
- return;
- }
-
- canvasPriv->mouseGrabberItem = 0;
- mouseUngrabEvent();
-}
-
-bool QQuickItem::keepMouseGrab() const
-{
- Q_D(const QQuickItem);
- return d->keepMouse;
-}
-
-/*!
- The flag indicating whether the mouse should remain
- with this item is set to \a keep.
-
- This is useful for items that wish to grab and keep mouse
- interaction following a predefined gesture. For example,
- an item that is interested in horizontal mouse movement
- may set keepMouseGrab to true once a threshold has been
- exceeded. Once keepMouseGrab has been set to true, filtering
- items will not react to mouse events.
-
- If the item does not indicate that it wishes to retain mouse grab,
- a filtering item may steal the grab. For example, Flickable may attempt
- to steal a mouse grab if it detects that the user has begun to
- move the viewport.
-
- \sa keepMouseGrab()
- */
-void QQuickItem::setKeepMouseGrab(bool keep)
-{
- Q_D(QQuickItem);
- d->keepMouse = keep;
-}
-
-/*!
- Grabs the touch points specified by \a ids.
-
- These touch points will be owned by the item until
- they are released. Alternatively, the grab can be stolen
- by a filtering item like Flickable. Use setKeepTouchGrab()
- to prevent the grab from being stolen.
-
- \sa ungrabTouchPoints(), setKeepTouchGrab()
-*/
-void QQuickItem::grabTouchPoints(const QList<int> &ids)
-{
- Q_D(QQuickItem);
- if (!d->canvas)
- return;
- QQuickCanvasPrivate *canvasPriv = QQuickCanvasPrivate::get(d->canvas);
-
- QSet<QQuickItem*> ungrab;
- for (int i = 0; i < ids.count(); ++i) {
- QQuickItem *oldGrabber = canvasPriv->itemForTouchPointId.value(ids.at(i));
- if (oldGrabber == this)
- return;
-
- canvasPriv->itemForTouchPointId[ids.at(i)] = this;
- if (oldGrabber)
- ungrab.insert(oldGrabber);
- }
- foreach (QQuickItem *oldGrabber, ungrab)
- oldGrabber->touchUngrabEvent();
-}
-
-/*!
- Ungrabs the touch points owned by this item.
-
- \sa grabTouchPoints()
-*/
-void QQuickItem::ungrabTouchPoints()
-{
- Q_D(QQuickItem);
- if (!d->canvas)
- return;
- QQuickCanvasPrivate *canvasPriv = QQuickCanvasPrivate::get(d->canvas);
-
- QMutableHashIterator<int, QQuickItem*> i(canvasPriv->itemForTouchPointId);
- while (i.hasNext()) {
- i.next();
- if (i.value() == this)
- i.remove();
- }
- touchUngrabEvent();
-}
-
-/*!
- Returns a value indicating whether the touch points grabbed by this item
- should remain with this item exclusively.
-
- \sa setKeepTouchGrab(), keepMouseGrab()
-*/
-bool QQuickItem::keepTouchGrab() const
-{
- Q_D(const QQuickItem);
- return d->keepTouch;
-}
-
-/*!
- The flag indicating whether the touch points grabbed
- by this item should remain with this item is set to \a keep.
-
- This is useful for items that wish to grab and keep specific touch
- points following a predefined gesture. For example,
- an item that is interested in horizontal touch point movement
- may set setKeepTouchGrab to true once a threshold has been
- exceeded. Once setKeepTouchGrab has been set to true, filtering
- items will not react to the relevant touch points.
-
- If the item does not indicate that it wishes to retain touch point grab,
- a filtering item may steal the grab. For example, Flickable may attempt
- to steal a touch point grab if it detects that the user has begun to
- move the viewport.
-
- \sa keepTouchGrab(), setKeepMouseGrab()
- */
-void QQuickItem::setKeepTouchGrab(bool keep)
-{
- Q_D(QQuickItem);
- d->keepTouch = keep;
-}
-
-/*!
- \qmlmethod object QtQuick2::Item::mapFromItem(Item item, real x, real y)
-
- Maps the point (\a x, \a y), which is in \a item's coordinate system, to
- this item's coordinate system, and returns an object with \c x and \c y
- properties matching the mapped coordinate.
-
- If \a item is a \c null value, this maps the point from the coordinate
- system of the root QML view.
-*/
-/*!
- \qmlmethod object QtQuick2::Item::mapToItem(Item item, real x, real y)
-
- Maps the point (\a x, \a y), which is in this item's coordinate system, to
- \a item's coordinate system, and returns an object with \c x and \c y
- properties matching the mapped coordinate.
-
- If \a item is a \c null value, this maps \a x and \a y to the coordinate
- system of the root QML view.
-*/
-QPointF QQuickItem::mapToItem(const QQuickItem *item, const QPointF &point) const
-{
- QPointF p = mapToScene(point);
- if (item)
- p = item->mapFromScene(p);
- return p;
-}
-
-QPointF QQuickItem::mapToScene(const QPointF &point) const
-{
- Q_D(const QQuickItem);
- return d->itemToCanvasTransform().map(point);
-}
-
-QRectF QQuickItem::mapRectToItem(const QQuickItem *item, const QRectF &rect) const
-{
- Q_D(const QQuickItem);
- QTransform t = d->itemToCanvasTransform();
- if (item)
- t *= QQuickItemPrivate::get(item)->canvasToItemTransform();
- return t.mapRect(rect);
-}
-
-QRectF QQuickItem::mapRectToScene(const QRectF &rect) const
-{
- Q_D(const QQuickItem);
- return d->itemToCanvasTransform().mapRect(rect);
-}
-
-QPointF QQuickItem::mapFromItem(const QQuickItem *item, const QPointF &point) const
-{
- QPointF p = item?item->mapToScene(point):point;
- return mapFromScene(p);
-}
-
-QPointF QQuickItem::mapFromScene(const QPointF &point) const
-{
- Q_D(const QQuickItem);
- return d->canvasToItemTransform().map(point);
-}
-
-QRectF QQuickItem::mapRectFromItem(const QQuickItem *item, const QRectF &rect) const
-{
- Q_D(const QQuickItem);
- QTransform t = item?QQuickItemPrivate::get(item)->itemToCanvasTransform():QTransform();
- t *= d->canvasToItemTransform();
- return t.mapRect(rect);
-}
-
-QRectF QQuickItem::mapRectFromScene(const QRectF &rect) const
-{
- Q_D(const QQuickItem);
- return d->canvasToItemTransform().mapRect(rect);
-}
-
-
-/*!
- \qmlmethod QtQuick2::Item::forceActiveFocus()
-
- Forces active focus on the item.
-
- This method sets focus on the item and makes sure that all the focus scopes
- higher in the object hierarchy are also given the focus.
-*/
-
-/*!
- Forces active focus on the item.
-
- This method sets focus on the item and makes sure that all the focus scopes
- higher in the object hierarchy are also given the focus.
-*/
-
-/*!
- \qmlmethod QtQuick2::Item::childAt(real x, real y)
-
- Returns the visible child item at point (\a x, \a y), which is in this
- item's coordinate system, or \c null if there is no such item.
-*/
-
-/*!
- Returns the visible child item at point (\a x, \a y), which is in this
- item's coordinate system, or 0 if there is no such item.
-*/
-
-/*!
- \qmlproperty list<State> QtQuick2::Item::states
- This property holds a list of states defined by the item.
-
- \qml
- Item {
- states: [
- State {
- // ...
- },
- State {
- // ...
- }
- // ...
- ]
- }
- \endqml
-
- \sa {qmlstate}{States}
-*/
-/*!
- \qmlproperty list<Transition> QtQuick2::Item::transitions
- This property holds a list of transitions defined by the item.
-
- \qml
- Item {
- transitions: [
- Transition {
- // ...
- },
- Transition {
- // ...
- }
- // ...
- ]
- }
- \endqml
-
- \sa {QML Animation and Transitions}{Transitions}
-*/
-/*
- \qmlproperty list<Filter> QtQuick2::Item::filter
- This property holds a list of graphical filters to be applied to the item.
-
- \l {Filter}{Filters} include things like \l {Blur}{blurring}
- the item, or giving it a \l Reflection. Some
- filters may not be available on all canvases; if a filter is not
- available on a certain canvas, it will simply not be applied for
- that canvas (but the QML will still be considered valid).
-
- \qml
- Item {
- filter: [
- Blur {
- // ...
- },
- Reflection {
- // ...
- }
- // ...
- ]
- }
- \endqml
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Item::clip
- This property holds whether clipping is enabled. The default clip value is \c false.
-
- If clipping is enabled, an item will clip its own painting, as well
- as the painting of its children, to its bounding rectangle.
-
- Non-rectangular clipping regions are not supported for performance reasons.
-*/
-
-/*!
- \property QQuickItem::clip
- This property holds whether clipping is enabled. The default clip value is \c false.
-
- If clipping is enabled, an item will clip its own painting, as well
- as the painting of its children, to its bounding rectangle. If you set
- clipping during an item's paint operation, remember to re-set it to
- prevent clipping the rest of your scene.
-
- Non-rectangular clipping regions are not supported for performance reasons.
-*/
-
-/*!
- \qmlproperty string QtQuick2::Item::state
-
- This property holds the name of the current state of the item.
-
- This property is often used in scripts to change between states. For
- example:
-
- \js
- function toggle() {
- if (button.state == 'On')
- button.state = 'Off';
- else
- button.state = 'On';
- }
- \endjs
-
- If the item is in its base state (i.e. no explicit state has been
- set), \c state will be a blank string. Likewise, you can return an
- item to its base state by setting its current state to \c ''.
-
- \sa {qmlstates}{States}
-*/
-
-/*!
- \qmlproperty list<Transform> QtQuick2::Item::transform
- This property holds the list of transformations to apply.
-
- For more information see \l Transform.
-*/
-
-/*!
- \enum QQuickItem::TransformOrigin
-
- Controls the point about which simple transforms like scale apply.
-
- \value TopLeft The top-left corner of the item.
- \value Top The center point of the top of the item.
- \value TopRight The top-right corner of the item.
- \value Left The left most point of the vertical middle.
- \value Center The center of the item.
- \value Right The right most point of the vertical middle.
- \value BottomLeft The bottom-left corner of the item.
- \value Bottom The center point of the bottom of the item.
- \value BottomRight The bottom-right corner of the item.
-*/
-
-
-/*!
- \qmlproperty bool QtQuick2::Item::activeFocus
-
- This property indicates whether the item has active focus.
-
- An item with active focus will receive keyboard input,
- or is a FocusScope ancestor of the item that will receive keyboard input.
-
- Usually, activeFocus is gained by setting focus on an item and its enclosing
- FocusScopes. In the following example \c input will have activeFocus.
- \qml
- Rectangle {
- FocusScope {
- focus: true
- TextInput {
- id: input
- focus: true
- }
- }
- }
- \endqml
-
- \sa focus, {qmlfocus}{Keyboard Focus}
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Item::focus
- This property indicates whether the item has focus within the enclosing focus scope. If true, this item
- will gain active focus when the enclosing focus scope gains active focus.
- In the following example, \c input will be given active focus when \c scope gains active focus.
- \qml
- Rectangle {
- FocusScope {
- id: scope
- TextInput {
- id: input
- focus: true
- }
- }
- }
- \endqml
-
- For the purposes of this property, the scene as a whole is assumed to act like a focus scope.
- On a practical level, that means the following QML will give active focus to \c input on startup.
-
- \qml
- Rectangle {
- TextInput {
- id: input
- focus: true
- }
- }
- \endqml
-
- \sa activeFocus, {qmlfocus}{Keyboard Focus}
-*/
-
-
-/*!
- \property QQuickItem::anchors
- \internal
-*/
-
-/*!
- \property QQuickItem::left
- \internal
-*/
-
-/*!
- \property QQuickItem::right
- \internal
-*/
-
-/*!
- \property QQuickItem::horizontalCenter
- \internal
-*/
-
-/*!
- \property QQuickItem::top
- \internal
-*/
-
-/*!
- \property QQuickItem::bottom
- \internal
-*/
-
-/*!
- \property QQuickItem::verticalCenter
- \internal
-*/
-
-/*!
- \property QQuickItem::focus
- \internal
-*/
-
-/*!
- \property QQuickItem::transform
- \internal
-*/
-
-/*!
- \property QQuickItem::transformOrigin
- \internal
-*/
-
-/*!
- \property QQuickItem::activeFocus
- \internal
-*/
-
-/*!
- \property QQuickItem::baseline
- \internal
-*/
-
-/*!
- \property QQuickItem::data
- \internal
-*/
-
-/*!
- \property QQuickItem::resources
- \internal
-*/
-
-/*!
- \property QQuickItem::state
- \internal
-*/
-
-/*!
- \property QQuickItem::states
- \internal
-*/
-
-/*!
- \property QQuickItem::transformOriginPoint
- \internal
-*/
-
-/*!
- \property QQuickItem::transitions
- \internal
-*/
-
-bool QQuickItem::event(QEvent *ev)
-{
-#if 0
- if (ev->type() == QEvent::PolishRequest) {
- Q_D(QQuickItem);
- d->polishScheduled = false;
- updatePolish();
- return true;
- } else {
- return QObject::event(ev);
- }
-#endif
- if (ev->type() == QEvent::InputMethodQuery) {
- QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(ev);
- Qt::InputMethodQueries queries = query->queries();
- for (uint i = 0; i < 32; ++i) {
- Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
- if (q) {
- QVariant v = inputMethodQuery(q);
- query->setValue(q, v);
- }
- }
- query->accept();
- return true;
- } else if (ev->type() == QEvent::InputMethod) {
- inputMethodEvent(static_cast<QInputMethodEvent *>(ev));
- return true;
- }
- return QObject::event(ev);
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug debug, QQuickItem *item)
-{
- if (!item) {
- debug << "QQuickItem(0)";
- return debug;
- }
-
- debug << item->metaObject()->className() << "(this =" << ((void*)item)
- << ", name=" << item->objectName()
- << ", parent =" << ((void*)item->parentItem())
- << ", geometry =" << QRectF(item->pos(), QSizeF(item->width(), item->height()))
- << ", z =" << item->z() << ')';
- return debug;
-}
-#endif
-
-qint64 QQuickItemPrivate::consistentTime = -1;
-void QQuickItemPrivate::setConsistentTime(qint64 t)
-{
- consistentTime = t;
-}
-
-class QElapsedTimerConsistentTimeHack
-{
-public:
- void start() {
- t1 = QQuickItemPrivate::consistentTime;
- t2 = 0;
- }
- qint64 elapsed() {
- return QQuickItemPrivate::consistentTime - t1;
- }
- qint64 restart() {
- qint64 val = QQuickItemPrivate::consistentTime - t1;
- t1 = QQuickItemPrivate::consistentTime;
- t2 = 0;
- return val;
- }
-
-private:
- qint64 t1;
- qint64 t2;
-};
-
-void QQuickItemPrivate::start(QElapsedTimer &t)
-{
- if (QQuickItemPrivate::consistentTime == -1)
- t.start();
- else
- ((QElapsedTimerConsistentTimeHack*)&t)->start();
-}
-
-qint64 QQuickItemPrivate::elapsed(QElapsedTimer &t)
-{
- if (QQuickItemPrivate::consistentTime == -1)
- return t.elapsed();
- else
- return ((QElapsedTimerConsistentTimeHack*)&t)->elapsed();
-}
-
-qint64 QQuickItemPrivate::restart(QElapsedTimer &t)
-{
- if (QQuickItemPrivate::consistentTime == -1)
- return t.restart();
- else
- return ((QElapsedTimerConsistentTimeHack*)&t)->restart();
-}
-
-/*!
- \fn bool QQuickItem::isTextureProvider() const
-
- Returns true if this item is a texture provider. The default
- implementation returns false.
-
- This function can be called from any thread.
- */
-
-/*!
- \fn QSGTextureProvider *QQuickItem::textureProvider() const
-
- Returns the texture provider for an item. The default implementation
- returns 0.
-
- This function may only be called on the rendering thread.
- */
-
-QT_END_NAMESPACE
-
-#include <moc_qquickitem.cpp>
diff --git a/src/declarative/items/qquickitem.h b/src/declarative/items/qquickitem.h
deleted file mode 100644
index a3baecb9ea..0000000000
--- a/src/declarative/items/qquickitem.h
+++ /dev/null
@@ -1,421 +0,0 @@
-// Commit: 6f78a6080b84cc3ef96b73a4ff58d1b5a72f08f4
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKITEM_H
-#define QQUICKITEM_H
-
-#include <QtDeclarative/qdeclarative.h>
-#include <QtDeclarative/qdeclarativecomponent.h>
-
-#include <QtCore/QObject>
-#include <QtCore/QList>
-#include <QtGui/qevent.h>
-#include <QtGui/qfont.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickItem;
-class QQuickTransformPrivate;
-class QQuickTransform : public QObject
-{
- Q_OBJECT
-public:
- QQuickTransform(QObject *parent = 0);
- ~QQuickTransform();
-
- void appendToItem(QQuickItem *);
- void prependToItem(QQuickItem *);
-
- virtual void applyTo(QMatrix4x4 *matrix) const = 0;
-
-protected Q_SLOTS:
- void update();
-
-protected:
- QQuickTransform(QQuickTransformPrivate &dd, QObject *parent);
-
-private:
- Q_DECLARE_PRIVATE(QQuickTransform)
-};
-
-class QDeclarativeV8Function;
-class QDeclarativeState;
-class QQuickAnchorLine;
-class QDeclarativeTransition;
-class QQuickKeyEvent;
-class QQuickAnchors;
-class QQuickItemPrivate;
-class QQuickCanvas;
-class QSGEngine;
-class QTouchEvent;
-class QSGNode;
-class QSGTransformNode;
-class QSGTextureProvider;
-
-class Q_DECLARATIVE_EXPORT QQuickItem : public QObject, public QDeclarativeParserStatus
-{
- Q_OBJECT
- Q_INTERFACES(QDeclarativeParserStatus)
-
- Q_PROPERTY(QQuickItem *parent READ parentItem WRITE setParentItem NOTIFY parentChanged DESIGNABLE false FINAL)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QDeclarativeListProperty<QObject> data READ data DESIGNABLE false)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QDeclarativeListProperty<QObject> resources READ resources DESIGNABLE false)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QDeclarativeListProperty<QQuickItem> children READ children NOTIFY childrenChanged DESIGNABLE false)
-
- Q_PROPERTY(QPointF pos READ pos FINAL)
- Q_PROPERTY(qreal x READ x WRITE setX NOTIFY xChanged FINAL)
- Q_PROPERTY(qreal y READ y WRITE setY NOTIFY yChanged FINAL)
- Q_PROPERTY(qreal z READ z WRITE setZ NOTIFY zChanged FINAL)
- Q_PROPERTY(qreal width READ width WRITE setWidth NOTIFY widthChanged RESET resetWidth FINAL)
- Q_PROPERTY(qreal height READ height WRITE setHeight NOTIFY heightChanged RESET resetHeight FINAL)
-
- Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity NOTIFY opacityChanged FINAL)
- Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged)
- Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibleChanged FINAL)
-
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QDeclarativeListProperty<QDeclarativeState> states READ states DESIGNABLE false)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QDeclarativeListProperty<QDeclarativeTransition> transitions READ transitions DESIGNABLE false)
- Q_PROPERTY(QString state READ state WRITE setState NOTIFY stateChanged)
- Q_PROPERTY(QRectF childrenRect READ childrenRect NOTIFY childrenRectChanged DESIGNABLE false FINAL)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQuickAnchors * anchors READ anchors DESIGNABLE false CONSTANT FINAL)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQuickAnchorLine left READ left CONSTANT FINAL)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQuickAnchorLine right READ right CONSTANT FINAL)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQuickAnchorLine horizontalCenter READ horizontalCenter CONSTANT FINAL)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQuickAnchorLine top READ top CONSTANT FINAL)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQuickAnchorLine bottom READ bottom CONSTANT FINAL)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQuickAnchorLine verticalCenter READ verticalCenter CONSTANT FINAL)
- Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQuickAnchorLine baseline READ baseline CONSTANT FINAL)
- Q_PROPERTY(qreal baselineOffset READ baselineOffset WRITE setBaselineOffset NOTIFY baselineOffsetChanged)
-
- Q_PROPERTY(bool clip READ clip WRITE setClip NOTIFY clipChanged)
-
- Q_PROPERTY(bool focus READ hasFocus WRITE setFocus NOTIFY focusChanged FINAL)
- Q_PROPERTY(bool activeFocus READ hasActiveFocus NOTIFY activeFocusChanged FINAL)
-
- Q_PROPERTY(qreal rotation READ rotation WRITE setRotation NOTIFY rotationChanged)
- Q_PROPERTY(qreal scale READ scale WRITE setScale NOTIFY scaleChanged)
- Q_PROPERTY(TransformOrigin transformOrigin READ transformOrigin WRITE setTransformOrigin NOTIFY transformOriginChanged)
- Q_PROPERTY(QPointF transformOriginPoint READ transformOriginPoint) // XXX todo - notify?
- Q_PROPERTY(QDeclarativeListProperty<QQuickTransform> transform READ transform DESIGNABLE false FINAL)
-
- Q_PROPERTY(bool smooth READ smooth WRITE setSmooth NOTIFY smoothChanged)
- Q_PROPERTY(qreal implicitWidth READ implicitWidth WRITE setImplicitWidth NOTIFY implicitWidthChanged)
- Q_PROPERTY(qreal implicitHeight READ implicitHeight WRITE setImplicitHeight NOTIFY implicitHeightChanged)
-
- Q_ENUMS(TransformOrigin)
- Q_CLASSINFO("DefaultProperty", "data")
-
-public:
- enum Flag {
- ItemClipsChildrenToShape = 0x01,
- ItemAcceptsInputMethod = 0x02,
- ItemIsFocusScope = 0x04,
- ItemHasContents = 0x08,
- ItemAcceptsDrops = 0x10
- // Remember to increment the size of QQuickItemPrivate::flags
- };
- Q_DECLARE_FLAGS(Flags, Flag)
-
- enum ItemChange {
- ItemChildAddedChange, // value.item
- ItemChildRemovedChange, // value.item
- ItemSceneChange, // value.canvas
- ItemVisibleHasChanged, // value.realValue
- ItemParentHasChanged, // value.item
- ItemOpacityHasChanged, // value.realValue
- ItemActiveFocusHasChanged, // value.boolValue
- ItemRotationHasChanged // value.realValue
- };
-
- union ItemChangeData {
- ItemChangeData(QQuickItem *v) : item(v) {}
- ItemChangeData(QQuickCanvas *v) : canvas(v) {}
- ItemChangeData(qreal v) : realValue(v) {}
- ItemChangeData(bool v) : boolValue(v) {}
-
- QQuickItem *item;
- QQuickCanvas *canvas;
- qreal realValue;
- bool boolValue;
- };
-
- enum TransformOrigin {
- TopLeft, Top, TopRight,
- Left, Center, Right,
- BottomLeft, Bottom, BottomRight
- };
-
- QQuickItem(QQuickItem *parent = 0);
- virtual ~QQuickItem();
-
- QSGEngine *sceneGraphEngine() const;
-
- QQuickCanvas *canvas() const;
- QQuickItem *parentItem() const;
- void setParentItem(QQuickItem *parent);
- void stackBefore(const QQuickItem *);
- void stackAfter(const QQuickItem *);
-
- QRectF childrenRect();
- QList<QQuickItem *> childItems() const;
-
- bool clip() const;
- void setClip(bool);
-
- QString state() const;
- void setState(const QString &);
-
- qreal baselineOffset() const;
- void setBaselineOffset(qreal);
-
- QDeclarativeListProperty<QQuickTransform> transform();
-
- qreal x() const;
- qreal y() const;
- QPointF pos() const;
- void setX(qreal);
- void setY(qreal);
- void setPos(const QPointF &);
-
- qreal width() const;
- void setWidth(qreal);
- void resetWidth();
- qreal implicitWidth() const;
-
- qreal height() const;
- void setHeight(qreal);
- void resetHeight();
- qreal implicitHeight() const;
-
- void setSize(const QSizeF &size);
-
- TransformOrigin transformOrigin() const;
- void setTransformOrigin(TransformOrigin);
- QPointF transformOriginPoint() const;
- void setTransformOriginPoint(const QPointF &);
-
- qreal z() const;
- void setZ(qreal);
-
- qreal rotation() const;
- void setRotation(qreal);
- qreal scale() const;
- void setScale(qreal);
-
- qreal opacity() const;
- void setOpacity(qreal);
-
- bool isVisible() const;
- void setVisible(bool);
-
- bool isEnabled() const;
- void setEnabled(bool);
-
- bool smooth() const;
- void setSmooth(bool);
-
- Flags flags() const;
- void setFlag(Flag flag, bool enabled = true);
- void setFlags(Flags flags);
-
- virtual QRectF boundingRect() const;
-
- bool hasActiveFocus() const;
- bool hasFocus() const;
- void setFocus(bool);
- bool isFocusScope() const;
- QQuickItem *scopedFocusItem() const;
-
- Qt::MouseButtons acceptedMouseButtons() const;
- void setAcceptedMouseButtons(Qt::MouseButtons buttons);
- bool acceptHoverEvents() const;
- void setAcceptHoverEvents(bool enabled);
-
- bool isUnderMouse() const;
- void grabMouse();
- void ungrabMouse();
- bool keepMouseGrab() const;
- void setKeepMouseGrab(bool);
- bool filtersChildMouseEvents() const;
- void setFiltersChildMouseEvents(bool filter);
-
- void grabTouchPoints(const QList<int> &ids);
- void ungrabTouchPoints();
- bool keepTouchGrab() const;
- void setKeepTouchGrab(bool);
-
- QTransform itemTransform(QQuickItem *, bool *) const;
- QPointF mapToItem(const QQuickItem *item, const QPointF &point) const;
- QPointF mapToScene(const QPointF &point) const;
- QRectF mapRectToItem(const QQuickItem *item, const QRectF &rect) const;
- QRectF mapRectToScene(const QRectF &rect) const;
- QPointF mapFromItem(const QQuickItem *item, const QPointF &point) const;
- QPointF mapFromScene(const QPointF &point) const;
- QRectF mapRectFromItem(const QQuickItem *item, const QRectF &rect) const;
- QRectF mapRectFromScene(const QRectF &rect) const;
-
- void polish();
-
- Q_INVOKABLE void mapFromItem(QDeclarativeV8Function*) const;
- Q_INVOKABLE void mapToItem(QDeclarativeV8Function*) const;
- Q_INVOKABLE void forceActiveFocus();
- Q_INVOKABLE QQuickItem *childAt(qreal x, qreal y) const;
-
- Qt::InputMethodHints inputMethodHints() const;
- void setInputMethodHints(Qt::InputMethodHints hints);
- virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
-
- struct UpdatePaintNodeData {
- QSGTransformNode *transformNode;
- private:
- friend class QQuickCanvasPrivate;
- UpdatePaintNodeData();
- };
-
- virtual bool isTextureProvider() const { return false; }
- virtual QSGTextureProvider *textureProvider() const { return 0; }
-
-public Q_SLOTS:
- void update();
- void updateMicroFocus();
-
-Q_SIGNALS:
- void childrenRectChanged(const QRectF &);
- void baselineOffsetChanged(qreal);
- void stateChanged(const QString &);
- void focusChanged(bool);
- void activeFocusChanged(bool);
- void parentChanged(QQuickItem *);
- void transformOriginChanged(TransformOrigin);
- void smoothChanged(bool);
- void clipChanged(bool);
-
- // XXX todo
- void childrenChanged();
- void opacityChanged();
- void enabledChanged();
- void visibleChanged();
- void rotationChanged();
- void scaleChanged();
-
- void xChanged();
- void yChanged();
- void widthChanged();
- void heightChanged();
- void zChanged();
- void implicitWidthChanged();
- void implicitHeightChanged();
-
-protected:
- virtual bool event(QEvent *);
-
- bool isComponentComplete() const;
- virtual void itemChange(ItemChange, const ItemChangeData &);
-
- void setImplicitWidth(qreal);
- bool widthValid() const; // ### better name?
- void setImplicitHeight(qreal);
- bool heightValid() const; // ### better name?
- void setImplicitSize(qreal, qreal);
-
- virtual void classBegin();
- virtual void componentComplete();
-
- virtual void keyPressEvent(QKeyEvent *event);
- virtual void keyReleaseEvent(QKeyEvent *event);
- virtual void inputMethodEvent(QInputMethodEvent *);
- virtual void focusInEvent(QFocusEvent *);
- virtual void focusOutEvent(QFocusEvent *);
- virtual void mousePressEvent(QMouseEvent *event);
- virtual void mouseMoveEvent(QMouseEvent *event);
- virtual void mouseReleaseEvent(QMouseEvent *event);
- virtual void mouseDoubleClickEvent(QMouseEvent *event);
- virtual void mouseUngrabEvent(); // XXX todo - params?
- virtual void touchUngrabEvent();
- virtual void wheelEvent(QWheelEvent *event);
- virtual void touchEvent(QTouchEvent *event);
- virtual void hoverEnterEvent(QHoverEvent *event);
- virtual void hoverMoveEvent(QHoverEvent *event);
- virtual void hoverLeaveEvent(QHoverEvent *event);
- virtual void dragEnterEvent(QDragEnterEvent *);
- virtual void dragMoveEvent(QDragMoveEvent *);
- virtual void dragLeaveEvent(QDragLeaveEvent *);
- virtual void dropEvent(QDropEvent *);
- virtual bool childMouseEventFilter(QQuickItem *, QEvent *);
- virtual void windowDeactivateEvent();
-
- virtual void geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry);
-
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
- virtual void updatePolish();
-
-protected:
- QQuickItem(QQuickItemPrivate &dd, QQuickItem *parent = 0);
-
-private:
- friend class QQuickCanvas;
- friend class QQuickCanvasPrivate;
- friend class QSGRenderer;
- Q_DISABLE_COPY(QQuickItem)
- Q_DECLARE_PRIVATE(QQuickItem)
-};
-
-// XXX todo
-Q_DECLARE_OPERATORS_FOR_FLAGS(QQuickItem::Flags)
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug Q_DECLARATIVE_EXPORT operator<<(QDebug debug, QQuickItem *item);
-#endif
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickItem)
-QML_DECLARE_TYPE(QQuickTransform)
-
-QT_END_HEADER
-
-#endif // QQUICKITEM_H
diff --git a/src/declarative/items/qquickitem_p.h b/src/declarative/items/qquickitem_p.h
deleted file mode 100644
index 08ae7fac9b..0000000000
--- a/src/declarative/items/qquickitem_p.h
+++ /dev/null
@@ -1,752 +0,0 @@
-// Commit: 5c783d0a9a912816813945387903857a314040b5
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKITEM_P_H
-#define QQUICKITEM_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 "qquickitem.h"
-
-#include "qquickanchors_p.h"
-#include "qquickanchors_p_p.h"
-#include "qquickitemchangelistener_p.h"
-
-#include "qquickcanvas_p.h"
-
-#include <qsgnode.h>
-#include "qquickclipnode_p.h"
-
-#include <private/qpodvector_p.h>
-#include <private/qdeclarativestate_p.h>
-#include <private/qdeclarativenullablevalue_p_p.h>
-#include <private/qdeclarativenotifier_p.h>
-#include <private/qdeclarativeglobal_p.h>
-
-#include <qdeclarative.h>
-#include <qdeclarativecontext.h>
-
-#include <QtCore/qlist.h>
-#include <QtCore/qdebug.h>
-#include <QtCore/qelapsedtimer.h>
-
-QT_BEGIN_NAMESPACE
-
-class QNetworkReply;
-class QQuickItemKeyFilter;
-class QQuickLayoutMirroringAttached;
-
-class QQuickContents : public QQuickItemChangeListener
-{
-public:
- QQuickContents(QQuickItem *item);
- ~QQuickContents();
-
- QRectF rectF() const { return QRectF(m_x, m_y, m_width, m_height); }
-
- inline void calcGeometry(QQuickItem *changed = 0);
- void complete();
-
-protected:
- void itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry);
- void itemDestroyed(QQuickItem *item);
- void itemChildAdded(QQuickItem *, QQuickItem *);
- void itemChildRemoved(QQuickItem *, QQuickItem *);
- //void itemVisibilityChanged(QQuickItem *item)
-
-private:
- bool calcHeight(QQuickItem *changed = 0);
- bool calcWidth(QQuickItem *changed = 0);
- void updateRect();
-
- QQuickItem *m_item;
- qreal m_x;
- qreal m_y;
- qreal m_width;
- qreal m_height;
-};
-
-void QQuickContents::calcGeometry(QQuickItem *changed)
-{
- bool wChanged = calcWidth(changed);
- bool hChanged = calcHeight(changed);
- if (wChanged || hChanged)
- updateRect();
-}
-
-class QQuickTransformPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QQuickTransform);
-public:
- static QQuickTransformPrivate* get(QQuickTransform *transform) { return transform->d_func(); }
-
- QQuickTransformPrivate();
-
- QList<QQuickItem *> items;
-};
-
-class Q_DECLARATIVE_EXPORT QQuickItemPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QQuickItem)
-
-public:
- static QQuickItemPrivate* get(QQuickItem *item) { return item->d_func(); }
- static const QQuickItemPrivate* get(const QQuickItem *item) { return item->d_func(); }
-
- QQuickItemPrivate();
- ~QQuickItemPrivate();
- void init(QQuickItem *parent);
-
- QDeclarativeListProperty<QObject> data();
- QDeclarativeListProperty<QObject> resources();
- QDeclarativeListProperty<QQuickItem> children();
-
- QDeclarativeListProperty<QDeclarativeState> states();
- QDeclarativeListProperty<QDeclarativeTransition> transitions();
-
- QString state() const;
- void setState(const QString &);
-
- QQuickAnchorLine left() const;
- QQuickAnchorLine right() const;
- QQuickAnchorLine horizontalCenter() const;
- QQuickAnchorLine top() const;
- QQuickAnchorLine bottom() const;
- QQuickAnchorLine verticalCenter() const;
- QQuickAnchorLine baseline() const;
-
- // data property
- static void data_append(QDeclarativeListProperty<QObject> *, QObject *);
- static int data_count(QDeclarativeListProperty<QObject> *);
- static QObject *data_at(QDeclarativeListProperty<QObject> *, int);
- static void data_clear(QDeclarativeListProperty<QObject> *);
-
- // resources property
- static QObject *resources_at(QDeclarativeListProperty<QObject> *, int);
- static void resources_append(QDeclarativeListProperty<QObject> *, QObject *);
- static int resources_count(QDeclarativeListProperty<QObject> *);
- static void resources_clear(QDeclarativeListProperty<QObject> *);
-
- // children property
- static void children_append(QDeclarativeListProperty<QQuickItem> *, QQuickItem *);
- static int children_count(QDeclarativeListProperty<QQuickItem> *);
- static QQuickItem *children_at(QDeclarativeListProperty<QQuickItem> *, int);
- static void children_clear(QDeclarativeListProperty<QQuickItem> *);
-
- // transform property
- static int transform_count(QDeclarativeListProperty<QQuickTransform> *list);
- static void transform_append(QDeclarativeListProperty<QQuickTransform> *list, QQuickTransform *);
- static QQuickTransform *transform_at(QDeclarativeListProperty<QQuickTransform> *list, int);
- static void transform_clear(QDeclarativeListProperty<QQuickTransform> *list);
-
- QQuickAnchors *anchors() const;
- mutable QQuickAnchors *_anchors;
- QQuickContents *_contents;
-
- QDeclarativeNullableValue<qreal> baselineOffset;
-
- struct AnchorLines {
- AnchorLines(QQuickItem *);
- QQuickAnchorLine left;
- QQuickAnchorLine right;
- QQuickAnchorLine hCenter;
- QQuickAnchorLine top;
- QQuickAnchorLine bottom;
- QQuickAnchorLine vCenter;
- QQuickAnchorLine baseline;
- };
- mutable AnchorLines *_anchorLines;
- AnchorLines *anchorLines() const;
-
- enum ChangeType {
- Geometry = 0x01,
- SiblingOrder = 0x02,
- Visibility = 0x04,
- Opacity = 0x08,
- Destroyed = 0x10,
- Parent = 0x20,
- Children = 0x40,
- Rotation = 0x80,
- };
-
- Q_DECLARE_FLAGS(ChangeTypes, ChangeType)
-
- enum GeometryChangeType {
- NoChange = 0,
- XChange = 0x01,
- YChange = 0x02,
- WidthChange = 0x04,
- HeightChange = 0x08,
- SizeChange = WidthChange | HeightChange,
- GeometryChange = XChange | YChange | SizeChange
- };
-
- Q_DECLARE_FLAGS(GeometryChangeTypes, GeometryChangeType)
-
- struct ChangeListener {
- ChangeListener(QQuickItemChangeListener *l, QQuickItemPrivate::ChangeTypes t) : listener(l), types(t), gTypes(GeometryChange) {}
- ChangeListener(QQuickItemChangeListener *l, QQuickItemPrivate::GeometryChangeTypes gt) : listener(l), types(Geometry), gTypes(gt) {}
- QQuickItemChangeListener *listener;
- QQuickItemPrivate::ChangeTypes types;
- QQuickItemPrivate::GeometryChangeTypes gTypes; //NOTE: not used for ==
- bool operator==(const ChangeListener &other) const { return listener == other.listener && types == other.types; }
- };
-
- void addItemChangeListener(QQuickItemChangeListener *listener, ChangeTypes types) {
- changeListeners.append(ChangeListener(listener, types));
- }
- void removeItemChangeListener(QQuickItemChangeListener *, ChangeTypes types);
- void updateOrAddGeometryChangeListener(QQuickItemChangeListener *listener, GeometryChangeTypes types);
- void updateOrRemoveGeometryChangeListener(QQuickItemChangeListener *listener, GeometryChangeTypes types);
- QPODVector<ChangeListener,4> changeListeners;
-
- QDeclarativeStateGroup *_states();
- QDeclarativeStateGroup *_stateGroup;
-
- QQuickItem::TransformOrigin origin:5;
- quint32 flags:5;
- bool widthValid:1;
- bool heightValid:1;
- bool componentComplete:1;
- bool keepMouse:1;
- bool keepTouch:1;
- bool hoverEnabled:1;
- bool smooth:1;
- bool focus:1;
- bool activeFocus:1;
- bool notifiedFocus:1;
- bool notifiedActiveFocus:1;
- bool filtersChildMouseEvents:1;
- bool explicitVisible:1;
- bool effectiveVisible:1;
- bool explicitEnable:1;
- bool effectiveEnable:1;
- bool polishScheduled:1;
- bool inheritedLayoutMirror:1;
- bool effectiveLayoutMirror:1;
- bool isMirrorImplicit:1;
- bool inheritMirrorFromParent:1;
- bool inheritMirrorFromItem:1;
- bool childrenDoNotOverlap:1;
-
- QQuickCanvas *canvas;
- QSGContext *sceneGraphContext() const { Q_ASSERT(canvas); return static_cast<QQuickCanvasPrivate *>(QObjectPrivate::get(canvas))->context; }
-
- QQuickItem *parentItem;
- QList<QQuickItem *> childItems;
- mutable QList<QQuickItem *> *sortedChildItems;
- QList<QQuickItem *> paintOrderChildItems() const;
- void addChild(QQuickItem *);
- void removeChild(QQuickItem *);
- void siblingOrderChanged();
-
- inline void markSortedChildrenDirty(QQuickItem *child) {
- // If sortedChildItems == &childItems then all in childItems have z == 0
- // and we don't need to invalidate if the changed item also has z == 0.
- if (child->z() != 0. || sortedChildItems != &childItems) {
- if (sortedChildItems != &childItems)
- delete sortedChildItems;
- sortedChildItems = 0;
- }
- }
-
- class InitializationState {
- public:
- QQuickItem *getFocusScope(QQuickItem *item);
- void clear();
- void clear(QQuickItem *focusScope);
- private:
- QQuickItem *focusScope;
- };
- void initCanvas(InitializationState *, QQuickCanvas *);
-
- QQuickItem *subFocusItem;
-
- QTransform canvasToItemTransform() const;
- QTransform itemToCanvasTransform() const;
- void itemToParentTransform(QTransform &) const;
-
- qreal x;
- qreal y;
- qreal width;
- qreal height;
- qreal implicitWidth;
- qreal implicitHeight;
-
- qreal z;
- qreal scale;
- qreal rotation;
- qreal opacity;
-
- QQuickLayoutMirroringAttached* attachedLayoutDirection;
-
- Qt::MouseButtons acceptedMouseButtons;
- Qt::InputMethodHints imHints;
-
- QPointF transformOriginPoint;
-
- virtual qreal getImplicitWidth() const;
- virtual qreal getImplicitHeight() const;
- virtual void implicitWidthChanged();
- virtual void implicitHeightChanged();
-
- void resolveLayoutMirror();
- void setImplicitLayoutMirror(bool mirror, bool inherit);
- void setLayoutMirror(bool mirror);
- bool isMirrored() const {
- return effectiveLayoutMirror;
- }
-
- void emitChildrenRectChanged(const QRectF &rect) {
- Q_Q(QQuickItem);
- emit q->childrenRectChanged(rect);
- }
-
- QPointF computeTransformOrigin() const;
- QList<QQuickTransform *> transforms;
- virtual void transformChanged();
-
- QQuickItemKeyFilter *keyHandler;
- void deliverKeyEvent(QKeyEvent *);
- void deliverInputMethodEvent(QInputMethodEvent *);
- void deliverFocusEvent(QFocusEvent *);
- void deliverMouseEvent(QMouseEvent *);
- void deliverWheelEvent(QWheelEvent *);
- void deliverTouchEvent(QTouchEvent *);
- void deliverHoverEvent(QHoverEvent *);
- void deliverDragEvent(QEvent *);
-
- bool calcEffectiveVisible() const;
- void setEffectiveVisibleRecur(bool);
- bool calcEffectiveEnable() const;
- void setEffectiveEnableRecur(bool);
-
- // XXX todo
- enum DirtyType {
- TransformOrigin = 0x00000001,
- Transform = 0x00000002,
- BasicTransform = 0x00000004,
- Position = 0x00000008,
- Size = 0x00000010,
-
- ZValue = 0x00000020,
- Content = 0x00000040,
- Smooth = 0x00000080,
- OpacityValue = 0x00000100,
- ChildrenChanged = 0x00000200,
- ChildrenStackingChanged = 0x00000400,
- ParentChanged = 0x00000800,
-
- Clip = 0x00001000,
- Canvas = 0x00002000,
-
- EffectReference = 0x00008000,
- Visible = 0x00010000,
- HideReference = 0x00020000,
- // When you add an attribute here, don't forget to update
- // dirtyToString()
-
- TransformUpdateMask = TransformOrigin | Transform | BasicTransform | Position | Size | Canvas,
- ComplexTransformUpdateMask = Transform | Canvas,
- ContentUpdateMask = Size | Content | Smooth | Canvas,
- ChildrenUpdateMask = ChildrenChanged | ChildrenStackingChanged | EffectReference | Canvas,
-
- };
- quint32 dirtyAttributes;
- QString dirtyToString() const;
- void dirty(DirtyType);
- void addToDirtyList();
- void removeFromDirtyList();
- QQuickItem *nextDirtyItem;
- QQuickItem**prevDirtyItem;
-
- inline QSGTransformNode *itemNode();
- inline QSGNode *childContainerNode();
-
- /*
- QSGNode order is:
- - itemNode
- - (opacityNode)
- - (clipNode)
- - (effectNode)
- - groupNode
- */
-
- QSGTransformNode *itemNodeInstance;
- QSGOpacityNode *opacityNode;
- QQuickDefaultClipNode *clipNode;
- QSGRootNode *rootNode;
- QSGNode *groupNode;
- QSGNode *paintNode;
- QSGNode *beforePaintNode;
-
- virtual QSGTransformNode *createTransformNode();
-
- // A reference from an effect item means that this item is used by the effect, so
- // it should insert a root node.
- void refFromEffectItem(bool hide);
- void derefFromEffectItem(bool unhide);
- int effectRefCount;
- int hideRefCount;
-
- void itemChange(QQuickItem::ItemChange, const QQuickItem::ItemChangeData &);
-
- virtual void mirrorChange() {}
-
- static qint64 consistentTime;
- static void setConsistentTime(qint64 t);
- static void start(QElapsedTimer &);
- static qint64 elapsed(QElapsedTimer &);
- static qint64 restart(QElapsedTimer &);
-};
-
-/*
- Key filters can be installed on a QQuickItem, but not removed. Currently they
- are only used by attached objects (which are only destroyed on Item
- destruction), so this isn't a problem. If in future this becomes any form
- of public API, they will have to support removal too.
-*/
-class QQuickItemKeyFilter
-{
-public:
- QQuickItemKeyFilter(QQuickItem * = 0);
- virtual ~QQuickItemKeyFilter();
-
- virtual void keyPressed(QKeyEvent *event, bool post);
- virtual void keyReleased(QKeyEvent *event, bool post);
- virtual void inputMethodEvent(QInputMethodEvent *event, bool post);
- virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
- virtual void componentComplete();
-
- bool m_processPost;
-
-private:
- QQuickItemKeyFilter *m_next;
-};
-
-class QQuickKeyNavigationAttachedPrivate : public QObjectPrivate
-{
-public:
- QQuickKeyNavigationAttachedPrivate()
- : QObjectPrivate(),
- left(0), right(0), up(0), down(0), tab(0), backtab(0),
- leftSet(false), rightSet(false), upSet(false), downSet(false),
- tabSet(false), backtabSet(false) {}
-
- QQuickItem *left;
- QQuickItem *right;
- QQuickItem *up;
- QQuickItem *down;
- QQuickItem *tab;
- QQuickItem *backtab;
- bool leftSet : 1;
- bool rightSet : 1;
- bool upSet : 1;
- bool downSet : 1;
- bool tabSet : 1;
- bool backtabSet : 1;
-};
-
-class QQuickKeyNavigationAttached : public QObject, public QQuickItemKeyFilter
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickKeyNavigationAttached)
-
- Q_PROPERTY(QQuickItem *left READ left WRITE setLeft NOTIFY leftChanged)
- Q_PROPERTY(QQuickItem *right READ right WRITE setRight NOTIFY rightChanged)
- Q_PROPERTY(QQuickItem *up READ up WRITE setUp NOTIFY upChanged)
- Q_PROPERTY(QQuickItem *down READ down WRITE setDown NOTIFY downChanged)
- Q_PROPERTY(QQuickItem *tab READ tab WRITE setTab NOTIFY tabChanged)
- Q_PROPERTY(QQuickItem *backtab READ backtab WRITE setBacktab NOTIFY backtabChanged)
- Q_PROPERTY(Priority priority READ priority WRITE setPriority NOTIFY priorityChanged)
-
- Q_ENUMS(Priority)
-
-public:
- QQuickKeyNavigationAttached(QObject * = 0);
-
- QQuickItem *left() const;
- void setLeft(QQuickItem *);
- QQuickItem *right() const;
- void setRight(QQuickItem *);
- QQuickItem *up() const;
- void setUp(QQuickItem *);
- QQuickItem *down() const;
- void setDown(QQuickItem *);
- QQuickItem *tab() const;
- void setTab(QQuickItem *);
- QQuickItem *backtab() const;
- void setBacktab(QQuickItem *);
-
- enum Priority { BeforeItem, AfterItem };
- Priority priority() const;
- void setPriority(Priority);
-
- static QQuickKeyNavigationAttached *qmlAttachedProperties(QObject *);
-
-Q_SIGNALS:
- void leftChanged();
- void rightChanged();
- void upChanged();
- void downChanged();
- void tabChanged();
- void backtabChanged();
- void priorityChanged();
-
-private:
- virtual void keyPressed(QKeyEvent *event, bool post);
- virtual void keyReleased(QKeyEvent *event, bool post);
- void setFocusNavigation(QQuickItem *currentItem, const char *dir);
-};
-
-class QQuickLayoutMirroringAttached : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(bool enabled READ enabled WRITE setEnabled RESET resetEnabled NOTIFY enabledChanged)
- Q_PROPERTY(bool childrenInherit READ childrenInherit WRITE setChildrenInherit NOTIFY childrenInheritChanged)
-
-public:
- explicit QQuickLayoutMirroringAttached(QObject *parent = 0);
-
- bool enabled() const;
- void setEnabled(bool);
- void resetEnabled();
-
- bool childrenInherit() const;
- void setChildrenInherit(bool);
-
- static QQuickLayoutMirroringAttached *qmlAttachedProperties(QObject *);
-Q_SIGNALS:
- void enabledChanged();
- void childrenInheritChanged();
-private:
- friend class QQuickItemPrivate;
- QQuickItemPrivate *itemPrivate;
-};
-
-class QQuickKeysAttachedPrivate : public QObjectPrivate
-{
-public:
- QQuickKeysAttachedPrivate()
- : QObjectPrivate(), inPress(false), inRelease(false)
- , inIM(false), enabled(true), imeItem(0), item(0)
- {}
-
- bool isConnected(const char *signalName);
-
- //loop detection
- bool inPress:1;
- bool inRelease:1;
- bool inIM:1;
-
- bool enabled : 1;
-
- QQuickItem *imeItem;
- QList<QQuickItem *> targets;
- QQuickItem *item;
-};
-
-class QQuickKeysAttached : public QObject, public QQuickItemKeyFilter
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickKeysAttached)
-
- Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
- Q_PROPERTY(QDeclarativeListProperty<QQuickItem> forwardTo READ forwardTo)
- Q_PROPERTY(Priority priority READ priority WRITE setPriority NOTIFY priorityChanged)
-
- Q_ENUMS(Priority)
-
-public:
- QQuickKeysAttached(QObject *parent=0);
- ~QQuickKeysAttached();
-
- bool enabled() const { Q_D(const QQuickKeysAttached); return d->enabled; }
- void setEnabled(bool enabled) {
- Q_D(QQuickKeysAttached);
- if (enabled != d->enabled) {
- d->enabled = enabled;
- emit enabledChanged();
- }
- }
-
- enum Priority { BeforeItem, AfterItem};
- Priority priority() const;
- void setPriority(Priority);
-
- QDeclarativeListProperty<QQuickItem> forwardTo() {
- Q_D(QQuickKeysAttached);
- return QDeclarativeListProperty<QQuickItem>(this, d->targets);
- }
-
- virtual void componentComplete();
-
- static QQuickKeysAttached *qmlAttachedProperties(QObject *);
-
-Q_SIGNALS:
- void enabledChanged();
- void priorityChanged();
- void pressed(QQuickKeyEvent *event);
- void released(QQuickKeyEvent *event);
- void digit0Pressed(QQuickKeyEvent *event);
- void digit1Pressed(QQuickKeyEvent *event);
- void digit2Pressed(QQuickKeyEvent *event);
- void digit3Pressed(QQuickKeyEvent *event);
- void digit4Pressed(QQuickKeyEvent *event);
- void digit5Pressed(QQuickKeyEvent *event);
- void digit6Pressed(QQuickKeyEvent *event);
- void digit7Pressed(QQuickKeyEvent *event);
- void digit8Pressed(QQuickKeyEvent *event);
- void digit9Pressed(QQuickKeyEvent *event);
-
- void leftPressed(QQuickKeyEvent *event);
- void rightPressed(QQuickKeyEvent *event);
- void upPressed(QQuickKeyEvent *event);
- void downPressed(QQuickKeyEvent *event);
- void tabPressed(QQuickKeyEvent *event);
- void backtabPressed(QQuickKeyEvent *event);
-
- void asteriskPressed(QQuickKeyEvent *event);
- void numberSignPressed(QQuickKeyEvent *event);
- void escapePressed(QQuickKeyEvent *event);
- void returnPressed(QQuickKeyEvent *event);
- void enterPressed(QQuickKeyEvent *event);
- void deletePressed(QQuickKeyEvent *event);
- void spacePressed(QQuickKeyEvent *event);
- void backPressed(QQuickKeyEvent *event);
- void cancelPressed(QQuickKeyEvent *event);
- void selectPressed(QQuickKeyEvent *event);
- void yesPressed(QQuickKeyEvent *event);
- void noPressed(QQuickKeyEvent *event);
- void context1Pressed(QQuickKeyEvent *event);
- void context2Pressed(QQuickKeyEvent *event);
- void context3Pressed(QQuickKeyEvent *event);
- void context4Pressed(QQuickKeyEvent *event);
- void callPressed(QQuickKeyEvent *event);
- void hangupPressed(QQuickKeyEvent *event);
- void flipPressed(QQuickKeyEvent *event);
- void menuPressed(QQuickKeyEvent *event);
- void volumeUpPressed(QQuickKeyEvent *event);
- void volumeDownPressed(QQuickKeyEvent *event);
-
-private:
- virtual void keyPressed(QKeyEvent *event, bool post);
- virtual void keyReleased(QKeyEvent *event, bool post);
- virtual void inputMethodEvent(QInputMethodEvent *, bool post);
- virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
-
- const QByteArray keyToSignal(int key) {
- QByteArray keySignal;
- if (key >= Qt::Key_0 && key <= Qt::Key_9) {
- keySignal = "digit0Pressed";
- keySignal[5] = '0' + (key - Qt::Key_0);
- } else {
- int i = 0;
- while (sigMap[i].key && sigMap[i].key != key)
- ++i;
- keySignal = sigMap[i].sig;
- }
- return keySignal;
- }
-
- struct SigMap {
- int key;
- const char *sig;
- };
-
- static const SigMap sigMap[];
-};
-
-QSGTransformNode *QQuickItemPrivate::itemNode()
-{
- if (!itemNodeInstance) {
- itemNodeInstance = createTransformNode();
- itemNodeInstance->setFlag(QSGNode::OwnedByParent, false);
-#ifdef QML_RUNTIME_TESTING
- Q_Q(QQuickItem);
- itemNodeInstance->description = QString::fromLatin1("QQuickItem(%1)").arg(QString::fromLatin1(q->metaObject()->className()));
-#endif
- }
- return itemNodeInstance;
-}
-
-QSGNode *QQuickItemPrivate::childContainerNode()
-{
- if (!groupNode) {
- groupNode = new QSGNode();
- if (rootNode)
- rootNode->appendChildNode(groupNode);
- else if (clipNode)
- clipNode->appendChildNode(groupNode);
- else if (opacityNode)
- opacityNode->appendChildNode(groupNode);
- else
- itemNode()->appendChildNode(groupNode);
- groupNode->setFlag(QSGNode::ChildrenDoNotOverlap, childrenDoNotOverlap);
-#ifdef QML_RUNTIME_TESTING
- groupNode->description = QLatin1String("group");
-#endif
- }
- return groupNode;
-}
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QQuickItemPrivate::ChangeTypes);
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickKeysAttached)
-QML_DECLARE_TYPEINFO(QQuickKeysAttached, QML_HAS_ATTACHED_PROPERTIES)
-QML_DECLARE_TYPE(QQuickKeyNavigationAttached)
-QML_DECLARE_TYPEINFO(QQuickKeyNavigationAttached, QML_HAS_ATTACHED_PROPERTIES)
-QML_DECLARE_TYPE(QQuickLayoutMirroringAttached)
-QML_DECLARE_TYPEINFO(QQuickLayoutMirroringAttached, QML_HAS_ATTACHED_PROPERTIES)
-
-#endif // QQUICKITEM_P_H
diff --git a/src/declarative/items/qquickitemchangelistener_p.h b/src/declarative/items/qquickitemchangelistener_p.h
deleted file mode 100644
index a021658f9e..0000000000
--- a/src/declarative/items/qquickitemchangelistener_p.h
+++ /dev/null
@@ -1,82 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKITEMCHANGELISTENER_P_H
-#define QQUICKITEMCHANGELISTENER_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 <QtCore/qglobal.h>
-
-QT_BEGIN_NAMESPACE
-
-class QRectF;
-class QQuickItem;
-class QQuickAnchorsPrivate;
-class QQuickItemChangeListener
-{
-public:
- virtual void itemGeometryChanged(QQuickItem *, const QRectF &, const QRectF &) {}
- virtual void itemSiblingOrderChanged(QQuickItem *) {}
- virtual void itemVisibilityChanged(QQuickItem *) {}
- virtual void itemOpacityChanged(QQuickItem *) {}
- virtual void itemDestroyed(QQuickItem *) {}
- virtual void itemChildAdded(QQuickItem *, QQuickItem *) {}
- virtual void itemChildRemoved(QQuickItem *, QQuickItem *) {}
- virtual void itemParentChanged(QQuickItem *, QQuickItem *) {}
- virtual void itemRotationChanged(QQuickItem *) {}
-
- virtual QQuickAnchorsPrivate *anchorPrivate() { return 0; }
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKITEMCHANGELISTENER_P_H
diff --git a/src/declarative/items/qquickitemsmodule.cpp b/src/declarative/items/qquickitemsmodule.cpp
deleted file mode 100644
index 060d51e092..0000000000
--- a/src/declarative/items/qquickitemsmodule.cpp
+++ /dev/null
@@ -1,241 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickitemsmodule_p.h"
-
-#include "qquickitem.h"
-#include "qquickitem_p.h"
-#include "qquickevents_p_p.h"
-#include "qquickrectangle_p.h"
-#include "qquickfocusscope_p.h"
-#include "qquicktext_p.h"
-#include "qquicktextinput_p.h"
-#include "qquicktextedit_p.h"
-#include "qquickimage_p.h"
-#include "qquickborderimage_p.h"
-#include "qquickscalegrid_p_p.h"
-#include "qquickmousearea_p.h"
-#include "qquickpincharea_p.h"
-#include "qquickflickable_p.h"
-#include "qquickflickable_p_p.h"
-#include "qquicklistview_p.h"
-#include "qquickvisualitemmodel_p.h"
-#include "qquickvisualdatamodel_p.h"
-#include "qquickgridview_p.h"
-#include "qquickpathview_p.h"
-#include <private/qdeclarativepath_p.h>
-#include <private/qdeclarativepathinterpolator_p.h>
-#include "qquickpositioners_p.h"
-#include "qquickrepeater_p.h"
-#include "qquickloader_p.h"
-#include "qquickanimatedimage_p.h"
-#include "qquickflipable_p.h"
-#include "qquicktranslate_p.h"
-#include "qquickstateoperations_p.h"
-#include "qquickanimation_p.h"
-#include <private/qquickshadereffect_p.h>
-#include <private/qquickshadereffectsource_p.h>
-//#include <private/qquickpincharea_p.h>
-#include <private/qquickcanvasitem_p.h>
-#include <private/qquickcontext2d_p.h>
-#include "qquicksprite_p.h"
-#include "qquickspriteimage_p.h"
-#include "qquickdrag_p.h"
-#include "qquickdroparea_p.h"
-#include "qquickmultipointtoucharea_p.h"
-#include <private/qdeclarativemetatype_p.h>
-
-static QDeclarativePrivate::AutoParentResult qquickitem_autoParent(QObject *obj, QObject *parent)
-{
- QQuickItem *item = qobject_cast<QQuickItem *>(obj);
- if (!item)
- return QDeclarativePrivate::IncompatibleObject;
-
- QQuickItem *parentItem = qobject_cast<QQuickItem *>(parent);
- if (!parentItem)
- return QDeclarativePrivate::IncompatibleParent;
-
- item->setParentItem(parentItem);
- return QDeclarativePrivate::Parented;
-}
-
-static bool compareQQuickAnchorLines(const void *p1, const void *p2)
-{
- const QQuickAnchorLine &l1 = *static_cast<const QQuickAnchorLine*>(p1);
- const QQuickAnchorLine &l2 = *static_cast<const QQuickAnchorLine*>(p2);
- return l1 == l2;
-}
-
-static void qt_quickitems_defineModule(const char *uri, int major, int minor)
-{
- QDeclarativePrivate::RegisterAutoParent autoparent = { 0, &qquickitem_autoParent };
- QDeclarativePrivate::qmlregister(QDeclarativePrivate::AutoParentRegistration, &autoparent);
-
-#ifdef QT_NO_MOVIE
- qmlRegisterTypeNotAvailable(uri,major,minor,"AnimatedImage", qApp->translate("QQuickAnimatedImage","Qt was built without support for QMovie"));
-#else
- qmlRegisterType<QQuickAnimatedImage>(uri,major,minor,"AnimatedImage");
-#endif
- qmlRegisterType<QQuickBorderImage>(uri,major,minor,"BorderImage");
- qmlRegisterType<QQuickColumn>(uri,major,minor,"Column");
- qmlRegisterType<QQuickFlickable>(uri,major,minor,"Flickable");
- qmlRegisterType<QQuickFlipable>(uri,major,minor,"Flipable");
- qmlRegisterType<QQuickFlow>(uri,major,minor,"Flow");
-// qmlRegisterType<QDeclarativeFocusPanel>(uri,major,minor,"FocusPanel");
- qmlRegisterType<QQuickFocusScope>(uri,major,minor,"FocusScope");
- qmlRegisterType<QQuickGradient>(uri,major,minor,"Gradient");
- qmlRegisterType<QQuickGradientStop>(uri,major,minor,"GradientStop");
- qmlRegisterType<QQuickGrid>(uri,major,minor,"Grid");
- qmlRegisterType<QQuickGridView>(uri,major,minor,"GridView");
- qmlRegisterType<QQuickImage>(uri,major,minor,"Image");
- qmlRegisterType<QQuickItem>(uri,major,minor,"Item");
- qmlRegisterType<QQuickListView>(uri,major,minor,"ListView");
- qmlRegisterType<QQuickLoader>(uri,major,minor,"Loader");
- qmlRegisterType<QQuickMouseArea>(uri,major,minor,"MouseArea");
- qmlRegisterType<QDeclarativePath>(uri,major,minor,"Path");
- qmlRegisterType<QDeclarativePathAttribute>(uri,major,minor,"PathAttribute");
- qmlRegisterType<QDeclarativePathCubic>(uri,major,minor,"PathCubic");
- qmlRegisterType<QDeclarativePathLine>(uri,major,minor,"PathLine");
- qmlRegisterType<QDeclarativePathPercent>(uri,major,minor,"PathPercent");
- qmlRegisterType<QDeclarativePathQuad>(uri,major,minor,"PathQuad");
- qmlRegisterType<QDeclarativePathCatmullRomCurve>("QtQuick",2,0,"PathCurve");
- qmlRegisterType<QDeclarativePathArc>("QtQuick",2,0,"PathArc");
- qmlRegisterType<QDeclarativePathSvg>("QtQuick",2,0,"PathSvg");
- qmlRegisterType<QQuickPathView>(uri,major,minor,"PathView");
- qmlRegisterUncreatableType<QQuickBasePositioner>(uri,major,minor,"Positioner",
- QStringLiteral("Positioner is an abstract type that is only available as an attached property."));
-#ifndef QT_NO_VALIDATOR
- qmlRegisterType<QIntValidator>(uri,major,minor,"IntValidator");
- qmlRegisterType<QDoubleValidator>(uri,major,minor,"DoubleValidator");
- qmlRegisterType<QRegExpValidator>(uri,major,minor,"RegExpValidator");
-#endif
- qmlRegisterType<QQuickRectangle>(uri,major,minor,"Rectangle");
- qmlRegisterType<QQuickRepeater>(uri,major,minor,"Repeater");
- qmlRegisterType<QQuickRow>(uri,major,minor,"Row");
- qmlRegisterType<QQuickTranslate>(uri,major,minor,"Translate");
- qmlRegisterType<QQuickRotation>(uri,major,minor,"Rotation");
- qmlRegisterType<QQuickScale>(uri,major,minor,"Scale");
- qmlRegisterType<QQuickText>(uri,major,minor,"Text");
- qmlRegisterType<QQuickTextEdit>(uri,major,minor,"TextEdit");
- qmlRegisterType<QQuickTextInput>(uri,major,minor,"TextInput");
- qmlRegisterType<QQuickViewSection>(uri,major,minor,"ViewSection");
- qmlRegisterType<QQuickVisualDataModel>(uri,major,minor,"VisualDataModel");
- qmlRegisterType<QQuickVisualDataGroup>(uri,major,minor,"VisualDataGroup");
- qmlRegisterType<QQuickVisualItemModel>(uri,major,minor,"VisualItemModel");
-
- qmlRegisterType<QQuickAnchors>();
- qmlRegisterType<QQuickKeyEvent>();
- qmlRegisterType<QQuickMouseEvent>();
- qmlRegisterType<QQuickTransform>();
- qmlRegisterType<QDeclarativePathElement>();
- qmlRegisterType<QDeclarativeCurve>();
- qmlRegisterType<QQuickScaleGrid>();
- qmlRegisterType<QQuickTextLine>();
-#ifndef QT_NO_VALIDATOR
- qmlRegisterType<QValidator>();
-#endif
- qmlRegisterType<QQuickVisualModel>();
- qmlRegisterType<QQuickPen>();
- qmlRegisterType<QQuickFlickableVisibleArea>();
- qRegisterMetaType<QQuickAnchorLine>("QQuickAnchorLine");
- QDeclarativeMetaType::setQQuickAnchorLineCompareFunction(compareQQuickAnchorLines);
-
- qmlRegisterUncreatableType<QQuickKeyNavigationAttached>(uri,major,minor,"KeyNavigation",QQuickKeyNavigationAttached::tr("KeyNavigation is only available via attached properties"));
- qmlRegisterUncreatableType<QQuickKeysAttached>(uri,major,minor,"Keys",QQuickKeysAttached::tr("Keys is only available via attached properties"));
- qmlRegisterUncreatableType<QQuickLayoutMirroringAttached>(uri,major,minor,"LayoutMirroring", QQuickLayoutMirroringAttached::tr("LayoutMirroring is only available via attached properties"));
-
- qmlRegisterType<QQuickPinchArea>(uri,major,minor,"PinchArea");
- qmlRegisterType<QQuickPinch>(uri,major,minor,"Pinch");
- qmlRegisterType<QQuickPinchEvent>();
-
- qmlRegisterType<QQuickShaderEffect>("QtQuick", 2, 0, "ShaderEffect");
- qmlRegisterType<QQuickShaderEffectSource>("QtQuick", 2, 0, "ShaderEffectSource");
- qmlRegisterUncreatableType<QQuickShaderEffectMesh>("QtQuick", 2, 0, "ShaderEffectMesh", QQuickShaderEffectMesh::tr("Cannot create instance of abstract class ShaderEffectMesh."));
- qmlRegisterType<QQuickGridMesh>("QtQuick", 2, 0, "GridMesh");
-
- qmlRegisterUncreatableType<QQuickPaintedItem>("QtQuick", 2, 0, "PaintedItem", QQuickPaintedItem::tr("Cannot create instance of abstract class PaintedItem"));
-
- qmlRegisterType<QQuickCanvasItem>("QtQuick", 2, 0, "Canvas");
-
- qmlRegisterType<QQuickSprite>("QtQuick", 2, 0, "Sprite");
- qmlRegisterType<QQuickSpriteImage>("QtQuick", 2, 0, "SpriteImage");
-
- qmlRegisterType<QQuickParentChange>(uri, major, minor,"ParentChange");
- qmlRegisterType<QQuickAnchorChanges>(uri, major, minor,"AnchorChanges");
- qmlRegisterType<QQuickAnchorSet>();
- qmlRegisterType<QQuickAnchorAnimation>(uri, major, minor,"AnchorAnimation");
- qmlRegisterType<QQuickParentAnimation>(uri, major, minor,"ParentAnimation");
- qmlRegisterType<QQuickPathAnimation>("QtQuick",2,0,"PathAnimation");
- qmlRegisterType<QDeclarativePathInterpolator>("QtQuick",2,0,"PathInterpolator");
-
- qmlRegisterType<QQuickDropArea>("QtQuick", 2, 0, "DropArea");
- qmlRegisterType<QQuickDropEvent>();
- qmlRegisterType<QQuickDropAreaDrag>();
- qmlRegisterUncreatableType<QQuickDrag>("QtQuick", 2, 0, "Drag", QQuickDragAttached::tr("Drag is only available via attached properties"));
-
- qmlRegisterType<QQuickMultiPointTouchArea>("QtQuick", 2, 0, "MultiPointTouchArea");
- qmlRegisterType<QQuickTouchPoint>("QtQuick", 2, 0, "TouchPoint");
- qmlRegisterType<QQuickGrabGestureEvent>();
-}
-
-void QQuickItemsModule::defineModule()
-{
- static bool initialized = false;
- if (initialized)
- return;
- initialized = true;
-
- // XXX todo - Remove before final integration...
- QByteArray mode = qgetenv("QMLSCENE_IMPORT_NAME");
- QByteArray name = "QtQuick";
- int majorVersion = 2;
- int minorVersion = 0;
- if (mode == "quick1") {
- majorVersion = 1;
- } else if (mode == "qt") {
- name = "Qt";
- majorVersion = 4;
- minorVersion = 7;
- }
-
- qt_quickitems_defineModule(name, majorVersion, minorVersion);
-}
-
diff --git a/src/declarative/items/qquickitemsmodule_p.h b/src/declarative/items/qquickitemsmodule_p.h
deleted file mode 100644
index d3682007d7..0000000000
--- a/src/declarative/items/qquickitemsmodule_p.h
+++ /dev/null
@@ -1,65 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKITEMSMODULE_P_H
-#define QQUICKITEMSMODULE_P_H
-
-#include <qdeclarative.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickItemsModule
-{
-public:
- static void defineModule();
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKITEMSMODULE_P_H
-
diff --git a/src/declarative/items/qquickitemview.cpp b/src/declarative/items/qquickitemview.cpp
deleted file mode 100644
index edbe2a5d06..0000000000
--- a/src/declarative/items/qquickitemview.cpp
+++ /dev/null
@@ -1,1732 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickitemview_p_p.h"
-
-QT_BEGIN_NAMESPACE
-
-
-FxViewItem::FxViewItem(QQuickItem *i, bool own)
- : item(i), ownItem(own), index(-1)
-{
-}
-
-FxViewItem::~FxViewItem()
-{
- if (ownItem && item) {
- item->setParentItem(0);
- item->deleteLater();
- item = 0;
- }
-}
-
-
-QQuickItemViewChangeSet::QQuickItemViewChangeSet()
- : active(false)
-{
- reset();
-}
-
-bool QQuickItemViewChangeSet::hasPendingChanges() const
-{
- return !pendingChanges.isEmpty();
-}
-
-void QQuickItemViewChangeSet::applyChanges(const QDeclarativeChangeSet &changeSet)
-{
- pendingChanges.apply(changeSet);
-
- int moveId = -1;
- int moveOffset;
-
- foreach (const QDeclarativeChangeSet::Remove &r, changeSet.removes()) {
- itemCount -= r.count;
- if (moveId == -1 && newCurrentIndex >= r.index + r.count) {
- newCurrentIndex -= r.count;
- currentChanged = true;
- } else if (moveId == -1 && newCurrentIndex >= r.index && newCurrentIndex < r.index + r.count) {
- // current item has been removed.
- if (r.isMove()) {
- moveId = r.moveId;
- moveOffset = newCurrentIndex - r.index;
- } else {
- currentRemoved = true;
- newCurrentIndex = -1;
- if (itemCount)
- newCurrentIndex = qMin(r.index, itemCount - 1);
- }
- currentChanged = true;
- }
- }
- foreach (const QDeclarativeChangeSet::Insert &i, changeSet.inserts()) {
- if (moveId == -1) {
- if (itemCount && newCurrentIndex >= i.index) {
- newCurrentIndex += i.count;
- currentChanged = true;
- } else if (newCurrentIndex < 0) {
- newCurrentIndex = 0;
- currentChanged = true;
- } else if (newCurrentIndex == 0 && !itemCount) {
- // this is the first item, set the initial current index
- currentChanged = true;
- }
- } else if (moveId == i.moveId) {
- newCurrentIndex = i.index + moveOffset;
- }
- itemCount += i.count;
- }
-}
-
-void QQuickItemViewChangeSet::prepare(int currentIndex, int count)
-{
- if (active)
- return;
- reset();
- active = true;
- itemCount = count;
- newCurrentIndex = currentIndex;
-}
-
-void QQuickItemViewChangeSet::reset()
-{
- itemCount = 0;
- newCurrentIndex = -1;
- pendingChanges.clear();
- removedItems.clear();
- active = false;
- currentChanged = false;
- currentRemoved = false;
-}
-
-
-QQuickItemView::QQuickItemView(QQuickFlickablePrivate &dd, QQuickItem *parent)
- : QQuickFlickable(dd, parent)
-{
- Q_D(QQuickItemView);
- d->init();
-}
-
-QQuickItemView::~QQuickItemView()
-{
- Q_D(QQuickItemView);
- d->clear();
- if (d->ownModel)
- delete d->model;
- delete d->header;
- delete d->footer;
-}
-
-
-QQuickItem *QQuickItemView::currentItem() const
-{
- Q_D(const QQuickItemView);
- if (!d->currentItem)
- return 0;
- const_cast<QQuickItemViewPrivate*>(d)->applyPendingChanges();
- return d->currentItem->item;
-}
-
-QVariant QQuickItemView::model() const
-{
- Q_D(const QQuickItemView);
- return d->modelVariant;
-}
-
-void QQuickItemView::setModel(const QVariant &model)
-{
- Q_D(QQuickItemView);
- if (d->modelVariant == model)
- return;
- if (d->model) {
- disconnect(d->model, SIGNAL(modelUpdated(QDeclarativeChangeSet,bool)),
- this, SLOT(modelUpdated(QDeclarativeChangeSet,bool)));
- disconnect(d->model, SIGNAL(initItem(int,QQuickItem*)), this, SLOT(initItem(int,QQuickItem*)));
- disconnect(d->model, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(createdItem(int,QQuickItem*)));
- disconnect(d->model, SIGNAL(destroyingItem(QQuickItem*)), this, SLOT(destroyingItem(QQuickItem*)));
- }
-
- QQuickVisualModel *oldModel = d->model;
-
- d->clear();
- d->setPosition(d->contentStartPosition());
- d->model = 0;
- d->modelVariant = model;
-
- QObject *object = qvariant_cast<QObject*>(model);
- QQuickVisualModel *vim = 0;
- if (object && (vim = qobject_cast<QQuickVisualModel *>(object))) {
- if (d->ownModel) {
- delete oldModel;
- d->ownModel = false;
- }
- d->model = vim;
- } else {
- if (!d->ownModel) {
- d->model = new QQuickVisualDataModel(qmlContext(this), this);
- d->ownModel = true;
- if (isComponentComplete())
- static_cast<QQuickVisualDataModel *>(d->model.data())->componentComplete();
- } else {
- d->model = oldModel;
- }
- if (QQuickVisualDataModel *dataModel = qobject_cast<QQuickVisualDataModel*>(d->model))
- dataModel->setModel(model);
- }
-
- if (d->model) {
- d->bufferMode = QQuickItemViewPrivate::BufferBefore | QQuickItemViewPrivate::BufferAfter;
- connect(d->model, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(createdItem(int,QQuickItem*)));
- connect(d->model, SIGNAL(initItem(int,QQuickItem*)), this, SLOT(initItem(int,QQuickItem*)));
- connect(d->model, SIGNAL(destroyingItem(QQuickItem*)), this, SLOT(destroyingItem(QQuickItem*)));
- if (isComponentComplete()) {
- updateSections();
- d->refill();
- if ((d->currentIndex >= d->model->count() || d->currentIndex < 0) && !d->currentIndexCleared) {
- setCurrentIndex(0);
- } else {
- d->moveReason = QQuickItemViewPrivate::SetIndex;
- d->updateCurrent(d->currentIndex);
- if (d->highlight && d->currentItem) {
- if (d->autoHighlight)
- d->resetHighlightPosition();
- d->updateTrackedItem();
- }
- d->moveReason = QQuickItemViewPrivate::Other;
- }
- d->updateViewport();
- }
- connect(d->model, SIGNAL(modelUpdated(QDeclarativeChangeSet,bool)),
- this, SLOT(modelUpdated(QDeclarativeChangeSet,bool)));
- emit countChanged();
- }
- emit modelChanged();
-}
-
-QDeclarativeComponent *QQuickItemView::delegate() const
-{
- Q_D(const QQuickItemView);
- if (d->model) {
- if (QQuickVisualDataModel *dataModel = qobject_cast<QQuickVisualDataModel*>(d->model))
- return dataModel->delegate();
- }
-
- return 0;
-}
-
-void QQuickItemView::setDelegate(QDeclarativeComponent *delegate)
-{
- Q_D(QQuickItemView);
- if (delegate == this->delegate())
- return;
- if (!d->ownModel) {
- d->model = new QQuickVisualDataModel(qmlContext(this));
- d->ownModel = true;
- }
- if (QQuickVisualDataModel *dataModel = qobject_cast<QQuickVisualDataModel*>(d->model)) {
- int oldCount = dataModel->count();
- dataModel->setDelegate(delegate);
- if (isComponentComplete()) {
- for (int i = 0; i < d->visibleItems.count(); ++i)
- d->releaseItem(d->visibleItems.at(i));
- d->visibleItems.clear();
- d->releaseItem(d->currentItem);
- d->currentItem = 0;
- updateSections();
- d->refill();
- d->moveReason = QQuickItemViewPrivate::SetIndex;
- d->updateCurrent(d->currentIndex);
- if (d->highlight && d->currentItem) {
- if (d->autoHighlight)
- d->resetHighlightPosition();
- d->updateTrackedItem();
- }
- d->moveReason = QQuickItemViewPrivate::Other;
- d->updateViewport();
- }
- if (oldCount != dataModel->count())
- emit countChanged();
- }
- emit delegateChanged();
-}
-
-
-int QQuickItemView::count() const
-{
- Q_D(const QQuickItemView);
- if (!d->model)
- return 0;
- const_cast<QQuickItemViewPrivate*>(d)->applyPendingChanges();
- return d->model->count();
-}
-
-int QQuickItemView::currentIndex() const
-{
- Q_D(const QQuickItemView);
- const_cast<QQuickItemViewPrivate*>(d)->applyPendingChanges();
- return d->currentIndex;
-}
-
-void QQuickItemView::setCurrentIndex(int index)
-{
- Q_D(QQuickItemView);
- if (d->requestedIndex >= 0 && !d->requestedAsync) // currently creating item
- return;
- d->currentIndexCleared = (index == -1);
-
- d->applyPendingChanges();
- if (index == d->currentIndex)
- return;
- if (isComponentComplete() && d->isValid()) {
- d->moveReason = QQuickItemViewPrivate::SetIndex;
- d->updateCurrent(index);
- } else if (d->currentIndex != index) {
- d->currentIndex = index;
- emit currentIndexChanged();
- }
-}
-
-
-bool QQuickItemView::isWrapEnabled() const
-{
- Q_D(const QQuickItemView);
- return d->wrap;
-}
-
-void QQuickItemView::setWrapEnabled(bool wrap)
-{
- Q_D(QQuickItemView);
- if (d->wrap == wrap)
- return;
- d->wrap = wrap;
- emit keyNavigationWrapsChanged();
-}
-
-int QQuickItemView::cacheBuffer() const
-{
- Q_D(const QQuickItemView);
- return d->buffer;
-}
-
-void QQuickItemView::setCacheBuffer(int b)
-{
- Q_D(QQuickItemView);
- if (d->buffer != b) {
- d->buffer = b;
- if (isComponentComplete()) {
- d->bufferMode = QQuickItemViewPrivate::BufferBefore | QQuickItemViewPrivate::BufferAfter;
- d->refill();
- }
- emit cacheBufferChanged();
- }
-}
-
-
-Qt::LayoutDirection QQuickItemView::layoutDirection() const
-{
- Q_D(const QQuickItemView);
- return d->layoutDirection;
-}
-
-void QQuickItemView::setLayoutDirection(Qt::LayoutDirection layoutDirection)
-{
- Q_D(QQuickItemView);
- if (d->layoutDirection != layoutDirection) {
- d->layoutDirection = layoutDirection;
- d->regenerate();
- emit layoutDirectionChanged();
- emit effectiveLayoutDirectionChanged();
- }
-}
-
-Qt::LayoutDirection QQuickItemView::effectiveLayoutDirection() const
-{
- Q_D(const QQuickItemView);
- if (d->effectiveLayoutMirror)
- return d->layoutDirection == Qt::RightToLeft ? Qt::LeftToRight : Qt::RightToLeft;
- else
- return d->layoutDirection;
-}
-
-
-QDeclarativeComponent *QQuickItemView::header() const
-{
- Q_D(const QQuickItemView);
- return d->headerComponent;
-}
-
-QQuickItem *QQuickItemView::headerItem() const
-{
- Q_D(const QQuickItemView);
- const_cast<QQuickItemViewPrivate*>(d)->applyPendingChanges();
- return d->header ? d->header->item : 0;
-}
-
-void QQuickItemView::setHeader(QDeclarativeComponent *headerComponent)
-{
- Q_D(QQuickItemView);
- if (d->headerComponent != headerComponent) {
- d->applyPendingChanges();
- delete d->header;
- d->header = 0;
- d->headerComponent = headerComponent;
-
- d->markExtentsDirty();
-
- if (isComponentComplete()) {
- d->updateHeader();
- d->updateFooter();
- d->updateViewport();
- d->fixupPosition();
- } else {
- emit headerItemChanged();
- }
- emit headerChanged();
- }
-}
-
-QDeclarativeComponent *QQuickItemView::footer() const
-{
- Q_D(const QQuickItemView);
- return d->footerComponent;
-}
-
-QQuickItem *QQuickItemView::footerItem() const
-{
- Q_D(const QQuickItemView);
- const_cast<QQuickItemViewPrivate*>(d)->applyPendingChanges();
- return d->footer ? d->footer->item : 0;
-}
-
-void QQuickItemView::setFooter(QDeclarativeComponent *footerComponent)
-{
- Q_D(QQuickItemView);
- if (d->footerComponent != footerComponent) {
- d->applyPendingChanges();
- delete d->footer;
- d->footer = 0;
- d->footerComponent = footerComponent;
-
- if (isComponentComplete()) {
- d->updateFooter();
- d->updateViewport();
- d->fixupPosition();
- } else {
- emit footerItemChanged();
- }
- emit footerChanged();
- }
-}
-
-QDeclarativeComponent *QQuickItemView::highlight() const
-{
- Q_D(const QQuickItemView);
- const_cast<QQuickItemViewPrivate*>(d)->applyPendingChanges();
- return d->highlightComponent;
-}
-
-void QQuickItemView::setHighlight(QDeclarativeComponent *highlightComponent)
-{
- Q_D(QQuickItemView);
- if (highlightComponent != d->highlightComponent) {
- d->applyPendingChanges();
- d->highlightComponent = highlightComponent;
- d->createHighlight();
- if (d->currentItem)
- d->updateHighlight();
- emit highlightChanged();
- }
-}
-
-QQuickItem *QQuickItemView::highlightItem() const
-{
- Q_D(const QQuickItemView);
- const_cast<QQuickItemViewPrivate*>(d)->applyPendingChanges();
- return d->highlight ? d->highlight->item : 0;
-}
-
-bool QQuickItemView::highlightFollowsCurrentItem() const
-{
- Q_D(const QQuickItemView);
- return d->autoHighlight;
-}
-
-void QQuickItemView::setHighlightFollowsCurrentItem(bool autoHighlight)
-{
- Q_D(QQuickItemView);
- if (d->autoHighlight != autoHighlight) {
- d->autoHighlight = autoHighlight;
- if (autoHighlight)
- d->updateHighlight();
- emit highlightFollowsCurrentItemChanged();
- }
-}
-
-QQuickItemView::HighlightRangeMode QQuickItemView::highlightRangeMode() const
-{
- Q_D(const QQuickItemView);
- return static_cast<QQuickItemView::HighlightRangeMode>(d->highlightRange);
-}
-
-void QQuickItemView::setHighlightRangeMode(HighlightRangeMode mode)
-{
- Q_D(QQuickItemView);
- if (d->highlightRange == mode)
- return;
- d->highlightRange = mode;
- d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd;
- emit highlightRangeModeChanged();
-}
-
-//###Possibly rename these properties, since they are very useful even without a highlight?
-qreal QQuickItemView::preferredHighlightBegin() const
-{
- Q_D(const QQuickItemView);
- return d->highlightRangeStart;
-}
-
-void QQuickItemView::setPreferredHighlightBegin(qreal start)
-{
- Q_D(QQuickItemView);
- d->highlightRangeStartValid = true;
- if (d->highlightRangeStart == start)
- return;
- d->highlightRangeStart = start;
- d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd;
- emit preferredHighlightBeginChanged();
-}
-
-void QQuickItemView::resetPreferredHighlightBegin()
-{
- Q_D(QQuickItemView);
- d->highlightRangeStartValid = false;
- if (d->highlightRangeStart == 0)
- return;
- d->highlightRangeStart = 0;
- emit preferredHighlightBeginChanged();
-}
-
-qreal QQuickItemView::preferredHighlightEnd() const
-{
- Q_D(const QQuickItemView);
- return d->highlightRangeEnd;
-}
-
-void QQuickItemView::setPreferredHighlightEnd(qreal end)
-{
- Q_D(QQuickItemView);
- d->highlightRangeEndValid = true;
- if (d->highlightRangeEnd == end)
- return;
- d->highlightRangeEnd = end;
- d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd;
- emit preferredHighlightEndChanged();
-}
-
-void QQuickItemView::resetPreferredHighlightEnd()
-{
- Q_D(QQuickItemView);
- d->highlightRangeEndValid = false;
- if (d->highlightRangeEnd == 0)
- return;
- d->highlightRangeEnd = 0;
- emit preferredHighlightEndChanged();
-}
-
-int QQuickItemView::highlightMoveDuration() const
-{
- Q_D(const QQuickItemView);
- return d->highlightMoveDuration;
-}
-
-void QQuickItemView::setHighlightMoveDuration(int duration)
-{
- Q_D(QQuickItemView);
- if (d->highlightMoveDuration != duration) {
- d->highlightMoveDuration = duration;
- emit highlightMoveDurationChanged();
- }
-}
-
-void QQuickItemViewPrivate::positionViewAtIndex(int index, int mode)
-{
- Q_Q(QQuickItemView);
- if (!isValid())
- return;
- if (mode < QQuickItemView::Beginning || mode > QQuickItemView::Contain)
- return;
-
- applyPendingChanges();
- int idx = qMax(qMin(index, model->count()-1), 0);
-
- qreal pos = isContentFlowReversed() ? -position() - size() : position();
- FxViewItem *item = visibleItem(idx);
- qreal maxExtent;
- if (layoutOrientation() == Qt::Vertical)
- maxExtent = -q->maxYExtent();
- else
- maxExtent = isContentFlowReversed() ? q->minXExtent()-size(): -q->maxXExtent();
- if (!item) {
- int itemPos = positionAt(idx);
- changedVisibleIndex(idx);
- // save the currently visible items in case any of them end up visible again
- QList<FxViewItem *> oldVisible = visibleItems;
- visibleItems.clear();
- setPosition(qMin(qreal(itemPos), maxExtent));
- // now release the reference to all the old visible items.
- for (int i = 0; i < oldVisible.count(); ++i)
- releaseItem(oldVisible.at(i));
- item = visibleItem(idx);
- }
- if (item) {
- const qreal itemPos = item->position();
- switch (mode) {
- case QQuickItemView::Beginning:
- pos = itemPos;
- if (index < 0 && header)
- pos -= headerSize();
- break;
- case QQuickItemView::Center:
- pos = itemPos - (size() - item->size())/2;
- break;
- case QQuickItemView::End:
- pos = itemPos - size() + item->size();
- if (index >= model->count() && footer)
- pos += footerSize();
- break;
- case QQuickItemView::Visible:
- if (itemPos > pos + size())
- pos = itemPos - size() + item->size();
- else if (item->endPosition() <= pos)
- pos = itemPos;
- break;
- case QQuickItemView::Contain:
- if (item->endPosition() >= pos + size())
- pos = itemPos - size() + item->size();
- if (itemPos < pos)
- pos = itemPos;
- }
- pos = qMin(pos, maxExtent);
- qreal minExtent;
- if (layoutOrientation() == Qt::Vertical)
- minExtent = -q->minYExtent();
- else
- minExtent = isContentFlowReversed() ? q->maxXExtent()-size(): -q->minXExtent();
- pos = qMax(pos, minExtent);
- moveReason = QQuickItemViewPrivate::Other;
- q->cancelFlick();
- setPosition(pos);
-
- if (highlight) {
- if (autoHighlight)
- resetHighlightPosition();
- updateHighlight();
- }
- }
- fixupPosition();
-}
-
-void QQuickItemView::positionViewAtIndex(int index, int mode)
-{
- Q_D(QQuickItemView);
- if (!d->isValid() || index < 0 || index >= d->model->count())
- return;
- d->positionViewAtIndex(index, mode);
-}
-
-
-void QQuickItemView::positionViewAtBeginning()
-{
- Q_D(QQuickItemView);
- if (!d->isValid())
- return;
- d->positionViewAtIndex(-1, Beginning);
-}
-
-void QQuickItemView::positionViewAtEnd()
-{
- Q_D(QQuickItemView);
- if (!d->isValid())
- return;
- d->positionViewAtIndex(d->model->count(), End);
-}
-
-int QQuickItemView::indexAt(qreal x, qreal y) const
-{
- Q_D(const QQuickItemView);
- for (int i = 0; i < d->visibleItems.count(); ++i) {
- const FxViewItem *item = d->visibleItems.at(i);
- if (item->contains(x, y))
- return item->index;
- }
-
- return -1;
-}
-
-void QQuickItemViewPrivate::applyPendingChanges()
-{
- Q_Q(QQuickItemView);
- if (q->isComponentComplete() && currentChanges.hasPendingChanges())
- layout();
-}
-
-// for debugging only
-void QQuickItemViewPrivate::checkVisible() const
-{
- int skip = 0;
- for (int i = 0; i < visibleItems.count(); ++i) {
- FxViewItem *item = visibleItems.at(i);
- if (item->index == -1) {
- ++skip;
- } else if (item->index != visibleIndex + i - skip) {
- qFatal("index %d %d %d", visibleIndex, i, item->index);
- }
- }
-}
-
-void QQuickItemViewPrivate::itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_Q(QQuickItemView);
- QQuickFlickablePrivate::itemGeometryChanged(item, newGeometry, oldGeometry);
- if (!q->isComponentComplete())
- return;
-
- if (header && header->item == item) {
- updateHeader();
- markExtentsDirty();
- if (!q->isMoving() && !q->isFlicking())
- fixupPosition();
- } else if (footer && footer->item == item) {
- updateFooter();
- markExtentsDirty();
- if (!q->isMoving() && !q->isFlicking())
- fixupPosition();
- }
-
- if (currentItem && currentItem->item == item)
- updateHighlight();
- if (trackedItem && trackedItem->item == item)
- q->trackedPositionChanged();
-}
-
-void QQuickItemView::destroyRemoved()
-{
- Q_D(QQuickItemView);
- for (QList<FxViewItem*>::Iterator it = d->visibleItems.begin();
- it != d->visibleItems.end();) {
- FxViewItem *item = *it;
- if (item->index == -1 && item->attached->delayRemove() == false) {
- d->releaseItem(item);
- it = d->visibleItems.erase(it);
- } else {
- ++it;
- }
- }
-
- // Correct the positioning of the items
- d->updateSections();
- d->forceLayout = true;
- d->layout();
-}
-
-void QQuickItemView::modelUpdated(const QDeclarativeChangeSet &changeSet, bool reset)
-{
- Q_D(QQuickItemView);
- if (reset) {
- d->moveReason = QQuickItemViewPrivate::SetIndex;
- d->regenerate();
- if (d->highlight && d->currentItem) {
- if (d->autoHighlight)
- d->resetHighlightPosition();
- d->updateTrackedItem();
- }
- d->moveReason = QQuickItemViewPrivate::Other;
-
- emit countChanged();
- } else {
- d->currentChanges.prepare(d->currentIndex, d->itemCount);
- d->currentChanges.applyChanges(changeSet);
- polish();
- }
-}
-
-void QQuickItemView::animStopped()
-{
- Q_D(QQuickItemView);
- d->bufferMode = QQuickItemViewPrivate::BufferBefore | QQuickItemViewPrivate::BufferAfter;
- d->refill();
- if (d->haveHighlightRange && d->highlightRange == QQuickItemView::StrictlyEnforceRange)
- d->updateHighlight();
-}
-
-
-void QQuickItemView::trackedPositionChanged()
-{
- Q_D(QQuickItemView);
- if (!d->trackedItem || !d->currentItem)
- return;
- if (d->moveReason == QQuickItemViewPrivate::SetIndex) {
- qreal trackedPos = d->trackedItem->position();
- qreal trackedSize = d->trackedItem->size();
- if (d->trackedItem != d->currentItem) {
- trackedSize += d->currentItem->sectionSize();
- }
- qreal viewPos = d->isContentFlowReversed() ? -d->position()-d->size() : d->position();
- qreal pos = viewPos;
- if (d->haveHighlightRange) {
- if (trackedPos > pos + d->highlightRangeEnd - trackedSize)
- pos = trackedPos - d->highlightRangeEnd + trackedSize;
- if (trackedPos < pos + d->highlightRangeStart)
- pos = trackedPos - d->highlightRangeStart;
- if (d->highlightRange != StrictlyEnforceRange) {
- if (pos > d->endPosition() - d->size())
- pos = d->endPosition() - d->size();
- if (pos < d->startPosition())
- pos = d->startPosition();
- }
- } else {
- qreal trackedEndPos = d->trackedItem->endPosition();
- qreal toItemPos = d->currentItem->position();
- qreal toItemEndPos = d->currentItem->endPosition();
-
- if (d->header && d->showHeaderForIndex(d->currentIndex)) {
- trackedPos -= d->headerSize();
- trackedEndPos -= d->headerSize();
- toItemPos -= d->headerSize();
- toItemEndPos -= d->headerSize();
- } else if (d->footer && d->showFooterForIndex(d->currentIndex)) {
- trackedPos += d->footerSize();
- trackedEndPos += d->footerSize();
- toItemPos += d->footerSize();
- toItemEndPos += d->footerSize();
- }
-
- if (trackedPos < viewPos && toItemPos < viewPos) {
- pos = qMax(trackedPos, toItemPos);
- } else if (trackedEndPos >= viewPos + d->size()
- && toItemEndPos >= viewPos + d->size()) {
- if (trackedEndPos <= toItemEndPos) {
- pos = trackedEndPos - d->size();
- if (trackedSize > d->size())
- pos = trackedPos;
- } else {
- pos = toItemEndPos - d->size();
- if (d->currentItem->size() > d->size())
- pos = d->currentItem->position();
- }
- }
- }
- if (viewPos != pos) {
- cancelFlick();
- d->calcVelocity = true;
- d->setPosition(pos);
- d->calcVelocity = false;
- }
- }
-}
-
-void QQuickItemView::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_D(QQuickItemView);
- d->markExtentsDirty();
- QQuickFlickable::geometryChanged(newGeometry, oldGeometry);
-}
-
-
-qreal QQuickItemView::minYExtent() const
-{
- Q_D(const QQuickItemView);
- if (d->layoutOrientation() == Qt::Horizontal)
- return QQuickFlickable::minYExtent();
-
- if (d->vData.minExtentDirty) {
- d->minExtent = d->vData.startMargin-d->startPosition();
- if (d->header)
- d->minExtent += d->headerSize();
- if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) {
- d->minExtent += d->highlightRangeStart;
- if (d->visibleItem(0))
- d->minExtent -= d->visibleItem(0)->sectionSize();
- d->minExtent = qMax(d->minExtent, -(d->endPositionAt(0) - d->highlightRangeEnd));
- }
- d->vData.minExtentDirty = false;
- }
-
- return d->minExtent;
-}
-
-qreal QQuickItemView::maxYExtent() const
-{
- Q_D(const QQuickItemView);
- if (d->layoutOrientation() == Qt::Horizontal)
- return height();
-
- if (d->vData.maxExtentDirty) {
- if (!d->model || !d->model->count()) {
- d->maxExtent = d->header ? -d->headerSize() : 0;
- d->maxExtent += height();
- } else if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) {
- d->maxExtent = -(d->positionAt(d->model->count()-1) - d->highlightRangeStart);
- if (d->highlightRangeEnd != d->highlightRangeStart)
- d->maxExtent = qMin(d->maxExtent, -(d->endPosition() - d->highlightRangeEnd));
- } else {
- d->maxExtent = -(d->endPosition() - height());
- }
-
- if (d->footer)
- d->maxExtent -= d->footerSize();
- d->maxExtent -= d->vData.endMargin;
- qreal minY = minYExtent();
- if (d->maxExtent > minY)
- d->maxExtent = minY;
- d->vData.maxExtentDirty = false;
- }
- return d->maxExtent;
-}
-
-qreal QQuickItemView::minXExtent() const
-{
- Q_D(const QQuickItemView);
- if (d->layoutOrientation() == Qt::Vertical)
- return QQuickFlickable::minXExtent();
-
- if (d->hData.minExtentDirty) {
- d->minExtent = -d->startPosition();
- qreal highlightStart;
- qreal highlightEnd;
- qreal endPositionFirstItem = 0;
- if (d->isContentFlowReversed()) {
- d->minExtent += d->hData.endMargin;
- if (d->model && d->model->count())
- endPositionFirstItem = d->positionAt(d->model->count()-1);
- else if (d->header)
- d->minExtent += d->headerSize();
- highlightStart = d->highlightRangeEndValid ? d->size() - d->highlightRangeEnd : d->size();
- highlightEnd = d->highlightRangeStartValid ? d->size() - d->highlightRangeStart : d->size();
- if (d->footer)
- d->minExtent += d->footerSize();
- qreal maxX = maxXExtent();
- if (d->minExtent < maxX)
- d->minExtent = maxX;
- } else {
- d->minExtent += d->hData.startMargin;
- endPositionFirstItem = d->endPositionAt(0);
- highlightStart = d->highlightRangeStart;
- highlightEnd = d->highlightRangeEnd;
- if (d->header)
- d->minExtent += d->headerSize();
- }
- if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) {
- d->minExtent += highlightStart;
- d->minExtent = d->isContentFlowReversed()
- ? qMin(d->minExtent, endPositionFirstItem + highlightEnd)
- : qMax(d->minExtent, -(endPositionFirstItem - highlightEnd));
- }
- d->hData.minExtentDirty = false;
- }
-
- return d->minExtent;
-}
-
-qreal QQuickItemView::maxXExtent() const
-{
- Q_D(const QQuickItemView);
- if (d->layoutOrientation() == Qt::Vertical)
- return width();
-
- if (d->hData.maxExtentDirty) {
- qreal highlightStart;
- qreal highlightEnd;
- qreal lastItemPosition = 0;
- d->maxExtent = 0;
- if (d->isContentFlowReversed()) {
- highlightStart = d->highlightRangeEndValid ? d->size() - d->highlightRangeEnd : d->size();
- highlightEnd = d->highlightRangeStartValid ? d->size() - d->highlightRangeStart : d->size();
- lastItemPosition = d->endPosition();
- } else {
- highlightStart = d->highlightRangeStart;
- highlightEnd = d->highlightRangeEnd;
- if (d->model && d->model->count())
- lastItemPosition = d->positionAt(d->model->count()-1);
- }
- if (!d->model || !d->model->count()) {
- if (!d->isContentFlowReversed())
- d->maxExtent = d->header ? -d->headerSize() : 0;
- d->maxExtent += width();
- } else if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) {
- d->maxExtent = -(lastItemPosition - highlightStart);
- if (highlightEnd != highlightStart) {
- d->maxExtent = d->isContentFlowReversed()
- ? qMax(d->maxExtent, -(d->endPosition() - highlightEnd))
- : qMin(d->maxExtent, -(d->endPosition() - highlightEnd));
- }
- } else {
- d->maxExtent = -(d->endPosition() - width());
- }
- if (d->isContentFlowReversed()) {
- if (d->header)
- d->maxExtent -= d->headerSize();
- d->maxExtent -= d->hData.startMargin;
- } else {
- if (d->footer)
- d->maxExtent -= d->footerSize();
- d->maxExtent -= d->hData.endMargin;
- qreal minX = minXExtent();
- if (d->maxExtent > minX)
- d->maxExtent = minX;
- }
- d->hData.maxExtentDirty = false;
- }
-
- return d->maxExtent;
-}
-
-void QQuickItemView::setContentX(qreal pos)
-{
- Q_D(QQuickItemView);
- // Positioning the view manually should override any current movement state
- d->moveReason = QQuickItemViewPrivate::Other;
- QQuickFlickable::setContentX(pos);
-}
-
-void QQuickItemView::setContentY(qreal pos)
-{
- Q_D(QQuickItemView);
- // Positioning the view manually should override any current movement state
- d->moveReason = QQuickItemViewPrivate::Other;
- QQuickFlickable::setContentY(pos);
-}
-
-qreal QQuickItemView::xOrigin() const
-{
- Q_D(const QQuickItemView);
- if (d->isContentFlowReversed())
- return -maxXExtent() + d->size() - d->hData.startMargin;
- else
- return -minXExtent() + d->hData.startMargin;
-}
-
-void QQuickItemView::updatePolish()
-{
- Q_D(QQuickItemView);
- QQuickFlickable::updatePolish();
- d->layout();
-}
-
-void QQuickItemView::componentComplete()
-{
- Q_D(QQuickItemView);
- if (d->model && d->ownModel)
- static_cast<QQuickVisualDataModel *>(d->model.data())->componentComplete();
-
- QQuickFlickable::componentComplete();
-
- updateSections();
- d->updateHeader();
- d->updateFooter();
- d->updateViewport();
- d->setPosition(d->contentStartPosition());
- if (d->isValid()) {
- d->refill();
- d->moveReason = QQuickItemViewPrivate::SetIndex;
- if (d->currentIndex < 0 && !d->currentIndexCleared)
- d->updateCurrent(0);
- else
- d->updateCurrent(d->currentIndex);
- if (d->highlight && d->currentItem) {
- if (d->autoHighlight)
- d->resetHighlightPosition();
- d->updateTrackedItem();
- }
- d->moveReason = QQuickItemViewPrivate::Other;
- d->fixupPosition();
- }
- if (d->model && d->model->count())
- emit countChanged();
-}
-
-
-
-QQuickItemViewPrivate::QQuickItemViewPrivate()
- : itemCount(0)
- , buffer(0), bufferMode(BufferBefore | BufferAfter)
- , layoutDirection(Qt::LeftToRight)
- , moveReason(Other)
- , visibleIndex(0)
- , currentIndex(-1), currentItem(0)
- , trackedItem(0), requestedIndex(-1), requestedItem(0)
- , highlightComponent(0), highlight(0)
- , highlightRange(QQuickItemView::NoHighlightRange)
- , highlightRangeStart(0), highlightRangeEnd(0)
- , highlightMoveDuration(150)
- , headerComponent(0), header(0), footerComponent(0), footer(0)
- , minExtent(0), maxExtent(0)
- , ownModel(false), wrap(false), deferredRelease(false)
- , inApplyModelChanges(false), inViewportMoved(false), forceLayout(false), currentIndexCleared(false)
- , haveHighlightRange(false), autoHighlight(true), highlightRangeStartValid(false), highlightRangeEndValid(false)
- , fillCacheBuffer(false), inRequest(false), requestedAsync(false)
-{
-}
-
-bool QQuickItemViewPrivate::isValid() const
-{
- return model && model->count() && model->isValid();
-}
-
-qreal QQuickItemViewPrivate::position() const
-{
- Q_Q(const QQuickItemView);
- return layoutOrientation() == Qt::Vertical ? q->contentY() : q->contentX();
-}
-
-qreal QQuickItemViewPrivate::size() const
-{
- Q_Q(const QQuickItemView);
- return layoutOrientation() == Qt::Vertical ? q->height() : q->width();
-}
-
-qreal QQuickItemViewPrivate::startPosition() const
-{
- return isContentFlowReversed() ? -lastPosition() : originPosition();
-}
-
-qreal QQuickItemViewPrivate::endPosition() const
-{
- return isContentFlowReversed() ? -originPosition() : lastPosition();
-}
-
-qreal QQuickItemViewPrivate::contentStartPosition() const
-{
- qreal pos = -headerSize();
- if (layoutOrientation() == Qt::Vertical)
- pos -= vData.startMargin;
- else if (isContentFlowReversed())
- pos -= hData.endMargin;
- else
- pos -= hData.startMargin;
-
- return pos;
-}
-
-int QQuickItemViewPrivate::findLastVisibleIndex(int defaultValue) const
-{
- if (visibleItems.count()) {
- int i = visibleItems.count() - 1;
- while (i > 0 && visibleItems.at(i)->index == -1)
- --i;
- if (visibleItems.at(i)->index != -1)
- return visibleItems.at(i)->index;
- }
- return defaultValue;
-}
-
-FxViewItem *QQuickItemViewPrivate::visibleItem(int modelIndex) const {
- if (modelIndex >= visibleIndex && modelIndex < visibleIndex + visibleItems.count()) {
- for (int i = modelIndex - visibleIndex; i < visibleItems.count(); ++i) {
- FxViewItem *item = visibleItems.at(i);
- if (item->index == modelIndex)
- return item;
- }
- }
- return 0;
-}
-
-FxViewItem *QQuickItemViewPrivate::firstVisibleItem() const {
- const qreal pos = isContentFlowReversed() ? -position()-size() : position();
- for (int i = 0; i < visibleItems.count(); ++i) {
- FxViewItem *item = visibleItems.at(i);
- if (item->index != -1 && item->endPosition() > pos)
- return item;
- }
- return visibleItems.count() ? visibleItems.first() : 0;
-}
-
-// Map a model index to visibleItems list index.
-// These may differ if removed items are still present in the visible list,
-// e.g. doing a removal animation
-int QQuickItemViewPrivate::mapFromModel(int modelIndex) const
-{
- if (modelIndex < visibleIndex || modelIndex >= visibleIndex + visibleItems.count())
- return -1;
- for (int i = 0; i < visibleItems.count(); ++i) {
- FxViewItem *item = visibleItems.at(i);
- if (item->index == modelIndex)
- return i;
- if (item->index > modelIndex)
- return -1;
- }
- return -1; // Not in visibleList
-}
-
-void QQuickItemViewPrivate::init()
-{
- Q_Q(QQuickItemView);
- QQuickItemPrivate::get(contentItem)->childrenDoNotOverlap = true;
- q->setFlag(QQuickItem::ItemIsFocusScope);
- addItemChangeListener(this, Geometry);
- QObject::connect(q, SIGNAL(movementEnded()), q, SLOT(animStopped()));
- q->setFlickableDirection(QQuickFlickable::VerticalFlick);
-}
-
-void QQuickItemViewPrivate::updateCurrent(int modelIndex)
-{
- Q_Q(QQuickItemView);
- applyPendingChanges();
-
- if (!q->isComponentComplete() || !isValid() || modelIndex < 0 || modelIndex >= model->count()) {
- if (currentItem) {
- currentItem->attached->setIsCurrentItem(false);
- releaseItem(currentItem);
- currentItem = 0;
- currentIndex = modelIndex;
- emit q->currentIndexChanged();
- emit q->currentItemChanged();
- updateHighlight();
- } else if (currentIndex != modelIndex) {
- currentIndex = modelIndex;
- emit q->currentIndexChanged();
- }
- return;
- }
-
- if (currentItem && currentIndex == modelIndex) {
- updateHighlight();
- return;
- }
-
- FxViewItem *oldCurrentItem = currentItem;
- int oldCurrentIndex = currentIndex;
- currentIndex = modelIndex;
- currentItem = createItem(modelIndex, false);
- if (oldCurrentItem && (!currentItem || oldCurrentItem->item != currentItem->item))
- oldCurrentItem->attached->setIsCurrentItem(false);
- if (currentItem) {
- currentItem->item->setFocus(true);
- currentItem->attached->setIsCurrentItem(true);
- initializeCurrentItem();
- }
-
- updateHighlight();
- if (oldCurrentIndex != currentIndex)
- emit q->currentIndexChanged();
- if (oldCurrentItem != currentItem)
- emit q->currentItemChanged();
- releaseItem(oldCurrentItem);
-}
-
-void QQuickItemViewPrivate::clear()
-{
- currentChanges.reset();
- timeline.clear();
-
- for (int i = 0; i < visibleItems.count(); ++i)
- releaseItem(visibleItems.at(i));
- visibleItems.clear();
- visibleIndex = 0;
-
- releaseItem(currentItem);
- currentItem = 0;
- createHighlight();
- trackedItem = 0;
-
- markExtentsDirty();
- itemCount = 0;
-}
-
-
-void QQuickItemViewPrivate::mirrorChange()
-{
- Q_Q(QQuickItemView);
- regenerate();
- emit q->effectiveLayoutDirectionChanged();
-}
-
-void QQuickItemViewPrivate::refill()
-{
- if (isContentFlowReversed())
- refill(-position()-size(), -position());
- else
- refill(position(), position()+size());
-}
-
-void QQuickItemViewPrivate::refill(qreal from, qreal to, bool doBuffer)
-{
- Q_Q(QQuickItemView);
- if (!isValid() || !q->isComponentComplete())
- return;
-
- currentChanges.reset();
-
- int prevCount = itemCount;
- itemCount = model->count();
- qreal bufferFrom = from - buffer;
- qreal bufferTo = to + buffer;
- qreal fillFrom = from;
- qreal fillTo = to;
- if (doBuffer && (bufferMode & BufferAfter))
- fillTo = bufferTo;
- if (doBuffer && (bufferMode & BufferBefore))
- fillFrom = bufferFrom;
-
- // Item creation and release is staggered in order to avoid
- // creating/releasing multiple items in one frame
- // while flicking (as much as possible).
-
- bool changed = addVisibleItems(fillFrom, fillTo, doBuffer);
-
- if (!changed || deferredRelease) { // avoid destroying items in the same frame that we create
- if (removeNonVisibleItems(bufferFrom, bufferTo))
- changed = true;
- deferredRelease = false;
- } else {
- deferredRelease = true;
- }
-
- if (changed) {
- markExtentsDirty();
- visibleItemsChanged();
- } else if (!doBuffer && buffer && bufferMode != NoBuffer) {
- refill(from, to, true);
- }
-
- if (!q->isMoving() && changed) {
- fillCacheBuffer = true;
- q->polish();
- }
-
- if (prevCount != itemCount)
- emit q->countChanged();
-}
-
-void QQuickItemViewPrivate::regenerate()
-{
- Q_Q(QQuickItemView);
- if (q->isComponentComplete()) {
- currentChanges.reset();
- delete header;
- header = 0;
- delete footer;
- footer = 0;
- updateHeader();
- updateFooter();
- clear();
- updateViewport();
- setPosition(contentStartPosition());
- refill();
- updateCurrent(currentIndex);
- }
-}
-
-void QQuickItemViewPrivate::updateViewport()
-{
- Q_Q(QQuickItemView);
- if (isValid()) {
- if (layoutOrientation() == Qt::Vertical)
- q->setContentHeight(endPosition() - startPosition());
- else
- q->setContentWidth(endPosition() - startPosition());
- }
-}
-
-void QQuickItemViewPrivate::layout()
-{
- Q_Q(QQuickItemView);
- if (inApplyModelChanges)
- return;
-
- if (!isValid() && !visibleItems.count()) {
- clear();
- setPosition(contentStartPosition());
- return;
- }
-
- if (!applyModelChanges() && !forceLayout) {
- if (fillCacheBuffer)
- refill();
- return;
- }
- forceLayout = false;
-
- layoutVisibleItems();
- refill();
-
- markExtentsDirty();
-
- updateHighlight();
-
- if (!q->isMoving() && !q->isFlicking()) {
- fixupPosition();
- refill();
- }
-
- updateHeader();
- updateFooter();
- updateViewport();
- updateUnrequestedPositions();
-}
-
-bool QQuickItemViewPrivate::applyModelChanges()
-{
- Q_Q(QQuickItemView);
- if (!q->isComponentComplete() || !currentChanges.hasPendingChanges() || inApplyModelChanges)
- return false;
-
- inApplyModelChanges = true;
-
- updateUnrequestedIndexes();
- moveReason = QQuickItemViewPrivate::Other;
-
- int prevCount = itemCount;
- bool visibleAffected = false;
- bool viewportChanged = !currentChanges.pendingChanges.removes().isEmpty()
- || !currentChanges.pendingChanges.inserts().isEmpty();
-
- FxViewItem *firstVisible = firstVisibleItem();
- FxViewItem *origVisibleItemsFirst = visibleItems.count() ? visibleItems.first() : 0;
- int firstItemIndex = firstVisible ? firstVisible->index : -1;
- qreal removedBeforeFirstVisibleBy = 0;
-
- const QVector<QDeclarativeChangeSet::Remove> &removals = currentChanges.pendingChanges.removes();
- for (int i=0; i<removals.count(); i++) {
- itemCount -= removals[i].count;
-
- // Remove the items from the visible list, skipping anything already marked for removal
- QList<FxViewItem*>::Iterator it = visibleItems.begin();
- while (it != visibleItems.end()) {
- FxViewItem *item = *it;
- if (item->index == -1 || item->index < removals[i].index) {
- // already removed, or before removed items
- if (!visibleAffected && item->index < removals[i].index)
- visibleAffected = true;
- ++it;
- } else if (item->index >= removals[i].index + removals[i].count) {
- // after removed items
- item->index -= removals[i].count;
- ++it;
- } else {
- // removed item
- visibleAffected = true;
- if (!removals[i].isMove())
- item->attached->emitRemove();
-
- if (item->attached->delayRemove() && !removals[i].isMove()) {
- item->index = -1;
- QObject::connect(item->attached, SIGNAL(delayRemoveChanged()), q, SLOT(destroyRemoved()), Qt::QueuedConnection);
- ++it;
- } else {
- if (firstVisible && item->position() < firstVisible->position() && item != visibleItems.first())
- removedBeforeFirstVisibleBy += item->size();
- if (removals[i].isMove()) {
- currentChanges.removedItems.insert(removals[i].moveKey(item->index), item);
- } else {
- if (item == firstVisible)
- firstVisible = 0;
- currentChanges.removedItems.insertMulti(QDeclarativeChangeSet::MoveKey(), item);
- }
- it = visibleItems.erase(it);
- }
- }
- }
- if (!visibleAffected && needsRefillForAddedOrRemovedIndex(removals[i].index))
- visibleAffected = true;
- }
- if (!removals.isEmpty())
- updateVisibleIndex();
-
- const QVector<QDeclarativeChangeSet::Insert> &insertions = currentChanges.pendingChanges.inserts();
- InsertionsResult insertResult;
- bool allInsertionsBeforeVisible = true;
-
- for (int i=0; i<insertions.count(); i++) {
- bool wasEmpty = visibleItems.isEmpty();
- if (applyInsertionChange(insertions[i], firstVisible, &insertResult))
- visibleAffected = true;
- if (!visibleAffected && needsRefillForAddedOrRemovedIndex(insertions[i].index))
- visibleAffected = true;
- if (insertions[i].index >= visibleIndex)
- allInsertionsBeforeVisible = false;
- if (wasEmpty && !visibleItems.isEmpty())
- resetFirstItemPosition();
- itemCount += insertions[i].count;
- }
- for (int i=0; i<insertResult.addedItems.count(); ++i)
- insertResult.addedItems.at(i)->attached->emitAdd();
-
- // if the first visible item has moved, ensure another one takes its place
- // so that we avoid shifting all content forwards
- // (if an item is removed from before the first visible, the first visible should not move upwards)
- bool movedBackToFirstVisible = false;
- if (firstVisible && firstItemIndex >= 0) {
- for (int i=0; i<insertResult.movedBackwards.count(); i++) {
- if (insertResult.movedBackwards[i]->index == firstItemIndex) {
- // an item has moved backwards up to the first visible's position
- resetItemPosition(insertResult.movedBackwards[i], firstVisible);
- insertResult.movedBackwards.removeAt(i);
- movedBackToFirstVisible = true;
- break;
- }
- }
- if (!movedBackToFirstVisible && !allInsertionsBeforeVisible) {
- // first visible item has moved forward, another visible item takes its place
- FxViewItem *item = visibleItem(firstItemIndex);
- if (item)
- resetItemPosition(item, firstVisible);
- }
- }
-
- // Ensure we don't cause an ugly list scroll
- if (firstVisible && visibleItems.count() && visibleItems.first() != firstVisible) {
- // ensure first item is placed at correct postion if moving backward
- // since it will be used to position all subsequent items
- if (insertResult.movedBackwards.count() && origVisibleItemsFirst)
- resetItemPosition(visibleItems.first(), origVisibleItemsFirst);
-
- // correct the first item position (unless it has already been fixed)
- if (!movedBackToFirstVisible) {
- qreal moveBackwardsBy = insertResult.sizeAddedBeforeVisible;
- for (int i=0; i<insertResult.movedBackwards.count(); i++)
- moveBackwardsBy += insertResult.movedBackwards[i]->size();
- moveItemBy(visibleItems.first(), removedBeforeFirstVisibleBy, moveBackwardsBy);
- }
- }
-
- // Whatever removed/moved items remain are no longer visible items.
- for (QHash<QDeclarativeChangeSet::MoveKey, FxViewItem *>::Iterator it = currentChanges.removedItems.begin();
- it != currentChanges.removedItems.end(); ++it) {
- releaseItem(it.value());
- }
- currentChanges.removedItems.clear();
-
- if (currentChanges.currentChanged) {
- if (currentChanges.currentRemoved && currentItem) {
- currentItem->attached->setIsCurrentItem(false);
- releaseItem(currentItem);
- currentItem = 0;
- }
- if (!currentIndexCleared)
- updateCurrent(currentChanges.newCurrentIndex);
- }
- currentChanges.reset();
-
- updateSections();
- if (prevCount != itemCount)
- emit q->countChanged();
-
- if (!visibleAffected)
- visibleAffected = !currentChanges.pendingChanges.changes().isEmpty();
- if (!visibleAffected && viewportChanged)
- updateViewport();
-
- inApplyModelChanges = false;
- return visibleAffected;
-}
-
-/*
- This may return 0 if the item is being created asynchronously.
- When the item becomes available, refill() will be called and the item
- will be returned on the next call to createItem().
-*/
-FxViewItem *QQuickItemViewPrivate::createItem(int modelIndex, bool asynchronous)
-{
- Q_Q(QQuickItemView);
- if (requestedIndex == modelIndex && (asynchronous || requestedAsync == asynchronous))
- return 0;
-
- if (requestedIndex != -1 && requestedIndex != modelIndex) {
- delete requestedItem;
- requestedItem = 0;
- }
-
- requestedIndex = modelIndex;
- requestedAsync = asynchronous;
- inRequest = true;
-
- if (QQuickItem *item = model->item(modelIndex, asynchronous)) {
- item->setParentItem(q->contentItem());
- QDeclarative_setParent_noEvent(item, q->contentItem());
- requestedIndex = -1;
- fillCacheBuffer = false;
- FxViewItem *viewItem = requestedItem;
- if (!viewItem)
- viewItem = newViewItem(modelIndex, item); // already in cache, so viewItem not initialized in initItem()
- if (viewItem) {
- viewItem->index = modelIndex;
- // do other set up for the new item that should not happen
- // until after bindings are evaluated
- initializeViewItem(viewItem);
- unrequestedItems.remove(item);
- }
- requestedItem = 0;
- inRequest = false;
- return viewItem;
- }
-
- inRequest = false;
- return 0;
-}
-
-void QQuickItemView::createdItem(int index, QQuickItem *item)
-{
- Q_D(QQuickItemView);
- if (d->requestedIndex != index) {
- item->setParentItem(contentItem());
- d->unrequestedItems.insert(item, index);
- item->setVisible(false);
- d->repositionPackageItemAt(item, index);
- } else {
- d->requestedIndex = -1;
- if (!d->inRequest) {
- if (index == d->currentIndex)
- d->updateCurrent(index);
- d->refill();
- } else {
- d->fillCacheBuffer = true;
- polish();
- }
- }
-}
-
-void QQuickItemView::initItem(int index, QQuickItem *item)
-{
- Q_D(QQuickItemView);
- item->setZ(1);
- if (d->requestedIndex == index) {
- item->setParentItem(contentItem());
- QDeclarative_setParent_noEvent(item, contentItem());
- d->requestedItem = d->newViewItem(index, item);
- }
-}
-
-void QQuickItemView::destroyingItem(QQuickItem *item)
-{
- Q_D(QQuickItemView);
- d->unrequestedItems.remove(item);
-}
-
-void QQuickItemViewPrivate::releaseItem(FxViewItem *item)
-{
- Q_Q(QQuickItemView);
- if (!item || !model)
- return;
- if (trackedItem == item)
- trackedItem = 0;
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item->item);
- itemPrivate->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
- if (model->release(item->item) == 0) {
- // item was not destroyed, and we no longer reference it.
- unrequestedItems.insert(item->item, model->indexOf(item->item, q));
- }
- delete item;
-}
-
-QQuickItem *QQuickItemViewPrivate::createHighlightItem()
-{
- return createComponentItem(highlightComponent, true, true);
-}
-
-QQuickItem *QQuickItemViewPrivate::createComponentItem(QDeclarativeComponent *component, bool receiveItemGeometryChanges, bool createDefault)
-{
- Q_Q(QQuickItemView);
-
- QQuickItem *item = 0;
- if (component) {
- QDeclarativeContext *creationContext = component->creationContext();
- QDeclarativeContext *context = new QDeclarativeContext(
- creationContext ? creationContext : qmlContext(q));
- QObject *nobj = component->create(context);
- if (nobj) {
- QDeclarative_setParent_noEvent(context, nobj);
- item = qobject_cast<QQuickItem *>(nobj);
- if (!item)
- delete nobj;
- } else {
- delete context;
- }
- } else if (createDefault) {
- item = new QQuickItem;
- }
- if (item) {
- QDeclarative_setParent_noEvent(item, q->contentItem());
- item->setParentItem(q->contentItem());
- if (receiveItemGeometryChanges) {
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
- itemPrivate->addItemChangeListener(this, QQuickItemPrivate::Geometry);
- }
- }
- return item;
-}
-
-void QQuickItemViewPrivate::updateTrackedItem()
-{
- Q_Q(QQuickItemView);
- FxViewItem *item = currentItem;
- if (highlight)
- item = highlight;
- trackedItem = item;
-
- if (trackedItem)
- q->trackedPositionChanged();
-}
-
-void QQuickItemViewPrivate::updateUnrequestedIndexes()
-{
- Q_Q(QQuickItemView);
- for (QHash<QQuickItem*,int>::iterator it = unrequestedItems.begin(); it != unrequestedItems.end(); ++it)
- *it = model->indexOf(it.key(), q);
-}
-
-void QQuickItemViewPrivate::updateUnrequestedPositions()
-{
- for (QHash<QQuickItem*,int>::const_iterator it = unrequestedItems.begin(); it != unrequestedItems.end(); ++it)
- repositionPackageItemAt(it.key(), it.value());
-}
-
-void QQuickItemViewPrivate::updateVisibleIndex()
-{
- visibleIndex = 0;
- for (QList<FxViewItem*>::Iterator it = visibleItems.begin(); it != visibleItems.end(); ++it) {
- if ((*it)->index != -1) {
- visibleIndex = (*it)->index;
- break;
- }
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickitemview_p.h b/src/declarative/items/qquickitemview_p.h
deleted file mode 100644
index b8e27e4741..0000000000
--- a/src/declarative/items/qquickitemview_p.h
+++ /dev/null
@@ -1,296 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKITEMVIEW_P_H
-#define QQUICKITEMVIEW_P_H
-
-#include "qquickflickable_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeChangeSet;
-
-class QQuickItemViewPrivate;
-
-class Q_AUTOTEST_EXPORT QQuickItemView : public QQuickFlickable
-{
- Q_OBJECT
-
- Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged)
- Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged)
- Q_PROPERTY(int count READ count NOTIFY countChanged)
-
- Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
- Q_PROPERTY(QQuickItem *currentItem READ currentItem NOTIFY currentItemChanged)
-
- Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled NOTIFY keyNavigationWrapsChanged)
- Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer NOTIFY cacheBufferChanged)
-
- Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection NOTIFY layoutDirectionChanged)
- Q_PROPERTY(Qt::LayoutDirection effectiveLayoutDirection READ effectiveLayoutDirection NOTIFY effectiveLayoutDirectionChanged)
-
- Q_PROPERTY(QDeclarativeComponent *header READ header WRITE setHeader NOTIFY headerChanged)
- Q_PROPERTY(QQuickItem *headerItem READ headerItem NOTIFY headerItemChanged)
- Q_PROPERTY(QDeclarativeComponent *footer READ footer WRITE setFooter NOTIFY footerChanged)
- Q_PROPERTY(QQuickItem *footerItem READ footerItem NOTIFY footerItemChanged)
-
- Q_PROPERTY(QDeclarativeComponent *highlight READ highlight WRITE setHighlight NOTIFY highlightChanged)
- Q_PROPERTY(QQuickItem *highlightItem READ highlightItem NOTIFY highlightItemChanged)
- Q_PROPERTY(bool highlightFollowsCurrentItem READ highlightFollowsCurrentItem WRITE setHighlightFollowsCurrentItem NOTIFY highlightFollowsCurrentItemChanged)
- Q_PROPERTY(HighlightRangeMode highlightRangeMode READ highlightRangeMode WRITE setHighlightRangeMode NOTIFY highlightRangeModeChanged)
- Q_PROPERTY(qreal preferredHighlightBegin READ preferredHighlightBegin WRITE setPreferredHighlightBegin NOTIFY preferredHighlightBeginChanged RESET resetPreferredHighlightBegin)
- Q_PROPERTY(qreal preferredHighlightEnd READ preferredHighlightEnd WRITE setPreferredHighlightEnd NOTIFY preferredHighlightEndChanged RESET resetPreferredHighlightEnd)
- Q_PROPERTY(int highlightMoveDuration READ highlightMoveDuration WRITE setHighlightMoveDuration NOTIFY highlightMoveDurationChanged)
-
- Q_ENUMS(HighlightRangeMode)
- Q_ENUMS(PositionMode)
-
-public:
- QQuickItemView(QQuickFlickablePrivate &dd, QQuickItem *parent = 0);
- ~QQuickItemView();
-
- QVariant model() const;
- void setModel(const QVariant &);
-
- QDeclarativeComponent *delegate() const;
- void setDelegate(QDeclarativeComponent *);
-
- int count() const;
-
- int currentIndex() const;
- void setCurrentIndex(int idx);
-
- QQuickItem *currentItem() const;
-
- bool isWrapEnabled() const;
- void setWrapEnabled(bool);
-
- int cacheBuffer() const;
- void setCacheBuffer(int);
-
- Qt::LayoutDirection layoutDirection() const;
- void setLayoutDirection(Qt::LayoutDirection);
- Qt::LayoutDirection effectiveLayoutDirection() const;
-
- QDeclarativeComponent *footer() const;
- void setFooter(QDeclarativeComponent *);
- QQuickItem *footerItem() const;
-
- QDeclarativeComponent *header() const;
- void setHeader(QDeclarativeComponent *);
- QQuickItem *headerItem() const;
-
- QDeclarativeComponent *highlight() const;
- void setHighlight(QDeclarativeComponent *);
-
- QQuickItem *highlightItem() const;
-
- bool highlightFollowsCurrentItem() const;
- virtual void setHighlightFollowsCurrentItem(bool);
-
- enum HighlightRangeMode { NoHighlightRange, ApplyRange, StrictlyEnforceRange };
- HighlightRangeMode highlightRangeMode() const;
- void setHighlightRangeMode(HighlightRangeMode mode);
-
- qreal preferredHighlightBegin() const;
- void setPreferredHighlightBegin(qreal);
- void resetPreferredHighlightBegin();
-
- qreal preferredHighlightEnd() const;
- void setPreferredHighlightEnd(qreal);
- void resetPreferredHighlightEnd();
-
- int highlightMoveDuration() const;
- virtual void setHighlightMoveDuration(int);
-
- enum PositionMode { Beginning, Center, End, Visible, Contain };
-
- Q_INVOKABLE void positionViewAtIndex(int index, int mode);
- Q_INVOKABLE int indexAt(qreal x, qreal y) const;
- Q_INVOKABLE void positionViewAtBeginning();
- Q_INVOKABLE void positionViewAtEnd();
-
- virtual void setContentX(qreal pos);
- virtual void setContentY(qreal pos);
- virtual qreal xOrigin() const;
-
-signals:
- void modelChanged();
- void delegateChanged();
- void countChanged();
- void currentIndexChanged();
- void currentItemChanged();
-
- void keyNavigationWrapsChanged();
- void cacheBufferChanged();
-
- void layoutDirectionChanged();
- void effectiveLayoutDirectionChanged();
-
- void headerChanged();
- void footerChanged();
- void headerItemChanged();
- void footerItemChanged();
-
- void highlightChanged();
- void highlightItemChanged();
- void highlightFollowsCurrentItemChanged();
- void highlightRangeModeChanged();
- void preferredHighlightBeginChanged();
- void preferredHighlightEndChanged();
- void highlightMoveDurationChanged();
-
-protected:
- virtual void updatePolish();
- virtual void componentComplete();
- virtual void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry);
- virtual qreal minYExtent() const;
- virtual qreal maxYExtent() const;
- virtual qreal minXExtent() const;
- virtual qreal maxXExtent() const;
-
-protected slots:
- virtual void updateSections() {}
- void destroyRemoved();
- void createdItem(int index, QQuickItem *item);
- void initItem(int index, QQuickItem *item);
- void modelUpdated(const QDeclarativeChangeSet &changeSet, bool reset);
- void destroyingItem(QQuickItem *item);
- void animStopped();
- void trackedPositionChanged();
-
-
-
-private:
- Q_DECLARE_PRIVATE(QQuickItemView)
-};
-
-
-class Q_AUTOTEST_EXPORT QQuickItemViewAttached : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(bool isCurrentItem READ isCurrentItem NOTIFY currentItemChanged)
- Q_PROPERTY(bool delayRemove READ delayRemove WRITE setDelayRemove NOTIFY delayRemoveChanged)
-
- Q_PROPERTY(QString section READ section NOTIFY sectionChanged)
- Q_PROPERTY(QString previousSection READ prevSection NOTIFY prevSectionChanged)
- Q_PROPERTY(QString nextSection READ nextSection NOTIFY nextSectionChanged)
-
-public:
- QQuickItemViewAttached(QObject *parent)
- : QObject(parent), m_isCurrent(false), m_delayRemove(false) {}
- ~QQuickItemViewAttached() {}
-
- bool isCurrentItem() const { return m_isCurrent; }
- void setIsCurrentItem(bool c) {
- if (m_isCurrent != c) {
- m_isCurrent = c;
- emit currentItemChanged();
- }
- }
-
- bool delayRemove() const { return m_delayRemove; }
- void setDelayRemove(bool delay) {
- if (m_delayRemove != delay) {
- m_delayRemove = delay;
- emit delayRemoveChanged();
- }
- }
-
- QString section() const { return m_section; }
- void setSection(const QString &sect) {
- if (m_section != sect) {
- m_section = sect;
- emit sectionChanged();
- }
- }
-
- QString prevSection() const { return m_prevSection; }
- void setPrevSection(const QString &sect) {
- if (m_prevSection != sect) {
- m_prevSection = sect;
- emit prevSectionChanged();
- }
- }
-
- QString nextSection() const { return m_nextSection; }
- void setNextSection(const QString &sect) {
- if (m_nextSection != sect) {
- m_nextSection = sect;
- emit nextSectionChanged();
- }
- }
-
- void emitAdd() { emit add(); }
- void emitRemove() { emit remove(); }
-
-signals:
- void currentItemChanged();
- void delayRemoveChanged();
-
- void add();
- void remove();
-
- void sectionChanged();
- void prevSectionChanged();
- void nextSectionChanged();
-
-public:
- bool m_isCurrent : 1;
- bool m_delayRemove : 1;
-
- // current only used by list view
- mutable QString m_section;
- QString m_prevSection;
- QString m_nextSection;
-};
-
-
-QT_END_NAMESPACE
-QT_END_HEADER
-
-#endif // QQUICKITEMVIEW_P_H
-
diff --git a/src/declarative/items/qquickitemview_p_p.h b/src/declarative/items/qquickitemview_p_p.h
deleted file mode 100644
index 4db274e045..0000000000
--- a/src/declarative/items/qquickitemview_p_p.h
+++ /dev/null
@@ -1,260 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKITEMVIEW_P_P_H
-#define QQUICKITEMVIEW_P_P_H
-
-#include "qquickitemview_p.h"
-#include "qquickflickable_p_p.h"
-#include "qquickvisualdatamodel_p.h"
-#include <private/qdeclarativechangeset_p.h>
-
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class FxViewItem
-{
-public:
- FxViewItem(QQuickItem *, bool own);
- ~FxViewItem();
-
- // these are positions and sizes along the current direction of scrolling/flicking
- virtual qreal position() const = 0;
- virtual qreal endPosition() const = 0;
- virtual qreal size() const = 0;
- virtual qreal sectionSize() const = 0;
-
- virtual bool contains(qreal x, qreal y) const = 0;
-
- QQuickItem *item;
- bool ownItem;
- int index;
- QQuickItemViewAttached *attached;
-};
-
-class QQuickItemViewChangeSet
-{
-public:
- QQuickItemViewChangeSet();
-
- bool hasPendingChanges() const;
- void prepare(int currentIndex, int count);
- void reset();
-
- void applyChanges(const QDeclarativeChangeSet &changeSet);
-
- int itemCount;
- int newCurrentIndex;
- QDeclarativeChangeSet pendingChanges;
- QHash<QDeclarativeChangeSet::MoveKey, FxViewItem *> removedItems;
-
- bool active : 1;
- bool currentChanged : 1;
- bool currentRemoved : 1;
-};
-
-class QQuickItemViewPrivate : public QQuickFlickablePrivate
-{
- Q_DECLARE_PUBLIC(QQuickItemView)
-public:
- QQuickItemViewPrivate();
-
- struct InsertionsResult {
- QList<FxViewItem *> addedItems;
- QList<FxViewItem *> movedBackwards;
- qreal sizeAddedBeforeVisible;
-
- InsertionsResult() : sizeAddedBeforeVisible(0) {}
- };
-
- enum BufferMode { NoBuffer = 0x00, BufferBefore = 0x01, BufferAfter = 0x02 };
- enum MovementReason { Other, SetIndex, Mouse };
-
- bool isValid() const;
- qreal position() const;
- qreal size() const;
- qreal startPosition() const;
- qreal endPosition() const;
- qreal contentStartPosition() const;
- int findLastVisibleIndex(int defaultValue = -1) const;
- FxViewItem *visibleItem(int modelIndex) const;
- FxViewItem *firstVisibleItem() const;
- int mapFromModel(int modelIndex) const;
-
- virtual void init();
- virtual void clear();
- virtual void updateViewport();
-
- void regenerate();
- void layout();
- void refill();
- void refill(qreal from, qreal to, bool doBuffer = false);
- void mirrorChange();
-
- FxViewItem *createItem(int modelIndex, bool asynchronous = false);
- virtual void releaseItem(FxViewItem *item);
-
- QQuickItem *createHighlightItem();
- QQuickItem *createComponentItem(QDeclarativeComponent *component, bool receiveItemGeometryChanges, bool createDefault = false);
-
- void updateCurrent(int modelIndex);
- void updateTrackedItem();
- void updateUnrequestedIndexes();
- void updateUnrequestedPositions();
- void updateVisibleIndex();
- void positionViewAtIndex(int index, int mode);
- void applyPendingChanges();
- bool applyModelChanges();
-
- void checkVisible() const;
-
- void markExtentsDirty() {
- if (layoutOrientation() == Qt::Vertical)
- vData.markExtentsDirty();
- else
- hData.markExtentsDirty();
- }
-
- QDeclarativeGuard<QQuickVisualModel> model;
- QVariant modelVariant;
- int itemCount;
- int buffer;
- int bufferMode;
- Qt::LayoutDirection layoutDirection;
-
- MovementReason moveReason;
-
- QList<FxViewItem *> visibleItems;
- int visibleIndex;
- int currentIndex;
- FxViewItem *currentItem;
- FxViewItem *trackedItem;
- QHash<QQuickItem*,int> unrequestedItems;
- int requestedIndex;
- FxViewItem *requestedItem;
- QQuickItemViewChangeSet currentChanges;
-
- // XXX split into struct
- QDeclarativeComponent *highlightComponent;
- FxViewItem *highlight;
- int highlightRange; // enum value
- qreal highlightRangeStart;
- qreal highlightRangeEnd;
- int highlightMoveDuration;
-
- QDeclarativeComponent *headerComponent;
- FxViewItem *header;
- QDeclarativeComponent *footerComponent;
- FxViewItem *footer;
-
- mutable qreal minExtent;
- mutable qreal maxExtent;
-
- bool ownModel : 1;
- bool wrap : 1;
- bool deferredRelease : 1;
- bool inApplyModelChanges : 1;
- bool inViewportMoved : 1;
- bool forceLayout : 1;
- bool currentIndexCleared : 1;
- bool haveHighlightRange : 1;
- bool autoHighlight : 1;
- bool highlightRangeStartValid : 1;
- bool highlightRangeEndValid : 1;
- bool fillCacheBuffer : 1;
- bool inRequest : 1;
- bool requestedAsync : 1;
-
-protected:
- virtual Qt::Orientation layoutOrientation() const = 0;
- virtual bool isContentFlowReversed() const = 0;
-
- virtual qreal positionAt(int index) const = 0;
- virtual qreal endPositionAt(int index) const = 0;
- virtual qreal originPosition() const = 0;
- virtual qreal lastPosition() const = 0;
-
- virtual qreal headerSize() const = 0;
- virtual qreal footerSize() const = 0;
- virtual bool showHeaderForIndex(int index) const = 0;
- virtual bool showFooterForIndex(int index) const = 0;
- virtual void updateHeader() = 0;
- virtual void updateFooter() = 0;
-
- virtual void createHighlight() = 0;
- virtual void updateHighlight() = 0;
- virtual void resetHighlightPosition() = 0;
-
- virtual void setPosition(qreal pos) = 0;
- virtual void fixupPosition() = 0;
-
- virtual bool addVisibleItems(qreal fillFrom, qreal fillTo, bool doBuffer) = 0;
- virtual bool removeNonVisibleItems(qreal bufferFrom, qreal bufferTo) = 0;
- virtual void visibleItemsChanged() = 0;
-
- virtual FxViewItem *newViewItem(int index, QQuickItem *item) = 0;
- virtual void repositionPackageItemAt(QQuickItem *item, int index) = 0;
- virtual void resetItemPosition(FxViewItem *item, FxViewItem *toItem) = 0;
- virtual void resetFirstItemPosition() = 0;
- virtual void moveItemBy(FxViewItem *item, qreal forwards, qreal backwards) = 0;
-
- virtual void layoutVisibleItems() = 0;
- virtual void changedVisibleIndex(int newIndex) = 0;
- virtual bool applyInsertionChange(const QDeclarativeChangeSet::Insert &, FxViewItem *, InsertionsResult *) = 0;
- virtual bool needsRefillForAddedOrRemovedIndex(int) const { return false; }
-
- virtual void initializeViewItem(FxViewItem *) {}
- virtual void initializeCurrentItem() {}
- virtual void updateSections() {}
-
- virtual void itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry);
-};
-
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKITEMVIEW_P_P_H
diff --git a/src/declarative/items/qquicklistview.cpp b/src/declarative/items/qquicklistview.cpp
deleted file mode 100644
index 86af39075a..0000000000
--- a/src/declarative/items/qquicklistview.cpp
+++ /dev/null
@@ -1,2533 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquicklistview_p.h"
-#include "qquickitemview_p_p.h"
-#include "qquickvisualitemmodel_p.h"
-
-#include <QtDeclarative/qdeclarativeexpression.h>
-#include <QtDeclarative/qdeclarativeengine.h>
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtGui/qevent.h>
-#include <QtCore/qmath.h>
-#include <QtCore/qcoreapplication.h>
-
-#include <private/qdeclarativesmoothedanimation_p_p.h>
-#include <private/qlistmodelinterface_p.h>
-#include "qplatformdefs.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QML_FLICK_SNAPONETHRESHOLD
-#define QML_FLICK_SNAPONETHRESHOLD 30
-#endif
-
-class FxListItemSG;
-
-class QQuickListViewPrivate : public QQuickItemViewPrivate
-{
- Q_DECLARE_PUBLIC(QQuickListView)
-public:
- static QQuickListViewPrivate* get(QQuickListView *item) { return item->d_func(); }
-
- virtual Qt::Orientation layoutOrientation() const;
- virtual bool isContentFlowReversed() const;
- bool isRightToLeft() const;
-
- virtual qreal positionAt(int index) const;
- virtual qreal endPositionAt(int index) const;
- virtual qreal originPosition() const;
- virtual qreal lastPosition() const;
-
- FxViewItem *itemBefore(int modelIndex) const;
- QString sectionAt(int modelIndex);
- qreal snapPosAt(qreal pos);
- FxViewItem *snapItemAt(qreal pos);
-
- virtual void init();
- virtual void clear();
-
- virtual bool addVisibleItems(qreal fillFrom, qreal fillTo, bool doBuffer);
- virtual bool removeNonVisibleItems(qreal bufferFrom, qreal bufferTo);
- virtual void visibleItemsChanged();
-
- virtual FxViewItem *newViewItem(int index, QQuickItem *item);
- virtual void initializeViewItem(FxViewItem *item);
- virtual void releaseItem(FxViewItem *item);
- virtual void repositionPackageItemAt(QQuickItem *item, int index);
- virtual void resetItemPosition(FxViewItem *item, FxViewItem *toItem);
- virtual void resetFirstItemPosition();
- virtual void moveItemBy(FxViewItem *item, qreal forwards, qreal backwards);
-
- virtual void createHighlight();
- virtual void updateHighlight();
- virtual void resetHighlightPosition();
-
- virtual void setPosition(qreal pos);
- virtual void layoutVisibleItems();
- bool applyInsertionChange(const QDeclarativeChangeSet::Insert &, FxViewItem *firstVisible, InsertionsResult *);
-
- virtual void updateSections();
- QQuickItem *getSectionItem(const QString &section);
- void releaseSectionItem(QQuickItem *item);
- void updateInlineSection(FxListItemSG *);
- void updateCurrentSection();
- void updateStickySections();
-
- virtual qreal headerSize() const;
- virtual qreal footerSize() const;
- virtual bool showHeaderForIndex(int index) const;
- virtual bool showFooterForIndex(int index) const;
- virtual void updateHeader();
- virtual void updateFooter();
-
- virtual void changedVisibleIndex(int newIndex);
- virtual void initializeCurrentItem();
-
- void updateAverage();
-
- void itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry);
- virtual void fixupPosition();
- virtual void fixup(AxisData &data, qreal minExtent, qreal maxExtent);
- virtual void flick(QQuickItemViewPrivate::AxisData &data, qreal minExtent, qreal maxExtent, qreal vSize,
- QDeclarativeTimeLineCallback::Callback fixupCallback, qreal velocity);
-
- QQuickListView::Orientation orient;
- qreal visiblePos;
- qreal averageSize;
- qreal spacing;
- QQuickListView::SnapMode snapMode;
-
- QSmoothedAnimation *highlightPosAnimator;
- QSmoothedAnimation *highlightSizeAnimator;
- qreal highlightMoveSpeed;
- qreal highlightResizeSpeed;
- int highlightResizeDuration;
-
- QQuickViewSection *sectionCriteria;
- QString currentSection;
- static const int sectionCacheSize = 5;
- QQuickItem *sectionCache[sectionCacheSize];
- QQuickItem *currentSectionItem;
- QString currentStickySection;
- QQuickItem *nextSectionItem;
- QString nextStickySection;
- QString lastVisibleSection;
- QString nextSection;
-
- qreal overshootDist;
- bool correctFlick : 1;
- bool inFlickCorrection : 1;
-
- QQuickListViewPrivate()
- : orient(QQuickListView::Vertical)
- , visiblePos(0)
- , averageSize(100.0), spacing(0.0)
- , snapMode(QQuickListView::NoSnap)
- , highlightPosAnimator(0), highlightSizeAnimator(0)
- , highlightMoveSpeed(400), highlightResizeSpeed(400), highlightResizeDuration(-1)
- , sectionCriteria(0), currentSectionItem(0), nextSectionItem(0)
- , overshootDist(0.0), correctFlick(false), inFlickCorrection(false)
- {}
-
- friend class QQuickViewSection;
-};
-
-//----------------------------------------------------------------------------
-
-QQuickViewSection::QQuickViewSection(QQuickListView *parent)
- : QObject(parent), m_criteria(FullString), m_delegate(0), m_labelPositioning(InlineLabels)
- , m_view(parent ? QQuickListViewPrivate::get(parent) : 0)
-{
-}
-
-void QQuickViewSection::setProperty(const QString &property)
-{
- if (property != m_property) {
- m_property = property;
- emit propertyChanged();
- m_view->updateSections();
- }
-}
-
-void QQuickViewSection::setCriteria(QQuickViewSection::SectionCriteria criteria)
-{
- if (criteria != m_criteria) {
- m_criteria = criteria;
- emit criteriaChanged();
- m_view->updateSections();
- }
-}
-
-void QQuickViewSection::setDelegate(QDeclarativeComponent *delegate)
-{
- if (delegate != m_delegate) {
- m_delegate = delegate;
- emit delegateChanged();
- m_view->updateSections();
- }
-}
-
-QString QQuickViewSection::sectionString(const QString &value)
-{
- if (m_criteria == FirstCharacter)
- return value.isEmpty() ? QString() : value.at(0);
- else
- return value;
-}
-
-void QQuickViewSection::setLabelPositioning(int l)
-{
- if (m_labelPositioning != l) {
- m_labelPositioning = l;
- emit labelPositioningChanged();
- m_view->updateSections();
- }
-}
-
-//----------------------------------------------------------------------------
-
-class FxListItemSG : public FxViewItem
-{
-public:
- FxListItemSG(QQuickItem *i, QQuickListView *v, bool own) : FxViewItem(i, own), section(0), view(v) {
- attached = static_cast<QQuickListViewAttached*>(qmlAttachedPropertiesObject<QQuickListView>(item));
- if (attached)
- static_cast<QQuickListViewAttached*>(attached)->setView(view);
- }
-
- ~FxListItemSG() {}
-
- qreal position() const {
- if (section) {
- if (view->orientation() == QQuickListView::Vertical)
- return section->y();
- else
- return (view->effectiveLayoutDirection() == Qt::RightToLeft ? -section->width()-section->x() : section->x());
- } else {
- return itemPosition();
- }
- }
- qreal itemPosition() const {
- if (view->orientation() == QQuickListView::Vertical)
- return item->y();
- else
- return (view->effectiveLayoutDirection() == Qt::RightToLeft ? -item->width()-item->x() : item->x());
- }
- qreal size() const {
- if (section)
- return (view->orientation() == QQuickListView::Vertical ? item->height()+section->height() : item->width()+section->width());
- else
- return (view->orientation() == QQuickListView::Vertical ? item->height() : item->width());
- }
- qreal itemSize() const {
- return (view->orientation() == QQuickListView::Vertical ? item->height() : item->width());
- }
- qreal sectionSize() const {
- if (section)
- return (view->orientation() == QQuickListView::Vertical ? section->height() : section->width());
- return 0.0;
- }
- qreal endPosition() const {
- if (view->orientation() == QQuickListView::Vertical) {
- return item->y() + item->height();
- } else {
- return (view->effectiveLayoutDirection() == Qt::RightToLeft
- ? -item->x()
- : item->x() + item->width());
- }
- }
- void setPosition(qreal pos) {
- if (view->orientation() == QQuickListView::Vertical) {
- if (section) {
- section->setY(pos);
- pos += section->height();
- }
- item->setY(pos);
- } else {
- if (view->effectiveLayoutDirection() == Qt::RightToLeft) {
- if (section) {
- section->setX(-section->width()-pos);
- pos += section->width();
- }
- item->setX(-item->width()-pos);
- } else {
- if (section) {
- section->setX(pos);
- pos += section->width();
- }
- item->setX(pos);
- }
- }
- }
- void setSize(qreal size) {
- if (view->orientation() == QQuickListView::Vertical)
- item->setHeight(size);
- else
- item->setWidth(size);
- }
- bool contains(qreal x, qreal y) const {
- return (x >= item->x() && x < item->x() + item->width() &&
- y >= item->y() && y < item->y() + item->height());
- }
-
- QQuickItem *section;
- QQuickListView *view;
-};
-
-//----------------------------------------------------------------------------
-
-bool QQuickListViewPrivate::isContentFlowReversed() const
-{
- return isRightToLeft();
-}
-
-Qt::Orientation QQuickListViewPrivate::layoutOrientation() const
-{
- return static_cast<Qt::Orientation>(orient);
-}
-
-bool QQuickListViewPrivate::isRightToLeft() const
-{
- Q_Q(const QQuickListView);
- return orient == QQuickListView::Horizontal && q->effectiveLayoutDirection() == Qt::RightToLeft;
-}
-
-// Returns the item before modelIndex, if created.
-// May return an item marked for removal.
-FxViewItem *QQuickListViewPrivate::itemBefore(int modelIndex) const
-{
- if (modelIndex < visibleIndex)
- return 0;
- int idx = 1;
- int lastIndex = -1;
- while (idx < visibleItems.count()) {
- FxViewItem *item = visibleItems.at(idx);
- if (item->index != -1)
- lastIndex = item->index;
- if (item->index == modelIndex)
- return visibleItems.at(idx-1);
- ++idx;
- }
- if (lastIndex == modelIndex-1)
- return visibleItems.last();
- return 0;
-}
-
-void QQuickListViewPrivate::setPosition(qreal pos)
-{
- Q_Q(QQuickListView);
- if (orient == QQuickListView::Vertical) {
- q->QQuickFlickable::setContentY(pos);
- } else {
- if (isRightToLeft())
- q->QQuickFlickable::setContentX(-pos-size());
- else
- q->QQuickFlickable::setContentX(pos);
- }
-}
-
-qreal QQuickListViewPrivate::originPosition() const
-{
- qreal pos = 0;
- if (!visibleItems.isEmpty()) {
- pos = (*visibleItems.constBegin())->position();
- if (visibleIndex > 0)
- pos -= visibleIndex * (averageSize + spacing);
- }
- return pos;
-}
-
-qreal QQuickListViewPrivate::lastPosition() const
-{
- qreal pos = 0;
- if (!visibleItems.isEmpty()) {
- int invisibleCount = visibleItems.count() - visibleIndex;
- for (int i = visibleItems.count()-1; i >= 0; --i) {
- if (visibleItems.at(i)->index != -1) {
- invisibleCount = model->count() - visibleItems.at(i)->index - 1;
- break;
- }
- }
- pos = (*(--visibleItems.constEnd()))->endPosition() + invisibleCount * (averageSize + spacing);
- } else if (model && model->count()) {
- pos = (model->count() * averageSize + (model->count()-1) * spacing);
- }
- return pos;
-}
-
-qreal QQuickListViewPrivate::positionAt(int modelIndex) const
-{
- if (FxViewItem *item = visibleItem(modelIndex))
- return item->position();
- if (!visibleItems.isEmpty()) {
- if (modelIndex < visibleIndex) {
- int count = visibleIndex - modelIndex;
- qreal cs = 0;
- if (modelIndex == currentIndex && currentItem) {
- cs = currentItem->size() + spacing;
- --count;
- }
- return (*visibleItems.constBegin())->position() - count * (averageSize + spacing) - cs;
- } else {
- int count = modelIndex - findLastVisibleIndex(visibleIndex) - 1;
- return (*(--visibleItems.constEnd()))->endPosition() + spacing + count * (averageSize + spacing);
- }
- }
- return 0;
-}
-
-qreal QQuickListViewPrivate::endPositionAt(int modelIndex) const
-{
- if (FxViewItem *item = visibleItem(modelIndex))
- return item->endPosition();
- if (!visibleItems.isEmpty()) {
- if (modelIndex < visibleIndex) {
- int count = visibleIndex - modelIndex;
- return (*visibleItems.constBegin())->position() - (count - 1) * (averageSize + spacing) - spacing;
- } else {
- int count = modelIndex - findLastVisibleIndex(visibleIndex) - 1;
- return (*(--visibleItems.constEnd()))->endPosition() + count * (averageSize + spacing);
- }
- }
- return 0;
-}
-
-QString QQuickListViewPrivate::sectionAt(int modelIndex)
-{
- if (FxViewItem *item = visibleItem(modelIndex))
- return item->attached->section();
-
- QString section;
- if (sectionCriteria) {
- QString propValue = model->stringValue(modelIndex, sectionCriteria->property());
- section = sectionCriteria->sectionString(propValue);
- }
-
- return section;
-}
-
-qreal QQuickListViewPrivate::snapPosAt(qreal pos)
-{
- if (FxViewItem *snapItem = snapItemAt(pos))
- return snapItem->position();
- if (visibleItems.count()) {
- qreal firstPos = (*visibleItems.constBegin())->position();
- qreal endPos = (*(--visibleItems.constEnd()))->position();
- if (pos < firstPos) {
- return firstPos - qRound((firstPos - pos) / averageSize) * averageSize;
- } else if (pos > endPos)
- return endPos + qRound((pos - endPos) / averageSize) * averageSize;
- }
- return qRound((pos - originPosition()) / averageSize) * averageSize + originPosition();
-}
-
-FxViewItem *QQuickListViewPrivate::snapItemAt(qreal pos)
-{
- FxViewItem *snapItem = 0;
- qreal prevItemSize = 0;
- for (int i = 0; i < visibleItems.count(); ++i) {
- FxViewItem *item = visibleItems.at(i);
- if (item->index == -1)
- continue;
- qreal itemTop = item->position();
- if (highlight && itemTop >= pos && item->endPosition() <= pos + highlight->size())
- return item;
- if (itemTop+item->size()/2 >= pos && itemTop-prevItemSize/2 < pos)
- snapItem = item;
- prevItemSize = item->size();
- }
- return snapItem;
-}
-
-void QQuickListViewPrivate::changedVisibleIndex(int newIndex)
-{
- visiblePos = positionAt(newIndex);
- visibleIndex = newIndex;
-}
-
-void QQuickListViewPrivate::init()
-{
- QQuickItemViewPrivate::init();
- ::memset(sectionCache, 0, sizeof(QQuickItem*) * sectionCacheSize);
-}
-
-void QQuickListViewPrivate::clear()
-{
- for (int i = 0; i < sectionCacheSize; ++i) {
- delete sectionCache[i];
- sectionCache[i] = 0;
- }
- visiblePos = 0;
- currentSectionItem = 0;
- nextSectionItem = 0;
- lastVisibleSection = QString();
- QQuickItemViewPrivate::clear();
-}
-
-FxViewItem *QQuickListViewPrivate::newViewItem(int modelIndex, QQuickItem *item)
-{
- Q_Q(QQuickListView);
-
- FxListItemSG *listItem = new FxListItemSG(item, q, false);
- listItem->index = modelIndex;
-
- // initialise attached properties
- if (sectionCriteria) {
- QString propValue = model->stringValue(modelIndex, sectionCriteria->property());
- listItem->attached->m_section = sectionCriteria->sectionString(propValue);
- if (modelIndex > 0) {
- if (FxViewItem *item = itemBefore(modelIndex))
- listItem->attached->m_prevSection = item->attached->section();
- else
- listItem->attached->m_prevSection = sectionAt(modelIndex-1);
- }
- if (modelIndex < model->count()-1) {
- if (FxViewItem *item = visibleItem(modelIndex+1))
- listItem->attached->m_nextSection = static_cast<QQuickListViewAttached*>(item->attached)->section();
- else
- listItem->attached->m_nextSection = sectionAt(modelIndex+1);
- }
- }
-
- return listItem;
-}
-
-void QQuickListViewPrivate::initializeViewItem(FxViewItem *item)
-{
- QQuickItemViewPrivate::initializeViewItem(item);
-
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item->item);
- itemPrivate->addItemChangeListener(this, QQuickItemPrivate::Geometry);
-
- if (sectionCriteria && sectionCriteria->delegate()) {
- if (item->attached->m_prevSection != item->attached->m_section)
- updateInlineSection(static_cast<FxListItemSG*>(item));
- }
-}
-
-void QQuickListViewPrivate::releaseItem(FxViewItem *item)
-{
- if (item) {
- FxListItemSG* listItem = static_cast<FxListItemSG*>(item);
- if (listItem->section) {
- int i = 0;
- do {
- if (!sectionCache[i]) {
- sectionCache[i] = listItem->section;
- sectionCache[i]->setVisible(false);
- listItem->section = 0;
- break;
- }
- ++i;
- } while (i < sectionCacheSize);
- delete listItem->section;
- }
- }
- QQuickItemViewPrivate::releaseItem(item);
-}
-
-bool QQuickListViewPrivate::addVisibleItems(qreal fillFrom, qreal fillTo, bool doBuffer)
-{
- qreal itemEnd = visiblePos;
- if (visibleItems.count()) {
- visiblePos = (*visibleItems.constBegin())->position();
- itemEnd = (*(--visibleItems.constEnd()))->endPosition() + spacing;
- }
-
- int modelIndex = findLastVisibleIndex();
- bool haveValidItems = modelIndex >= 0;
- modelIndex = modelIndex < 0 ? visibleIndex : modelIndex + 1;
-
- if (haveValidItems && (fillFrom > itemEnd+averageSize+spacing
- || fillTo < visiblePos - averageSize - spacing)) {
- // We've jumped more than a page. Estimate which items are now
- // visible and fill from there.
- int count = (fillFrom - itemEnd) / (averageSize + spacing);
- for (int i = 0; i < visibleItems.count(); ++i)
- releaseItem(visibleItems.at(i));
- visibleItems.clear();
- modelIndex += count;
- if (modelIndex >= model->count()) {
- count -= modelIndex - model->count() + 1;
- modelIndex = model->count() - 1;
- } else if (modelIndex < 0) {
- count -= modelIndex;
- modelIndex = 0;
- }
- visibleIndex = modelIndex;
- visiblePos = itemEnd + count * (averageSize + spacing);
- itemEnd = visiblePos;
- }
-
- bool changed = false;
- FxListItemSG *item = 0;
- qreal pos = itemEnd;
- while (modelIndex < model->count() && pos <= fillTo) {
-// qDebug() << "refill: append item" << modelIndex << "pos" << pos;
- if (!(item = static_cast<FxListItemSG*>(createItem(modelIndex, doBuffer))))
- break;
- item->setPosition(pos);
- item->item->setVisible(!doBuffer);
- pos += item->size() + spacing;
- visibleItems.append(item);
- ++modelIndex;
- changed = true;
- }
- while (visibleIndex > 0 && visibleIndex <= model->count() && visiblePos > fillFrom) {
-// qDebug() << "refill: prepend item" << visibleIndex-1 << "current top pos" << visiblePos;
- if (!(item = static_cast<FxListItemSG*>(createItem(visibleIndex-1, doBuffer))))
- break;
- --visibleIndex;
- visiblePos -= item->size() + spacing;
- item->setPosition(visiblePos);
- item->item->setVisible(!doBuffer);
- visibleItems.prepend(item);
- changed = true;
- }
-
- return changed;
-}
-
-bool QQuickListViewPrivate::removeNonVisibleItems(qreal bufferFrom, qreal bufferTo)
-{
- FxViewItem *item = 0;
- bool changed = false;
-
- // Remove items from the start of the view.
- // Zero-sized items shouldn't be removed unless a non-zero-sized item is also being
- // removed, otherwise a zero-sized item is infinitely added and removed over and
- // over by refill().
- int index = 0;
- while (visibleItems.count() > 1 && index < visibleItems.count()
- && (item = visibleItems.at(index)) && item->endPosition() < bufferFrom) {
- if (item->attached->delayRemove())
- break;
- if (item->size() > 0) {
-// qDebug() << "refill: remove first" << visibleIndex << "top end pos" << item->endPosition();
-
- // remove this item and all zero-sized items before it
- while (item) {
- if (item->index != -1)
- visibleIndex++;
- visibleItems.removeAt(index);
- releaseItem(item);
- if (index == 0)
- break;
- item = visibleItems.at(--index);
- }
- changed = true;
- } else {
- index++;
- }
- }
-
- while (visibleItems.count() > 1 && (item = visibleItems.last()) && item->position() > bufferTo) {
- if (item->attached->delayRemove())
- break;
-// qDebug() << "refill: remove last" << visibleIndex+visibleItems.count()-1 << item->position();
- visibleItems.removeLast();
- releaseItem(item);
- changed = true;
- }
-
- return changed;
-}
-
-void QQuickListViewPrivate::visibleItemsChanged()
-{
- if (visibleItems.count())
- visiblePos = (*visibleItems.constBegin())->position();
- updateAverage();
- if (currentIndex >= 0 && currentItem && !visibleItem(currentIndex)) {
- static_cast<FxListItemSG*>(currentItem)->setPosition(positionAt(currentIndex));
- updateHighlight();
- }
- if (sectionCriteria)
- updateCurrentSection();
- updateHeader();
- updateFooter();
- updateViewport();
- updateUnrequestedPositions();
-}
-
-void QQuickListViewPrivate::layoutVisibleItems()
-{
- if (!visibleItems.isEmpty()) {
- bool fixedCurrent = currentItem && (*visibleItems.constBegin())->item == currentItem->item;
- qreal sum = (*visibleItems.constBegin())->size();
- qreal pos = (*visibleItems.constBegin())->position() + (*visibleItems.constBegin())->size() + spacing;
- for (int i=1; i < visibleItems.count(); ++i) {
- FxListItemSG *item = static_cast<FxListItemSG*>(visibleItems.at(i));
- item->setPosition(pos);
- pos += item->size() + spacing;
- sum += item->size();
- fixedCurrent = fixedCurrent || (currentItem && item->item == currentItem->item);
- }
- averageSize = qRound(sum / visibleItems.count());
-
- // move current item if it is not a visible item.
- if (currentIndex >= 0 && currentItem && !fixedCurrent) {
- static_cast<FxListItemSG*>(currentItem)->setPosition(positionAt(currentIndex));
- }
- }
-}
-
-void QQuickListViewPrivate::repositionPackageItemAt(QQuickItem *item, int index)
-{
- Q_Q(QQuickListView);
- qreal pos = position();
- if (orient == QQuickListView::Vertical) {
- if (item->y() + item->height() > pos && item->y() < pos + q->height())
- item->setY(positionAt(index));
- } else {
- if (item->x() + item->width() > pos && item->x() < pos + q->width()) {
- if (isRightToLeft())
- item->setX(-positionAt(index)-item->width());
- else
- item->setX(positionAt(index));
- }
- }
-}
-
-void QQuickListViewPrivate::resetItemPosition(FxViewItem *item, FxViewItem *toItem)
-{
- if (item == toItem)
- return;
- static_cast<FxListItemSG*>(item)->setPosition(toItem->position());
-}
-
-void QQuickListViewPrivate::resetFirstItemPosition()
-{
- FxListItemSG *item = static_cast<FxListItemSG*>(visibleItems.first());
- item->setPosition(0);
-}
-
-void QQuickListViewPrivate::moveItemBy(FxViewItem *item, qreal forwards, qreal backwards)
-{
- qreal diff = forwards - backwards;
- static_cast<FxListItemSG*>(item)->setPosition(item->position() + diff);
-}
-
-void QQuickListViewPrivate::createHighlight()
-{
- Q_Q(QQuickListView);
- bool changed = false;
- if (highlight) {
- if (trackedItem == highlight)
- trackedItem = 0;
- delete highlight;
- highlight = 0;
-
- delete highlightPosAnimator;
- delete highlightSizeAnimator;
- highlightPosAnimator = 0;
- highlightSizeAnimator = 0;
-
- changed = true;
- }
-
- if (currentItem) {
- QQuickItem *item = createHighlightItem();
- if (item) {
- FxListItemSG *newHighlight = new FxListItemSG(item, q, true);
-
- if (autoHighlight) {
- newHighlight->setSize(static_cast<FxListItemSG*>(currentItem)->itemSize());
- newHighlight->setPosition(static_cast<FxListItemSG*>(currentItem)->itemPosition());
- }
- const QLatin1String posProp(orient == QQuickListView::Vertical ? "y" : "x");
- highlightPosAnimator = new QSmoothedAnimation(q);
- highlightPosAnimator->target = QDeclarativeProperty(item, posProp);
- highlightPosAnimator->velocity = highlightMoveSpeed;
- highlightPosAnimator->userDuration = highlightMoveDuration;
-
- const QLatin1String sizeProp(orient == QQuickListView::Vertical ? "height" : "width");
- highlightSizeAnimator = new QSmoothedAnimation(q);
- highlightSizeAnimator->velocity = highlightResizeSpeed;
- highlightSizeAnimator->userDuration = highlightResizeDuration;
- highlightSizeAnimator->target = QDeclarativeProperty(item, sizeProp);
-
- highlight = newHighlight;
- changed = true;
- }
- }
- if (changed)
- emit q->highlightItemChanged();
-}
-
-void QQuickListViewPrivate::updateHighlight()
-{
- applyPendingChanges();
-
- if ((!currentItem && highlight) || (currentItem && !highlight))
- createHighlight();
- bool strictHighlight = haveHighlightRange && highlightRange == QQuickListView::StrictlyEnforceRange;
- if (currentItem && autoHighlight && highlight && (!strictHighlight || !pressed)) {
- // auto-update highlight
- FxListItemSG *listItem = static_cast<FxListItemSG*>(currentItem);
- highlightPosAnimator->to = isRightToLeft()
- ? -listItem->itemPosition()-listItem->itemSize()
- : listItem->itemPosition();
- highlightSizeAnimator->to = listItem->itemSize();
- if (orient == QQuickListView::Vertical) {
- if (highlight->item->width() == 0)
- highlight->item->setWidth(currentItem->item->width());
- } else {
- if (highlight->item->height() == 0)
- highlight->item->setHeight(currentItem->item->height());
- }
-
- highlightPosAnimator->restart();
- highlightSizeAnimator->restart();
- }
- updateTrackedItem();
-}
-
-void QQuickListViewPrivate::resetHighlightPosition()
-{
- if (highlight && currentItem)
- static_cast<FxListItemSG*>(highlight)->setPosition(static_cast<FxListItemSG*>(currentItem)->itemPosition());
-}
-
-QQuickItem * QQuickListViewPrivate::getSectionItem(const QString &section)
-{
- Q_Q(QQuickListView);
- QQuickItem *sectionItem = 0;
- int i = sectionCacheSize-1;
- while (i >= 0 && !sectionCache[i])
- --i;
- if (i >= 0) {
- sectionItem = sectionCache[i];
- sectionCache[i] = 0;
- sectionItem->setVisible(true);
- QDeclarativeContext *context = QDeclarativeEngine::contextForObject(sectionItem)->parentContext();
- context->setContextProperty(QLatin1String("section"), section);
- } else {
- QDeclarativeContext *creationContext = sectionCriteria->delegate()->creationContext();
- QDeclarativeContext *context = new QDeclarativeContext(
- creationContext ? creationContext : qmlContext(q));
- context->setContextProperty(QLatin1String("section"), section);
- QObject *nobj = sectionCriteria->delegate()->beginCreate(context);
- if (nobj) {
- QDeclarative_setParent_noEvent(context, nobj);
- sectionItem = qobject_cast<QQuickItem *>(nobj);
- if (!sectionItem) {
- delete nobj;
- } else {
- sectionItem->setZ(2);
- QDeclarative_setParent_noEvent(sectionItem, contentItem);
- sectionItem->setParentItem(contentItem);
- }
- } else {
- delete context;
- }
- sectionCriteria->delegate()->completeCreate();
- }
-
- return sectionItem;
-}
-
-void QQuickListViewPrivate::releaseSectionItem(QQuickItem *item)
-{
- int i = 0;
- do {
- if (!sectionCache[i]) {
- sectionCache[i] = item;
- sectionCache[i]->setVisible(false);
- return;
- }
- ++i;
- } while (i < sectionCacheSize);
- delete item;
-}
-
-void QQuickListViewPrivate::updateInlineSection(FxListItemSG *listItem)
-{
- if (!sectionCriteria || !sectionCriteria->delegate())
- return;
- if (listItem->attached->m_prevSection != listItem->attached->m_section
- && (sectionCriteria->labelPositioning() & QQuickViewSection::InlineLabels
- || (listItem->index == 0 && sectionCriteria->labelPositioning() & QQuickViewSection::CurrentLabelAtStart))) {
- if (!listItem->section) {
- qreal pos = listItem->position();
- listItem->section = getSectionItem(listItem->attached->m_section);
- listItem->setPosition(pos);
- } else {
- QDeclarativeContext *context = QDeclarativeEngine::contextForObject(listItem->section)->parentContext();
- context->setContextProperty(QLatin1String("section"), listItem->attached->m_section);
- }
- } else if (listItem->section) {
- qreal pos = listItem->position();
- releaseSectionItem(listItem->section);
- listItem->section = 0;
- listItem->setPosition(pos);
- }
-}
-
-void QQuickListViewPrivate::updateStickySections()
-{
- if (!sectionCriteria || visibleItems.isEmpty()
- || (!sectionCriteria->labelPositioning() && !currentSectionItem && !nextSectionItem))
- return;
-
- bool isRtl = isRightToLeft();
- qreal viewPos = isRightToLeft() ? -position()-size() : position();
- QQuickItem *sectionItem = 0;
- QQuickItem *lastSectionItem = 0;
- int index = 0;
- while (index < visibleItems.count()) {
- if (QQuickItem *section = static_cast<FxListItemSG *>(visibleItems.at(index))->section) {
- // Find the current section header and last visible section header
- // and hide them if they will overlap a static section header.
- qreal sectionPos = orient == QQuickListView::Vertical ? section->y() : section->x();
- qreal sectionSize = orient == QQuickListView::Vertical ? section->height() : section->width();
- bool visTop = true;
- if (sectionCriteria->labelPositioning() & QQuickViewSection::CurrentLabelAtStart)
- visTop = isRtl ? -sectionPos-sectionSize >= viewPos : sectionPos >= viewPos;
- bool visBot = true;
- if (sectionCriteria->labelPositioning() & QQuickViewSection::NextLabelAtEnd)
- visBot = isRtl ? -sectionPos <= viewPos + size() : sectionPos + sectionSize < viewPos + size();
- section->setVisible(visBot && visTop);
- if (visTop && !sectionItem)
- sectionItem = section;
- if (isRtl) {
- if (-sectionPos <= viewPos + size())
- lastSectionItem = section;
- } else {
- if (sectionPos + sectionSize < viewPos + size())
- lastSectionItem = section;
- }
- }
- ++index;
- }
-
- // Current section header
- if (sectionCriteria->labelPositioning() & QQuickViewSection::CurrentLabelAtStart) {
- if (!currentSectionItem) {
- currentSectionItem = getSectionItem(currentSection);
- } else if (currentStickySection != currentSection) {
- QDeclarativeContext *context = QDeclarativeEngine::contextForObject(currentSectionItem)->parentContext();
- context->setContextProperty(QLatin1String("section"), currentSection);
- }
- currentStickySection = currentSection;
- if (!currentSectionItem)
- return;
-
- qreal sectionSize = orient == QQuickListView::Vertical ? currentSectionItem->height() : currentSectionItem->width();
- bool atBeginning = orient == QQuickListView::Vertical ? vData.atBeginning : (isRightToLeft() ? hData.atEnd : hData.atBeginning);
- currentSectionItem->setVisible(!atBeginning && (!header || header->endPosition() < viewPos));
- qreal pos = isRtl ? position() + size() - sectionSize : viewPos;
- if (sectionItem) {
- qreal sectionPos = orient == QQuickListView::Vertical ? sectionItem->y() : sectionItem->x();
- pos = isRtl ? qMax(pos, sectionPos + sectionSize) : qMin(pos, sectionPos - sectionSize);
- }
- if (header)
- pos = isRtl ? qMin(header->endPosition(), pos) : qMax(header->endPosition(), pos);
- if (footer)
- pos = isRtl ? qMax(-footer->position(), pos) : qMin(footer->position() - sectionSize, pos);
- if (orient == QQuickListView::Vertical)
- currentSectionItem->setY(pos);
- else
- currentSectionItem->setX(pos);
- } else if (currentSectionItem) {
- releaseSectionItem(currentSectionItem);
- currentSectionItem = 0;
- }
-
- // Next section footer
- if (sectionCriteria->labelPositioning() & QQuickViewSection::NextLabelAtEnd) {
- if (!nextSectionItem) {
- nextSectionItem = getSectionItem(nextSection);
- } else if (nextStickySection != nextSection) {
- QDeclarativeContext *context = QDeclarativeEngine::contextForObject(nextSectionItem)->parentContext();
- context->setContextProperty(QLatin1String("section"), nextSection);
- }
- nextStickySection = nextSection;
- if (!nextSectionItem)
- return;
-
- qreal sectionSize = orient == QQuickListView::Vertical ? nextSectionItem->height() : nextSectionItem->width();
- nextSectionItem->setVisible(!nextSection.isEmpty());
- qreal pos = isRtl ? position() : viewPos + size() - sectionSize;
- if (lastSectionItem) {
- qreal sectionPos = orient == QQuickListView::Vertical ? lastSectionItem->y() : lastSectionItem->x();
- pos = isRtl ? qMin(pos, sectionPos - sectionSize) : qMax(pos, sectionPos + sectionSize);
- }
- if (header)
- pos = isRtl ? qMin(header->endPosition() - sectionSize, pos) : qMax(header->endPosition(), pos);
- if (orient == QQuickListView::Vertical)
- nextSectionItem->setY(pos);
- else
- nextSectionItem->setX(pos);
- } else if (nextSectionItem) {
- releaseSectionItem(nextSectionItem);
- nextSectionItem = 0;
- }
-}
-
-void QQuickListViewPrivate::updateSections()
-{
- Q_Q(QQuickListView);
- if (!q->isComponentComplete())
- return;
-
- QQuickItemViewPrivate::updateSections();
-
- if (sectionCriteria && !visibleItems.isEmpty()) {
- QString prevSection;
- if (visibleIndex > 0)
- prevSection = sectionAt(visibleIndex-1);
- QQuickListViewAttached *prevAtt = 0;
- int idx = -1;
- for (int i = 0; i < visibleItems.count(); ++i) {
- QQuickListViewAttached *attached = static_cast<QQuickListViewAttached*>(visibleItems.at(i)->attached);
- attached->setPrevSection(prevSection);
- if (visibleItems.at(i)->index != -1) {
- QString propValue = model->stringValue(visibleItems.at(i)->index, sectionCriteria->property());
- attached->setSection(sectionCriteria->sectionString(propValue));
- idx = visibleItems.at(i)->index;
- }
- updateInlineSection(static_cast<FxListItemSG*>(visibleItems.at(i)));
- if (prevAtt)
- prevAtt->setNextSection(attached->section());
- prevSection = attached->section();
- prevAtt = attached;
- }
- if (prevAtt) {
- if (idx > 0 && idx < model->count()-1)
- prevAtt->setNextSection(sectionAt(idx+1));
- else
- prevAtt->setNextSection(QString());
- }
- }
-
- lastVisibleSection = QString();
- updateCurrentSection();
- updateStickySections();
-}
-
-void QQuickListViewPrivate::updateCurrentSection()
-{
- Q_Q(QQuickListView);
- if (!sectionCriteria || visibleItems.isEmpty()) {
- if (!currentSection.isEmpty()) {
- currentSection.clear();
- emit q->currentSectionChanged();
- }
- return;
- }
- bool inlineSections = sectionCriteria->labelPositioning() & QQuickViewSection::InlineLabels;
- qreal sectionThreshold = position();
- if (currentSectionItem && !inlineSections)
- sectionThreshold += orient == QQuickListView::Vertical ? currentSectionItem->height() : currentSectionItem->width();
- int index = 0;
- int modelIndex = visibleIndex;
- while (index < visibleItems.count() && visibleItems.at(index)->endPosition() <= sectionThreshold) {
- if (visibleItems.at(index)->index != -1)
- modelIndex = visibleItems.at(index)->index;
- ++index;
- }
-
- QString newSection = currentSection;
- if (index < visibleItems.count())
- newSection = visibleItems.at(index)->attached->section();
- else
- newSection = (*visibleItems.constBegin())->attached->section();
- if (newSection != currentSection) {
- currentSection = newSection;
- updateStickySections();
- emit q->currentSectionChanged();
- }
-
- if (sectionCriteria->labelPositioning() & QQuickViewSection::NextLabelAtEnd) {
- // Don't want to scan for next section on every movement, so remember
- // the last section in the visible area and only scan for the next
- // section when that changes. Clearing lastVisibleSection will also
- // force searching.
- QString lastSection = currentSection;
- qreal endPos = isRightToLeft() ? -position() : position() + size();
- if (nextSectionItem && !inlineSections)
- endPos -= orient == QQuickListView::Vertical ? nextSectionItem->height() : nextSectionItem->width();
- while (index < visibleItems.count() && static_cast<FxListItemSG*>(visibleItems.at(index))->itemPosition() < endPos) {
- if (visibleItems.at(index)->index != -1)
- modelIndex = visibleItems.at(index)->index;
- lastSection = visibleItems.at(index)->attached->section();
- ++index;
- }
-
- if (lastVisibleSection != lastSection) {
- nextSection = QString();
- lastVisibleSection = lastSection;
- for (int i = modelIndex; i < itemCount; ++i) {
- QString section = sectionAt(i);
- if (section != lastSection) {
- nextSection = section;
- updateStickySections();
- break;
- }
- }
- }
- }
-}
-
-void QQuickListViewPrivate::initializeCurrentItem()
-{
- QQuickItemViewPrivate::initializeCurrentItem();
-
- if (currentItem) {
- FxListItemSG *listItem = static_cast<FxListItemSG *>(currentItem);
-
- if (currentIndex == visibleIndex - 1 && visibleItems.count()) {
- // We can calculate exact postion in this case
- listItem->setPosition(visibleItems.first()->position() - currentItem->size() - spacing);
- } else {
- // Create current item now and position as best we can.
- // Its position will be corrected when it becomes visible.
- listItem->setPosition(positionAt(currentIndex));
- }
-
- // Avoid showing section delegate twice. We still need the section heading so that
- // currentItem positioning works correctly.
- // This is slightly sub-optimal, but section heading caching minimizes the impact.
- if (listItem->section)
- listItem->section->setVisible(false);
-
- if (visibleItems.isEmpty())
- averageSize = listItem->size();
- }
-}
-
-void QQuickListViewPrivate::updateAverage()
-{
- if (!visibleItems.count())
- return;
- qreal sum = 0.0;
- for (int i = 0; i < visibleItems.count(); ++i)
- sum += visibleItems.at(i)->size();
- averageSize = qRound(sum / visibleItems.count());
-}
-
-qreal QQuickListViewPrivate::headerSize() const
-{
- return header ? header->size() : 0.0;
-}
-
-qreal QQuickListViewPrivate::footerSize() const
-{
- return footer ? footer->size() : 0.0;
-}
-
-bool QQuickListViewPrivate::showHeaderForIndex(int index) const
-{
- return index == 0;
-}
-
-bool QQuickListViewPrivate::showFooterForIndex(int index) const
-{
- return index == model->count()-1;
-}
-
-void QQuickListViewPrivate::updateFooter()
-{
- Q_Q(QQuickListView);
- bool created = false;
- if (!footer) {
- QQuickItem *item = createComponentItem(footerComponent, true);
- if (!item)
- return;
- item->setZ(1);
- footer = new FxListItemSG(item, q, true);
- created = true;
- }
-
- FxListItemSG *listItem = static_cast<FxListItemSG*>(footer);
- if (visibleItems.count()) {
- qreal endPos = lastPosition();
- if (findLastVisibleIndex() == model->count()-1) {
- listItem->setPosition(endPos);
- } else {
- qreal visiblePos = position() + q->height();
- if (endPos <= visiblePos || listItem->position() < endPos)
- listItem->setPosition(endPos);
- }
- } else {
- listItem->setPosition(visiblePos);
- }
-
- if (created)
- emit q->footerItemChanged();
-}
-
-void QQuickListViewPrivate::updateHeader()
-{
- Q_Q(QQuickListView);
- bool created = false;
- if (!header) {
- QQuickItem *item = createComponentItem(headerComponent, true);
- if (!item)
- return;
- item->setZ(1);
- header = new FxListItemSG(item, q, true);
- created = true;
- }
-
- FxListItemSG *listItem = static_cast<FxListItemSG*>(header);
- if (listItem) {
- if (visibleItems.count()) {
- qreal startPos = originPosition();
- if (visibleIndex == 0) {
- listItem->setPosition(startPos - headerSize());
- } else {
- if (position() <= startPos || listItem->position() > startPos - headerSize())
- listItem->setPosition(startPos - headerSize());
- }
- } else {
- listItem->setPosition(-headerSize());
- }
- }
-
- if (created)
- emit q->headerItemChanged();
-}
-
-void QQuickListViewPrivate::itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_Q(QQuickListView);
- QQuickItemViewPrivate::itemGeometryChanged(item, newGeometry, oldGeometry);
- if (!q->isComponentComplete())
- return;
- if (item != contentItem && (!highlight || item != highlight->item)) {
- if ((orient == QQuickListView::Vertical && newGeometry.height() != oldGeometry.height())
- || (orient == QQuickListView::Horizontal && newGeometry.width() != oldGeometry.width())) {
- forceLayout = true;
- q->polish();
- }
- }
-}
-
-void QQuickListViewPrivate::fixupPosition()
-{
- if ((haveHighlightRange && highlightRange == QQuickListView::StrictlyEnforceRange)
- || snapMode != QQuickListView::NoSnap)
- moveReason = Other;
- if (orient == QQuickListView::Vertical)
- fixupY();
- else
- fixupX();
-}
-
-void QQuickListViewPrivate::fixup(AxisData &data, qreal minExtent, qreal maxExtent)
-{
- if ((orient == QQuickListView::Horizontal && &data == &vData)
- || (orient == QQuickListView::Vertical && &data == &hData))
- return;
-
- correctFlick = false;
- fixupMode = moveReason == Mouse ? fixupMode : Immediate;
- bool strictHighlightRange = haveHighlightRange && highlightRange == QQuickListView::StrictlyEnforceRange;
-
- qreal viewPos = isRightToLeft() ? -position()-size() : position();
-
- if (snapMode != QQuickListView::NoSnap && moveReason != QQuickListViewPrivate::SetIndex) {
- qreal tempPosition = isRightToLeft() ? -position()-size() : position();
- if (snapMode == QQuickListView::SnapOneItem && moveReason == Mouse) {
- // if we've been dragged < averageSize/2 then bias towards the next item
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
- qreal bias = 0;
- if (data.velocity > 0 && dist > QML_FLICK_SNAPONETHRESHOLD && dist < averageSize/2)
- bias = averageSize/2;
- else if (data.velocity < 0 && dist < -QML_FLICK_SNAPONETHRESHOLD && dist > -averageSize/2)
- bias = -averageSize/2;
- if (isRightToLeft())
- bias = -bias;
- tempPosition -= bias;
- }
- FxViewItem *topItem = snapItemAt(tempPosition+highlightRangeStart);
- if (!topItem && strictHighlightRange && currentItem) {
- // StrictlyEnforceRange always keeps an item in range
- updateHighlight();
- topItem = currentItem;
- }
- FxViewItem *bottomItem = snapItemAt(tempPosition+highlightRangeEnd);
- if (!bottomItem && strictHighlightRange && currentItem) {
- // StrictlyEnforceRange always keeps an item in range
- updateHighlight();
- bottomItem = currentItem;
- }
- qreal pos;
- bool isInBounds = -position() > maxExtent && -position() <= minExtent;
- if (topItem && (isInBounds || strictHighlightRange)) {
- if (topItem->index == 0 && header && tempPosition+highlightRangeStart < header->position()+header->size()/2 && !strictHighlightRange) {
- pos = isRightToLeft() ? - header->position() + highlightRangeStart - size() : header->position() - highlightRangeStart;
- } else {
- if (isRightToLeft())
- pos = qMax(qMin(-topItem->position() + highlightRangeStart - size(), -maxExtent), -minExtent);
- else
- pos = qMax(qMin(topItem->position() - highlightRangeStart, -maxExtent), -minExtent);
- }
- } else if (bottomItem && isInBounds) {
- if (isRightToLeft())
- pos = qMax(qMin(-bottomItem->position() + highlightRangeEnd - size(), -maxExtent), -minExtent);
- else
- pos = qMax(qMin(bottomItem->position() - highlightRangeEnd, -maxExtent), -minExtent);
- } else {
- QQuickItemViewPrivate::fixup(data, minExtent, maxExtent);
- return;
- }
-
- qreal dist = qAbs(data.move + pos);
- if (dist > 0) {
- timeline.reset(data.move);
- if (fixupMode != Immediate) {
- timeline.move(data.move, -pos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2);
- data.fixingUp = true;
- } else {
- timeline.set(data.move, -pos);
- }
- vTime = timeline.time();
- }
- } else if (currentItem && strictHighlightRange && moveReason != QQuickListViewPrivate::SetIndex) {
- updateHighlight();
- qreal pos = static_cast<FxListItemSG*>(currentItem)->itemPosition();
- if (viewPos < pos + static_cast<FxListItemSG*>(currentItem)->itemSize() - highlightRangeEnd)
- viewPos = pos + static_cast<FxListItemSG*>(currentItem)->itemSize() - highlightRangeEnd;
- if (viewPos > pos - highlightRangeStart)
- viewPos = pos - highlightRangeStart;
- if (isRightToLeft())
- viewPos = -viewPos-size();
-
- timeline.reset(data.move);
- if (viewPos != position()) {
- if (fixupMode != Immediate) {
- timeline.move(data.move, -viewPos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2);
- data.fixingUp = true;
- } else {
- timeline.set(data.move, -viewPos);
- }
- }
- vTime = timeline.time();
- } else {
- QQuickItemViewPrivate::fixup(data, minExtent, maxExtent);
- }
- data.inOvershoot = false;
- fixupMode = Normal;
-}
-
-void QQuickListViewPrivate::flick(AxisData &data, qreal minExtent, qreal maxExtent, qreal vSize,
- QDeclarativeTimeLineCallback::Callback fixupCallback, qreal velocity)
-{
- Q_Q(QQuickListView);
-
- data.fixingUp = false;
- moveReason = Mouse;
- if ((!haveHighlightRange || highlightRange != QQuickListView::StrictlyEnforceRange) && snapMode == QQuickListView::NoSnap) {
- correctFlick = true;
- QQuickItemViewPrivate::flick(data, minExtent, maxExtent, vSize, fixupCallback, velocity);
- return;
- }
- qreal maxDistance = 0;
- qreal dataValue = isRightToLeft() ? -data.move.value()+size() : data.move.value();
-
- // -ve velocity means list is moving up/left
- if (velocity > 0) {
- if (data.move.value() < minExtent) {
- if (snapMode == QQuickListView::SnapOneItem && !hData.flicking && !vData.flicking) {
- // if we've been dragged < averageSize/2 then bias towards the next item
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
- qreal bias = dist < averageSize/2 ? averageSize/2 : 0;
- if (isRightToLeft())
- bias = -bias;
- data.flickTarget = -snapPosAt(-(dataValue - highlightRangeStart) - bias) + highlightRangeStart;
- maxDistance = qAbs(data.flickTarget - data.move.value());
- velocity = maxVelocity;
- } else {
- maxDistance = qAbs(minExtent - data.move.value());
- }
- }
- if (snapMode == QQuickListView::NoSnap && highlightRange != QQuickListView::StrictlyEnforceRange)
- data.flickTarget = minExtent;
- } else {
- if (data.move.value() > maxExtent) {
- if (snapMode == QQuickListView::SnapOneItem && !hData.flicking && !vData.flicking) {
- // if we've been dragged < averageSize/2 then bias towards the next item
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
- qreal bias = -dist < averageSize/2 ? averageSize/2 : 0;
- if (isRightToLeft())
- bias = -bias;
- data.flickTarget = -snapPosAt(-(dataValue - highlightRangeStart) + bias) + highlightRangeStart;
- maxDistance = qAbs(data.flickTarget - data.move.value());
- velocity = -maxVelocity;
- } else {
- maxDistance = qAbs(maxExtent - data.move.value());
- }
- }
- if (snapMode == QQuickListView::NoSnap && highlightRange != QQuickListView::StrictlyEnforceRange)
- data.flickTarget = maxExtent;
- }
- bool overShoot = boundsBehavior == QQuickFlickable::DragAndOvershootBounds;
- if (maxDistance > 0 || overShoot) {
- // These modes require the list to stop exactly on an item boundary.
- // The initial flick will estimate the boundary to stop on.
- // Since list items can have variable sizes, the boundary will be
- // reevaluated and adjusted as we approach the boundary.
- qreal v = velocity;
- if (maxVelocity != -1 && maxVelocity < qAbs(v)) {
- if (v < 0)
- v = -maxVelocity;
- else
- v = maxVelocity;
- }
- if (!hData.flicking && !vData.flicking) {
- // the initial flick - estimate boundary
- qreal accel = deceleration;
- qreal v2 = v * v;
- overshootDist = 0.0;
- // + averageSize/4 to encourage moving at least one item in the flick direction
- qreal dist = v2 / (accel * 2.0) + averageSize/4;
- if (maxDistance > 0)
- dist = qMin(dist, maxDistance);
- if (v > 0)
- dist = -dist;
- if ((maxDistance > 0.0 && v2 / (2.0f * maxDistance) < accel) || snapMode == QQuickListView::SnapOneItem) {
- if (snapMode != QQuickListView::SnapOneItem) {
- qreal distTemp = isRightToLeft() ? -dist : dist;
- data.flickTarget = -snapPosAt(-(dataValue - highlightRangeStart) + distTemp) + highlightRangeStart;
- }
- data.flickTarget = isRightToLeft() ? -data.flickTarget+size() : data.flickTarget;
- if (overShoot) {
- if (data.flickTarget >= minExtent) {
- overshootDist = overShootDistance(vSize);
- data.flickTarget += overshootDist;
- } else if (data.flickTarget <= maxExtent) {
- overshootDist = overShootDistance(vSize);
- data.flickTarget -= overshootDist;
- }
- }
- qreal adjDist = -data.flickTarget + data.move.value();
- if (qAbs(adjDist) > qAbs(dist)) {
- // Prevent painfully slow flicking - adjust velocity to suit flickDeceleration
- qreal adjv2 = accel * 2.0f * qAbs(adjDist);
- if (adjv2 > v2) {
- v2 = adjv2;
- v = qSqrt(v2);
- if (dist > 0)
- v = -v;
- }
- }
- dist = adjDist;
- accel = v2 / (2.0f * qAbs(dist));
- } else if (overShoot) {
- data.flickTarget = data.move.value() - dist;
- if (data.flickTarget >= minExtent) {
- overshootDist = overShootDistance(vSize);
- data.flickTarget += overshootDist;
- } else if (data.flickTarget <= maxExtent) {
- overshootDist = overShootDistance(vSize);
- data.flickTarget -= overshootDist;
- }
- }
- timeline.reset(data.move);
- timeline.accel(data.move, v, accel, maxDistance + overshootDist);
- timeline.callback(QDeclarativeTimeLineCallback(&data.move, fixupCallback, this));
- if (!hData.flicking && q->xflick()) {
- hData.flicking = true;
- emit q->flickingChanged();
- emit q->flickingHorizontallyChanged();
- emit q->flickStarted();
- }
- if (!vData.flicking && q->yflick()) {
- vData.flicking = true;
- emit q->flickingChanged();
- emit q->flickingVerticallyChanged();
- emit q->flickStarted();
- }
- correctFlick = true;
- } else {
- // reevaluate the target boundary.
- qreal newtarget = data.flickTarget;
- if (snapMode != QQuickListView::NoSnap || highlightRange == QQuickListView::StrictlyEnforceRange) {
- qreal tempFlickTarget = isRightToLeft() ? -data.flickTarget+size() : data.flickTarget;
- newtarget = -snapPosAt(-(tempFlickTarget - highlightRangeStart)) + highlightRangeStart;
- newtarget = isRightToLeft() ? -newtarget+size() : newtarget;
- }
- if (velocity < 0 && newtarget <= maxExtent)
- newtarget = maxExtent - overshootDist;
- else if (velocity > 0 && newtarget >= minExtent)
- newtarget = minExtent + overshootDist;
- if (newtarget == data.flickTarget) { // boundary unchanged - nothing to do
- if (qAbs(velocity) < MinimumFlickVelocity)
- correctFlick = false;
- return;
- }
- data.flickTarget = newtarget;
- qreal dist = -newtarget + data.move.value();
- if ((v < 0 && dist < 0) || (v > 0 && dist > 0)) {
- correctFlick = false;
- timeline.reset(data.move);
- fixup(data, minExtent, maxExtent);
- return;
- }
- timeline.reset(data.move);
- timeline.accelDistance(data.move, v, -dist);
- timeline.callback(QDeclarativeTimeLineCallback(&data.move, fixupCallback, this));
- }
- } else {
- correctFlick = false;
- timeline.reset(data.move);
- fixup(data, minExtent, maxExtent);
- }
-}
-
-//----------------------------------------------------------------------------
-
-/*!
- \qmlclass ListView QQuickListView
- \inqmlmodule QtQuick 2
- \ingroup qml-view-elements
- \inherits Flickable
- \brief The ListView item provides a list view of items provided by a model.
-
- A ListView displays data from models created from built-in QML elements like ListModel
- and XmlListModel, or custom model classes defined in C++ that inherit from
- QAbstractListModel.
-
- A ListView has a \l model, which defines the data to be displayed, and
- a \l delegate, which defines how the data should be displayed. Items in a
- ListView are laid out horizontally or vertically. List views are inherently
- flickable because ListView inherits from \l Flickable.
-
- \section1 Example Usage
-
- The following example shows the definition of a simple list model defined
- in a file called \c ContactModel.qml:
-
- \snippet doc/src/snippets/declarative/listview/ContactModel.qml 0
-
- Another component can display this model data in a ListView, like this:
-
- \snippet doc/src/snippets/declarative/listview/listview.qml import
- \codeline
- \snippet doc/src/snippets/declarative/listview/listview.qml classdocs simple
-
- \image listview-simple.png
-
- Here, the ListView creates a \c ContactModel component for its model, and a \l Text element
- for its delegate. The view will create a new \l Text component for each item in the model. Notice
- the delegate is able to access the model's \c name and \c number data directly.
-
- An improved list view is shown below. The delegate is visually improved and is moved
- into a separate \c contactDelegate component.
-
- \snippet doc/src/snippets/declarative/listview/listview.qml classdocs advanced
- \image listview-highlight.png
-
- The currently selected item is highlighted with a blue \l Rectangle using the \l highlight property,
- and \c focus is set to \c true to enable keyboard navigation for the list view.
- The list view itself is a focus scope (see \l{qmlfocus#Acquiring Focus and Focus Scopes}{the focus documentation page} for more details).
-
- Delegates are instantiated as needed and may be destroyed at any time.
- State should \e never be stored in a delegate.
-
- ListView attaches a number of properties to the root item of the delegate, for example
- \c {ListView.isCurrentItem}. In the following example, the root delegate item can access
- this attached property directly as \c ListView.isCurrentItem, while the child
- \c contactInfo object must refer to this property as \c wrapper.ListView.isCurrentItem.
-
- \snippet doc/src/snippets/declarative/listview/listview.qml isCurrentItem
-
- \note Views do not enable \e clip automatically. If the view
- is not clipped by another item or the screen, it will be necessary
- to set \e {clip: true} in order to have the out of view items clipped
- nicely.
-
- \sa {QML Data Models}, GridView, {declarative/modelviews/listview}{ListView examples}
-*/
-QQuickListView::QQuickListView(QQuickItem *parent)
- : QQuickItemView(*(new QQuickListViewPrivate), parent)
-{
-}
-
-QQuickListView::~QQuickListView()
-{
-}
-
-/*!
- \qmlattachedproperty bool QtQuick2::ListView::isCurrentItem
- This attached property is true if this delegate is the current item; otherwise false.
-
- It is attached to each instance of the delegate.
-
- This property may be used to adjust the appearance of the current item, for example:
-
- \snippet doc/src/snippets/declarative/listview/listview.qml isCurrentItem
-*/
-
-/*!
- \qmlattachedproperty ListView QtQuick2::ListView::view
- This attached property holds the view that manages this delegate instance.
-
- It is attached to each instance of the delegate.
-*/
-
-/*!
- \qmlattachedproperty string QtQuick2::ListView::previousSection
- This attached property holds the section of the previous element.
-
- It is attached to each instance of the delegate.
-
- The section is evaluated using the \l {ListView::section.property}{section} properties.
-*/
-
-/*!
- \qmlattachedproperty string QtQuick2::ListView::nextSection
- This attached property holds the section of the next element.
-
- It is attached to each instance of the delegate.
-
- The section is evaluated using the \l {ListView::section.property}{section} properties.
-*/
-
-/*!
- \qmlattachedproperty string QtQuick2::ListView::section
- This attached property holds the section of this element.
-
- It is attached to each instance of the delegate.
-
- The section is evaluated using the \l {ListView::section.property}{section} properties.
-*/
-
-/*!
- \qmlattachedproperty bool QtQuick2::ListView::delayRemove
- This attached property holds whether the delegate may be destroyed.
-
- It is attached to each instance of the delegate.
-
- It is sometimes necessary to delay the destruction of an item
- until an animation completes.
-
- The example delegate below ensures that the animation completes before
- the item is removed from the list.
-
- \snippet doc/src/snippets/declarative/listview/listview.qml delayRemove
-*/
-
-/*!
- \qmlattachedsignal QtQuick2::ListView::onAdd()
- This attached handler is called immediately after an item is added to the view.
-*/
-
-/*!
- \qmlattachedsignal QtQuick2::ListView::onRemove()
- This attached handler is called immediately before an item is removed from the view.
-*/
-
-/*!
- \qmlproperty model QtQuick2::ListView::model
- This property holds the model providing data for the list.
-
- The model provides the set of data that is used to create the items
- in the view. Models can be created directly in QML using \l ListModel, \l XmlListModel
- or \l VisualItemModel, or provided by C++ model classes. If a C++ model class is
- used, it must be a subclass of \l QAbstractItemModel or a simple list.
-
- \sa {qmlmodels}{Data Models}
-*/
-
-/*!
- \qmlproperty Component QtQuick2::ListView::delegate
-
- The delegate provides a template defining each item instantiated by the view.
- The index is exposed as an accessible \c index property. Properties of the
- model are also available depending upon the type of \l {qmlmodels}{Data Model}.
-
- The number of elements in the delegate has a direct effect on the
- flicking performance of the view. If at all possible, place functionality
- that is not needed for the normal display of the delegate in a \l Loader which
- can load additional elements when needed.
-
- The ListView will lay out the items based on the size of the root item
- in the delegate.
-
- It is recommended that the delegate's size be a whole number to avoid sub-pixel
- alignment of items.
-
- \note Delegates are instantiated as needed and may be destroyed at any time.
- State should \e never be stored in a delegate.
-*/
-/*!
- \qmlproperty int QtQuick2::ListView::currentIndex
- \qmlproperty Item QtQuick2::ListView::currentItem
-
- The \c currentIndex property holds the index of the current item, and
- \c currentItem holds the current item. Setting the currentIndex to -1
- will clear the highlight and set currentItem to null.
-
- If highlightFollowsCurrentItem is \c true, setting either of these
- properties will smoothly scroll the ListView so that the current
- item becomes visible.
-
- Note that the position of the current item
- may only be approximate until it becomes visible in the view.
-*/
-
-/*!
- \qmlproperty Item QtQuick2::ListView::highlightItem
-
- This holds the highlight item created from the \l highlight component.
-
- The \c highlightItem is managed by the view unless
- \l highlightFollowsCurrentItem is set to false.
-
- \sa highlight, highlightFollowsCurrentItem
-*/
-
-/*!
- \qmlproperty int QtQuick2::ListView::count
- This property holds the number of items in the view.
-*/
-
-/*!
- \qmlproperty Component QtQuick2::ListView::highlight
- This property holds the component to use as the highlight.
-
- An instance of the highlight component is created for each list.
- The geometry of the resulting component instance is managed by the list
- so as to stay with the current item, unless the highlightFollowsCurrentItem
- property is false.
-
- \sa highlightItem, highlightFollowsCurrentItem, {declarative/modelviews/listview}{ListView examples}
-*/
-
-/*!
- \qmlproperty bool QtQuick2::ListView::highlightFollowsCurrentItem
- This property holds whether the highlight is managed by the view.
-
- If this property is true (the default value), the highlight is moved smoothly
- to follow the current item. Otherwise, the
- highlight is not moved by the view, and any movement must be implemented
- by the highlight.
-
- Here is a highlight with its motion defined by a \l {SpringAnimation} item:
-
- \snippet doc/src/snippets/declarative/listview/listview.qml highlightFollowsCurrentItem
-
- Note that the highlight animation also affects the way that the view
- is scrolled. This is because the view moves to maintain the
- highlight within the preferred highlight range (or visible viewport).
-
- \sa highlight, highlightMoveSpeed
-*/
-//###Possibly rename these properties, since they are very useful even without a highlight?
-/*!
- \qmlproperty real QtQuick2::ListView::preferredHighlightBegin
- \qmlproperty real QtQuick2::ListView::preferredHighlightEnd
- \qmlproperty enumeration QtQuick2::ListView::highlightRangeMode
-
- These properties define the preferred range of the highlight (for the current item)
- within the view. The \c preferredHighlightBegin value must be less than the
- \c preferredHighlightEnd value.
-
- These properties affect the position of the current item when the list is scrolled.
- For example, if the currently selected item should stay in the middle of the
- list when the view is scrolled, set the \c preferredHighlightBegin and
- \c preferredHighlightEnd values to the top and bottom coordinates of where the middle
- item would be. If the \c currentItem is changed programmatically, the list will
- automatically scroll so that the current item is in the middle of the view.
- Furthermore, the behavior of the current item index will occur whether or not a
- highlight exists.
-
- Valid values for \c highlightRangeMode are:
-
- \list
- \o ListView.ApplyRange - the view attempts to maintain the highlight within the range.
- However, the highlight can move outside of the range at the ends of the list or due
- to mouse interaction.
- \o ListView.StrictlyEnforceRange - the highlight never moves outside of the range.
- The current item changes if a keyboard or mouse action would cause the highlight to move
- outside of the range.
- \o ListView.NoHighlightRange - this is the default value.
- \endlist
-*/
-void QQuickListView::setHighlightFollowsCurrentItem(bool autoHighlight)
-{
- Q_D(QQuickListView);
- if (d->autoHighlight != autoHighlight) {
- if (!autoHighlight) {
- if (d->highlightPosAnimator)
- d->highlightPosAnimator->stop();
- if (d->highlightSizeAnimator)
- d->highlightSizeAnimator->stop();
- }
- QQuickItemView::setHighlightFollowsCurrentItem(autoHighlight);
- }
-}
-
-/*!
- \qmlproperty real QtQuick2::ListView::spacing
-
- This property holds the spacing between items.
-
- The default value is 0.
-*/
-qreal QQuickListView::spacing() const
-{
- Q_D(const QQuickListView);
- return d->spacing;
-}
-
-void QQuickListView::setSpacing(qreal spacing)
-{
- Q_D(QQuickListView);
- if (spacing != d->spacing) {
- d->spacing = spacing;
- d->forceLayout = true;
- d->layout();
- emit spacingChanged();
- }
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::ListView::orientation
- This property holds the orientation of the list.
-
- Possible values:
-
- \list
- \o ListView.Horizontal - Items are laid out horizontally
- \o ListView.Vertical (default) - Items are laid out vertically
- \endlist
-
- \table
- \row
- \o Horizontal orientation:
- \image ListViewHorizontal.png
-
- \row
- \o Vertical orientation:
- \image listview-highlight.png
- \endtable
-*/
-QQuickListView::Orientation QQuickListView::orientation() const
-{
- Q_D(const QQuickListView);
- return d->orient;
-}
-
-void QQuickListView::setOrientation(QQuickListView::Orientation orientation)
-{
- Q_D(QQuickListView);
- if (d->orient != orientation) {
- d->orient = orientation;
- if (d->orient == Vertical) {
- setContentWidth(-1);
- setFlickableDirection(VerticalFlick);
- setContentX(0);
- } else {
- setContentHeight(-1);
- setFlickableDirection(HorizontalFlick);
- setContentY(0);
- }
- d->regenerate();
- emit orientationChanged();
- }
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::ListView::layoutDirection
- This property holds the layout direction of the horizontal list.
-
- Possible values:
-
- \list
- \o Qt.LeftToRight (default) - Items will be laid out from left to right.
- \o Qt.RightToLeft - Items will be laid out from right to let.
- \endlist
-
- \sa ListView::effectiveLayoutDirection
-*/
-
-
-/*!
- \qmlproperty enumeration QtQuick2::ListView::effectiveLayoutDirection
- This property holds the effective layout direction of the horizontal list.
-
- When using the attached property \l {LayoutMirroring::enabled}{LayoutMirroring::enabled} for locale layouts,
- the visual layout direction of the horizontal list will be mirrored. However, the
- property \l {ListView::layoutDirection}{layoutDirection} will remain unchanged.
-
- \sa ListView::layoutDirection, {LayoutMirroring}{LayoutMirroring}
-*/
-
-/*!
- \qmlproperty bool QtQuick2::ListView::keyNavigationWraps
- This property holds whether the list wraps key navigation.
-
- If this is true, key navigation that would move the current item selection
- past the end of the list instead wraps around and moves the selection to
- the start of the list, and vice-versa.
-
- By default, key navigation is not wrapped.
-*/
-
-
-/*!
- \qmlproperty int QtQuick2::ListView::cacheBuffer
- This property determines whether delegates are retained outside the
- visible area of the view.
-
- If this value is non-zero, the view may keep as many delegates
- instantiated as it can fit within the buffer specified. For example,
- if in a vertical view the delegate is 20 pixels high and \c cacheBuffer is
- set to 40, then up to 2 delegates above and 2 delegates below the visible
- area may be created/retained. The buffered delegates are created asynchronously,
- allowing creation to occur across multiple frames and reducing the
- likelihood of skipping frames. In order to improve painting performance
- delegates outside the visible area have their \l visible property set to
- false until they are moved into the visible area.
-
- Note that cacheBuffer is not a pixel buffer - it only maintains additional
- instantiated delegates.
-
- Setting this value can improve the smoothness of scrolling behavior at the expense
- of additional memory usage. It is not a substitute for creating efficient
- delegates; the fewer elements in a delegate, the faster a view can be
- scrolled.
-*/
-
-
-/*!
- \qmlproperty string QtQuick2::ListView::section.property
- \qmlproperty enumeration QtQuick2::ListView::section.criteria
- \qmlproperty Component QtQuick2::ListView::section.delegate
- \qmlproperty enumeration QtQuick2::ListView::section.labelPositioning
-
- These properties determine the expression to be evaluated and appearance
- of the section labels.
-
- \c section.property holds the name of the property that is the basis
- of each section.
-
- \c section.criteria holds the criteria for forming each section based on
- \c section.property. This value can be one of:
-
- \list
- \o ViewSection.FullString (default) - sections are created based on the
- \c section.property value.
- \o ViewSection.FirstCharacter - sections are created based on the first
- character of the \c section.property value (for example, 'A', 'B', 'C'
- sections, etc. for an address book)
- \endlist
-
- \c section.delegate holds the delegate component for each section.
-
- \c section.labelPositioning determines whether the current and/or
- next section labels stick to the start/end of the view, and whether
- the labels are shown inline. This value can be a combination of:
-
- \list
- \o ViewSection.InlineLabels - section labels are shown inline between
- the item delegates separating sections (default).
- \o ViewSection.CurrentLabelAtStart - the current section label sticks to the
- start of the view as it is moved.
- \o ViewSection.NextLabelAtEnd - the next section label (beyond all visible
- sections) sticks to the end of the view as it is moved. \note Enabling
- \c ViewSection.NextLabelAtEnd requires the view to scan ahead for the next
- section, which has performance implications, especially for slower models.
- \endlist
-
- Each item in the list has attached properties named \c ListView.section,
- \c ListView.previousSection and \c ListView.nextSection.
-
- For example, here is a ListView that displays a list of animals, separated
- into sections. Each item in the ListView is placed in a different section
- depending on the "size" property of the model item. The \c sectionHeading
- delegate component provides the light blue bar that marks the beginning of
- each section.
-
-
- \snippet examples/declarative/modelviews/listview/sections.qml 0
-
- \image qml-listview-sections-example.png
-
- \note Adding sections to a ListView does not automatically re-order the
- list items by the section criteria.
- If the model is not ordered by section, then it is possible that
- the sections created will not be unique; each boundary between
- differing sections will result in a section header being created
- even if that section exists elsewhere.
-
- \sa {declarative/modelviews/listview}{ListView examples}
-*/
-QQuickViewSection *QQuickListView::sectionCriteria()
-{
- Q_D(QQuickListView);
- if (!d->sectionCriteria) {
- d->sectionCriteria = new QQuickViewSection(this);
- connect(d->sectionCriteria, SIGNAL(propertyChanged()), this, SLOT(updateSections()));
- }
- return d->sectionCriteria;
-}
-
-/*!
- \qmlproperty string QtQuick2::ListView::currentSection
- This property holds the section that is currently at the beginning of the view.
-*/
-QString QQuickListView::currentSection() const
-{
- Q_D(const QQuickListView);
- return d->currentSection;
-}
-
-/*!
- \qmlproperty real QtQuick2::ListView::highlightMoveSpeed
- \qmlproperty int QtQuick2::ListView::highlightMoveDuration
- \qmlproperty real QtQuick2::ListView::highlightResizeSpeed
- \qmlproperty int QtQuick2::ListView::highlightResizeDuration
-
- These properties hold the move and resize animation speed of the highlight delegate.
-
- \l highlightFollowsCurrentItem must be true for these properties
- to have effect.
-
- The default value for the speed properties is 400 pixels/second.
- The default value for the duration properties is -1, i.e. the
- highlight will take as much time as necessary to move at the set speed.
-
- These properties have the same characteristics as a SmoothedAnimation.
-
- \sa highlightFollowsCurrentItem
-*/
-qreal QQuickListView::highlightMoveSpeed() const
-{
- Q_D(const QQuickListView);
- return d->highlightMoveSpeed;
-}
-
-void QQuickListView::setHighlightMoveSpeed(qreal speed)
-{
- Q_D(QQuickListView);
- if (d->highlightMoveSpeed != speed) {
- d->highlightMoveSpeed = speed;
- if (d->highlightPosAnimator)
- d->highlightPosAnimator->velocity = d->highlightMoveSpeed;
- emit highlightMoveSpeedChanged();
- }
-}
-
-void QQuickListView::setHighlightMoveDuration(int duration)
-{
- Q_D(QQuickListView);
- if (d->highlightMoveDuration != duration) {
- if (d->highlightPosAnimator)
- d->highlightPosAnimator->userDuration = duration;
- QQuickItemView::setHighlightMoveDuration(duration);
- }
-}
-
-qreal QQuickListView::highlightResizeSpeed() const
-{
- Q_D(const QQuickListView);
- return d->highlightResizeSpeed;
-}
-
-void QQuickListView::setHighlightResizeSpeed(qreal speed)
-{
- Q_D(QQuickListView);
- if (d->highlightResizeSpeed != speed) {
- d->highlightResizeSpeed = speed;
- if (d->highlightSizeAnimator)
- d->highlightSizeAnimator->velocity = d->highlightResizeSpeed;
- emit highlightResizeSpeedChanged();
- }
-}
-
-int QQuickListView::highlightResizeDuration() const
-{
- Q_D(const QQuickListView);
- return d->highlightResizeDuration;
-}
-
-void QQuickListView::setHighlightResizeDuration(int duration)
-{
- Q_D(QQuickListView);
- if (d->highlightResizeDuration != duration) {
- d->highlightResizeDuration = duration;
- if (d->highlightSizeAnimator)
- d->highlightSizeAnimator->userDuration = d->highlightResizeDuration;
- emit highlightResizeDurationChanged();
- }
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::ListView::snapMode
-
- This property determines how the view scrolling will settle following a drag or flick.
- The possible values are:
-
- \list
- \o ListView.NoSnap (default) - the view stops anywhere within the visible area.
- \o ListView.SnapToItem - the view settles with an item aligned with the start of
- the view.
- \o ListView.SnapOneItem - the view settles no more than one item away from the first
- visible item at the time the mouse button is released. This mode is particularly
- useful for moving one page at a time.
- \endlist
-
- \c snapMode does not affect the \l currentIndex. To update the
- \l currentIndex as the list is moved, set \l highlightRangeMode
- to \c ListView.StrictlyEnforceRange.
-
- \sa highlightRangeMode
-*/
-QQuickListView::SnapMode QQuickListView::snapMode() const
-{
- Q_D(const QQuickListView);
- return d->snapMode;
-}
-
-void QQuickListView::setSnapMode(SnapMode mode)
-{
- Q_D(QQuickListView);
- if (d->snapMode != mode) {
- d->snapMode = mode;
- emit snapModeChanged();
- }
-}
-
-
-/*!
- \qmlproperty Component QtQuick2::ListView::footer
- This property holds the component to use as the footer.
-
- An instance of the footer component is created for each view. The
- footer is positioned at the end of the view, after any items.
-
- \sa header
-*/
-
-
-/*!
- \qmlproperty Component QtQuick2::ListView::header
- This property holds the component to use as the header.
-
- An instance of the header component is created for each view. The
- header is positioned at the beginning of the view, before any items.
-
- \sa footer
-*/
-
-void QQuickListView::viewportMoved()
-{
- Q_D(QQuickListView);
- QQuickItemView::viewportMoved();
- if (!d->itemCount)
- return;
- // Recursion can occur due to refill changing the content size.
- if (d->inViewportMoved)
- return;
- d->inViewportMoved = true;
-
- // Set visibility of items to eliminate cost of items outside the visible area.
- qreal from = d->isContentFlowReversed() ? -d->position()-d->size() : d->position();
- qreal to = d->isContentFlowReversed() ? -d->position() : d->position()+d->size();
- for (int i = 0; i < d->visibleItems.count(); ++i) {
- FxViewItem *item = static_cast<FxListItemSG*>(d->visibleItems.at(i));
- item->item->setVisible(item->endPosition() >= from && item->position() <= to);
- }
-
- if (yflick())
- d->bufferMode = d->vData.smoothVelocity < 0 ? QQuickListViewPrivate::BufferBefore : QQuickListViewPrivate::BufferAfter;
- else if (d->isRightToLeft())
- d->bufferMode = d->hData.smoothVelocity < 0 ? QQuickListViewPrivate::BufferAfter : QQuickListViewPrivate::BufferBefore;
- else
- d->bufferMode = d->hData.smoothVelocity < 0 ? QQuickListViewPrivate::BufferBefore : QQuickListViewPrivate::BufferAfter;
-
- d->refill();
- if (d->hData.flicking || d->vData.flicking || d->hData.moving || d->vData.moving)
- d->moveReason = QQuickListViewPrivate::Mouse;
- if (d->moveReason != QQuickListViewPrivate::SetIndex) {
- if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange && d->highlight) {
- // reposition highlight
- qreal pos = d->highlight->position();
- qreal viewPos = d->isRightToLeft() ? -d->position()-d->size() : d->position();
- if (pos > viewPos + d->highlightRangeEnd - d->highlight->size())
- pos = viewPos + d->highlightRangeEnd - d->highlight->size();
- if (pos < viewPos + d->highlightRangeStart)
- pos = viewPos + d->highlightRangeStart;
- if (pos != d->highlight->position()) {
- d->highlightPosAnimator->stop();
- static_cast<FxListItemSG*>(d->highlight)->setPosition(pos);
- } else {
- d->updateHighlight();
- }
-
- // update current index
- if (FxViewItem *snapItem = d->snapItemAt(d->highlight->position())) {
- if (snapItem->index >= 0 && snapItem->index != d->currentIndex)
- d->updateCurrent(snapItem->index);
- }
- }
- }
-
- if ((d->hData.flicking || d->vData.flicking) && d->correctFlick && !d->inFlickCorrection) {
- d->inFlickCorrection = true;
- // Near an end and it seems that the extent has changed?
- // Recalculate the flick so that we don't end up in an odd position.
- if (yflick() && !d->vData.inOvershoot) {
- if (d->vData.velocity > 0) {
- const qreal minY = minYExtent();
- if ((minY - d->vData.move.value() < height()/2 || d->vData.flickTarget - d->vData.move.value() < height()/2)
- && minY != d->vData.flickTarget)
- d->flickY(-d->vData.smoothVelocity.value());
- } else if (d->vData.velocity < 0) {
- const qreal maxY = maxYExtent();
- if ((d->vData.move.value() - maxY < height()/2 || d->vData.move.value() - d->vData.flickTarget < height()/2)
- && maxY != d->vData.flickTarget)
- d->flickY(-d->vData.smoothVelocity.value());
- }
- }
-
- if (xflick() && !d->hData.inOvershoot) {
- if (d->hData.velocity > 0) {
- const qreal minX = minXExtent();
- if ((minX - d->hData.move.value() < width()/2 || d->hData.flickTarget - d->hData.move.value() < width()/2)
- && minX != d->hData.flickTarget)
- d->flickX(-d->hData.smoothVelocity.value());
- } else if (d->hData.velocity < 0) {
- const qreal maxX = maxXExtent();
- if ((d->hData.move.value() - maxX < width()/2 || d->hData.move.value() - d->hData.flickTarget < width()/2)
- && maxX != d->hData.flickTarget)
- d->flickX(-d->hData.smoothVelocity.value());
- }
- }
- d->inFlickCorrection = false;
- }
- if (d->sectionCriteria) {
- d->updateCurrentSection();
- d->updateStickySections();
- }
- d->inViewportMoved = false;
-}
-
-void QQuickListView::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QQuickListView);
- if (d->model && d->model->count() && d->interactive) {
- if ((d->orient == QQuickListView::Horizontal && !d->isRightToLeft() && event->key() == Qt::Key_Left)
- || (d->orient == QQuickListView::Horizontal && d->isRightToLeft() && event->key() == Qt::Key_Right)
- || (d->orient == QQuickListView::Vertical && event->key() == Qt::Key_Up)) {
- if (currentIndex() > 0 || (d->wrap && !event->isAutoRepeat())) {
- decrementCurrentIndex();
- event->accept();
- return;
- } else if (d->wrap) {
- event->accept();
- return;
- }
- } else if ((d->orient == QQuickListView::Horizontal && !d->isRightToLeft() && event->key() == Qt::Key_Right)
- || (d->orient == QQuickListView::Horizontal && d->isRightToLeft() && event->key() == Qt::Key_Left)
- || (d->orient == QQuickListView::Vertical && event->key() == Qt::Key_Down)) {
- if (currentIndex() < d->model->count() - 1 || (d->wrap && !event->isAutoRepeat())) {
- incrementCurrentIndex();
- event->accept();
- return;
- } else if (d->wrap) {
- event->accept();
- return;
- }
- }
- }
- event->ignore();
- QQuickItemView::keyPressEvent(event);
-}
-
-void QQuickListView::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_D(QQuickListView);
- if (d->isRightToLeft() && d->orient == QQuickListView::Horizontal) {
- // maintain position relative to the right edge
- int dx = newGeometry.width() - oldGeometry.width();
- setContentX(contentX() - dx);
- }
- QQuickItemView::geometryChanged(newGeometry, oldGeometry);
-}
-
-
-/*!
- \qmlmethod QtQuick2::ListView::incrementCurrentIndex()
-
- Increments the current index. The current index will wrap
- if keyNavigationWraps is true and it is currently at the end.
- This method has no effect if the \l count is zero.
-
- \bold Note: methods should only be called after the Component has completed.
-*/
-void QQuickListView::incrementCurrentIndex()
-{
- Q_D(QQuickListView);
- int count = d->model ? d->model->count() : 0;
- if (count && (currentIndex() < count - 1 || d->wrap)) {
- d->moveReason = QQuickListViewPrivate::SetIndex;
- int index = currentIndex()+1;
- setCurrentIndex((index >= 0 && index < count) ? index : 0);
- }
-}
-
-/*!
- \qmlmethod QtQuick2::ListView::decrementCurrentIndex()
-
- Decrements the current index. The current index will wrap
- if keyNavigationWraps is true and it is currently at the beginning.
- This method has no effect if the \l count is zero.
-
- \bold Note: methods should only be called after the Component has completed.
-*/
-void QQuickListView::decrementCurrentIndex()
-{
- Q_D(QQuickListView);
- int count = d->model ? d->model->count() : 0;
- if (count && (currentIndex() > 0 || d->wrap)) {
- d->moveReason = QQuickListViewPrivate::SetIndex;
- int index = currentIndex()-1;
- setCurrentIndex((index >= 0 && index < count) ? index : count-1);
- }
-}
-
-void QQuickListView::updateSections()
-{
- Q_D(QQuickListView);
- if (isComponentComplete() && d->model) {
- QList<QByteArray> roles;
- if (d->sectionCriteria && !d->sectionCriteria->property().isEmpty())
- roles << d->sectionCriteria->property().toUtf8();
- d->model->setWatchedRoles(roles);
- d->updateSections();
- if (d->itemCount) {
- d->forceLayout = true;
- d->layout();
- }
- }
-}
-
-bool QQuickListViewPrivate::applyInsertionChange(const QDeclarativeChangeSet::Insert &change, FxViewItem *firstVisible, InsertionsResult *insertResult)
-{
- int modelIndex = change.index;
- int count = change.count;
-
-
- qreal tempPos = isRightToLeft() ? -position()-size() : position();
- int index = visibleItems.count() ? mapFromModel(modelIndex) : 0;
-
- if (index < 0) {
- int i = visibleItems.count() - 1;
- while (i > 0 && visibleItems.at(i)->index == -1)
- --i;
- if (i == 0 && visibleItems.first()->index == -1) {
- // there are no visible items except items marked for removal
- index = visibleItems.count();
- } else if (visibleItems.at(i)->index + 1 == modelIndex
- && visibleItems.at(i)->endPosition() <= buffer+tempPos+size()) {
- // Special case of appending an item to the model.
- index = visibleItems.count();
- } else {
- if (modelIndex < visibleIndex) {
- // Insert before visible items
- visibleIndex += count;
- for (int i = 0; i < visibleItems.count(); ++i) {
- FxViewItem *item = visibleItems.at(i);
- if (item->index != -1 && item->index >= modelIndex)
- item->index += count;
- }
- }
- return true;
- }
- }
-
- // index can be the next item past the end of the visible items list (i.e. appended)
- int pos = 0;
- if (visibleItems.count()) {
- pos = index < visibleItems.count() ? visibleItems.at(index)->position()
- : visibleItems.last()->endPosition()+spacing;
- }
-
- int prevAddedCount = insertResult->addedItems.count();
- if (firstVisible && pos < firstVisible->position()) {
- // Insert items before the visible item.
- int insertionIdx = index;
- int i = 0;
- int from = tempPos - buffer;
-
- for (i = count-1; i >= 0; --i) {
- if (pos > from && insertionIdx < visibleIndex) {
- // item won't be visible, just note the size for repositioning
- insertResult->sizeAddedBeforeVisible += averageSize + spacing;
- pos -= averageSize + spacing;
- } else {
- // item is before first visible e.g. in cache buffer
- FxViewItem *item = 0;
- if (change.isMove() && (item = currentChanges.removedItems.take(change.moveKey(modelIndex + i)))) {
- if (item->index > modelIndex + i)
- insertResult->movedBackwards.append(item);
- item->index = modelIndex + i;
- }
- if (!item)
- item = createItem(modelIndex + i);
- if (!item)
- return false;
-
- visibleItems.insert(insertionIdx, item);
- if (!change.isMove()) {
- insertResult->addedItems.append(item);
- insertResult->sizeAddedBeforeVisible += item->size();
- }
- pos -= item->size() + spacing;
- }
- index++;
- }
- } else {
- int i = 0;
- int to = buffer+tempPos+size();
- for (i = 0; i < count && pos <= to; ++i) {
- FxViewItem *item = 0;
- if (change.isMove() && (item = currentChanges.removedItems.take(change.moveKey(modelIndex + i)))) {
- if (item->index > modelIndex + i)
- insertResult->movedBackwards.append(item);
- item->index = modelIndex + i;
- }
- if (!item)
- item = createItem(modelIndex + i);
- if (!item)
- return false;
-
- visibleItems.insert(index, item);
- if (!change.isMove())
- insertResult->addedItems.append(item);
- pos += item->size() + spacing;
- ++index;
- }
- }
-
- for (; index < visibleItems.count(); ++index) {
- FxViewItem *item = visibleItems.at(index);
- if (item->index != -1)
- item->index += count;
- }
-
- updateVisibleIndex();
-
- return insertResult->addedItems.count() > prevAddedCount;
-}
-
-
-/*!
- \qmlmethod QtQuick2::ListView::positionViewAtIndex(int index, PositionMode mode)
-
- Positions the view such that the \a index is at the position specified by
- \a mode:
-
- \list
- \o ListView.Beginning - position item at the top (or left for horizontal orientation) of the view.
- \o ListView.Center - position item in the center of the view.
- \o ListView.End - position item at bottom (or right for horizontal orientation) of the view.
- \o ListView.Visible - if any part of the item is visible then take no action, otherwise
- bring the item into view.
- \o ListView.Contain - ensure the entire item is visible. If the item is larger than
- the view the item is positioned at the top (or left for horizontal orientation) of the view.
- \endlist
-
- If positioning the view at \a index would cause empty space to be displayed at
- the beginning or end of the view, the view will be positioned at the boundary.
-
- It is not recommended to use \l {Flickable::}{contentX} or \l {Flickable::}{contentY} to position the view
- at a particular index. This is unreliable since removing items from the start
- of the list does not cause all other items to be repositioned, and because
- the actual start of the view can vary based on the size of the delegates.
- The correct way to bring an item into view is with \c positionViewAtIndex.
-
- \bold Note: methods should only be called after the Component has completed. To position
- the view at startup, this method should be called by Component.onCompleted. For
- example, to position the view at the end:
-
- \code
- Component.onCompleted: positionViewAtIndex(count - 1, ListView.Beginning)
- \endcode
-*/
-
-/*!
- \qmlmethod QtQuick2::ListView::positionViewAtBeginning()
- \qmlmethod QtQuick2::ListView::positionViewAtEnd()
-
- Positions the view at the beginning or end, taking into account any header or footer.
-
- It is not recommended to use \l {Flickable::}{contentX} or \l {Flickable::}{contentY} to position the view
- at a particular index. This is unreliable since removing items from the start
- of the list does not cause all other items to be repositioned, and because
- the actual start of the view can vary based on the size of the delegates.
-
- \bold Note: methods should only be called after the Component has completed. To position
- the view at startup, this method should be called by Component.onCompleted. For
- example, to position the view at the end on startup:
-
- \code
- Component.onCompleted: positionViewAtEnd()
- \endcode
-*/
-
-/*!
- \qmlmethod int QtQuick2::ListView::indexAt(int x, int y)
-
- Returns the index of the visible item containing the point \a x, \a y in content
- coordinates. If there is no item at the point specified, or the item is
- not visible -1 is returned.
-
- If the item is outside the visible area, -1 is returned, regardless of
- whether an item will exist at that point when scrolled into view.
-
- \bold Note: methods should only be called after the Component has completed.
-*/
-
-QQuickListViewAttached *QQuickListView::qmlAttachedProperties(QObject *obj)
-{
- return new QQuickListViewAttached(obj);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquicklistview_p.h b/src/declarative/items/qquicklistview_p.h
deleted file mode 100644
index 0266e23cd5..0000000000
--- a/src/declarative/items/qquicklistview_p.h
+++ /dev/null
@@ -1,215 +0,0 @@
-// Commit: 95814418f9d6adeba365c795462e8afb00138211
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKLISTVIEW_P_H
-#define QQUICKLISTVIEW_P_H
-
-#include "qquickitemview_p.h"
-
-#include <private/qdeclarativeguard_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickListView;
-class QQuickListViewPrivate;
-class Q_AUTOTEST_EXPORT QQuickViewSection : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QString property READ property WRITE setProperty NOTIFY propertyChanged)
- Q_PROPERTY(SectionCriteria criteria READ criteria WRITE setCriteria NOTIFY criteriaChanged)
- Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged)
- Q_PROPERTY(int labelPositioning READ labelPositioning WRITE setLabelPositioning NOTIFY labelPositioningChanged)
- Q_ENUMS(SectionCriteria)
- Q_ENUMS(LabelPositioning)
-public:
- QQuickViewSection(QQuickListView *parent=0);
-
- QString property() const { return m_property; }
- void setProperty(const QString &);
-
- enum SectionCriteria { FullString, FirstCharacter };
- SectionCriteria criteria() const { return m_criteria; }
- void setCriteria(SectionCriteria);
-
- QDeclarativeComponent *delegate() const { return m_delegate; }
- void setDelegate(QDeclarativeComponent *delegate);
-
- QString sectionString(const QString &value);
-
- enum LabelPositioning { InlineLabels = 0x01, CurrentLabelAtStart = 0x02, NextLabelAtEnd = 0x04 };
- int labelPositioning() { return m_labelPositioning; }
- void setLabelPositioning(int pos);
-
-Q_SIGNALS:
- void propertyChanged();
- void criteriaChanged();
- void delegateChanged();
- void labelPositioningChanged();
-
-private:
- QString m_property;
- SectionCriteria m_criteria;
- QDeclarativeComponent *m_delegate;
- int m_labelPositioning;
- QQuickListViewPrivate *m_view;
-};
-
-
-class QQuickVisualModel;
-class QQuickListViewAttached;
-class Q_AUTOTEST_EXPORT QQuickListView : public QQuickItemView
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickListView)
-
- // XXX deprecate these two properties (only duration should be necessary)
- Q_PROPERTY(qreal highlightMoveSpeed READ highlightMoveSpeed WRITE setHighlightMoveSpeed NOTIFY highlightMoveSpeedChanged)
- Q_PROPERTY(qreal highlightResizeSpeed READ highlightResizeSpeed WRITE setHighlightResizeSpeed NOTIFY highlightResizeSpeedChanged)
-
- Q_PROPERTY(int highlightResizeDuration READ highlightResizeDuration WRITE setHighlightResizeDuration NOTIFY highlightResizeDurationChanged)
-
- Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing NOTIFY spacingChanged)
- Q_PROPERTY(Orientation orientation READ orientation WRITE setOrientation NOTIFY orientationChanged)
-
- Q_PROPERTY(QQuickViewSection *section READ sectionCriteria CONSTANT)
- Q_PROPERTY(QString currentSection READ currentSection NOTIFY currentSectionChanged)
-
- Q_PROPERTY(SnapMode snapMode READ snapMode WRITE setSnapMode NOTIFY snapModeChanged)
-
- Q_ENUMS(Orientation)
- Q_ENUMS(SnapMode)
- Q_CLASSINFO("DefaultProperty", "data")
-
-public:
- QQuickListView(QQuickItem *parent=0);
- ~QQuickListView();
-
- qreal spacing() const;
- void setSpacing(qreal spacing);
-
- enum Orientation { Horizontal = Qt::Horizontal, Vertical = Qt::Vertical };
- Orientation orientation() const;
- void setOrientation(Orientation);
-
- QQuickViewSection *sectionCriteria();
- QString currentSection() const;
-
- virtual void setHighlightFollowsCurrentItem(bool);
-
- qreal highlightMoveSpeed() const;
- void setHighlightMoveSpeed(qreal);
-
- qreal highlightResizeSpeed() const;
- void setHighlightResizeSpeed(qreal);
-
- int highlightResizeDuration() const;
- void setHighlightResizeDuration(int);
-
- virtual void setHighlightMoveDuration(int);
-
- enum SnapMode { NoSnap, SnapToItem, SnapOneItem };
- SnapMode snapMode() const;
- void setSnapMode(SnapMode mode);
-
- static QQuickListViewAttached *qmlAttachedProperties(QObject *);
-
-public Q_SLOTS:
- void incrementCurrentIndex();
- void decrementCurrentIndex();
-
-Q_SIGNALS:
- void spacingChanged();
- void orientationChanged();
- void currentSectionChanged();
- void highlightMoveSpeedChanged();
- void highlightResizeSpeedChanged();
- void highlightResizeDurationChanged();
- void snapModeChanged();
-
-protected:
- virtual void viewportMoved();
- virtual void keyPressEvent(QKeyEvent *);
- virtual void geometryChanged(const QRectF &newGeometry,const QRectF &oldGeometry);
-
-protected Q_SLOTS:
- void updateSections();
-};
-
-class QQuickListViewAttached : public QQuickItemViewAttached
-{
- Q_OBJECT
-
-public:
- QQuickListViewAttached(QObject *parent)
- : QQuickItemViewAttached(parent), m_view(0) {}
- ~QQuickListViewAttached() {}
-
- Q_PROPERTY(QQuickListView *view READ view NOTIFY viewChanged)
- QQuickListView *view() { return m_view; }
- void setView(QQuickListView *view) {
- if (view != m_view) {
- m_view = view;
- emit viewChanged();
- }
- }
-
-Q_SIGNALS:
- void viewChanged();
-
-public:
- QDeclarativeGuard<QQuickListView> m_view;
-};
-
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPEINFO(QQuickListView, QML_HAS_ATTACHED_PROPERTIES)
-QML_DECLARE_TYPE(QQuickListView)
-QML_DECLARE_TYPE(QQuickViewSection)
-
-QT_END_HEADER
-
-#endif // QQUICKLISTVIEW_P_H
diff --git a/src/declarative/items/qquickloader.cpp b/src/declarative/items/qquickloader.cpp
deleted file mode 100644
index f9fd9148ee..0000000000
--- a/src/declarative/items/qquickloader.cpp
+++ /dev/null
@@ -1,858 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickloader_p_p.h"
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-
-#include <private/qdeclarativeengine_p.h>
-#include <private/qdeclarativeglobal_p.h>
-
-#include <private/qdeclarativecomponent_p.h>
-
-#include <private/qv8_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QQuickLoaderPrivate::QQuickLoaderPrivate()
- : item(0), component(0), itemContext(0), incubator(0), updatingSize(false),
- itemWidthValid(false), itemHeightValid(false),
- active(true), loadingFromSource(false), asynchronous(false)
-{
-}
-
-QQuickLoaderPrivate::~QQuickLoaderPrivate()
-{
- delete incubator;
- disposeInitialPropertyValues();
-}
-
-void QQuickLoaderPrivate::itemGeometryChanged(QQuickItem *resizeItem, const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- if (resizeItem == item) {
- if (!updatingSize && newGeometry.width() != oldGeometry.width())
- itemWidthValid = true;
- if (!updatingSize && newGeometry.height() != oldGeometry.height())
- itemHeightValid = true;
- _q_updateSize(false);
- }
- QQuickItemChangeListener::itemGeometryChanged(resizeItem, newGeometry, oldGeometry);
-}
-
-void QQuickLoaderPrivate::clear()
-{
- disposeInitialPropertyValues();
-
- if (incubator)
- incubator->clear();
-
- if (loadingFromSource && component) {
- component->deleteLater();
- component = 0;
- }
- source = QUrl();
-
- if (item) {
- QQuickItemPrivate *p = QQuickItemPrivate::get(item);
- p->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
-
- // We can't delete immediately because our item may have triggered
- // the Loader to load a different item.
- item->setParentItem(0);
- item->setVisible(false);
- item->deleteLater();
- item = 0;
- }
-}
-
-void QQuickLoaderPrivate::initResize()
-{
- QQuickItemPrivate *p = QQuickItemPrivate::get(item);
- p->addItemChangeListener(this, QQuickItemPrivate::Geometry);
- // We may override the item's size, so we need to remember
- // whether the item provided its own valid size.
- itemWidthValid = p->widthValid;
- itemHeightValid = p->heightValid;
- _q_updateSize();
-}
-
-/*!
- \qmlclass Loader QQuickLoader
- \inqmlmodule QtQuick 2
- \ingroup qml-utility-elements
- \inherits Item
-
- \brief The Loader item allows dynamically loading an Item-based
- subtree from a URL or Component.
-
- Loader is used to dynamically load visual QML components. It can load a
- QML file (using the \l source property) or a \l Component object (using
- the \l sourceComponent property). It is useful for delaying the creation
- of a component until it is required: for example, when a component should
- be created on demand, or when a component should not be created
- unnecessarily for performance reasons.
-
- Here is a Loader that loads "Page1.qml" as a component when the
- \l MouseArea is clicked:
-
- \snippet doc/src/snippets/declarative/loader/simple.qml 0
-
- The loaded item can be accessed using the \l item property.
-
- If the \l source or \l sourceComponent changes, any previously instantiated
- items are destroyed. Setting \l source to an empty string or setting
- \l sourceComponent to \c undefined destroys the currently loaded item,
- freeing resources and leaving the Loader empty.
-
- \section2 Loader sizing behavior
-
- Loader is like any other visual item and must be positioned and sized
- accordingly to become visible.
-
- \list
- \o If an explicit size is not specified for the Loader, the Loader
- is automatically resized to the size of the loaded item once the
- component is loaded.
- \o If the size of the Loader is specified explicitly by setting
- the width, height or by anchoring, the loaded item will be resized
- to the size of the Loader.
- \endlist
-
- In both scenarios the size of the item and the Loader are identical.
- This ensures that anchoring to the Loader is equivalent to anchoring
- to the loaded item.
-
- \table
- \row
- \o sizeloader.qml
- \o sizeitem.qml
- \row
- \o \snippet doc/src/snippets/declarative/loader/sizeloader.qml 0
- \o \snippet doc/src/snippets/declarative/loader/sizeitem.qml 0
- \row
- \o The red rectangle will be sized to the size of the root item.
- \o The red rectangle will be 50x50, centered in the root item.
- \endtable
-
-
- \section2 Receiving signals from loaded items
-
- Any signals emitted from the loaded item can be received using the
- \l Connections element. For example, the following \c application.qml
- loads \c MyItem.qml, and is able to receive the \c message signal from
- the loaded item through a \l Connections object:
-
- \table
- \row
- \o application.qml
- \o MyItem.qml
- \row
- \o \snippet doc/src/snippets/declarative/loader/connections.qml 0
- \o \snippet doc/src/snippets/declarative/loader/MyItem.qml 0
- \endtable
-
- Alternatively, since \c MyItem.qml is loaded within the scope of the
- Loader, it could also directly call any function defined in the Loader or
- its parent \l Item.
-
-
- \section2 Focus and key events
-
- Loader is a focus scope. Its \l {Item::}{focus} property must be set to
- \c true for any of its children to get the \e {active focus}. (See
- \l{qmlfocus#Acquiring Focus and Focus Scopes}{the focus documentation page}
- for more details.) Any key events received in the loaded item should likely
- also be \l {KeyEvent::}{accepted} so they are not propagated to the Loader.
-
- For example, the following \c application.qml loads \c KeyReader.qml when
- the \l MouseArea is clicked. Notice the \l {Item::}{focus} property is
- set to \c true for the Loader as well as the \l Item in the dynamically
- loaded object:
-
- \table
- \row
- \o application.qml
- \o KeyReader.qml
- \row
- \o \snippet doc/src/snippets/declarative/loader/focus.qml 0
- \o \snippet doc/src/snippets/declarative/loader/KeyReader.qml 0
- \endtable
-
- Once \c KeyReader.qml is loaded, it accepts key events and sets
- \c event.accepted to \c true so that the event is not propagated to the
- parent \l Rectangle.
-
- \sa {dynamic-object-creation}{Dynamic Object Creation}
-*/
-
-QQuickLoader::QQuickLoader(QQuickItem *parent)
- : QQuickImplicitSizeItem(*(new QQuickLoaderPrivate), parent)
-{
- setFlag(ItemIsFocusScope);
-}
-
-QQuickLoader::~QQuickLoader()
-{
- Q_D(QQuickLoader);
- if (d->item) {
- QQuickItemPrivate *p = QQuickItemPrivate::get(d->item);
- p->removeItemChangeListener(d, QQuickItemPrivate::Geometry);
- }
-}
-
-/*!
- \qmlproperty bool QtQuick2::Loader::active
- This property is \c true if the Loader is currently active.
- The default value for the \l active property is \c true.
-
- If the Loader is inactive, changing the \l source or \l sourceComponent
- will not cause the item to be instantiated until the Loader is made active.
-
- Setting the value to inactive will cause any \l item loaded by the loader
- to be released, but will not affect the \l source or \l sourceComponent.
-
- The \l status of an inactive loader is always \c Null.
-
- \sa source, sourceComponent
- */
-bool QQuickLoader::active() const
-{
- Q_D(const QQuickLoader);
- return d->active;
-}
-
-void QQuickLoader::setActive(bool newVal)
-{
- Q_D(QQuickLoader);
- if (d->active != newVal) {
- d->active = newVal;
- if (newVal == true) {
- if (d->loadingFromSource) {
- loadFromSource();
- } else {
- loadFromSourceComponent();
- }
- } else {
- if (d->item) {
- QQuickItemPrivate *p = QQuickItemPrivate::get(d->item);
- p->removeItemChangeListener(d, QQuickItemPrivate::Geometry);
-
- // We can't delete immediately because our item may have triggered
- // the Loader to load a different item.
- d->item->setParentItem(0);
- d->item->setVisible(false);
- d->item->deleteLater();
- d->item = 0;
- emit itemChanged();
- }
- emit statusChanged();
- }
- emit activeChanged();
- }
-}
-
-
-/*!
- \qmlproperty url QtQuick2::Loader::source
- This property holds the URL of the QML component to instantiate.
-
- Note the QML component must be an \l{Item}-based component. The loader
- cannot load non-visual components.
-
- To unload the currently loaded item, set this property to an empty string,
- or set \l sourceComponent to \c undefined. Setting \c source to a
- new URL will also cause the item created by the previous URL to be unloaded.
-
- \sa sourceComponent, status, progress
-*/
-QUrl QQuickLoader::source() const
-{
- Q_D(const QQuickLoader);
- return d->source;
-}
-
-void QQuickLoader::setSource(const QUrl &url)
-{
- setSource(url, true); // clear previous values
-}
-
-void QQuickLoader::setSource(const QUrl &url, bool needsClear)
-{
- Q_D(QQuickLoader);
- if (d->source == url)
- return;
-
- if (needsClear)
- d->clear();
-
- d->source = url;
- d->loadingFromSource = true;
-
- if (d->active)
- loadFromSource();
- else
- emit sourceChanged();
-}
-
-void QQuickLoader::loadFromSource()
-{
- Q_D(QQuickLoader);
- if (d->source.isEmpty()) {
- emit sourceChanged();
- emit statusChanged();
- emit progressChanged();
- emit itemChanged();
- return;
- }
-
- if (isComponentComplete()) {
- d->component = new QDeclarativeComponent(qmlEngine(this), d->source, this);
- d->load();
- }
-}
-
-/*!
- \qmlproperty Component QtQuick2::Loader::sourceComponent
- This property holds the \l{Component} to instantiate.
-
- \qml
- Item {
- Component {
- id: redSquare
- Rectangle { color: "red"; width: 10; height: 10 }
- }
-
- Loader { sourceComponent: redSquare }
- Loader { sourceComponent: redSquare; x: 10 }
- }
- \endqml
-
- To unload the currently loaded item, set this property to an empty string
- or \c undefined.
-
- \sa source, progress
-*/
-
-QDeclarativeComponent *QQuickLoader::sourceComponent() const
-{
- Q_D(const QQuickLoader);
- return d->component;
-}
-
-void QQuickLoader::setSourceComponent(QDeclarativeComponent *comp)
-{
- Q_D(QQuickLoader);
- if (comp == d->component)
- return;
-
- d->clear();
-
- d->component = comp;
- d->loadingFromSource = false;
-
- if (d->active)
- loadFromSourceComponent();
- else
- emit sourceComponentChanged();
-}
-
-void QQuickLoader::resetSourceComponent()
-{
- setSourceComponent(0);
-}
-
-void QQuickLoader::loadFromSourceComponent()
-{
- Q_D(QQuickLoader);
- if (!d->component) {
- emit sourceComponentChanged();
- emit statusChanged();
- emit progressChanged();
- emit itemChanged();
- return;
- }
-
- if (isComponentComplete())
- d->load();
-}
-
-/*!
- \qmlmethod object QtQuick2::Loader::setSource(url source, object properties)
-
- Creates an object instance of the given \a source component that will have
- the given \a properties. The \a properties argument is optional. The instance
- will be accessible via the \l item property once loading and instantiation
- is complete.
-
- If the \l active property is \c false at the time when this function is called,
- the given \a source component will not be loaded but the \a source and initial
- \a properties will be cached. When the loader is made \l active, an instance of
- the \a source component will be created with the initial \a properties set.
-
- Setting the initial property values of an instance of a component in this manner
- will \bold{not} trigger any associated \l{Behavior}s.
-
- Note that the cached \a properties will be cleared if the \l source or \l sourceComponent
- is changed after calling this function but prior to setting the loader \l active.
-
- Example:
- \table
- \row
- \o
- \qml
- // ExampleComponent.qml
- import QtQuick 2.0
- Rectangle {
- id: rect
- color: "red"
- width: 10
- height: 10
-
- Behavior on color {
- NumberAnimation {
- target: rect
- property: "width"
- to: (rect.width + 20)
- duration: 0
- }
- }
- }
- \endqml
- \o
- \qml
- // example.qml
- import QtQuick 2.0
- Item {
- Loader {
- id: squareLoader
- onLoaded: console.log(squareLoader.item.width); // prints [10], not [30]
- }
-
- Component.onCompleted: {
- squareLoader.setSource("ExampleComponent.qml", { "color": "blue" });
- // will trigger the onLoaded code when complete.
- }
- }
- \endqml
- \endtable
-
- \sa source, active
-*/
-void QQuickLoader::setSource(QDeclarativeV8Function *args)
-{
- Q_ASSERT(args);
- Q_D(QQuickLoader);
-
- bool ipvError = false;
- args->returnValue(v8::Undefined());
- v8::Handle<v8::Object> ipv = d->extractInitialPropertyValues(args, this, &ipvError);
- if (ipvError)
- return;
-
- d->clear();
- QUrl sourceUrl = d->resolveSourceUrl(args);
- if (!ipv.IsEmpty()) {
- d->disposeInitialPropertyValues();
- d->initialPropertyValues = qPersistentNew(ipv);
- d->qmlGlobalForIpv = qPersistentNew(args->qmlGlobal());
- }
-
- setSource(sourceUrl, false); // already cleared and set ipv above.
-}
-
-void QQuickLoaderPrivate::disposeInitialPropertyValues()
-{
- if (!initialPropertyValues.IsEmpty())
- qPersistentDispose(initialPropertyValues);
- if (!qmlGlobalForIpv.IsEmpty())
- qPersistentDispose(qmlGlobalForIpv);
-}
-
-void QQuickLoaderPrivate::load()
-{
- Q_Q(QQuickLoader);
-
- if (!q->isComponentComplete() || !component)
- return;
-
- if (!component->isLoading()) {
- _q_sourceLoaded();
- } else {
- QObject::connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)),
- q, SLOT(_q_sourceLoaded()));
- QObject::connect(component, SIGNAL(progressChanged(qreal)),
- q, SIGNAL(progressChanged()));
- emit q->statusChanged();
- emit q->progressChanged();
- if (loadingFromSource)
- emit q->sourceChanged();
- else
- emit q->sourceComponentChanged();
- emit q->itemChanged();
- }
-}
-
-void QQuickLoaderIncubator::setInitialState(QObject *o)
-{
- loader->setInitialState(o);
-}
-
-void QQuickLoaderPrivate::setInitialState(QObject *obj)
-{
- Q_Q(QQuickLoader);
-
- QQuickItem *item = qobject_cast<QQuickItem*>(obj);
- if (item) {
- QDeclarative_setParent_noEvent(itemContext, obj);
- QDeclarative_setParent_noEvent(item, q);
- item->setParentItem(q);
- }
-
- if (initialPropertyValues.IsEmpty())
- return;
-
- QDeclarativeComponentPrivate *d = QDeclarativeComponentPrivate::get(component);
- Q_ASSERT(d && d->engine);
- d->initializeObjectWithInitialProperties(qmlGlobalForIpv, initialPropertyValues, obj);
-}
-
-void QQuickLoaderIncubator::statusChanged(Status status)
-{
- loader->incubatorStateChanged(status);
-}
-
-void QQuickLoaderPrivate::incubatorStateChanged(QDeclarativeIncubator::Status status)
-{
- Q_Q(QQuickLoader);
- if (status == QDeclarativeIncubator::Loading || status == QDeclarativeIncubator::Null)
- return;
-
- if (status == QDeclarativeIncubator::Ready) {
- QObject *obj = incubator->object();
- item = qobject_cast<QQuickItem*>(obj);
- if (item) {
- initResize();
- } else {
- qmlInfo(q) << QQuickLoader::tr("Loader does not support loading non-visual elements.");
- delete itemContext;
- itemContext = 0;
- delete obj;
- }
- incubator->clear();
- } else if (status == QDeclarativeIncubator::Error) {
- if (!incubator->errors().isEmpty())
- QDeclarativeEnginePrivate::warning(qmlEngine(q), incubator->errors());
- delete itemContext;
- itemContext = 0;
- delete incubator->object();
- source = QUrl();
- }
- if (loadingFromSource)
- emit q->sourceChanged();
- else
- emit q->sourceComponentChanged();
- emit q->statusChanged();
- emit q->progressChanged();
- emit q->itemChanged();
- emit q->loaded();
- disposeInitialPropertyValues(); // cleanup
-}
-
-void QQuickLoaderPrivate::_q_sourceLoaded()
-{
- Q_Q(QQuickLoader);
- if (!component || !component->errors().isEmpty()) {
- if (component)
- QDeclarativeEnginePrivate::warning(qmlEngine(q), component->errors());
- if (loadingFromSource)
- emit q->sourceChanged();
- else
- emit q->sourceComponentChanged();
- emit q->statusChanged();
- emit q->progressChanged();
- disposeInitialPropertyValues(); // cleanup
- return;
- }
-
- QDeclarativeContext *creationContext = component->creationContext();
- if (!creationContext) creationContext = qmlContext(q);
- itemContext = new QDeclarativeContext(creationContext);
- itemContext->setContextObject(q);
-
- delete incubator;
- incubator = new QQuickLoaderIncubator(this, asynchronous ? QDeclarativeIncubator::Asynchronous : QDeclarativeIncubator::AsynchronousIfNested);
-
- component->create(*incubator, itemContext);
-
- if (incubator && incubator->status() == QDeclarativeIncubator::Loading)
- emit q->statusChanged();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Loader::status
-
- This property holds the status of QML loading. It can be one of:
- \list
- \o Loader.Null - the loader is inactive or no QML source has been set
- \o Loader.Ready - the QML source has been loaded
- \o Loader.Loading - the QML source is currently being loaded
- \o Loader.Error - an error occurred while loading the QML source
- \endlist
-
- Use this status to provide an update or respond to the status change in some way.
- For example, you could:
-
- \list
- \o Trigger a state change:
- \qml
- State { name: 'loaded'; when: loader.status == Loader.Ready }
- \endqml
-
- \o Implement an \c onStatusChanged signal handler:
- \qml
- Loader {
- id: loader
- onStatusChanged: if (loader.status == Loader.Ready) console.log('Loaded')
- }
- \endqml
-
- \o Bind to the status value:
- \qml
- Text { text: loader.status == Loader.Ready ? 'Loaded' : 'Not loaded' }
- \endqml
- \endlist
-
- Note that if the source is a local file, the status will initially be Ready (or Error). While
- there will be no onStatusChanged signal in that case, the onLoaded will still be invoked.
-
- \sa progress
-*/
-
-QQuickLoader::Status QQuickLoader::status() const
-{
- Q_D(const QQuickLoader);
-
- if (!d->active)
- return Null;
-
- if (d->component) {
- switch (d->component->status()) {
- case QDeclarativeComponent::Loading:
- return Loading;
- case QDeclarativeComponent::Error:
- return Error;
- case QDeclarativeComponent::Null:
- return Null;
- default:
- break;
- }
- }
-
- if (d->incubator) {
- switch (d->incubator->status()) {
- case QDeclarativeIncubator::Loading:
- return Loading;
- case QDeclarativeIncubator::Error:
- return Error;
- default:
- break;
- }
- }
-
- if (d->item)
- return Ready;
-
- return d->source.isEmpty() ? Null : Error;
-}
-
-void QQuickLoader::componentComplete()
-{
- Q_D(QQuickLoader);
- QQuickItem::componentComplete();
- if (active()) {
- if (d->loadingFromSource) {
- d->component = new QDeclarativeComponent(qmlEngine(this), d->source, this);
- }
- d->load();
- }
-}
-
-/*!
- \qmlsignal QtQuick2::Loader::onLoaded()
-
- This handler is called when the \l status becomes \c Loader.Ready, or on successful
- initial load.
-*/
-
-
-/*!
-\qmlproperty real QtQuick2::Loader::progress
-
-This property holds the progress of loading QML data from the network, from
-0.0 (nothing loaded) to 1.0 (finished). Most QML files are quite small, so
-this value will rapidly change from 0 to 1.
-
-\sa status
-*/
-qreal QQuickLoader::progress() const
-{
- Q_D(const QQuickLoader);
-
- if (d->item)
- return 1.0;
-
- if (d->component)
- return d->component->progress();
-
- return 0.0;
-}
-
-/*!
-\qmlproperty bool QtQuick2::Loader::asynchronous
-
-This property holds whether the component will be instantiated asynchronously.
-
-Loading asynchronously creates the objects declared by the component
-across multiple frames, and reduces the
-likelihood of glitches in animation. When loading asynchronously the status
-will change to Loader.Loading. Once the entire component has been created, the
-\l item will be available and the status will change to Loader.Ready.
-
-To avoid seeing the items loading progressively set \c visible appropriately, e.g.
-
-\code
-Loader {
- source: "mycomponent.qml"
- asynchronous: true
- visible: status == Loader.Ready
-}
-\endcode
-
-Note that this property affects object instantiation only; it is unrelated to
-loading a component asynchronously via a network.
-*/
-bool QQuickLoader::asynchronous() const
-{
- Q_D(const QQuickLoader);
- return d->asynchronous;
-}
-
-void QQuickLoader::setAsynchronous(bool a)
-{
- Q_D(QQuickLoader);
- if (d->asynchronous == a)
- return;
-
- d->asynchronous = a;
- emit asynchronousChanged();
-}
-
-void QQuickLoaderPrivate::_q_updateSize(bool loaderGeometryChanged)
-{
- Q_Q(QQuickLoader);
- if (!item || updatingSize)
- return;
-
- updatingSize = true;
-
- qreal iWidth = !itemWidthValid ? item->implicitWidth() : item->width();
- qreal iHeight = !itemHeightValid ? item->implicitHeight() : item->height();
- q->setImplicitSize(iWidth, iHeight);
-
- if (loaderGeometryChanged && q->widthValid())
- item->setWidth(q->width());
- if (loaderGeometryChanged && q->heightValid())
- item->setHeight(q->height());
-
- updatingSize = false;
-}
-
-/*!
- \qmlproperty Item QtQuick2::Loader::item
- This property holds the top-level item that is currently loaded.
-*/
-QQuickItem *QQuickLoader::item() const
-{
- Q_D(const QQuickLoader);
- return d->item;
-}
-
-void QQuickLoader::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_D(QQuickLoader);
- if (newGeometry != oldGeometry) {
- d->_q_updateSize();
- }
- QQuickItem::geometryChanged(newGeometry, oldGeometry);
-}
-
-QUrl QQuickLoaderPrivate::resolveSourceUrl(QDeclarativeV8Function *args)
-{
- QV8Engine *v8engine = args->engine();
- QString arg = v8engine->toString((*args)[0]->ToString());
- if (arg.isEmpty())
- return QUrl();
-
- QDeclarativeContextData *context = args->context();
- Q_ASSERT(context);
- return context->resolvedUrl(QUrl(arg));
-}
-
-v8::Handle<v8::Object> QQuickLoaderPrivate::extractInitialPropertyValues(QDeclarativeV8Function *args, QObject *loader, bool *error)
-{
- v8::Local<v8::Object> valuemap;
- if (args->Length() >= 2) {
- v8::Local<v8::Value> v = (*args)[1];
- if (!v->IsObject() || v->IsArray()) {
- *error = true;
- qmlInfo(loader) << loader->tr("setSource: value is not an object");
- } else {
- *error = false;
- valuemap = v8::Local<v8::Object>::Cast(v);
- }
- }
-
- return valuemap;
-}
-
-#include <moc_qquickloader_p.cpp>
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickloader_p.h b/src/declarative/items/qquickloader_p.h
deleted file mode 100644
index 3dcab4c654..0000000000
--- a/src/declarative/items/qquickloader_p.h
+++ /dev/null
@@ -1,123 +0,0 @@
-// Commit: 6f78a6080b84cc3ef96b73a4ff58d1b5a72f08f4
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKLOADER_P_H
-#define QQUICKLOADER_P_H
-
-#include "qquickimplicitsizeitem_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickLoaderPrivate;
-class Q_AUTOTEST_EXPORT QQuickLoader : public QQuickImplicitSizeItem
-{
- Q_OBJECT
- Q_ENUMS(Status)
-
- Q_PROPERTY(bool active READ active WRITE setActive NOTIFY activeChanged)
- Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
- Q_PROPERTY(QDeclarativeComponent *sourceComponent READ sourceComponent WRITE setSourceComponent RESET resetSourceComponent NOTIFY sourceComponentChanged)
- Q_PROPERTY(QQuickItem *item READ item NOTIFY itemChanged)
- Q_PROPERTY(Status status READ status NOTIFY statusChanged)
- Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged)
- Q_PROPERTY(bool asynchronous READ asynchronous WRITE setAsynchronous NOTIFY asynchronousChanged)
-
-public:
- QQuickLoader(QQuickItem *parent = 0);
- virtual ~QQuickLoader();
-
- bool active() const;
- void setActive(bool newVal);
-
- Q_INVOKABLE void setSource(QDeclarativeV8Function *);
-
- QUrl source() const;
- void setSource(const QUrl &);
-
- QDeclarativeComponent *sourceComponent() const;
- void setSourceComponent(QDeclarativeComponent *);
- void resetSourceComponent();
-
- enum Status { Null, Ready, Loading, Error };
- Status status() const;
- qreal progress() const;
-
- bool asynchronous() const;
- void setAsynchronous(bool a);
-
- QQuickItem *item() const;
-
-Q_SIGNALS:
- void itemChanged();
- void activeChanged();
- void sourceChanged();
- void sourceComponentChanged();
- void statusChanged();
- void progressChanged();
- void loaded();
- void asynchronousChanged();
-
-protected:
- void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry);
- void componentComplete();
-
-private:
- void setSource(const QUrl &sourceUrl, bool needsClear);
- void loadFromSource();
- void loadFromSourceComponent();
- Q_DISABLE_COPY(QQuickLoader)
- Q_DECLARE_PRIVATE(QQuickLoader)
- Q_PRIVATE_SLOT(d_func(), void _q_sourceLoaded())
- Q_PRIVATE_SLOT(d_func(), void _q_updateSize())
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickLoader)
-
-QT_END_HEADER
-
-#endif // QQUICKLOADER_P_H
diff --git a/src/declarative/items/qquickloader_p_p.h b/src/declarative/items/qquickloader_p_p.h
deleted file mode 100644
index 63d73e8da2..0000000000
--- a/src/declarative/items/qquickloader_p_p.h
+++ /dev/null
@@ -1,121 +0,0 @@
-// Commit: 5d2817cd668a705729df1727de49adf00713ac97
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKLOADER_P_P_H
-#define QQUICKLOADER_P_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 "qquickloader_p.h"
-#include "qquickimplicitsizeitem_p_p.h"
-#include "qquickitemchangelistener_p.h"
-#include <qdeclarativeincubator.h>
-
-#include <private/qv8_p.h>
-
-QT_BEGIN_NAMESPACE
-
-
-class QQuickLoaderPrivate;
-class QQuickLoaderIncubator : public QDeclarativeIncubator
-{
-public:
- QQuickLoaderIncubator(QQuickLoaderPrivate *l, IncubationMode mode) : QDeclarativeIncubator(mode), loader(l) {}
-
-protected:
- virtual void statusChanged(Status);
- virtual void setInitialState(QObject *);
-
-private:
- QQuickLoaderPrivate *loader;
-};
-
-class QDeclarativeContext;
-class QQuickLoaderPrivate : public QQuickImplicitSizeItemPrivate, public QQuickItemChangeListener
-{
- Q_DECLARE_PUBLIC(QQuickLoader)
-
-public:
- QQuickLoaderPrivate();
- ~QQuickLoaderPrivate();
-
- void itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry);
- void clear();
- void initResize();
- void load();
-
- void incubatorStateChanged(QDeclarativeIncubator::Status status);
- void setInitialState(QObject *o);
- void disposeInitialPropertyValues();
- QUrl resolveSourceUrl(QDeclarativeV8Function *args);
- v8::Handle<v8::Object> extractInitialPropertyValues(QDeclarativeV8Function *args, QObject *loader, bool *error);
-
- QUrl source;
- QQuickItem *item;
- QDeclarativeComponent *component;
- QDeclarativeContext *itemContext;
- QQuickLoaderIncubator *incubator;
- v8::Persistent<v8::Object> initialPropertyValues;
- v8::Persistent<v8::Object> qmlGlobalForIpv;
- bool updatingSize: 1;
- bool itemWidthValid : 1;
- bool itemHeightValid : 1;
- bool active : 1;
- bool loadingFromSource : 1;
- bool asynchronous : 1;
-
- void _q_sourceLoaded();
- void _q_updateSize(bool loaderGeometryChanged = true);
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKLOADER_P_P_H
diff --git a/src/declarative/items/qquickmousearea.cpp b/src/declarative/items/qquickmousearea.cpp
deleted file mode 100644
index 8d4f3e86b0..0000000000
--- a/src/declarative/items/qquickmousearea.cpp
+++ /dev/null
@@ -1,1168 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickmousearea_p.h"
-#include "qquickmousearea_p_p.h"
-#include "qquickcanvas.h"
-#include "qquickevents_p_p.h"
-#include "qquickdrag_p.h"
-
-#include <QtGui/qevent.h>
-#include <QtGui/qguiapplication.h>
-#include <QtGui/qstylehints.h>
-
-#include <float.h>
-
-QT_BEGIN_NAMESPACE
-static const int PressAndHoldDelay = 800;
-
-QQuickDrag::QQuickDrag(QObject *parent)
-: QObject(parent), _target(0), _axis(XandYAxis), _xmin(-FLT_MAX),
-_xmax(FLT_MAX), _ymin(-FLT_MAX), _ymax(FLT_MAX), _active(false), _filterChildren(false)
-{
-}
-
-QQuickDrag::~QQuickDrag()
-{
-}
-
-QQuickItem *QQuickDrag::target() const
-{
- return _target;
-}
-
-void QQuickDrag::setTarget(QQuickItem *t)
-{
- if (_target == t)
- return;
- _target = t;
- emit targetChanged();
-}
-
-void QQuickDrag::resetTarget()
-{
- if (_target == 0)
- return;
- _target = 0;
- emit targetChanged();
-}
-
-QQuickDrag::Axis QQuickDrag::axis() const
-{
- return _axis;
-}
-
-void QQuickDrag::setAxis(QQuickDrag::Axis a)
-{
- if (_axis == a)
- return;
- _axis = a;
- emit axisChanged();
-}
-
-qreal QQuickDrag::xmin() const
-{
- return _xmin;
-}
-
-void QQuickDrag::setXmin(qreal m)
-{
- if (_xmin == m)
- return;
- _xmin = m;
- emit minimumXChanged();
-}
-
-qreal QQuickDrag::xmax() const
-{
- return _xmax;
-}
-
-void QQuickDrag::setXmax(qreal m)
-{
- if (_xmax == m)
- return;
- _xmax = m;
- emit maximumXChanged();
-}
-
-qreal QQuickDrag::ymin() const
-{
- return _ymin;
-}
-
-void QQuickDrag::setYmin(qreal m)
-{
- if (_ymin == m)
- return;
- _ymin = m;
- emit minimumYChanged();
-}
-
-qreal QQuickDrag::ymax() const
-{
- return _ymax;
-}
-
-void QQuickDrag::setYmax(qreal m)
-{
- if (_ymax == m)
- return;
- _ymax = m;
- emit maximumYChanged();
-}
-
-bool QQuickDrag::active() const
-{
- return _active;
-}
-
-void QQuickDrag::setActive(bool drag)
-{
- if (_active == drag)
- return;
- _active = drag;
- emit activeChanged();
-}
-
-bool QQuickDrag::filterChildren() const
-{
- return _filterChildren;
-}
-
-void QQuickDrag::setFilterChildren(bool filter)
-{
- if (_filterChildren == filter)
- return;
- _filterChildren = filter;
- emit filterChildrenChanged();
-}
-
-QQuickDragAttached *QQuickDrag::qmlAttachedProperties(QObject *obj)
-{
- return new QQuickDragAttached(obj);
-}
-
-QQuickMouseAreaPrivate::QQuickMouseAreaPrivate()
-: absorb(true), hovered(false), pressed(false), longPress(false),
- moved(false), stealMouse(false), doubleClick(false), preventStealing(false),
- propagateComposedEvents(false), drag(0)
-{
-}
-
-QQuickMouseAreaPrivate::~QQuickMouseAreaPrivate()
-{
- delete drag;
-}
-
-void QQuickMouseAreaPrivate::init()
-{
- Q_Q(QQuickMouseArea);
- q->setAcceptedMouseButtons(Qt::LeftButton);
- q->setFiltersChildMouseEvents(true);
-}
-
-void QQuickMouseAreaPrivate::saveEvent(QMouseEvent *event)
-{
- lastPos = event->localPos();
- lastScenePos = event->windowPos();
- lastButton = event->button();
- lastButtons = event->buttons();
- lastModifiers = event->modifiers();
-}
-
-bool QQuickMouseAreaPrivate::isPressAndHoldConnected()
-{
- Q_Q(QQuickMouseArea);
- static int idx = QObjectPrivate::get(q)->signalIndex("pressAndHold(QQuickMouseEvent*)");
- return QObjectPrivate::get(q)->isSignalConnected(idx);
-}
-
-bool QQuickMouseAreaPrivate::isDoubleClickConnected()
-{
- Q_Q(QQuickMouseArea);
- static int idx = QObjectPrivate::get(q)->signalIndex("doubleClicked(QQuickMouseEvent*)");
- return QObjectPrivate::get(q)->isSignalConnected(idx);
-}
-
-bool QQuickMouseAreaPrivate::isClickConnected()
-{
- Q_Q(QQuickMouseArea);
- static int idx = QObjectPrivate::get(q)->signalIndex("clicked(QQuickMouseEvent*)");
- return QObjectPrivate::get(q)->isSignalConnected(idx);
-}
-
-void QQuickMouseAreaPrivate::propagate(QQuickMouseEvent* event, PropagateType t)
-{
- Q_Q(QQuickMouseArea);
- if (!propagateComposedEvents)
- return;
- QPointF scenePos = q->mapToScene(QPointF(event->x(), event->y()));
- propagateHelper(event, canvas->rootItem(), scenePos, t);
-}
-
-bool QQuickMouseAreaPrivate::propagateHelper(QQuickMouseEvent *ev, QQuickItem *item,const QPointF &sp, PropagateType sig)
-{
- //Based off of QQuickCanvas::deliverInitialMousePressEvent
- //But specific to MouseArea, so doesn't belong in canvas
- Q_Q(const QQuickMouseArea);
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
- if (itemPrivate->opacity == 0.0)
- return false;
-
- if (itemPrivate->flags & QQuickItem::ItemClipsChildrenToShape) {
- QPointF p = item->mapFromScene(sp);
- if (!QRectF(0, 0, item->width(), item->height()).contains(p))
- return false;
- }
-
- QList<QQuickItem *> children = itemPrivate->paintOrderChildItems();
- for (int ii = children.count() - 1; ii >= 0; --ii) {
- QQuickItem *child = children.at(ii);
- if (!child->isVisible() || !child->isEnabled())
- continue;
- if (propagateHelper(ev, child, sp, sig))
- return true;
- }
-
- QQuickMouseArea* ma = qobject_cast<QQuickMouseArea*>(item);
- if (ma && ma != q && itemPrivate->acceptedMouseButtons & ev->button()) {
- switch (sig) {
- case Click:
- if (!ma->d_func()->isClickConnected())
- return false;
- break;
- case DoubleClick:
- if (!ma->d_func()->isDoubleClickConnected())
- return false;
- break;
- case PressAndHold:
- if (!ma->d_func()->isPressAndHoldConnected())
- return false;
- break;
- }
- QPointF p = item->mapFromScene(sp);
- if (QRectF(0, 0, item->width(), item->height()).contains(p)) {
- ev->setX(p.x());
- ev->setY(p.y());
- ev->setAccepted(true);//It is connected, they have to explicitly ignore to let it slide
- switch (sig) {
- case Click: emit ma->clicked(ev); break;
- case DoubleClick: emit ma->doubleClicked(ev); break;
- case PressAndHold: emit ma->pressAndHold(ev); break;
- }
- if (ev->isAccepted())
- return true;
- }
- }
- return false;
-
-}
-
-/*!
- \qmlclass MouseArea QQuickMouseArea
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-interaction-elements
- \brief The MouseArea item enables simple mouse handling.
- \inherits Item
-
- A MouseArea is an invisible item that is typically used in conjunction with
- a visible item in order to provide mouse handling for that item.
- By effectively acting as a proxy, the logic for mouse handling can be
- contained within a MouseArea item.
-
- For basic key handling, see the \l{Keys}{Keys attached property}.
-
- The \l enabled property is used to enable and disable mouse handling for
- the proxied item. When disabled, the mouse area becomes transparent to
- mouse events.
-
- The \l pressed read-only property indicates whether or not the user is
- holding down a mouse button over the mouse area. This property is often
- used in bindings between properties in a user interface. The containsMouse
- read-only property indicates the presence of the mouse cursor over the
- mouse area but, by default, only when a mouse button is held down; see below
- for further details.
-
- Information about the mouse position and button clicks are provided via
- signals for which event handler properties are defined. The most commonly
- used involved handling mouse presses and clicks: onClicked, onDoubleClicked,
- onPressed, onReleased and onPressAndHold.
-
- By default, MouseArea items only report mouse clicks and not changes to the
- position of the mouse cursor. Setting the hoverEnabled property ensures that
- handlers defined for onPositionChanged, onEntered and onExited are used and
- that the containsMouse property is updated even when no mouse buttons are
- pressed.
-
- \section1 Example Usage
-
- \div {class="float-right"}
- \inlineimage qml-mousearea-snippet.png
- \enddiv
-
- The following example uses a MouseArea in a \l Rectangle that changes
- the \l Rectangle color to red when clicked:
-
- \snippet doc/src/snippets/declarative/mousearea/mousearea.qml import
- \codeline
- \snippet doc/src/snippets/declarative/mousearea/mousearea.qml intro
-
- \clearfloat
- Many MouseArea signals pass a \l{MouseEvent}{mouse} parameter that contains
- additional information about the mouse event, such as the position, button,
- and any key modifiers.
-
- Here is an extension of the previous example that produces a different
- color when the area is right clicked:
-
- \snippet doc/src/snippets/declarative/mousearea/mousearea.qml intro-extended
-
- Behavioral Change in QtQuick 2.0
-
- From QtQuick 2.0, the signals clicked, doubleClicked and pressAndHold have a different interaction
- model with regards to the delivery of events to multiple overlapping MouseAreas. These signals can now propagate
- to all MouseAreas in the area, in painting order, until accepted by one of them. A signal is accepted by
- default if there is a signal handler for it, use mouse.accepted = false; to ignore. This propagation
- can send the signal to MouseAreas other than the one which accepted the press event, although that MouseArea
- will receive the signal first. This behavior can be enabled by setting propagateComposedEvents to true.
-
- \sa MouseEvent, {declarative/touchinteraction/mousearea}{MouseArea example}
-*/
-
-/*!
- \qmlsignal QtQuick2::MouseArea::onEntered()
-
- This handler is called when the mouse enters the mouse area.
-
- By default the onEntered handler is only called while a button is
- pressed. Setting hoverEnabled to true enables handling of
- onEntered when no mouse button is pressed.
-
- \sa hoverEnabled
-*/
-
-/*!
- \qmlsignal QtQuick2::MouseArea::onExited()
-
- This handler is called when the mouse exits the mouse area.
-
- By default the onExited handler is only called while a button is
- pressed. Setting hoverEnabled to true enables handling of
- onExited when no mouse button is pressed.
-
- The example below shows a fairly typical relationship between
- two MouseAreas, with \c mouseArea2 on top of \c mouseArea1. Moving the
- mouse into \c mouseArea2 from \c mouseArea1 will cause \c onExited
- to be called for \c mouseArea1.
- \qml
- Rectangle {
- width: 400; height: 400
- MouseArea {
- id: mouseArea1
- anchors.fill: parent
- hoverEnabled: true
- }
- MouseArea {
- id: mouseArea2
- width: 100; height: 100
- anchors.centerIn: parent
- hoverEnabled: true
- }
- }
- \endqml
-
- If instead you give the two mouseAreas a parent-child relationship,
- moving the mouse into \c mouseArea2 from \c mouseArea1 will \b not
- cause \c onExited to be called for \c mouseArea1. Instead, they will
- both be considered to be simultaneously hovered.
-
- \sa hoverEnabled
-*/
-
-/*!
- \qmlsignal QtQuick2::MouseArea::onPositionChanged(MouseEvent mouse)
-
- This handler is called when the mouse position changes.
-
- The \l {MouseEvent}{mouse} parameter provides information about the mouse, including the x and y
- position, and any buttons currently pressed.
-
- The \e accepted property of the MouseEvent parameter is ignored in this handler.
-
- By default the onPositionChanged handler is only called while a button is
- pressed. Setting hoverEnabled to true enables handling of
- onPositionChanged when no mouse button is pressed.
-*/
-
-/*!
- \qmlsignal QtQuick2::MouseArea::onClicked(MouseEvent mouse)
-
- This handler is called when there is a click. A click is defined as a press followed by a release,
- both inside the MouseArea (pressing, moving outside the MouseArea, and then moving back inside and
- releasing is also considered a click).
-
- The \l {MouseEvent}{mouse} parameter provides information about the click, including the x and y
- position of the release of the click, and whether the click was held.
-
- The \e accepted property of the MouseEvent parameter is ignored in this handler.
-*/
-
-/*!
- \qmlsignal QtQuick2::MouseArea::onPressed(MouseEvent mouse)
-
- This handler is called when there is a press.
- The \l {MouseEvent}{mouse} parameter provides information about the press, including the x and y
- position and which button was pressed.
-
- The \e accepted property of the MouseEvent parameter determines whether this MouseArea
- will handle the press and all future mouse events until release. The default is to accept
- the event and not allow other MouseArea beneath this one to handle the event. If \e accepted
- is set to false, no further events will be sent to this MouseArea until the button is next
- pressed.
-*/
-
-/*!
- \qmlsignal QtQuick2::MouseArea::onReleased(MouseEvent mouse)
-
- This handler is called when there is a release.
- The \l {MouseEvent}{mouse} parameter provides information about the click, including the x and y
- position of the release of the click, and whether the click was held.
-
- The \e accepted property of the MouseEvent parameter is ignored in this handler.
-
- \sa onCanceled
-*/
-
-/*!
- \qmlsignal QtQuick2::MouseArea::onPressAndHold(MouseEvent mouse)
-
- This handler is called when there is a long press (currently 800ms).
- The \l {MouseEvent}{mouse} parameter provides information about the press, including the x and y
- position of the press, and which button is pressed.
-
- The \e accepted property of the MouseEvent parameter is ignored in this handler.
-*/
-
-/*!
- \qmlsignal QtQuick2::MouseArea::onDoubleClicked(MouseEvent mouse)
-
- This handler is called when there is a double-click (a press followed by a release followed by a press).
- The \l {MouseEvent}{mouse} parameter provides information about the click, including the x and y
- position of the release of the click, and whether the click was held.
-
- If the \e accepted property of the \l {MouseEvent}{mouse} parameter is set to false
- in the handler, the onPressed/onReleased/onClicked handlers will be called for the second
- click; otherwise they are suppressed. The accepted property defaults to true.
-*/
-
-/*!
- \qmlsignal QtQuick2::MouseArea::onCanceled()
-
- This handler is called when mouse events have been canceled, either because an event was not accepted, or
- because another element stole the mouse event handling.
-
- This signal is for advanced use: it is useful when there is more than one MouseArea
- that is handling input, or when there is a MouseArea inside a \l Flickable. In the latter
- case, if you execute some logic on the pressed signal and then start dragging, the
- \l Flickable will steal the mouse handling from the MouseArea. In these cases, to reset
- the logic when the MouseArea has lost the mouse handling to the \l Flickable,
- \c onCanceled should be used in addition to onReleased.
-*/
-QQuickMouseArea::QQuickMouseArea(QQuickItem *parent)
- : QQuickItem(*(new QQuickMouseAreaPrivate), parent)
-{
- Q_D(QQuickMouseArea);
- d->init();
-}
-
-QQuickMouseArea::~QQuickMouseArea()
-{
-}
-
-/*!
- \qmlproperty real QtQuick2::MouseArea::mouseX
- \qmlproperty real QtQuick2::MouseArea::mouseY
- These properties hold the coordinates of the mouse cursor.
-
- If the hoverEnabled property is false then these properties will only be valid
- while a button is pressed, and will remain valid as long as the button is held
- down even if the mouse is moved outside the area.
-
- By default, this property is false.
-
- If hoverEnabled is true then these properties will be valid when:
- \list
- \i no button is pressed, but the mouse is within the MouseArea (containsMouse is true).
- \i a button is pressed and held, even if it has since moved out of the area.
- \endlist
-
- The coordinates are relative to the MouseArea.
-*/
-qreal QQuickMouseArea::mouseX() const
-{
- Q_D(const QQuickMouseArea);
- return d->lastPos.x();
-}
-
-qreal QQuickMouseArea::mouseY() const
-{
- Q_D(const QQuickMouseArea);
- return d->lastPos.y();
-}
-
-/*!
- \qmlproperty bool QtQuick2::MouseArea::enabled
- This property holds whether the item accepts mouse events.
-
- By default, this property is true.
-*/
-bool QQuickMouseArea::isEnabled() const
-{
- Q_D(const QQuickMouseArea);
- return d->absorb;
-}
-
-void QQuickMouseArea::setEnabled(bool a)
-{
- Q_D(QQuickMouseArea);
- if (a != d->absorb) {
- d->absorb = a;
- emit enabledChanged();
- }
-}
-
-/*!
- \qmlproperty bool QtQuick2::MouseArea::preventStealing
- This property holds whether the mouse events may be stolen from this
- MouseArea.
-
- If a MouseArea is placed within an item that filters child mouse
- events, such as Flickable, the mouse
- events may be stolen from the MouseArea if a gesture is recognized
- by the parent element, e.g. a flick gesture. If preventStealing is
- set to true, no element will steal the mouse events.
-
- Note that setting preventStealing to true once an element has started
- stealing events will have no effect until the next press event.
-
- By default this property is false.
-*/
-bool QQuickMouseArea::preventStealing() const
-{
- Q_D(const QQuickMouseArea);
- return d->preventStealing;
-}
-
-void QQuickMouseArea::setPreventStealing(bool prevent)
-{
- Q_D(QQuickMouseArea);
- if (prevent != d->preventStealing) {
- d->preventStealing = prevent;
- setKeepMouseGrab(d->preventStealing && d->absorb);
- emit preventStealingChanged();
- }
-}
-
-
-/*!
- \qmlproperty bool QtQuick2::MouseArea::propagateComposedEvents
- This property holds whether composed mouse events will automatically propagate to
- other MouseAreas.
-
- MouseArea contains several composed events, clicked, doubleClicked,
- and pressAndHold. These can propagate via a separate mechanism to basic
- mouse events, like pressed, which they are composed of.
-
- If propagateComposedEvents is set to true, then composed events will be automatically
- propagated to other MouseAreas in the same location in the scene. They are propagated
- in painting order until an item accepts them. Unlike pressed handling, events will
- not be automatically accepted if no handler is present.
-
- This property greatly simplifies the usecase of when you want to have overlapping MouseAreas
- handling the composed events together. For example: if you want one MouseArea to handle click
- signals and the other to handle pressAndHold, or if you want one MouseArea to handle click most
- of the time, but pass it through when certain conditions are met.
-
- By default this property is false.
-*/
-bool QQuickMouseArea::propagateComposedEvents() const
-{
- Q_D(const QQuickMouseArea);
- return d->propagateComposedEvents;
-}
-
-void QQuickMouseArea::setPropagateComposedEvents(bool prevent)
-{
- Q_D(QQuickMouseArea);
- if (prevent != d->propagateComposedEvents) {
- d->propagateComposedEvents = prevent;
- setKeepMouseGrab(d->propagateComposedEvents && d->absorb);
- emit propagateComposedEventsChanged();
- }
-}
-
-/*!
- \qmlproperty MouseButtons QtQuick2::MouseArea::pressedButtons
- This property holds the mouse buttons currently pressed.
-
- It contains a bitwise combination of:
- \list
- \o Qt.LeftButton
- \o Qt.RightButton
- \o Qt.MiddleButton
- \endlist
-
- The code below displays "right" when the right mouse buttons is pressed:
-
- \snippet doc/src/snippets/declarative/mousearea/mousearea.qml mousebuttons
-
- \sa acceptedButtons
-*/
-Qt::MouseButtons QQuickMouseArea::pressedButtons() const
-{
- Q_D(const QQuickMouseArea);
- return d->lastButtons;
-}
-
-void QQuickMouseArea::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QQuickMouseArea);
- d->moved = false;
- d->stealMouse = d->preventStealing;
- if (!d->absorb)
- QQuickItem::mousePressEvent(event);
- else {
- d->longPress = false;
- d->saveEvent(event);
- if (d->drag) {
- d->dragX = drag()->axis() & QQuickDrag::XAxis;
- d->dragY = drag()->axis() & QQuickDrag::YAxis;
- }
- if (d->drag)
- d->drag->setActive(false);
- setHovered(true);
- d->startScene = event->windowPos();
- d->pressAndHoldTimer.start(PressAndHoldDelay, this);
- setKeepMouseGrab(d->stealMouse);
- event->setAccepted(setPressed(true));
-
- }
-}
-
-void QQuickMouseArea::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QQuickMouseArea);
- if (!d->absorb) {
- QQuickItem::mouseMoveEvent(event);
- return;
- }
-
- d->saveEvent(event);
-
- // ### we should skip this if these signals aren't used
- // ### can GV handle this for us?
- bool contains = boundingRect().contains(d->lastPos);
- if (d->hovered && !contains)
- setHovered(false);
- else if (!d->hovered && contains)
- setHovered(true);
-
- if (d->drag && d->drag->target()) {
- if (!d->moved) {
- d->targetStartPos = d->drag->target()->parentItem()
- ? d->drag->target()->parentItem()->mapToScene(d->drag->target()->pos())
- : d->drag->target()->pos();
- }
-
- QPointF startLocalPos;
- QPointF curLocalPos;
- if (drag()->target()->parentItem()) {
- startLocalPos = drag()->target()->parentItem()->mapFromScene(d->startScene);
- curLocalPos = drag()->target()->parentItem()->mapFromScene(event->windowPos());
- } else {
- startLocalPos = d->startScene;
- curLocalPos = event->windowPos();
- }
-
- const int dragThreshold = qApp->styleHints()->startDragDistance();
- qreal dx = qAbs(curLocalPos.x() - startLocalPos.x());
- qreal dy = qAbs(curLocalPos.y() - startLocalPos.y());
-
- if (keepMouseGrab() && d->stealMouse && !d->drag->active())
- d->drag->setActive(true);
-
- QPointF startPos = d->drag->target()->parentItem()
- ? d->drag->target()->parentItem()->mapFromScene(d->targetStartPos)
- : d->targetStartPos;
-
- QPointF dragPos = d->drag->target()->pos();
-
- if (d->dragX && d->drag->active()) {
- qreal x = (curLocalPos.x() - startLocalPos.x()) + startPos.x();
- if (x < drag()->xmin())
- x = drag()->xmin();
- else if (x > drag()->xmax())
- x = drag()->xmax();
- dragPos.setX(x);
- }
- if (d->dragY && d->drag->active()) {
- qreal y = (curLocalPos.y() - startLocalPos.y()) + startPos.y();
- if (y < drag()->ymin())
- y = drag()->ymin();
- else if (y > drag()->ymax())
- y = drag()->ymax();
- dragPos.setY(y);
- }
- d->drag->target()->setPos(dragPos);
-
- if (!keepMouseGrab()) {
- if ((!d->dragY && dy < dragThreshold && d->dragX && dx > dragThreshold)
- || (!d->dragX && dx < dragThreshold && d->dragY && dy > dragThreshold)
- || (d->dragX && d->dragY && (dx > dragThreshold || dy > dragThreshold))) {
- setKeepMouseGrab(true);
- d->stealMouse = true;
- }
- }
-
- d->moved = true;
- }
- QQuickMouseEvent me(d->lastPos.x(), d->lastPos.y(), d->lastButton, d->lastButtons, d->lastModifiers, false, d->longPress);
- emit mouseXChanged(&me);
- me.setPosition(d->lastPos);
- emit mouseYChanged(&me);
- me.setPosition(d->lastPos);
- emit positionChanged(&me);
-}
-
-void QQuickMouseArea::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QQuickMouseArea);
- d->stealMouse = false;
- if (!d->absorb) {
- QQuickItem::mouseReleaseEvent(event);
- } else {
- d->saveEvent(event);
- setPressed(false);
- if (d->drag)
- d->drag->setActive(false);
- // If we don't accept hover, we need to reset containsMouse.
- if (!acceptHoverEvents())
- setHovered(false);
- QQuickCanvas *c = canvas();
- if (c && c->mouseGrabberItem() == this)
- ungrabMouse();
- setKeepMouseGrab(false);
-
- }
- d->doubleClick = false;
-}
-
-void QQuickMouseArea::mouseDoubleClickEvent(QMouseEvent *event)
-{
- Q_D(QQuickMouseArea);
- if (d->absorb) {
- d->saveEvent(event);
- QQuickMouseEvent me(d->lastPos.x(), d->lastPos.y(), d->lastButton, d->lastButtons, d->lastModifiers, true, false);
- me.setAccepted(d->isDoubleClickConnected());
- emit this->doubleClicked(&me);
- if (!me.isAccepted())
- d->propagate(&me, QQuickMouseAreaPrivate::DoubleClick);
- d->doubleClick = d->isDoubleClickConnected() || me.isAccepted();
- }
- QQuickItem::mouseDoubleClickEvent(event);
-}
-
-void QQuickMouseArea::hoverEnterEvent(QHoverEvent *event)
-{
- Q_D(QQuickMouseArea);
- if (!d->absorb) {
- QQuickItem::hoverEnterEvent(event);
- } else {
- d->lastPos = event->posF();
- d->lastModifiers = event->modifiers();
- setHovered(true);
- QQuickMouseEvent me(d->lastPos.x(), d->lastPos.y(), Qt::NoButton, Qt::NoButton, d->lastModifiers, false, false);
- emit mouseXChanged(&me);
- me.setPosition(d->lastPos);
- emit mouseYChanged(&me);
- me.setPosition(d->lastPos);
- }
-}
-
-void QQuickMouseArea::hoverMoveEvent(QHoverEvent *event)
-{
- Q_D(QQuickMouseArea);
- if (!d->absorb) {
- QQuickItem::hoverMoveEvent(event);
- } else {
- d->lastPos = event->posF();
- d->lastModifiers = event->modifiers();
- QQuickMouseEvent me(d->lastPos.x(), d->lastPos.y(), Qt::NoButton, Qt::NoButton, d->lastModifiers, false, false);
- emit mouseXChanged(&me);
- me.setPosition(d->lastPos);
- emit mouseYChanged(&me);
- me.setPosition(d->lastPos);
- emit positionChanged(&me);
- }
-}
-
-void QQuickMouseArea::hoverLeaveEvent(QHoverEvent *event)
-{
- Q_D(QQuickMouseArea);
- if (!d->absorb)
- QQuickItem::hoverLeaveEvent(event);
- else
- setHovered(false);
-}
-
-void QQuickMouseArea::ungrabMouse()
-{
- Q_D(QQuickMouseArea);
- if (d->pressed) {
- // if our mouse grab has been removed (probably by Flickable), fix our
- // state
- d->pressed = false;
- d->stealMouse = false;
- setKeepMouseGrab(false);
- emit canceled();
- emit pressedChanged();
- if (d->hovered) {
- d->hovered = false;
- emit hoveredChanged();
- }
- }
-}
-
-void QQuickMouseArea::mouseUngrabEvent()
-{
- ungrabMouse();
-}
-
-bool QQuickMouseArea::sendMouseEvent(QMouseEvent *event)
-{
- Q_D(QQuickMouseArea);
- QRectF myRect = mapRectToScene(QRectF(0, 0, width(), height()));
-
- QQuickCanvas *c = canvas();
- QQuickItem *grabber = c ? c->mouseGrabberItem() : 0;
- bool stealThisEvent = d->stealMouse;
- if ((stealThisEvent || myRect.contains(event->windowPos())) && (!grabber || !grabber->keepMouseGrab())) {
- QMouseEvent mouseEvent(event->type(), mapFromScene(event->windowPos()), event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers());
- mouseEvent.setAccepted(false);
-
- switch (event->type()) {
- case QEvent::MouseMove:
- mouseMoveEvent(&mouseEvent);
- break;
- case QEvent::MouseButtonPress:
- mousePressEvent(&mouseEvent);
- break;
- case QEvent::MouseButtonRelease:
- mouseReleaseEvent(&mouseEvent);
- break;
- default:
- break;
- }
- grabber = c->mouseGrabberItem();
- if (grabber && stealThisEvent && !grabber->keepMouseGrab() && grabber != this)
- grabMouse();
-
- return stealThisEvent;
- }
- if (event->type() == QEvent::MouseButtonRelease) {
- if (d->pressed) {
- d->pressed = false;
- d->stealMouse = false;
- if (c && c->mouseGrabberItem() == this)
- ungrabMouse();
- emit canceled();
- emit pressedChanged();
- if (d->hovered) {
- d->hovered = false;
- emit hoveredChanged();
- }
- }
- }
- return false;
-}
-
-bool QQuickMouseArea::childMouseEventFilter(QQuickItem *i, QEvent *e)
-{
- Q_D(QQuickMouseArea);
- if (!d->absorb || !isVisible() || !d->drag || !d->drag->filterChildren())
- return QQuickItem::childMouseEventFilter(i, e);
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease:
- return sendMouseEvent(static_cast<QMouseEvent *>(e));
- default:
- break;
- }
-
- return QQuickItem::childMouseEventFilter(i, e);
-}
-
-void QQuickMouseArea::timerEvent(QTimerEvent *event)
-{
- Q_D(QQuickMouseArea);
- if (event->timerId() == d->pressAndHoldTimer.timerId()) {
- d->pressAndHoldTimer.stop();
- bool dragged = d->drag && d->drag->active();
- if (d->pressed && dragged == false && d->hovered == true) {
- d->longPress = true;
- QQuickMouseEvent me(d->lastPos.x(), d->lastPos.y(), d->lastButton, d->lastButtons, d->lastModifiers, false, d->longPress);
- me.setAccepted(d->isPressAndHoldConnected());
- emit pressAndHold(&me);
- if (!me.isAccepted())
- d->propagate(&me, QQuickMouseAreaPrivate::PressAndHold);
- if (!me.isAccepted()) // no one handled the long press - allow click
- d->longPress = false;
- }
- }
-}
-
-void QQuickMouseArea::windowDeactivateEvent()
-{
- ungrabMouse();
- QQuickItem::windowDeactivateEvent();
-}
-
-void QQuickMouseArea::geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry)
-{
- Q_D(QQuickMouseArea);
- QQuickItem::geometryChanged(newGeometry, oldGeometry);
-
- if (d->lastScenePos.isNull)
- d->lastScenePos = mapToScene(d->lastPos);
- else if (newGeometry.x() != oldGeometry.x() || newGeometry.y() != oldGeometry.y())
- d->lastPos = mapFromScene(d->lastScenePos);
-}
-
-void QQuickMouseArea::itemChange(ItemChange change, const ItemChangeData &value)
-{
- Q_D(QQuickMouseArea);
- switch (change) {
- case ItemVisibleHasChanged:
- if (acceptHoverEvents() && d->hovered != (isVisible() && isUnderMouse()))
- setHovered(!d->hovered);
- break;
- default:
- break;
- }
-
- QQuickItem::itemChange(change, value);
-}
-
-/*!
- \qmlproperty bool QtQuick2::MouseArea::hoverEnabled
- This property holds whether hover events are handled.
-
- By default, mouse events are only handled in response to a button event, or when a button is
- pressed. Hover enables handling of all mouse events even when no mouse button is
- pressed.
-
- This property affects the containsMouse property and the onEntered, onExited and
- onPositionChanged signals.
-*/
-bool QQuickMouseArea::hoverEnabled() const
-{
- return acceptHoverEvents();
-}
-
-void QQuickMouseArea::setHoverEnabled(bool h)
-{
- if (h == acceptHoverEvents())
- return;
-
- setAcceptHoverEvents(h);
- emit hoverEnabledChanged();
-}
-
-
-/*!
- \qmlproperty bool QtQuick2::MouseArea::containsMouse
- This property holds whether the mouse is currently inside the mouse area.
-
- \warning This property is not updated if the area moves under the mouse: \e containsMouse will not change.
- In addition, if hoverEnabled is false, containsMouse will only be valid when the mouse is pressed.
-*/
-bool QQuickMouseArea::hovered() const
-{
- Q_D(const QQuickMouseArea);
- return d->hovered;
-}
-
-/*!
- \qmlproperty bool QtQuick2::MouseArea::pressed
- This property holds whether the mouse area is currently pressed.
-*/
-bool QQuickMouseArea::pressed() const
-{
- Q_D(const QQuickMouseArea);
- return d->pressed;
-}
-
-void QQuickMouseArea::setHovered(bool h)
-{
- Q_D(QQuickMouseArea);
- if (d->hovered != h) {
- d->hovered = h;
- emit hoveredChanged();
- d->hovered ? emit entered() : emit exited();
- }
-}
-/*!
- \qmlproperty QtQuick2::Qt::MouseButtons MouseArea::acceptedButtons
- This property holds the mouse buttons that the mouse area reacts to.
-
- The available buttons are:
- \list
- \o Qt.LeftButton
- \o Qt.RightButton
- \o Qt.MiddleButton
- \endlist
-
- To accept more than one button the flags can be combined with the
- "|" (or) operator:
-
- \code
- MouseArea { acceptedButtons: Qt.LeftButton | Qt.RightButton }
- \endcode
-
- The default value is \c Qt.LeftButton.
-*/
-Qt::MouseButtons QQuickMouseArea::acceptedButtons() const
-{
- return acceptedMouseButtons();
-}
-
-void QQuickMouseArea::setAcceptedButtons(Qt::MouseButtons buttons)
-{
- if (buttons != acceptedMouseButtons()) {
- setAcceptedMouseButtons(buttons);
- emit acceptedButtonsChanged();
- }
-}
-
-bool QQuickMouseArea::setPressed(bool p)
-{
- Q_D(QQuickMouseArea);
- bool dragged = d->drag && d->drag->active();
- bool isclick = d->pressed == true && p == false && dragged == false && d->hovered == true;
-
- if (d->pressed != p) {
- d->pressed = p;
- QQuickMouseEvent me(d->lastPos.x(), d->lastPos.y(), d->lastButton, d->lastButtons, d->lastModifiers, isclick, d->longPress);
- if (d->pressed) {
- if (!d->doubleClick)
- emit pressed(&me);
- me.setPosition(d->lastPos);
- emit mouseXChanged(&me);
- me.setPosition(d->lastPos);
- emit mouseYChanged(&me);
- emit pressedChanged();
- } else {
- emit released(&me);
- me.setPosition(d->lastPos);
- emit pressedChanged();
- if (isclick && !d->longPress && !d->doubleClick){
- me.setAccepted(d->isClickConnected());
- emit clicked(&me);
- if (!me.isAccepted())
- d->propagate(&me, QQuickMouseAreaPrivate::Click);
- }
- }
-
- return me.isAccepted();
- }
- return false;
-}
-
-/*!
- \qmlproperty Item QtQuick2::MouseArea::drag.target
- \qmlproperty bool QtQuick2::MouseArea::drag.active
- \qmlproperty enumeration QtQuick2::MouseArea::drag.axis
- \qmlproperty real QtQuick2::MouseArea::drag.minimumX
- \qmlproperty real QtQuick2::MouseArea::drag.maximumX
- \qmlproperty real QtQuick2::MouseArea::drag.minimumY
- \qmlproperty real QtQuick2::MouseArea::drag.maximumY
- \qmlproperty bool QtQuick2::MouseArea::drag.filterChildren
-
- \c drag provides a convenient way to make an item draggable.
-
- \list
- \i \c drag.target specifies the id of the item to drag.
- \i \c drag.active specifies if the target item is currently being dragged.
- \i \c drag.axis specifies whether dragging can be done horizontally (\c Drag.XAxis), vertically (\c Drag.YAxis), or both (\c Drag.XandYAxis)
- \i \c drag.minimum and \c drag.maximum limit how far the target can be dragged along the corresponding axes.
- \endlist
-
- The following example displays a \l Rectangle that can be dragged along the X-axis. The opacity
- of the rectangle is reduced when it is dragged to the right.
-
- \snippet doc/src/snippets/declarative/mousearea/mousearea.qml drag
-
- \note Items cannot be dragged if they are anchored for the requested
- \c drag.axis. For example, if \c anchors.left or \c anchors.right was set
- for \c rect in the above example, it cannot be dragged along the X-axis.
- This can be avoided by settng the anchor value to \c undefined in
- an \l onPressed handler.
-
- If \c drag.filterChildren is set to true, a drag can override descendant MouseAreas. This
- enables a parent MouseArea to handle drags, for example, while descendants handle clicks:
-
- \snippet doc/src/snippets/declarative/mousearea/mouseareadragfilter.qml dragfilter
-
-*/
-
-QQuickDrag *QQuickMouseArea::drag()
-{
- Q_D(QQuickMouseArea);
- if (!d->drag)
- d->drag = new QQuickDrag;
- return d->drag;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickmousearea_p.h b/src/declarative/items/qquickmousearea_p.h
deleted file mode 100644
index b8fa7d5ce8..0000000000
--- a/src/declarative/items/qquickmousearea_p.h
+++ /dev/null
@@ -1,231 +0,0 @@
-// Commit: c6e6a35aeb8794d68a3ca0c4e27a3a1181c066b5
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKMOUSEAREA_P_H
-#define QQUICKMOUSEAREA_P_H
-
-#include "qquickitem.h"
-
-#include <QtCore/qstringlist.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickDragAttached;
-class QQuickMouseEvent;
-class Q_AUTOTEST_EXPORT QQuickDrag : public QObject
-{
- Q_OBJECT
-
- Q_ENUMS(Axis)
- Q_PROPERTY(QQuickItem *target READ target WRITE setTarget NOTIFY targetChanged RESET resetTarget)
- Q_PROPERTY(Axis axis READ axis WRITE setAxis NOTIFY axisChanged)
- Q_PROPERTY(qreal minimumX READ xmin WRITE setXmin NOTIFY minimumXChanged)
- Q_PROPERTY(qreal maximumX READ xmax WRITE setXmax NOTIFY maximumXChanged)
- Q_PROPERTY(qreal minimumY READ ymin WRITE setYmin NOTIFY minimumYChanged)
- Q_PROPERTY(qreal maximumY READ ymax WRITE setYmax NOTIFY maximumYChanged)
- Q_PROPERTY(bool active READ active NOTIFY activeChanged)
- Q_PROPERTY(bool filterChildren READ filterChildren WRITE setFilterChildren NOTIFY filterChildrenChanged)
- //### consider drag and drop
-
-public:
- QQuickDrag(QObject *parent=0);
- ~QQuickDrag();
-
- QQuickItem *target() const;
- void setTarget(QQuickItem *target);
- void resetTarget();
-
- enum Axis { XAxis=0x01, YAxis=0x02, XandYAxis=0x03 };
- Axis axis() const;
- void setAxis(Axis);
-
- qreal xmin() const;
- void setXmin(qreal);
- qreal xmax() const;
- void setXmax(qreal);
- qreal ymin() const;
- void setYmin(qreal);
- qreal ymax() const;
- void setYmax(qreal);
-
- bool active() const;
- void setActive(bool);
-
- bool filterChildren() const;
- void setFilterChildren(bool);
-
- static QQuickDragAttached *qmlAttachedProperties(QObject *obj);
-
-Q_SIGNALS:
- void targetChanged();
- void axisChanged();
- void minimumXChanged();
- void maximumXChanged();
- void minimumYChanged();
- void maximumYChanged();
- void activeChanged();
- void filterChildrenChanged();
-
-private:
- QQuickItem *_target;
- Axis _axis;
- qreal _xmin;
- qreal _xmax;
- qreal _ymin;
- qreal _ymax;
- bool _active : 1;
- bool _filterChildren: 1;
- Q_DISABLE_COPY(QQuickDrag)
-};
-
-class QQuickMouseAreaPrivate;
-// used in QtLocation
-class Q_DECLARATIVE_EXPORT QQuickMouseArea : public QQuickItem
-{
- Q_OBJECT
-
- Q_PROPERTY(qreal mouseX READ mouseX NOTIFY mouseXChanged)
- Q_PROPERTY(qreal mouseY READ mouseY NOTIFY mouseYChanged)
- Q_PROPERTY(bool containsMouse READ hovered NOTIFY hoveredChanged)
- Q_PROPERTY(bool pressed READ pressed NOTIFY pressedChanged)
- Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged)
- Q_PROPERTY(Qt::MouseButtons pressedButtons READ pressedButtons NOTIFY pressedChanged)
- Q_PROPERTY(Qt::MouseButtons acceptedButtons READ acceptedButtons WRITE setAcceptedButtons NOTIFY acceptedButtonsChanged)
- Q_PROPERTY(bool hoverEnabled READ hoverEnabled WRITE setHoverEnabled NOTIFY hoverEnabledChanged)
- Q_PROPERTY(QQuickDrag *drag READ drag CONSTANT) //### add flicking to QQuickDrag or add a QDeclarativeFlick ???
- Q_PROPERTY(bool preventStealing READ preventStealing WRITE setPreventStealing NOTIFY preventStealingChanged)
- Q_PROPERTY(bool propagateComposedEvents READ propagateComposedEvents WRITE setPropagateComposedEvents NOTIFY propagateComposedEventsChanged)
-
-public:
- QQuickMouseArea(QQuickItem *parent=0);
- ~QQuickMouseArea();
-
- qreal mouseX() const;
- qreal mouseY() const;
-
- bool isEnabled() const;
- void setEnabled(bool);
-
- bool hovered() const;
- bool pressed() const;
-
- Qt::MouseButtons pressedButtons() const;
-
- Qt::MouseButtons acceptedButtons() const;
- void setAcceptedButtons(Qt::MouseButtons buttons);
-
- bool hoverEnabled() const;
- void setHoverEnabled(bool h);
-
- QQuickDrag *drag();
-
- bool preventStealing() const;
- void setPreventStealing(bool prevent);
-
- bool propagateComposedEvents() const;
- void setPropagateComposedEvents(bool propagate);
-
-Q_SIGNALS:
- void hoveredChanged();
- void pressedChanged();
- void enabledChanged();
- void acceptedButtonsChanged();
- void hoverEnabledChanged();
- void positionChanged(QQuickMouseEvent *mouse);
- void mouseXChanged(QQuickMouseEvent *mouse);
- void mouseYChanged(QQuickMouseEvent *mouse);
- void preventStealingChanged();
- void propagateComposedEventsChanged();
-
- void pressed(QQuickMouseEvent *mouse);
- void pressAndHold(QQuickMouseEvent *mouse);
- void released(QQuickMouseEvent *mouse);
- void clicked(QQuickMouseEvent *mouse);
- void doubleClicked(QQuickMouseEvent *mouse);
- void entered();
- void exited();
- void canceled();
-
-protected:
- void setHovered(bool);
- bool setPressed(bool);
- bool sendMouseEvent(QMouseEvent *event);
-
- virtual void mousePressEvent(QMouseEvent *event);
- virtual void mouseReleaseEvent(QMouseEvent *event);
- virtual void mouseDoubleClickEvent(QMouseEvent *event);
- virtual void mouseMoveEvent(QMouseEvent *event);
- virtual void mouseUngrabEvent();
- virtual void hoverEnterEvent(QHoverEvent *event);
- virtual void hoverMoveEvent(QHoverEvent *event);
- virtual void hoverLeaveEvent(QHoverEvent *event);
- virtual bool childMouseEventFilter(QQuickItem *i, QEvent *e);
- virtual void timerEvent(QTimerEvent *event);
- virtual void windowDeactivateEvent();
-
- virtual void geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry);
- virtual void itemChange(ItemChange change, const ItemChangeData& value);
-
-private:
- void handlePress();
- void handleRelease();
- void ungrabMouse();
-
-private:
- Q_DISABLE_COPY(QQuickMouseArea)
- Q_DECLARE_PRIVATE(QQuickMouseArea)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickDrag)
-QML_DECLARE_TYPEINFO(QQuickDrag, QML_HAS_ATTACHED_PROPERTIES)
-QML_DECLARE_TYPE(QQuickMouseArea)
-
-QT_END_HEADER
-
-#endif // QQUICKMOUSEAREA_P_H
diff --git a/src/declarative/items/qquickmousearea_p_p.h b/src/declarative/items/qquickmousearea_p_p.h
deleted file mode 100644
index c1c53c4302..0000000000
--- a/src/declarative/items/qquickmousearea_p_p.h
+++ /dev/null
@@ -1,112 +0,0 @@
-// Commit: c6e6a35aeb8794d68a3ca0c4e27a3a1181c066b5
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKMOUSEAREA_P_P_H
-#define QQUICKMOUSEAREA_P_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 "qquickitem_p.h"
-
-#include <QtGui/qevent.h>
-#include <QtCore/qbasictimer.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickMouseEvent;
-class QQuickMouseArea;
-class QQuickMouseAreaPrivate : public QQuickItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickMouseArea)
-
-public:
- QQuickMouseAreaPrivate();
- ~QQuickMouseAreaPrivate();
- void init();
-
- void saveEvent(QMouseEvent *event);
- enum PropagateType{
- Click,
- DoubleClick,
- PressAndHold
- };
- void propagate(QQuickMouseEvent* event, PropagateType);
- bool propagateHelper(QQuickMouseEvent*, QQuickItem*,const QPointF &, PropagateType);
-
- bool isPressAndHoldConnected();
- bool isDoubleClickConnected();
- bool isClickConnected();
-
- bool absorb : 1;
- bool hovered : 1;
- bool pressed : 1;
- bool longPress : 1;
- bool moved : 1;
- bool dragX : 1;
- bool dragY : 1;
- bool stealMouse : 1;
- bool doubleClick : 1;
- bool preventStealing : 1;
- bool propagateComposedEvents : 1;
- QQuickDrag *drag;
- QPointF startScene;
- QPointF targetStartPos;
- QPointF lastPos;
- QDeclarativeNullableValue<QPointF> lastScenePos;
- Qt::MouseButton lastButton;
- Qt::MouseButtons lastButtons;
- Qt::KeyboardModifiers lastModifiers;
- QBasicTimer pressAndHoldTimer;
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKMOUSEAREA_P_P_H
diff --git a/src/declarative/items/qquickmultipointtoucharea.cpp b/src/declarative/items/qquickmultipointtoucharea.cpp
deleted file mode 100644
index f7fdf97fb7..0000000000
--- a/src/declarative/items/qquickmultipointtoucharea.cpp
+++ /dev/null
@@ -1,729 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickmultipointtoucharea_p.h"
-#include <qquickcanvas.h>
-#include <QEvent>
-#include <QMouseEvent>
-#include <math.h>
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass TouchPoint QQuickTouchPoint
- \inqmlmodule QtQuick 2
- \ingroup qml-event-elements
- \brief The TouchPoint element describes a touch point in a MultiPointTouchArea.
-
- The TouchPoint element contains information about a touch point, such as the current
- position, pressure, and area.
-*/
-
-/*!
- \qmlproperty int QtQuick2::TouchPoint::pointId
-
- This property holds the point id of the touch point.
-
- Each touch point within a MultiPointTouchArea will have a unique id.
-*/
-void QQuickTouchPoint::setPointId(int id)
-{
- if (_id == id)
- return;
- _id = id;
- emit pointIdChanged();
-}
-
-/*!
- \qmlproperty real QtQuick2::TouchPoint::x
- \qmlproperty real QtQuick2::TouchPoint::y
-
- These properties hold the current position of the touch point.
-*/
-
-void QQuickTouchPoint::setX(qreal x)
-{
- if (_x == x)
- return;
- _x = x;
- emit xChanged();
-}
-
-void QQuickTouchPoint::setY(qreal y)
-{
- if (_y == y)
- return;
- _y = y;
- emit yChanged();
-}
-
-/*!
- \qmlproperty real QtQuick2::TouchPoint::pressure
- \qmlproperty rectangle QtQuick2::TouchPoint::area
-
- These properties hold additional information about the current state of the touch point.
-
- \list
- \i \c pressure is a value in the range of 0.0 to 1.0.
- \i \c area is a rectangle covering the area of the touch point, centered on the current position of the touch point.
- \endlist
-*/
-void QQuickTouchPoint::setPressure(qreal pressure)
-{
- if (_pressure == pressure)
- return;
- _pressure = pressure;
- emit pressureChanged();
-}
-
-void QQuickTouchPoint::setArea(const QRectF &area)
-{
- if (_area == area)
- return;
- _area = area;
- emit areaChanged();
-}
-
-/*!
- \qmlproperty bool QtQuick2::TouchPoint::valid
-
- This property holds whether the touch point is valid.
-
- An invalid touch point is one that has not yet been pressed,
- or has already been released.
-*/
-void QQuickTouchPoint::setValid(bool valid)
-{
- if (_valid == valid)
- return;
- _valid = valid;
- emit validityChanged();
-}
-
-/*!
- \qmlproperty real QtQuick2::TouchPoint::startX
- \qmlproperty real QtQuick2::TouchPoint::startY
-
- These properties hold the starting position of the touch point.
-*/
-
-void QQuickTouchPoint::setStartX(qreal startX)
-{
- if (_startX == startX)
- return;
- _startX = startX;
- emit startXChanged();
-}
-
-void QQuickTouchPoint::setStartY(qreal startY)
-{
- if (_startY == startY)
- return;
- _startY = startY;
- emit startYChanged();
-}
-
-/*!
- \qmlproperty real QtQuick2::TouchPoint::previousX
- \qmlproperty real QtQuick2::TouchPoint::previousY
-
- These properties hold the previous position of the touch point.
-*/
-void QQuickTouchPoint::setPreviousX(qreal previousX)
-{
- if (_previousX == previousX)
- return;
- _previousX = previousX;
- emit previousXChanged();
-}
-
-void QQuickTouchPoint::setPreviousY(qreal previousY)
-{
- if (_previousY == previousY)
- return;
- _previousY = previousY;
- emit previousYChanged();
-}
-
-/*!
- \qmlproperty real QtQuick2::TouchPoint::sceneX
- \qmlproperty real QtQuick2::TouchPoint::sceneY
-
- These properties hold the current position of the touch point in scene coordinates.
-*/
-
-void QQuickTouchPoint::setSceneX(qreal sceneX)
-{
- if (_sceneX == sceneX)
- return;
- _sceneX = sceneX;
- emit sceneXChanged();
-}
-
-void QQuickTouchPoint::setSceneY(qreal sceneY)
-{
- if (_sceneY == sceneY)
- return;
- _sceneY = sceneY;
- emit sceneYChanged();
-}
-
-/*!
- \qmlclass MultiPointTouchArea QQuickMultiPointTouchArea
- \inqmlmodule QtQuick 2
- \brief The MultiPointTouchArea item enables handling of multiple touch points.
- \inherits Item
-
- A MultiPointTouchArea is an invisible item that is used to track multiple touch points.
-
- The \l enabled property is used to enable and disable touch handling. When disabled,
- the touch area becomes transparent to mouse/touch events.
-
- MultiPointTouchArea can be used in two ways:
-
- \list
- \o setting \c touchPoints to provide touch point objects with properties that can be bound to
- \o using the onTouchUpdated or onTouchPointsPressed, onTouchPointsUpdated and onTouchPointsReleased handlers
- \endlist
-
- While a MultiPointTouchArea \i can take exclusive ownership of certain touch points, it is also possible to have
- multiple MultiPointTouchAreas active at the same time, each operating on a different set of touch points.
-
- \sa TouchPoint
-*/
-
-/*!
- \qmlsignal QtQuick2::MultiPointTouchArea::touchPointsPressed(list<TouchPoint> touchPoints)
-
- This handler is called when new touch points are added. \a touchPoints is a list of these new points.
-
- If minimumTouchPoints is set to a value greater than one, this handler will not be called until the minimum number
- of required touch points has been reached. At that point, touchPointsPressed will be called with all the current touch points.
-*/
-
-/*!
- \qmlsignal QtQuick2::MultiPointTouchArea::touchPointsUpdated(list<TouchPoint> touchPoints)
-
- This handler is called when existing touch points are updated. \a touchPoints is a list of these updated points.
-*/
-
-/*!
- \qmlsignal QtQuick2::MultiPointTouchArea::touchPointsReleased(list<TouchPoint> touchPoints)
-
- This handler is called when existing touch points are removed. \a touchPoints is a list of these removed points.
-*/
-
-/*!
- \qmlsignal QtQuick2::MultiPointTouchArea::touchPointsCanceled(list<TouchPoint> touchPoints)
-
- This handler is called when new touch events have been canceled because another element stole the touch event handling.
-
- This signal is for advanced use: it is useful when there is more than one MultiPointTouchArea
- that is handling input, or when there is a MultiPointTouchArea inside a \l Flickable. In the latter
- case, if you execute some logic on the touchPointsPressed signal and then start dragging, the
- \l Flickable may steal the touch handling from the MultiPointTouchArea. In these cases, to reset
- the logic when the MultiPointTouchArea has lost the touch handling to the \l Flickable,
- \c onTouchPointsCanceled should be used in addition to onTouchPointsReleased.
-
- \a touchPoints is the list of canceled points.
-*/
-
-/*!
- \qmlsignal QtQuick2::MultiPointTouchArea::gestureStarted(GestureEvent gesture)
-
- This handler is called when the global drag threshold has been reached.
-
- This function is typically used when a MultiPointTouchAreas has been nested in a Flickable or another MultiPointTouchArea.
- Wnen the threshold has been reached, and the handler called, you can determine whether or not the touch
- area should grab the current touch points. By default they will not be grabbed; to grab them call \c gesture.grab(). If the
- gesture is not grabbed, the nesting Flickable, for example, would also have an opportunity to grab.
-
- The gesture object also includes information on the current set of \c touchPoints and the \c dragThreshold.
-*/
-
-/*!
- \qmlsignal QtQuick2::MultiPointTouchArea::touchUpdated(list<TouchPoint> touchPoints)
-
- This handler is called when the touch points handled by the MultiPointTouchArea change. This includes adding new touch points,
- removing previous touch points, as well as updating current touch point data. \a touchPoints is the list of all current touch
- points.
-*/
-
-/*!
- \qmlproperty list<TouchPoint> QtQuick2::MultiPointTouchArea::touchPoints
-
- This property holds a set of user-defined touch point objects that can be bound to.
-
- In the following example, we have two small rectangles that follow our touch points.
-
- \snippet doc/src/snippets/declarative/multipointtoucharea/multipointtoucharea.qml 0
-
- By default this property holds an empty list.
-
- \sa TouchPoint
-*/
-
-QQuickMultiPointTouchArea::QQuickMultiPointTouchArea(QQuickItem *parent)
- : QQuickItem(parent),
- _minimumTouchPoints(0),
- _maximumTouchPoints(INT_MAX),
- _stealMouse(false)
-{
- setAcceptedMouseButtons(Qt::LeftButton);
- setFiltersChildMouseEvents(true);
-}
-
-QQuickMultiPointTouchArea::~QQuickMultiPointTouchArea()
-{
- clearTouchLists();
- foreach (QObject *obj, _touchPoints) {
- QQuickTouchPoint *dtp = static_cast<QQuickTouchPoint*>(obj);
- if (!dtp->isQmlDefined())
- delete dtp;
- }
-}
-
-/*!
- \qmlproperty int QtQuick2::MultiPointTouchArea::minimumTouchPoints
- \qmlproperty int QtQuick2::MultiPointTouchArea::maximumTouchPoints
-
- These properties hold the range of touch points to be handled by the touch area.
-
- These are convenience that allow you to, for example, have nested MultiPointTouchAreas,
- one handling two finger touches, and another handling three finger touches.
-
- By default, all touch points within the touch area are handled.
-*/
-
-int QQuickMultiPointTouchArea::minimumTouchPoints() const
-{
- return _minimumTouchPoints;
-}
-
-void QQuickMultiPointTouchArea::setMinimumTouchPoints(int num)
-{
- if (_minimumTouchPoints == num)
- return;
- _minimumTouchPoints = num;
- emit minimumTouchPointsChanged();
-}
-
-int QQuickMultiPointTouchArea::maximumTouchPoints() const
-{
- return _maximumTouchPoints;
-}
-
-void QQuickMultiPointTouchArea::setMaximumTouchPoints(int num)
-{
- if (_maximumTouchPoints == num)
- return;
- _maximumTouchPoints = num;
- emit maximumTouchPointsChanged();
-}
-
-void QQuickMultiPointTouchArea::touchEvent(QTouchEvent *event)
-{
- switch (event->type()) {
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd: {
- //if e.g. a parent Flickable has the mouse grab, don't process the touch events
- QQuickCanvas *c = canvas();
- QQuickItem *grabber = c ? c->mouseGrabberItem() : 0;
- if (grabber && grabber != this && grabber->keepMouseGrab() && grabber->isEnabled()) {
- QQuickItem *item = this;
- while ((item = item->parentItem())) {
- if (item == grabber)
- return;
- }
- }
- updateTouchData(event);
- if (event->type() == QEvent::TouchEnd) {
- //TODO: move to canvas
- _stealMouse = false;
- setKeepMouseGrab(false);
- QQuickCanvas *c = canvas();
- if (c && c->mouseGrabberItem() == this)
- ungrabMouse();
- setKeepTouchGrab(false);
- ungrabTouchPoints();
- }
- break;
- }
- default:
- QQuickItem::touchEvent(event);
- break;
- }
-}
-
-void QQuickMultiPointTouchArea::grabGesture()
-{
- _stealMouse = true;
-
- grabMouse();
- setKeepMouseGrab(true);
-
- grabTouchPoints(_touchPoints.keys());
- setKeepTouchGrab(true);
-}
-
-void QQuickMultiPointTouchArea::updateTouchData(QEvent *event)
-{
- bool ended = false;
- bool moved = false;
- bool started = false;
-
- clearTouchLists();
- QTouchEvent *e = static_cast<QTouchEvent*>(event);
- QList<QTouchEvent::TouchPoint> touchPoints = e->touchPoints();
- int numTouchPoints = touchPoints.count();
- //always remove released touches, and make sure we handle all releases before adds.
- foreach (QTouchEvent::TouchPoint p, touchPoints) {
- Qt::TouchPointState touchPointState = p.state();
- int id = p.id();
- if (touchPointState & Qt::TouchPointReleased) {
- QQuickTouchPoint* dtp = static_cast<QQuickTouchPoint*>(_touchPoints.value(id));
- if (!dtp)
- continue;
- _releasedTouchPoints.append(dtp);
- _touchPoints.remove(id);
- ended = true;
- }
- }
- if (numTouchPoints >= _minimumTouchPoints && numTouchPoints <= _maximumTouchPoints) {
- foreach (QTouchEvent::TouchPoint p, touchPoints) {
- Qt::TouchPointState touchPointState = p.state();
- int id = p.id();
- if (touchPointState & Qt::TouchPointReleased) {
- //handled above
- } else if (!_touchPoints.contains(id)) { //could be pressed, moved, or stationary
- addTouchPoint(&p);
- started = true;
- } else if (touchPointState & Qt::TouchPointMoved) {
- QQuickTouchPoint* dtp = static_cast<QQuickTouchPoint*>(_touchPoints[id]);
- Q_ASSERT(dtp);
- _movedTouchPoints.append(dtp);
- updateTouchPoint(dtp,&p);
- moved = true;
- } else {
- QQuickTouchPoint* dtp = static_cast<QQuickTouchPoint*>(_touchPoints[id]);
- Q_ASSERT(dtp);
- updateTouchPoint(dtp,&p);
- }
- }
-
- //see if we should be grabbing the gesture
- if (!_stealMouse /* !ignoring gesture*/) {
- bool offerGrab = false;
- const int dragThreshold = qApp->styleHints()->startDragDistance();
- foreach (const QTouchEvent::TouchPoint &p, touchPoints) {
- if (p.state() == Qt::TouchPointReleased)
- continue;
- const QPointF &currentPos = p.scenePos();
- const QPointF &startPos = p.startScenePos();
- if (qAbs(currentPos.x() - startPos.x()) > dragThreshold)
- offerGrab = true;
- else if (qAbs(currentPos.y() - startPos.y()) > dragThreshold)
- offerGrab = true;
- if (offerGrab)
- break;
- }
-
- if (offerGrab) {
- QQuickGrabGestureEvent event;
- event._touchPoints = _touchPoints.values();
- emit gestureStarted(&event);
- if (event.wantsGrab())
- grabGesture();
- }
- }
-
- if (ended) emit(touchPointsReleased(_releasedTouchPoints));
- if (moved) emit(touchPointsUpdated(_movedTouchPoints));
- if (started) emit(touchPointsPressed(_pressedTouchPoints));
- if (!_touchPoints.isEmpty()) emit touchUpdated(_touchPoints.values());
- }
-}
-
-void QQuickMultiPointTouchArea::clearTouchLists()
-{
- foreach (QObject *obj, _releasedTouchPoints) {
- QQuickTouchPoint *dtp = static_cast<QQuickTouchPoint*>(obj);
- if (!dtp->isQmlDefined())
- delete dtp;
- else
- dtp->setValid(false);
- }
- _releasedTouchPoints.clear();
- _pressedTouchPoints.clear();
- _movedTouchPoints.clear();
-}
-
-void QQuickMultiPointTouchArea::addTouchPoint(const QTouchEvent::TouchPoint *p)
-{
- QQuickTouchPoint *dtp = 0;
- foreach (QQuickTouchPoint* tp, _touchPrototypes) {
- if (!tp->isValid()) {
- tp->setValid(true);
- dtp = tp;
- break;
- }
- }
-
- if (dtp == 0)
- dtp = new QQuickTouchPoint(false);
- dtp->setPointId(p->id());
- updateTouchPoint(dtp,p);
- _touchPoints.insert(p->id(),dtp);
- //we may have just obtained enough points to start tracking them -- in that case moved or stationary count as newly pressed
- if (p->state() & Qt::TouchPointPressed || p->state() & Qt::TouchPointMoved || p->state() & Qt::TouchPointStationary)
- _pressedTouchPoints.append(dtp);
-}
-
-void QQuickMultiPointTouchArea::addTouchPrototype(QQuickTouchPoint *prototype)
-{
- int id = _touchPrototypes.count();
- prototype->setPointId(id);
- _touchPrototypes.insert(id, prototype);
-}
-
-void QQuickMultiPointTouchArea::updateTouchPoint(QQuickTouchPoint *dtp, const QTouchEvent::TouchPoint *p)
-{
- //TODO: if !qmlDefined, could bypass setters.
- // also, should only emit signals after all values have been set
- dtp->setX(p->pos().x());
- dtp->setY(p->pos().y());
- dtp->setPressure(p->pressure());
- dtp->setArea(p->rect());
- dtp->setStartX(p->startPos().x());
- dtp->setStartY(p->startPos().y());
- dtp->setPreviousX(p->lastPos().x());
- dtp->setPreviousY(p->lastPos().y());
- dtp->setSceneX(p->scenePos().x());
- dtp->setSceneY(p->scenePos().y());
-}
-
-void QQuickMultiPointTouchArea::mousePressEvent(QMouseEvent *event)
-{
- if (!isEnabled()) {
- QQuickItem::mousePressEvent(event);
- return;
- }
-
- _stealMouse = false;
- setKeepMouseGrab(false);
- event->setAccepted(true);
-}
-
-void QQuickMultiPointTouchArea::mouseMoveEvent(QMouseEvent *event)
-{
- if (!isEnabled()) {
- QQuickItem::mouseMoveEvent(event);
- return;
- }
-
- //do nothing
-}
-
-void QQuickMultiPointTouchArea::mouseReleaseEvent(QMouseEvent *event)
-{
- _stealMouse = false;
- if (!isEnabled()) {
- QQuickItem::mouseReleaseEvent(event);
- return;
- }
- QQuickCanvas *c = canvas();
- if (c && c->mouseGrabberItem() == this)
- ungrabMouse();
- setKeepMouseGrab(false);
-}
-
-void QQuickMultiPointTouchArea::ungrab()
-{
- if (_touchPoints.count()) {
- QQuickCanvas *c = canvas();
- if (c && c->mouseGrabberItem() == this) {
- _stealMouse = false;
- setKeepMouseGrab(false);
- }
- setKeepTouchGrab(false);
- emit touchPointsCanceled(_touchPoints.values());
- clearTouchLists();
- foreach (QObject *obj, _touchPoints) {
- QQuickTouchPoint *dtp = static_cast<QQuickTouchPoint*>(obj);
- if (!dtp->isQmlDefined())
- delete dtp;
- else
- dtp->setValid(false);
- }
- _touchPoints.clear();
- }
-}
-
-void QQuickMultiPointTouchArea::mouseUngrabEvent()
-{
- ungrab();
-}
-
-void QQuickMultiPointTouchArea::touchUngrabEvent()
-{
- ungrab();
-}
-
-bool QQuickMultiPointTouchArea::sendMouseEvent(QMouseEvent *event)
-{
- QRectF myRect = mapRectToScene(QRectF(0, 0, width(), height()));
-
- QQuickCanvas *c = canvas();
- QQuickItem *grabber = c ? c->mouseGrabberItem() : 0;
- bool stealThisEvent = _stealMouse;
- if ((stealThisEvent || myRect.contains(event->windowPos())) && (!grabber || !grabber->keepMouseGrab())) {
- QMouseEvent mouseEvent(event->type(), mapFromScene(event->windowPos()), event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers());
- mouseEvent.setAccepted(false);
-
- switch (mouseEvent.type()) {
- case QEvent::MouseMove:
- mouseMoveEvent(&mouseEvent);
- break;
- case QEvent::MouseButtonPress:
- mousePressEvent(&mouseEvent);
- break;
- case QEvent::MouseButtonRelease:
- mouseReleaseEvent(&mouseEvent);
- break;
- default:
- break;
- }
- grabber = c->mouseGrabberItem();
- if (grabber && stealThisEvent && !grabber->keepMouseGrab() && grabber != this)
- grabMouse();
-
- return stealThisEvent;
- }
- if (event->type() == QEvent::MouseButtonRelease) {
- _stealMouse = false;
- if (c && c->mouseGrabberItem() == this)
- ungrabMouse();
- setKeepMouseGrab(false);
- }
- return false;
-}
-
-bool QQuickMultiPointTouchArea::childMouseEventFilter(QQuickItem *i, QEvent *event)
-{
- if (!isEnabled() || !isVisible())
- return QQuickItem::childMouseEventFilter(i, event);
- switch (event->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease:
- return sendMouseEvent(static_cast<QMouseEvent *>(event));
- break;
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- if (!shouldFilter(event))
- return false;
- updateTouchData(event);
- return _stealMouse;
- case QEvent::TouchEnd: {
- if (!shouldFilter(event))
- return false;
- updateTouchData(event);
- //TODO: verify this behavior
- _stealMouse = false;
- setKeepMouseGrab(false);
- QQuickCanvas *c = canvas();
- if (c && c->mouseGrabberItem() == this)
- ungrabMouse();
- setKeepTouchGrab(false);
- ungrabTouchPoints();
- }
- break;
- default:
- break;
- }
- return QQuickItem::childMouseEventFilter(i, event);
-}
-
-bool QQuickMultiPointTouchArea::shouldFilter(QEvent *event)
-{
- QQuickCanvas *c = canvas();
- QQuickItem *grabber = c ? c->mouseGrabberItem() : 0;
- bool disabledItem = grabber && !grabber->isEnabled();
- bool stealThisEvent = _stealMouse;
- bool contains = false;
- if (!stealThisEvent) {
- switch (event->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease: {
- QMouseEvent *me = static_cast<QMouseEvent*>(event);
- QRectF myRect = mapRectToScene(QRectF(0, 0, width(), height()));
- contains = myRect.contains(me->windowPos());
- }
- break;
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd: {
- QTouchEvent *te = static_cast<QTouchEvent*>(event);
- QRectF myRect = mapRectToScene(QRectF(0, 0, width(), height()));
- foreach (const QTouchEvent::TouchPoint &point, te->touchPoints()) {
- if (myRect.contains(point.scenePos())) {
- contains = true;
- break;
- }
- }
- }
- break;
- default:
- break;
- }
- }
- if ((stealThisEvent || contains) && (!grabber || !grabber->keepMouseGrab() || disabledItem)) {
- return true;
- }
- ungrab();
- return false;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickmultipointtoucharea_p.h b/src/declarative/items/qquickmultipointtoucharea_p.h
deleted file mode 100644
index dac70453c5..0000000000
--- a/src/declarative/items/qquickmultipointtoucharea_p.h
+++ /dev/null
@@ -1,267 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKMULTIPOINTTOUCHAREA_H
-#define QQUICKMULTIPOINTTOUCHAREA_H
-
-#include "qquickitem.h"
-#include "qevent.h"
-
-#include <QMap>
-#include <QList>
-#include <QtGui/qguiapplication.h>
-#include <QtGui/qstylehints.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickMultiPointTouchArea;
-class Q_AUTOTEST_EXPORT QQuickTouchPoint : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(bool valid READ isValid NOTIFY validityChanged)
- Q_PROPERTY(int pointId READ pointId NOTIFY pointIdChanged)
- Q_PROPERTY(qreal x READ x NOTIFY xChanged)
- Q_PROPERTY(qreal y READ y NOTIFY yChanged)
- Q_PROPERTY(qreal pressure READ pressure NOTIFY pressureChanged)
- Q_PROPERTY(QRectF area READ area NOTIFY areaChanged)
-
- Q_PROPERTY(qreal startX READ startX NOTIFY startXChanged)
- Q_PROPERTY(qreal startY READ startY NOTIFY startYChanged)
- Q_PROPERTY(qreal previousX READ previousX NOTIFY previousXChanged)
- Q_PROPERTY(qreal previousY READ previousY NOTIFY previousYChanged)
- Q_PROPERTY(qreal sceneX READ sceneX NOTIFY sceneXChanged)
- Q_PROPERTY(qreal sceneY READ sceneY NOTIFY sceneYChanged)
-
-public:
- QQuickTouchPoint(bool qmlDefined = true)
- : _id(0),
- _x(0.0), _y(0.0),
- _pressure(0.0),
- _qmlDefined(qmlDefined),
- _valid(!qmlDefined),
- _previousX(0.0), _previousY(0.0),
- _sceneX(0.0), _sceneY(0.0)
- {}
-
- int pointId() const { return _id; }
- void setPointId(int id);
-
- qreal x() const { return _x; }
- void setX(qreal x);
-
- qreal y() const { return _y; }
- void setY(qreal y);
-
- qreal pressure() const { return _pressure; }
- void setPressure(qreal pressure);
-
- QRectF area() const { return _area; }
- void setArea(const QRectF &area);
-
- bool isQmlDefined() { return _qmlDefined; }
-
- bool isValid() { return _valid; }
- void setValid(bool valid);
-
- qreal startX() const { return _startX; }
- void setStartX(qreal startX);
-
- qreal startY() const { return _startY; }
- void setStartY(qreal startY);
-
- qreal previousX() const { return _previousX; }
- void setPreviousX(qreal previousX);
-
- qreal previousY() const { return _previousY; }
- void setPreviousY(qreal previousY);
-
- qreal sceneX() const { return _sceneX; }
- void setSceneX(qreal sceneX);
-
- qreal sceneY() const { return _sceneY; }
- void setSceneY(qreal sceneY);
-
-
-Q_SIGNALS:
- void pointIdChanged();
- void xChanged();
- void yChanged();
- void pressureChanged();
- void areaChanged();
- void validityChanged();
- void startXChanged();
- void startYChanged();
- void previousXChanged();
- void previousYChanged();
- void sceneXChanged();
- void sceneYChanged();
-
-private:
- friend class QQuickMultiPointTouchArea;
- int _id;
- qreal _x;
- qreal _y;
- qreal _pressure;
- QRectF _area;
- bool _qmlDefined;
- bool _valid;
- qreal _startX;
- qreal _startY;
- qreal _previousX;
- qreal _previousY;
- qreal _sceneX;
- qreal _sceneY;
-};
-
-class QQuickGrabGestureEvent : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QDeclarativeListProperty<QObject> touchPoints READ touchPoints)
- Q_PROPERTY(qreal dragThreshold READ dragThreshold)
-public:
- QQuickGrabGestureEvent() : _grab(false), _dragThreshold(qApp->styleHints()->startDragDistance()) {}
-
- Q_INVOKABLE void grab() { _grab = true; }
- bool wantsGrab() const { return _grab; }
-
- QDeclarativeListProperty<QObject> touchPoints() {
- return QDeclarativeListProperty<QObject>(this, _touchPoints);
- }
- qreal dragThreshold() const { return _dragThreshold; }
-
-private:
- friend class QQuickMultiPointTouchArea;
- bool _grab;
- qreal _dragThreshold;
- QList<QObject*> _touchPoints;
-};
-
-class Q_AUTOTEST_EXPORT QQuickMultiPointTouchArea : public QQuickItem
-{
- Q_OBJECT
-
- Q_PROPERTY(QDeclarativeListProperty<QQuickTouchPoint> touchPoints READ touchPoints)
- Q_PROPERTY(int minimumTouchPoints READ minimumTouchPoints WRITE setMinimumTouchPoints NOTIFY minimumTouchPointsChanged)
- Q_PROPERTY(int maximumTouchPoints READ maximumTouchPoints WRITE setMaximumTouchPoints NOTIFY maximumTouchPointsChanged)
-
-public:
- QQuickMultiPointTouchArea(QQuickItem *parent=0);
- ~QQuickMultiPointTouchArea();
-
- int minimumTouchPoints() const;
- void setMinimumTouchPoints(int num);
- int maximumTouchPoints() const;
- void setMaximumTouchPoints(int num);
-
- QDeclarativeListProperty<QQuickTouchPoint> touchPoints() {
- return QDeclarativeListProperty<QQuickTouchPoint>(this, 0, QQuickMultiPointTouchArea::touchPoint_append, QQuickMultiPointTouchArea::touchPoint_count, QQuickMultiPointTouchArea::touchPoint_at, 0);
- }
-
- static void touchPoint_append(QDeclarativeListProperty<QQuickTouchPoint> *list, QQuickTouchPoint* touch) {
- QQuickMultiPointTouchArea *q = static_cast<QQuickMultiPointTouchArea*>(list->object);
- q->addTouchPrototype(touch);
- }
-
- static int touchPoint_count(QDeclarativeListProperty<QQuickTouchPoint> *list) {
- QQuickMultiPointTouchArea *q = static_cast<QQuickMultiPointTouchArea*>(list->object);
- return q->_touchPrototypes.count();
- }
-
- static QQuickTouchPoint* touchPoint_at(QDeclarativeListProperty<QQuickTouchPoint> *list, int index) {
- QQuickMultiPointTouchArea *q = static_cast<QQuickMultiPointTouchArea*>(list->object);
- return q->_touchPrototypes[index];
- }
-
-Q_SIGNALS:
- void touchPointsPressed(const QList<QObject*> &touchPoints);
- void touchPointsUpdated(const QList<QObject*> &touchPoints);
- void touchPointsReleased(const QList<QObject*> &touchPoints);
- void touchPointsCanceled(const QList<QObject*> &touchPoints);
- void gestureStarted(QQuickGrabGestureEvent *gesture);
- void touchUpdated(const QList<QObject*> &touchPoints);
- void minimumTouchPointsChanged();
- void maximumTouchPointsChanged();
-
-protected:
- void touchEvent(QTouchEvent *);
- bool childMouseEventFilter(QQuickItem *i, QEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void mouseUngrabEvent();
- void touchUngrabEvent();
-
- void addTouchPrototype(QQuickTouchPoint* prototype);
- void addTouchPoint(const QTouchEvent::TouchPoint *p);
- void clearTouchLists();
-
- void updateTouchPoint(QQuickTouchPoint*, const QTouchEvent::TouchPoint*);
- void updateTouchData(QEvent*);
-
- bool sendMouseEvent(QMouseEvent *event);
- bool shouldFilter(QEvent *event);
- void grabGesture();
-
-private:
- void ungrab();
- QMap<int,QQuickTouchPoint*> _touchPrototypes; //TouchPoints defined in QML
- QMap<int,QObject*> _touchPoints; //All current touch points
- QList<QObject*> _releasedTouchPoints;
- QList<QObject*> _pressedTouchPoints;
- QList<QObject*> _movedTouchPoints;
- int _minimumTouchPoints;
- int _maximumTouchPoints;
- bool _stealMouse;
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickTouchPoint)
-QML_DECLARE_TYPE(QQuickGrabGestureEvent)
-QML_DECLARE_TYPE(QQuickMultiPointTouchArea)
-
-QT_END_HEADER
-
-#endif // QQUICKMULTIPOINTTOUCHAREA_H
diff --git a/src/declarative/items/qquickninepatchnode.cpp b/src/declarative/items/qquickninepatchnode.cpp
deleted file mode 100644
index 2974725348..0000000000
--- a/src/declarative/items/qquickninepatchnode.cpp
+++ /dev/null
@@ -1,302 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickninepatchnode_p.h"
-#include <private/qsgadaptationlayer_p.h>
-#include <private/qmath_p.h>
-
-QQuickNinePatchNode::QQuickNinePatchNode()
- : m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 0)
- , m_horizontalTileMode(QQuickBorderImage::Stretch)
- , m_verticalTileMode(QQuickBorderImage::Stretch)
- , m_dirtyGeometry(false)
- , m_mirror(false)
-{
- setOpaqueMaterial(&m_material);
- setMaterial(&m_materialO);
- setGeometry(&m_geometry);
- m_geometry.setDrawingMode(GL_TRIANGLES);
-#ifdef QML_RUNTIME_TESTING
- description = QLatin1String("borderimage");
-#endif
-}
-
-void QQuickNinePatchNode::setInnerRect(const QRectF &rect)
-{
- if (m_innerRect == rect)
- return;
- m_innerRect = rect;
- m_dirtyGeometry = true;
-}
-
-void QQuickNinePatchNode::setRect(const QRectF &rect)
-{
- if (m_targetRect == rect)
- return;
- m_targetRect = rect;
- m_dirtyGeometry = true;
-}
-
-void QQuickNinePatchNode::setHorzontalTileMode(QQuickBorderImage::TileMode mode)
-{
- if (mode == QQuickBorderImage::TileMode(m_horizontalTileMode))
- return;
- m_horizontalTileMode = mode;
- m_dirtyGeometry = true;
-}
-
-
-void QQuickNinePatchNode::setVerticalTileMode(QQuickBorderImage::TileMode mode)
-{
- if (mode == QQuickBorderImage::TileMode(m_verticalTileMode))
- return;
- m_verticalTileMode = mode;
- m_dirtyGeometry = true;
-}
-
-
-void QQuickNinePatchNode::setFiltering(QSGTexture::Filtering filtering)
-{
- if (m_material.filtering() == filtering)
- return;
-
- m_material.setFiltering(filtering);
- m_materialO.setFiltering(filtering);
- markDirty(DirtyMaterial);
-}
-
-QSGTexture::Filtering QQuickNinePatchNode::filtering() const
-{
- return m_material.filtering();
-}
-
-void QQuickNinePatchNode::setTexture(QSGTexture *texture)
-{
- if (texture == m_material.texture())
- return;
- m_material.setTexture(texture);
- m_materialO.setTexture(texture);
- markDirty(DirtyMaterial);
-}
-
-QSGTexture *QQuickNinePatchNode::texture() const
-{
- return m_material.texture();
-}
-
-void QQuickNinePatchNode::setMirror(bool m)
-{
- if (m_mirror == m)
- return;
- m_mirror = m;
- m_dirtyGeometry = true;
-}
-
-
-void QQuickNinePatchNode::update()
-{
- if (!m_dirtyGeometry)
- return;
-
- // For stretch this algorithm could be simplified to use less vertices
- // as more vertices could be reused then, but I doubt its where our main
- // problem will lie. This way, we at least share the algorithm between all
-
- Q_ASSERT(m_material.texture());
-
- float tw = m_material.texture()->textureSize().width();
- float th = m_material.texture()->textureSize().height();
-
- QRectF textureSubRect = m_material.texture()->textureSubRect();
- QSize textureSize = m_material.texture()->textureSize();
-
- float rightBorder = tw - m_innerRect.right();
- float bottomBorder = th - m_innerRect.bottom();
-
-// qDebug() << m_innerRect << m_targetRect << m_horizontalTileMode << m_verticalTileMode;
-
- int xChunkCount = 0; // Number of chunks
- float xChunkSize = 0; // Size of chunk in pixels
- float xTexSize = m_innerRect.width(); // Size of the texture to stretch/tile
- float xSize = m_targetRect.width() - m_innerRect.left() - rightBorder; // Size of area to fill with chunks
-
- if (m_horizontalTileMode == QQuickBorderImage::Repeat) {
- xChunkCount = qCeil(xSize / xTexSize);
- xChunkSize = xTexSize;
- } else if (m_horizontalTileMode == QQuickBorderImage::Round) {
- xChunkCount = qCeil(xSize / xTexSize);
- qreal fullWidth = xChunkCount * xTexSize;
- xChunkSize = xTexSize * xSize / fullWidth;
- } else {
- xChunkCount = 1;
- xChunkSize = xSize;
- }
-
- int yChunkCount = 0;
- float yChunkSize = 0; // Relative to target rect.
- float yTexSize = m_innerRect.height(); // Size of the texture to stretch/tile
- float ySize = m_targetRect.height() - m_innerRect.top() - bottomBorder;
-
- if (m_verticalTileMode == QQuickBorderImage::Repeat) {
- yChunkCount = qCeil(ySize / yTexSize);
- yChunkSize = yTexSize;
- } else if (m_verticalTileMode == QQuickBorderImage::Round) {
- yChunkCount = qCeil(ySize / yTexSize);
- qreal fullHeight = yChunkCount * yTexSize;
- yChunkSize = yTexSize * ySize / fullHeight;
- } else {
- yChunkCount = 1;
- yChunkSize = ySize;
- }
-
- int xTotalChunkCount = xChunkCount + 2;
- int yTotalChunkCount = yChunkCount + 2;
-
- int totalChunkCount = xTotalChunkCount * yTotalChunkCount;
- int vertexCount = totalChunkCount * 4;
- int indexCount = totalChunkCount * 6;
-
- if (vertexCount != m_geometry.vertexCount() || indexCount != m_geometry.indexCount())
- m_geometry.allocate(vertexCount, indexCount);
-
- QSGGeometry::TexturedPoint2D *v = m_geometry.vertexDataAsTexturedPoint2D();
-
-
- // Fill in the vertices.. The loop below is pretty much an exact replica
- // of the one inside fillRow.
- float yTexChunk1 = m_innerRect.top() / th;
- float yTexChunk2 = m_innerRect.bottom() / th;
-
- fillRow(v, 0, 0, xChunkCount, xChunkSize, textureSubRect, textureSize);
- fillRow(v, m_innerRect.y(), yTexChunk1, xChunkCount, xChunkSize, textureSubRect, textureSize);
-
- for (int yc=0; yc<yChunkCount; ++yc) {
- float yy = m_innerRect.y() + yChunkSize * yc;
- fillRow(v, yy, yTexChunk1, xChunkCount, xChunkSize, textureSubRect, textureSize);
-
- // Special case the last one
- if (yc == yChunkCount - 1) {
- float t = m_verticalTileMode == QQuickBorderImage::Repeat
- ? yTexChunk1 + (yTexChunk2 - yTexChunk1) * (m_targetRect.height() - bottomBorder - yy) / yChunkSize
- : yTexChunk2;
- fillRow(v, m_targetRect.height() - bottomBorder, t, xChunkCount, xChunkSize, textureSubRect, textureSize);
- } else {
- fillRow(v, yy + yChunkSize, yTexChunk2, xChunkCount, xChunkSize, textureSubRect, textureSize);
- }
- }
-
- fillRow(v, m_targetRect.height() - bottomBorder, yTexChunk2, xChunkCount, xChunkSize, textureSubRect, textureSize);
- fillRow(v, m_targetRect.height(), 1, xChunkCount, xChunkSize, textureSubRect, textureSize);
-
- if (m_mirror) {
- v = m_geometry.vertexDataAsTexturedPoint2D();
- for (int i=0; i<m_geometry.vertexCount(); ++i) {
- v->x = m_targetRect.width() - v->x;
- ++v;
- }
- }
-
-// v = m_geometry.vertexDataAsTexturedPoint2D();
-// for (int i=0; i<m_geometry.vertexCount(); ++i) {
-// printf("Vertex: %d: (%.3f, %.3f) - (%.3f, %.3f)\n",
-// i,
-// v->x, v->y, v->tx, v->ty);
-// ++v;
-// }
-
- quint16 *i = m_geometry.indexDataAsUShort();
- int row = xTotalChunkCount * 2;
- for (int r=0; r<yTotalChunkCount; ++r) {
- int offset = r * row * 2;
- for (int c=0; c<xTotalChunkCount; ++c) {
- *i++ = offset + c * 2;
- *i++ = offset + c * 2 + 1;
- *i++ = offset + c * 2 + row;
- *i++ = offset + c * 2 + 1;
- *i++ = offset + c * 2 + row + 1;
- *i++ = offset + c * 2 + row;
- }
- }
-
-// i = m_geometry.indexDataAsUShort();
-// for (int idx=0; idx<m_geometry.indexCount(); idx+=6) {
-// printf("%2d: ", idx / 6);
-// for (int s=0; s<6; ++s)
-// printf(" %d", i[idx + s]);
-// printf("\n");
-// }
-
- markDirty(QSGNode::DirtyGeometry);
-}
-
-void QQuickNinePatchNode::fillRow(QSGGeometry::TexturedPoint2D *&v, float y, float ty, int xChunkCount, float xChunkSize,
- const QRectF &tsr, // texture sub rect, for atlasses
- const QSize &ts) // texture size in pixels
-{
- ty = tsr.y() + ty * tsr.width();
-
- float tw = ts.width();
- float rightBorder = tw - m_innerRect.right();
- float xTexChunk1 = tsr.left() + tsr.width() * m_innerRect.left() / tw;
- float xTexChunk2 = tsr.left() + tsr.width() * m_innerRect.right() / tw;
-
- v++->set(0, y, tsr.left(), ty);
- v++->set(m_innerRect.x(), y, xTexChunk1, ty);
-
- for (int xc=0; xc<xChunkCount; ++xc) {
- float xx = m_innerRect.x() + xChunkSize * xc;
- v++->set(xx, y, xTexChunk1, ty);
-
- // Special case the last one
- if (xc == xChunkCount - 1) {
- float t = m_horizontalTileMode == QQuickBorderImage::Repeat
- ? xTexChunk1 + (xTexChunk2 - xTexChunk1) * (m_targetRect.width() - rightBorder - xx) / xChunkSize
- : xTexChunk2;
- v->set(m_targetRect.width() - rightBorder, y, t, ty);
- } else {
- v->set(xx + xChunkSize, y, xTexChunk2, ty);
- }
- ++v;
- }
-
- v++->set(m_targetRect.width() - rightBorder, y, xTexChunk2, ty);
- v++->set(m_targetRect.width(), y, tsr.right(), ty);
-}
diff --git a/src/declarative/items/qquickninepatchnode_p.h b/src/declarative/items/qquickninepatchnode_p.h
deleted file mode 100644
index cdb0fd8e70..0000000000
--- a/src/declarative/items/qquickninepatchnode_p.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKNINEPATCHNODE_H
-#define QQUICKNINEPATCHNODE_H
-
-#include "qsgnode.h"
-#include "qsgtexturematerial.h"
-#include "qquickborderimage_p.h"
-
-class TextureReference;
-
-class QQuickNinePatchNode : public QSGGeometryNode
-{
-public:
- QQuickNinePatchNode();
-
- void setTexture(QSGTexture *texture);
- QSGTexture *texture() const;
-
- void setRect(const QRectF &rect);
- QRectF rect() const { return m_targetRect; }
-
- void setInnerRect(const QRectF &rect);
- QRectF innerRect() const { return m_innerRect; }
-
- void setFiltering(QSGTexture::Filtering filtering);
- QSGTexture::Filtering filtering() const;
-
- void setHorzontalTileMode(QQuickBorderImage::TileMode mode);
- QQuickBorderImage::TileMode horizontalTileMode() const {
- return (QQuickBorderImage::TileMode) m_horizontalTileMode;
- }
-
- void setVerticalTileMode(QQuickBorderImage::TileMode mode);
- QQuickBorderImage::TileMode verticalTileMode() const {
- return (QQuickBorderImage::TileMode) m_verticalTileMode;
- }
-
- void setMirror(bool m);
- bool mirror() const { return m_mirror; }
-
- void update();
-
-private:
- void fillRow(QSGGeometry::TexturedPoint2D *&v, float y, float ty, int xChunkCount, float xChunkSize, const QRectF &tsr, const QSize &ts);
- QRectF m_targetRect;
- QRectF m_innerRect;
- QSGOpaqueTextureMaterial m_material;
- QSGTextureMaterial m_materialO;
- QSGGeometry m_geometry;
-
- uint m_horizontalTileMode : 2;
- uint m_verticalTileMode : 2;
-
- uint m_dirtyGeometry : 1;
- uint m_mirror : 1;
-};
-
-#endif // QQUICKNINEPATCHNODE_H
diff --git a/src/declarative/items/qquickpainteditem.cpp b/src/declarative/items/qquickpainteditem.cpp
deleted file mode 100644
index 4d96da2e1a..0000000000
--- a/src/declarative/items/qquickpainteditem.cpp
+++ /dev/null
@@ -1,528 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickpainteditem.h"
-#include <private/qquickpainteditem_p.h>
-
-#include <private/qsgpainternode_p.h>
-#include <private/qsgcontext_p.h>
-#include <private/qsgadaptationlayer_p.h>
-
-#include <qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QQuickPaintedItem
- \brief The QQuickPaintedItem class provides a way to use the QPainter API in the
- QML Scene Graph.
-
- \inmodule QtDeclarative
-
- The QQuickPaintedItem makes it possible to use the QPainter API with the QML Scene Graph.
- It sets up a textured rectangle in the Scene Graph and uses a QPainter to paint
- onto the texture. The render target can be either a QImage or a QOpenGLFramebufferObject.
- When the render target is a QImage, QPainter first renders into the image then
- the content is uploaded to the texture.
- When a QOpenGLFramebufferObject is used, QPainter paints directly onto the texture.
- Call update() to trigger a repaint.
-
- To enable QPainter to do anti-aliased rendering, use setAntialiasing().
-
- QQuickPaintedItem is meant to make it easier to port old code that is using the
- QPainter API to the QML Scene Graph API and it should be used only for that purpose.
-
- To write your own painted item, you first create a subclass of QQuickPaintedItem, and then
- start by implementing its only pure virtual public function: paint(), which implements
- the actual painting. To get the size of the area painted by the item, use
- contentsBoundingRect().
-*/
-
-/*!
- \enum QQuickPaintedItem::RenderTarget
-
- This enum describes QQuickPaintedItem's render targets. The render target is the
- surface QPainter paints onto before the item is rendered on screen.
-
- \value Image The default; QPainter paints into a QImage using the raster paint engine.
- The image's content needs to be uploaded to graphics memory afterward, this operation
- can potentially be slow if the item is large. This render target allows high quality
- anti-aliasing and fast item resizing.
-
- \value FramebufferObject QPainter paints into a QOpenGLFramebufferObject using the GL
- paint engine. Painting can be faster as no texture upload is required, but anti-aliasing
- quality is not as good as if using an image. This render target allows faster rendering
- in some cases, but you should avoid using it if the item is resized often.
-
- \value InvertedYFramebufferObject Exactly as for FramebufferObject above, except once
- the painting is done, prior to rendering the painted image is flipped about the
- x-axis so that the top-most pixels are now at the bottom. Since this is done with the
- OpenGL texture coordinates it is a much faster way to achieve this effect than using a
- painter transform.
-
- \sa setRenderTarget()
-*/
-
-/*!
- \enum QQuickPaintedItem::PerformanceHint
-
- This enum describes flags that you can enable to improve rendering
- performance in QQuickPaintedItem. By default, none of these flags are set.
-
- \value FastFBOResizing If your item gets resized often and you are using the
- QQuickPaintedItem::FramebufferObject render target, set this flag to true to reduce the
- item resizing time at the cost of using more graphics memory. Resizing a Framebuffer object
- is a costly operation, by enabling this property the Framebuffer Object will use a texture
- larger than the actual size of the item to avoid as much as possible resizing it.
-*/
-
-/*!
- \internal
-*/
-QQuickPaintedItemPrivate::QQuickPaintedItemPrivate()
- : QQuickItemPrivate()
- , contentsScale(1.0)
- , fillColor(Qt::transparent)
- , renderTarget(QQuickPaintedItem::Image)
- , performanceHints(0)
- , opaquePainting(false)
- , antialiasing(false)
- , mipmap(false)
-{
-}
-
-/*!
- Constructs a QQuickPaintedItem with the given \a parent item.
- */
-QQuickPaintedItem::QQuickPaintedItem(QQuickItem *parent)
- : QQuickItem(*(new QQuickPaintedItemPrivate), parent)
-{
- setFlag(ItemHasContents);
-}
-
-/*!
- \internal
-*/
-QQuickPaintedItem::QQuickPaintedItem(QQuickPaintedItemPrivate &dd, QQuickItem *parent)
- : QQuickItem(dd, parent)
-{
- setFlag(ItemHasContents);
-}
-
-/*!
- Destroys the QQuickPaintedItem.
-*/
-QQuickPaintedItem::~QQuickPaintedItem()
-{
-}
-
-/*!
- Schedules a redraw of the area covered by \a rect in this item. You can call this function
- whenever your item needs to be redrawn, such as if it changes appearance or size.
-
- This function does not cause an immediate paint; instead it schedules a paint request that
- is processed by the QML Scene Graph when the next frame is rendered. The item will only be
- redrawn if it is visible.
-
- Note that calling this function will trigger a repaint of the whole scene.
-
- \sa paint()
-*/
-void QQuickPaintedItem::update(const QRect &rect)
-{
- Q_D(QQuickPaintedItem);
-
- if (rect.isNull() && !d->dirtyRect.isNull())
- d->dirtyRect = contentsBoundingRect().toAlignedRect();
- else
- d->dirtyRect |= (contentsBoundingRect() & rect).toAlignedRect();
- QQuickItem::update();
-}
-
-/*!
- Returns true if this item is opaque; otherwise, false is returned.
-
- By default, painted items are not opaque.
-
- \sa setOpaquePainting()
-*/
-bool QQuickPaintedItem::opaquePainting() const
-{
- Q_D(const QQuickPaintedItem);
- return d->opaquePainting;
-}
-
-/*!
- If \a opaque is true, the item is opaque; otherwise, it is considered as translucent.
-
- Opaque items are not blended with the rest of the scene, you should set this to true
- if the content of the item is opaque to speed up rendering.
-
- By default, painted items are not opaque.
-
- \sa opaquePainting()
-*/
-void QQuickPaintedItem::setOpaquePainting(bool opaque)
-{
- Q_D(QQuickPaintedItem);
-
- if (d->opaquePainting == opaque)
- return;
-
- d->opaquePainting = opaque;
- QQuickItem::update();
-}
-
-/*!
- Returns true if antialiased painting is enabled; otherwise, false is returned.
-
- By default, antialiasing is not enabled.
-
- \sa setAntialiasing()
-*/
-bool QQuickPaintedItem::antialiasing() const
-{
- Q_D(const QQuickPaintedItem);
- return d->antialiasing;
-}
-
-/*!
- If \a enable is true, antialiased painting is enabled.
-
- By default, antialiasing is not enabled.
-
- \sa antialiasing()
-*/
-void QQuickPaintedItem::setAntialiasing(bool enable)
-{
- Q_D(QQuickPaintedItem);
-
- if (d->antialiasing == enable)
- return;
-
- d->antialiasing = enable;
- update();
-}
-
-/*!
- Returns true if mipmaps are enabled; otherwise, false is returned.
-
- By default, mipmapping is not enabled.
-
- \sa setMipmap()
-*/
-bool QQuickPaintedItem::mipmap() const
-{
- Q_D(const QQuickPaintedItem);
- return d->mipmap;
-}
-
-/*!
- If \a enable is true, mipmapping is enabled on the associated texture.
-
- Mipmapping increases rendering speed and reduces aliasing artifacts when the item is
- scaled down.
-
- By default, mipmapping is not enabled.
-
- \sa mipmap()
-*/
-void QQuickPaintedItem::setMipmap(bool enable)
-{
- Q_D(QQuickPaintedItem);
-
- if (d->mipmap == enable)
- return;
-
- d->mipmap = enable;
- update();
-}
-
-/*!
- Returns the performance hints.
-
- By default, no performance hint is enabled/
-
- \sa setPerformanceHint(), setPerformanceHints()
-*/
-QQuickPaintedItem::PerformanceHints QQuickPaintedItem::performanceHints() const
-{
- Q_D(const QQuickPaintedItem);
- return d->performanceHints;
-}
-
-/*!
- Sets the given performance \a hint on the item if \a enabled is true;
- otherwise clears the performance hint.
-
- By default, no performance hint is enabled/
-
- \sa setPerformanceHints(), performanceHints()
-*/
-void QQuickPaintedItem::setPerformanceHint(QQuickPaintedItem::PerformanceHint hint, bool enabled)
-{
- Q_D(QQuickPaintedItem);
- PerformanceHints oldHints = d->performanceHints;
- if (enabled)
- d->performanceHints |= hint;
- else
- d->performanceHints &= ~hint;
- if (oldHints != d->performanceHints)
- update();
-}
-
-/*!
- Sets the performance hints to \a hints
-
- By default, no performance hint is enabled/
-
- \sa setPerformanceHint(), performanceHints()
-*/
-void QQuickPaintedItem::setPerformanceHints(QQuickPaintedItem::PerformanceHints hints)
-{
- Q_D(QQuickPaintedItem);
- if (d->performanceHints == hints)
- return;
- d->performanceHints = hints;
- update();
-}
-
-/*!
- This function returns the outer bounds of the item as a rectangle; all painting must be
- restricted to inside an item's bounding rect.
-
- If the contents size has not been set it reflects the size of the item; otherwise
- it reflects the contents size scaled by the contents scale.
-
- Use this function to know the area painted by the item.
-
- \sa QQuickItem::width(), QQuickItem::height(), contentsSize(), contentsScale()
-*/
-QRectF QQuickPaintedItem::contentsBoundingRect() const
-{
- Q_D(const QQuickPaintedItem);
-
- qreal w = d->width;
- QSizeF sz = d->contentsSize * d->contentsScale;
- if (w < sz.width())
- w = sz.width();
- qreal h = d->height;
- if (h < sz.height())
- h = sz.height();
-
- return QRectF(0, 0, w, h);
-}
-
-/*!
- \property QQuickPaintedItem::contentsSize
- \brief The size of the contents
-
- The contents size is the size of the item in regards to how it is painted
- using the paint() function. This is distinct from the size of the
- item in regards to height() and width().
-*/
-QSize QQuickPaintedItem::contentsSize() const
-{
- Q_D(const QQuickPaintedItem);
- return d->contentsSize;
-}
-
-void QQuickPaintedItem::setContentsSize(const QSize &size)
-{
- Q_D(QQuickPaintedItem);
-
- if (d->contentsSize == size)
- return;
-
- d->contentsSize = size;
- update();
-}
-
-/*!
- This convenience function is equivalent to calling setContentsSize(QSize()).
-*/
-void QQuickPaintedItem::resetContentsSize()
-{
- setContentsSize(QSize());
-}
-
-/*!
- \property QQuickPaintedItem::contentsScale
- \brief The scale of the contents
-
- All painting happening in paint() is scaled by the contents scale. This is distinct
- from the scale of the item in regards to scale().
-
- The default value is 1.
-*/
-qreal QQuickPaintedItem::contentsScale() const
-{
- Q_D(const QQuickPaintedItem);
- return d->contentsScale;
-}
-
-void QQuickPaintedItem::setContentsScale(qreal scale)
-{
- Q_D(QQuickPaintedItem);
-
- if (d->contentsScale == scale)
- return;
-
- d->contentsScale = scale;
- update();
-}
-
-/*!
- \property QQuickPaintedItem::fillColor
- \brief The item's background fill color.
-
- By default, the fill color is set to Qt::transparent.
-*/
-QColor QQuickPaintedItem::fillColor() const
-{
- Q_D(const QQuickPaintedItem);
- return d->fillColor;
-}
-
-void QQuickPaintedItem::setFillColor(const QColor &c)
-{
- Q_D(QQuickPaintedItem);
-
- if (d->fillColor == c)
- return;
-
- d->fillColor = c;
- update();
-
- emit fillColorChanged();
-}
-
-/*!
- \property QQuickPaintedItem::renderTarget
- \brief The item's render target.
-
- This property defines which render target the QPainter renders into, it can be either
- QSGPaintedItem::Image, QSGPaintedItem::FramebufferObject or QSGPaintedItem::InvertedYFramebufferObject.
-
- Each has certain benefits, typically performance versus quality. Using a framebuffer
- object avoids a costly upload of the image contents to the texture in graphics memory,
- while using an image enables high quality anti-aliasing.
-
- \warning Resizing a framebuffer object is a costly operation, avoid using
- the QQuickPaintedItem::FramebufferObject render target if the item gets resized often.
-
- By default, the render target is QQuickPaintedItem::Image.
-*/
-QQuickPaintedItem::RenderTarget QQuickPaintedItem::renderTarget() const
-{
- Q_D(const QQuickPaintedItem);
- return d->renderTarget;
-}
-
-void QQuickPaintedItem::setRenderTarget(RenderTarget target)
-{
- Q_D(QQuickPaintedItem);
-
- if (d->renderTarget == target)
- return;
-
- d->renderTarget = target;
- update();
-
- emit renderTargetChanged();
-}
-
-/*!
- \fn virtual void QQuickPaintedItem::paint(QPainter *painter) = 0
-
- This function, which is usually called by the QML Scene Graph, paints the
- contents of an item in local coordinates.
-
- The function is called after the item has been filled with the fillColor.
-
- Reimplement this function in a QQuickPaintedItem subclass to provide the
- item's painting implementation, using \a painter.
-
- \note The QML Scene Graph uses two separate threads, the main thread does things such as
- processing events or updating animations while a second thread does the actual OpenGL rendering.
- As a consequence, paint() is not called from the main GUI thread but from the GL enabled
- renderer thread. At the moment paint() is called, the GUI thread is blocked and this is
- therefore thread-safe.
-*/
-
-/*!
- This function is called when the Scene Graph node associated to the item needs to
- be updated.
-*/
-QSGNode *QQuickPaintedItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
-{
- Q_UNUSED(data);
- Q_D(QQuickPaintedItem);
-
- if (width() <= 0 || height() <= 0) {
- delete oldNode;
- return 0;
- }
-
- QSGPainterNode *node = static_cast<QSGPainterNode *>(oldNode);
- if (!node)
- node = new QSGPainterNode(this);
-
- QRectF br = contentsBoundingRect();
-
- node->setPreferredRenderTarget(d->renderTarget);
- node->setFastFBOResizing(d->performanceHints & FastFBOResizing);
- node->setSize(QSize(qRound(br.width()), qRound(br.height())));
- node->setSmoothPainting(d->antialiasing);
- node->setLinearFiltering(d->smooth);
- node->setMipmapping(d->mipmap);
- node->setOpaquePainting(d->opaquePainting);
- node->setFillColor(d->fillColor);
- node->setContentsScale(d->contentsScale);
- node->setDirty(d->dirtyRect);
- node->update();
-
- d->dirtyRect = QRect();
-
- return node;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickpainteditem.h b/src/declarative/items/qquickpainteditem.h
deleted file mode 100644
index b2da9e6c7a..0000000000
--- a/src/declarative/items/qquickpainteditem.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKPAINTEDITEM_P_H
-#define QQUICKPAINTEDITEM_P_H
-
-#include <qquickitem.h>
-#include <QtGui/qcolor.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-class QQuickPaintedItemPrivate;
-class Q_DECLARATIVE_EXPORT QQuickPaintedItem : public QQuickItem
-{
- Q_OBJECT
- Q_ENUMS(RenderTarget)
-
- Q_PROPERTY(QSize contentsSize READ contentsSize WRITE setContentsSize NOTIFY contentsSizeChanged)
- Q_PROPERTY(QColor fillColor READ fillColor WRITE setFillColor NOTIFY fillColorChanged)
- Q_PROPERTY(qreal contentsScale READ contentsScale WRITE setContentsScale NOTIFY contentsScaleChanged)
- Q_PROPERTY(RenderTarget renderTarget READ renderTarget WRITE setRenderTarget NOTIFY renderTargetChanged)
-public:
- QQuickPaintedItem(QQuickItem *parent = 0);
- virtual ~QQuickPaintedItem();
-
- enum RenderTarget {
- Image,
- FramebufferObject,
- InvertedYFramebufferObject
- };
-
- enum PerformanceHint {
- FastFBOResizing = 0x1
- };
- Q_DECLARE_FLAGS(PerformanceHints, PerformanceHint)
-
- void update(const QRect &rect = QRect());
-
- bool opaquePainting() const;
- void setOpaquePainting(bool opaque);
-
- bool antialiasing() const;
- void setAntialiasing(bool enable);
-
- bool mipmap() const;
- void setMipmap(bool enable);
-
- PerformanceHints performanceHints() const;
- void setPerformanceHint(PerformanceHint hint, bool enabled = true);
- void setPerformanceHints(PerformanceHints hints);
-
- QRectF contentsBoundingRect() const;
-
- QSize contentsSize() const;
- void setContentsSize(const QSize &);
- void resetContentsSize();
-
- qreal contentsScale() const;
- void setContentsScale(qreal);
-
- QColor fillColor() const;
- void setFillColor(const QColor&);
-
- RenderTarget renderTarget() const;
- void setRenderTarget(RenderTarget target);
-
- virtual void paint(QPainter *painter) = 0;
-
-Q_SIGNALS:
- void fillColorChanged();
- void contentsSizeChanged();
- void contentsScaleChanged();
- void renderTargetChanged();
-
-protected:
- QQuickPaintedItem(QQuickPaintedItemPrivate &dd, QQuickItem *parent = 0);
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
-
-private:
- Q_DISABLE_COPY(QQuickPaintedItem)
- Q_DECLARE_PRIVATE(QQuickPaintedItem)
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QQuickPaintedItem::PerformanceHints)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKPAINTEDITEM_P_H
diff --git a/src/declarative/items/qquickpainteditem_p.h b/src/declarative/items/qquickpainteditem_p.h
deleted file mode 100644
index b847b0a4ef..0000000000
--- a/src/declarative/items/qquickpainteditem_p.h
+++ /dev/null
@@ -1,71 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKPAINTEDITEM_P_P_H
-#define QQUICKPAINTEDITEM_P_P_H
-
-#include "qquickitem_p.h"
-#include <QtGui/qcolor.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickPaintedItemPrivate : public QQuickItemPrivate
-{
-public:
- QQuickPaintedItemPrivate();
-
- QSize contentsSize;
- qreal contentsScale;
- QColor fillColor;
- QQuickPaintedItem::RenderTarget renderTarget;
- QQuickPaintedItem::PerformanceHints performanceHints;
-
- QRect dirtyRect;
-
- bool opaquePainting: 1;
- bool antialiasing: 1;
- bool mipmap: 1;
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKPAINTEDITEM_P_P_H
diff --git a/src/declarative/items/qquickpathview.cpp b/src/declarative/items/qquickpathview.cpp
deleted file mode 100644
index f262562edf..0000000000
--- a/src/declarative/items/qquickpathview.cpp
+++ /dev/null
@@ -1,1781 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickpathview_p.h"
-#include "qquickpathview_p_p.h"
-#include "qquickcanvas.h"
-
-#include <private/qdeclarativestate_p.h>
-#include <private/qdeclarativeopenmetaobject_p.h>
-#include <private/qlistmodelinterface_p.h>
-#include <private/qdeclarativechangeset_p.h>
-
-#include <QtGui/qevent.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qguiapplication.h>
-#include <QtGui/qstylehints.h>
-#include <QtCore/qmath.h>
-#include <math.h>
-
-QT_BEGIN_NAMESPACE
-
-inline qreal qmlMod(qreal x, qreal y)
-{
-#ifdef QT_USE_MATH_H_FLOATS
- if (sizeof(qreal) == sizeof(float))
- return fmodf(float(x), float(y));
- else
-#endif
- return fmod(x, y);
-}
-
-static QDeclarativeOpenMetaObjectType *qPathViewAttachedType = 0;
-
-QQuickPathViewAttached::QQuickPathViewAttached(QObject *parent)
-: QObject(parent), m_percent(-1), m_view(0), m_onPath(false), m_isCurrent(false)
-{
- if (qPathViewAttachedType) {
- m_metaobject = new QDeclarativeOpenMetaObject(this, qPathViewAttachedType);
- m_metaobject->setCached(true);
- } else {
- m_metaobject = new QDeclarativeOpenMetaObject(this);
- }
-}
-
-QQuickPathViewAttached::~QQuickPathViewAttached()
-{
-}
-
-QVariant QQuickPathViewAttached::value(const QByteArray &name) const
-{
- return m_metaobject->value(name);
-}
-void QQuickPathViewAttached::setValue(const QByteArray &name, const QVariant &val)
-{
- m_metaobject->setValue(name, val);
-}
-
-
-void QQuickPathViewPrivate::init()
-{
- Q_Q(QQuickPathView);
- offset = 0;
- q->setAcceptedMouseButtons(Qt::LeftButton);
- q->setFlag(QQuickItem::ItemIsFocusScope);
- q->setFiltersChildMouseEvents(true);
- FAST_CONNECT(&tl, SIGNAL(updated()), q, SLOT(ticked()))
- lastPosTime.invalidate();
- FAST_CONNECT(&tl, SIGNAL(completed()), q, SLOT(movementEnding()))
-}
-
-QQuickItem *QQuickPathViewPrivate::getItem(int modelIndex, qreal z, bool onPath)
-{
- Q_Q(QQuickPathView);
- requestedIndex = modelIndex;
- requestedOnPath = onPath;
- requestedZ = z;
- inRequest = true;
- QQuickItem *item = model->item(modelIndex, false);
- if (item) {
- QDeclarative_setParent_noEvent(item, q);
- item->setParentItem(q);
- requestedIndex = -1;
- qPathViewAttachedType = attType;
- QQuickPathViewAttached *att = static_cast<QQuickPathViewAttached *>(qmlAttachedPropertiesObject<QQuickPathView>(item));
- qPathViewAttachedType = 0;
- if (att)
- att->setOnPath(onPath);
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
- itemPrivate->addItemChangeListener(this, QQuickItemPrivate::Geometry);
- }
- inRequest = false;
- return item;
-}
-
-void QQuickPathView::createdItem(int index, QQuickItem *item)
-{
- Q_D(QQuickPathView);
- if (d->requestedIndex != index) {
- qPathViewAttachedType = d->attachedType();
- QQuickPathViewAttached *att = static_cast<QQuickPathViewAttached *>(qmlAttachedPropertiesObject<QQuickPathView>(item));
- qPathViewAttachedType = 0;
- if (att) {
- att->m_view = this;
- att->setOnPath(false);
- }
- item->setParentItem(this);
- QDeclarative_setParent_noEvent(item, this);
- d->updateItem(item, index < d->firstIndex ? 0.0 : 1.0);
- } else {
- d->requestedIndex = -1;
- if (!d->inRequest)
- refill();
- }
-}
-
-void QQuickPathView::initItem(int index, QQuickItem *item)
-{
- Q_D(QQuickPathView);
- if (d->requestedIndex == index) {
- item->setParentItem(this);
- qPathViewAttachedType = d->attachedType();
- QQuickPathViewAttached *att = static_cast<QQuickPathViewAttached *>(qmlAttachedPropertiesObject<QQuickPathView>(item));
- qPathViewAttachedType = 0;
- if (att) {
- att->m_view = this;
- qreal percent = d->positionOfIndex(index);
- foreach (const QString &attr, d->path->attributes())
- att->setValue(attr.toUtf8(), d->path->attributeAt(attr, percent));
- item->setZ(d->requestedZ);
- if (att)
- att->setOnPath(d->requestedOnPath);
- }
- }
-}
-
-void QQuickPathViewPrivate::releaseItem(QQuickItem *item)
-{
- if (!item || !model)
- return;
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
- itemPrivate->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
- if (model->release(item) == 0) {
- // item was not destroyed, and we no longer reference it.
- if (QQuickPathViewAttached *att = attached(item))
- att->setOnPath(false);
- }
-}
-
-QQuickPathViewAttached *QQuickPathViewPrivate::attached(QQuickItem *item)
-{
- return static_cast<QQuickPathViewAttached *>(qmlAttachedPropertiesObject<QQuickPathView>(item, false));
-}
-
-QDeclarativeOpenMetaObjectType *QQuickPathViewPrivate::attachedType()
-{
- Q_Q(QQuickPathView);
- if (!attType) {
- // pre-create one metatype to share with all attached objects
- attType = new QDeclarativeOpenMetaObjectType(&QQuickPathViewAttached::staticMetaObject, qmlEngine(q));
- foreach (const QString &attr, path->attributes())
- attType->createProperty(attr.toUtf8());
- }
-
- return attType;
-}
-
-void QQuickPathViewPrivate::clear()
-{
- if (currentItem) {
- releaseItem(currentItem);
- currentItem = 0;
- }
- for (int i=0; i<items.count(); i++){
- QQuickItem *p = items[i];
- releaseItem(p);
- }
- items.clear();
-}
-
-void QQuickPathViewPrivate::updateMappedRange()
-{
- if (model && pathItems != -1 && pathItems < modelCount)
- mappedRange = qreal(pathItems)/modelCount;
- else
- mappedRange = 1.0;
-}
-
-qreal QQuickPathViewPrivate::positionOfIndex(qreal index) const
-{
- qreal pos = -1.0;
-
- if (model && index >= 0 && index < modelCount) {
- qreal start = 0.0;
- if (haveHighlightRange && highlightRangeMode != QQuickPathView::NoHighlightRange)
- start = highlightRangeStart;
- qreal globalPos = index + offset;
- globalPos = qmlMod(globalPos, qreal(modelCount)) / modelCount;
- if (pathItems != -1 && pathItems < modelCount) {
- globalPos += start * mappedRange;
- globalPos = qmlMod(globalPos, 1.0);
- if (globalPos < mappedRange)
- pos = globalPos / mappedRange;
- } else {
- pos = qmlMod(globalPos + start, 1.0);
- }
- }
-
- return pos;
-}
-
-void QQuickPathViewPrivate::createHighlight()
-{
- Q_Q(QQuickPathView);
- if (!q->isComponentComplete())
- return;
-
- bool changed = false;
- if (highlightItem) {
- highlightItem->setParentItem(0);
- highlightItem->deleteLater();
- highlightItem = 0;
- changed = true;
- }
-
- QQuickItem *item = 0;
- if (highlightComponent) {
- QDeclarativeContext *creationContext = highlightComponent->creationContext();
- QDeclarativeContext *highlightContext = new QDeclarativeContext(
- creationContext ? creationContext : qmlContext(q));
- QObject *nobj = highlightComponent->create(highlightContext);
- if (nobj) {
- QDeclarative_setParent_noEvent(highlightContext, nobj);
- item = qobject_cast<QQuickItem *>(nobj);
- if (!item)
- delete nobj;
- } else {
- delete highlightContext;
- }
- } else {
- item = new QQuickItem;
- }
- if (item) {
- QDeclarative_setParent_noEvent(item, q);
- item->setParentItem(q);
- highlightItem = item;
- changed = true;
- }
- if (changed)
- emit q->highlightItemChanged();
-}
-
-void QQuickPathViewPrivate::updateHighlight()
-{
- Q_Q(QQuickPathView);
- if (!q->isComponentComplete() || !isValid())
- return;
- if (highlightItem) {
- if (haveHighlightRange && highlightRangeMode == QQuickPathView::StrictlyEnforceRange) {
- updateItem(highlightItem, highlightRangeStart);
- } else {
- qreal target = currentIndex;
-
- offsetAdj = 0.0;
- tl.reset(moveHighlight);
- moveHighlight.setValue(highlightPosition);
-
- const int duration = highlightMoveDuration;
-
- if (target - highlightPosition > modelCount/2) {
- highlightUp = false;
- qreal distance = modelCount - target + highlightPosition;
- tl.move(moveHighlight, 0.0, QEasingCurve(QEasingCurve::InQuad), int(duration * highlightPosition / distance));
- tl.set(moveHighlight, modelCount-0.01);
- tl.move(moveHighlight, target, QEasingCurve(QEasingCurve::OutQuad), int(duration * (modelCount-target) / distance));
- } else if (target - highlightPosition <= -modelCount/2) {
- highlightUp = true;
- qreal distance = modelCount - highlightPosition + target;
- tl.move(moveHighlight, modelCount-0.01, QEasingCurve(QEasingCurve::InQuad), int(duration * (modelCount-highlightPosition) / distance));
- tl.set(moveHighlight, 0.0);
- tl.move(moveHighlight, target, QEasingCurve(QEasingCurve::OutQuad), int(duration * target / distance));
- } else {
- highlightUp = highlightPosition - target < 0;
- tl.move(moveHighlight, target, QEasingCurve(QEasingCurve::InOutQuad), duration);
- }
- }
- }
-}
-
-void QQuickPathViewPrivate::setHighlightPosition(qreal pos)
-{
- if (pos != highlightPosition) {
- qreal start = 0.0;
- qreal end = 1.0;
- if (haveHighlightRange && highlightRangeMode != QQuickPathView::NoHighlightRange) {
- start = highlightRangeStart;
- end = highlightRangeEnd;
- }
-
- qreal range = qreal(modelCount);
- // calc normalized position of highlight relative to offset
- qreal relativeHighlight = qmlMod(pos + offset, range) / range;
-
- if (!highlightUp && relativeHighlight > end * mappedRange) {
- qreal diff = 1.0 - relativeHighlight;
- setOffset(offset + diff * range);
- } else if (highlightUp && relativeHighlight >= (end - start) * mappedRange) {
- qreal diff = relativeHighlight - (end - start) * mappedRange;
- setOffset(offset - diff * range - 0.00001);
- }
-
- highlightPosition = pos;
- qreal pathPos = positionOfIndex(pos);
- updateItem(highlightItem, pathPos);
- if (QQuickPathViewAttached *att = attached(highlightItem))
- att->setOnPath(pathPos != -1.0);
- }
-}
-
-void QQuickPathView::pathUpdated()
-{
- Q_D(QQuickPathView);
- QList<QQuickItem*>::iterator it = d->items.begin();
- while (it != d->items.end()) {
- QQuickItem *item = *it;
- if (QQuickPathViewAttached *att = d->attached(item))
- att->m_percent = -1;
- ++it;
- }
- refill();
-}
-
-void QQuickPathViewPrivate::updateItem(QQuickItem *item, qreal percent)
-{
- if (QQuickPathViewAttached *att = attached(item)) {
- if (qFuzzyCompare(att->m_percent, percent))
- return;
- att->m_percent = percent;
- foreach (const QString &attr, path->attributes())
- att->setValue(attr.toUtf8(), path->attributeAt(attr, percent));
- }
- QPointF pf = path->pointAt(percent);
- item->setX(qRound(pf.x() - item->width()/2));
- item->setY(qRound(pf.y() - item->height()/2));
-}
-
-void QQuickPathViewPrivate::regenerate()
-{
- Q_Q(QQuickPathView);
- if (!q->isComponentComplete())
- return;
-
- clear();
-
- if (!isValid())
- return;
-
- firstIndex = -1;
- updateMappedRange();
- q->refill();
-}
-
-/*!
- \qmlclass PathView QQuickPathView
- \inqmlmodule QtQuick 2
- \ingroup qml-view-elements
- \brief The PathView element lays out model-provided items on a path.
- \inherits Item
-
- A PathView displays data from models created from built-in QML elements like ListModel
- and XmlListModel, or custom model classes defined in C++ that inherit from
- QAbstractListModel.
-
- The view has a \l model, which defines the data to be displayed, and
- a \l delegate, which defines how the data should be displayed.
- The \l delegate is instantiated for each item on the \l path.
- The items may be flicked to move them along the path.
-
- For example, if there is a simple list model defined in a file \c ContactModel.qml like this:
-
- \snippet doc/src/snippets/declarative/pathview/ContactModel.qml 0
-
- This data can be represented as a PathView, like this:
-
- \snippet doc/src/snippets/declarative/pathview/pathview.qml 0
-
- \image pathview.gif
-
- (Note the above example uses PathAttribute to scale and modify the
- opacity of the items as they rotate. This additional code can be seen in the
- PathAttribute documentation.)
-
- PathView does not automatically handle keyboard navigation. This is because
- the keys to use for navigation will depend upon the shape of the path. Navigation
- can be added quite simply by setting \c focus to \c true and calling
- \l decrementCurrentIndex() or \l incrementCurrentIndex(), for example to navigate
- using the left and right arrow keys:
-
- \qml
- PathView {
- // ...
- focus: true
- Keys.onLeftPressed: decrementCurrentIndex()
- Keys.onRightPressed: incrementCurrentIndex()
- }
- \endqml
-
- The path view itself is a focus scope (see \l{qmlfocus#Acquiring Focus and Focus Scopes}{the focus documentation page} for more details).
-
- Delegates are instantiated as needed and may be destroyed at any time.
- State should \e never be stored in a delegate.
-
- PathView attaches a number of properties to the root item of the delegate, for example
- \c {PathView.isCurrentItem}. In the following example, the root delegate item can access
- this attached property directly as \c PathView.isCurrentItem, while the child
- \c nameText object must refer to this property as \c wrapper.PathView.isCurrentItem.
-
- \snippet doc/src/snippets/declarative/pathview/pathview.qml 1
-
- \bold Note that views do not enable \e clip automatically. If the view
- is not clipped by another item or the screen, it will be necessary
- to set \e {clip: true} in order to have the out of view items clipped
- nicely.
-
- \sa Path, {declarative/modelviews/pathview}{PathView example}
-*/
-
-QQuickPathView::QQuickPathView(QQuickItem *parent)
- : QQuickItem(*(new QQuickPathViewPrivate), parent)
-{
- Q_D(QQuickPathView);
- d->init();
-}
-
-QQuickPathView::~QQuickPathView()
-{
- Q_D(QQuickPathView);
- d->clear();
- if (d->attType)
- d->attType->release();
- if (d->ownModel)
- delete d->model;
-}
-
-/*!
- \qmlattachedproperty PathView QtQuick2::PathView::view
- This attached property holds the view that manages this delegate instance.
-
- It is attached to each instance of the delegate.
-*/
-
-/*!
- \qmlattachedproperty bool QtQuick2::PathView::onPath
- This attached property holds whether the item is currently on the path.
-
- If a pathItemCount has been set, it is possible that some items may
- be instantiated, but not considered to be currently on the path.
- Usually, these items would be set invisible, for example:
-
- \qml
- Component {
- Rectangle {
- visible: PathView.onPath
- // ...
- }
- }
- \endqml
-
- It is attached to each instance of the delegate.
-*/
-
-/*!
- \qmlattachedproperty bool QtQuick2::PathView::isCurrentItem
- This attached property is true if this delegate is the current item; otherwise false.
-
- It is attached to each instance of the delegate.
-
- This property may be used to adjust the appearance of the current item.
-
- \snippet doc/src/snippets/declarative/pathview/pathview.qml 1
-*/
-
-/*!
- \qmlproperty model QtQuick2::PathView::model
- This property holds the model providing data for the view.
-
- The model provides a set of data that is used to create the items for the view.
- For large or dynamic datasets the model is usually provided by a C++ model object.
- Models can also be created directly in QML, using the ListModel element.
-
- \sa {qmlmodels}{Data Models}
-*/
-QVariant QQuickPathView::model() const
-{
- Q_D(const QQuickPathView);
- return d->modelVariant;
-}
-
-void QQuickPathView::setModel(const QVariant &model)
-{
- Q_D(QQuickPathView);
- if (d->modelVariant == model)
- return;
-
- if (d->model) {
- disconnect(d->model, SIGNAL(modelUpdated(QDeclarativeChangeSet,bool)),
- this, SLOT(modelUpdated(QDeclarativeChangeSet,bool)));
- disconnect(d->model, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(createdItem(int,QQuickItem*)));
- disconnect(d->model, SIGNAL(initItem(int,QQuickItem*)), this, SLOT(initItem(int,QQuickItem*)));
- for (int i=0; i<d->items.count(); i++){
- QQuickItem *p = d->items[i];
- d->releaseItem(p);
- }
- d->items.clear();
- }
-
- d->modelVariant = model;
- QObject *object = qvariant_cast<QObject*>(model);
- QQuickVisualModel *vim = 0;
- if (object && (vim = qobject_cast<QQuickVisualModel *>(object))) {
- if (d->ownModel) {
- delete d->model;
- d->ownModel = false;
- }
- d->model = vim;
- } else {
- if (!d->ownModel) {
- d->model = new QQuickVisualDataModel(qmlContext(this));
- d->ownModel = true;
- if (isComponentComplete())
- static_cast<QQuickVisualDataModel *>(d->model.data())->componentComplete();
- }
- if (QQuickVisualDataModel *dataModel = qobject_cast<QQuickVisualDataModel*>(d->model))
- dataModel->setModel(model);
- }
- d->modelCount = 0;
- if (d->model) {
- connect(d->model, SIGNAL(modelUpdated(QDeclarativeChangeSet,bool)),
- this, SLOT(modelUpdated(QDeclarativeChangeSet,bool)));
- connect(d->model, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(createdItem(int,QQuickItem*)));
- connect(d->model, SIGNAL(initItem(int,QQuickItem*)), this, SLOT(initItem(int,QQuickItem*)));
- d->modelCount = d->model->count();
- if (d->model->count())
- d->offset = qmlMod(d->offset, qreal(d->model->count()));
- if (d->offset < 0)
- d->offset = d->model->count() + d->offset;
-}
- d->regenerate();
- if (d->currentIndex < d->modelCount)
- setOffset(qmlMod(d->modelCount - d->currentIndex, d->modelCount));
- else
- d->fixOffset();
- emit countChanged();
- emit modelChanged();
-}
-
-/*!
- \qmlproperty int QtQuick2::PathView::count
- This property holds the number of items in the model.
-*/
-int QQuickPathView::count() const
-{
- Q_D(const QQuickPathView);
- return d->model ? d->modelCount : 0;
-}
-
-/*!
- \qmlproperty Path QtQuick2::PathView::path
- This property holds the path used to lay out the items.
- For more information see the \l Path documentation.
-*/
-QDeclarativePath *QQuickPathView::path() const
-{
- Q_D(const QQuickPathView);
- return d->path;
-}
-
-void QQuickPathView::setPath(QDeclarativePath *path)
-{
- Q_D(QQuickPathView);
- if (d->path == path)
- return;
- if (d->path)
- disconnect(d->path, SIGNAL(changed()), this, SLOT(pathUpdated()));
- d->path = path;
- connect(d->path, SIGNAL(changed()), this, SLOT(pathUpdated()));
- if (d->isValid() && isComponentComplete()) {
- d->clear();
- if (d->attType) {
- d->attType->release();
- d->attType = 0;
- }
- d->regenerate();
- }
- emit pathChanged();
-}
-
-/*!
- \qmlproperty int QtQuick2::PathView::currentIndex
- This property holds the index of the current item.
-*/
-int QQuickPathView::currentIndex() const
-{
- Q_D(const QQuickPathView);
- return d->currentIndex;
-}
-
-void QQuickPathView::setCurrentIndex(int idx)
-{
- Q_D(QQuickPathView);
- if (d->model && d->modelCount)
- idx = qAbs(idx % d->modelCount);
- if (d->model && (idx != d->currentIndex || !d->currentItem)) {
- if (d->currentItem) {
- if (QQuickPathViewAttached *att = d->attached(d->currentItem))
- att->setIsCurrentItem(false);
- d->releaseItem(d->currentItem);
- }
- int oldCurrentIdx = d->currentIndex;
- QQuickItem *oldCurrentItem = d->currentItem;
- d->currentItem = 0;
- d->moveReason = QQuickPathViewPrivate::SetIndex;
- d->currentIndex = idx;
- if (d->modelCount) {
- d->createCurrentItem();
- if (d->haveHighlightRange && d->highlightRangeMode == QQuickPathView::StrictlyEnforceRange)
- d->snapToCurrent();
- d->currentItemOffset = d->positionOfIndex(d->currentIndex);
- d->updateHighlight();
- }
- if (oldCurrentIdx != d->currentIndex)
- emit currentIndexChanged();
- if (oldCurrentItem != d->currentItem)
- emit currentItemChanged();
- }
-}
-
-QQuickItem *QQuickPathView::currentItem() const
-{
- Q_D(const QQuickPathView);
- return d->currentItem;
-}
-
-/*!
- \qmlmethod QtQuick2::PathView::incrementCurrentIndex()
-
- Increments the current index.
-
- \bold Note: methods should only be called after the Component has completed.
-*/
-void QQuickPathView::incrementCurrentIndex()
-{
- Q_D(QQuickPathView);
- d->moveDirection = QQuickPathViewPrivate::Positive;
- setCurrentIndex(currentIndex()+1);
-}
-
-/*!
- \qmlmethod QtQuick2::PathView::decrementCurrentIndex()
-
- Decrements the current index.
-
- \bold Note: methods should only be called after the Component has completed.
-*/
-void QQuickPathView::decrementCurrentIndex()
-{
- Q_D(QQuickPathView);
- if (d->model && d->modelCount) {
- int idx = currentIndex()-1;
- if (idx < 0)
- idx = d->modelCount - 1;
- d->moveDirection = QQuickPathViewPrivate::Negative;
- setCurrentIndex(idx);
- }
-}
-
-/*!
- \qmlproperty real QtQuick2::PathView::offset
-
- The offset specifies how far along the path the items are from their initial positions.
- This is a real number that ranges from 0.0 to the count of items in the model.
-*/
-qreal QQuickPathView::offset() const
-{
- Q_D(const QQuickPathView);
- return d->offset;
-}
-
-void QQuickPathView::setOffset(qreal offset)
-{
- Q_D(QQuickPathView);
- d->setOffset(offset);
- d->updateCurrent();
-}
-
-void QQuickPathViewPrivate::setOffset(qreal o)
-{
- Q_Q(QQuickPathView);
- if (offset != o) {
- if (isValid() && q->isComponentComplete()) {
- offset = qmlMod(o, qreal(modelCount));
- if (offset < 0)
- offset += qreal(modelCount);
- q->refill();
- } else {
- offset = o;
- }
- emit q->offsetChanged();
- }
-}
-
-void QQuickPathViewPrivate::setAdjustedOffset(qreal o)
-{
- setOffset(o+offsetAdj);
-}
-
-/*!
- \qmlproperty Component QtQuick2::PathView::highlight
- This property holds the component to use as the highlight.
-
- An instance of the highlight component will be created for each view.
- The geometry of the resultant component instance will be managed by the view
- so as to stay with the current item.
-
- The below example demonstrates how to make a simple highlight. Note the use
- of the \l{PathView::onPath}{PathView.onPath} attached property to ensure that
- the highlight is hidden when flicked away from the path.
-
- \qml
- Component {
- Rectangle {
- visible: PathView.onPath
- // ...
- }
- }
- \endqml
-
- \sa highlightItem, highlightRangeMode
-*/
-
-QDeclarativeComponent *QQuickPathView::highlight() const
-{
- Q_D(const QQuickPathView);
- return d->highlightComponent;
-}
-
-void QQuickPathView::setHighlight(QDeclarativeComponent *highlight)
-{
- Q_D(QQuickPathView);
- if (highlight != d->highlightComponent) {
- d->highlightComponent = highlight;
- d->createHighlight();
- d->updateHighlight();
- emit highlightChanged();
- }
-}
-
-/*!
- \qmlproperty Item QtQuick2::PathView::highlightItem
-
- \c highlightItem holds the highlight item, which was created
- from the \l highlight component.
-
- \sa highlight
-*/
-QQuickItem *QQuickPathView::highlightItem()
-{
- Q_D(const QQuickPathView);
- return d->highlightItem;
-}
-/*!
- \qmlproperty real QtQuick2::PathView::preferredHighlightBegin
- \qmlproperty real QtQuick2::PathView::preferredHighlightEnd
- \qmlproperty enumeration QtQuick2::PathView::highlightRangeMode
-
- These properties set the preferred range of the highlight (current item)
- within the view. The preferred values must be in the range 0.0-1.0.
-
- If highlightRangeMode is set to \e PathView.NoHighlightRange
-
- If highlightRangeMode is set to \e PathView.ApplyRange the view will
- attempt to maintain the highlight within the range, however
- the highlight can move outside of the range at the ends of the path
- or due to a mouse interaction.
-
- If highlightRangeMode is set to \e PathView.StrictlyEnforceRange the highlight will never
- move outside of the range. This means that the current item will change
- if a keyboard or mouse action would cause the highlight to move
- outside of the range.
-
- Note that this is the correct way to influence where the
- current item ends up when the view moves. For example, if you want the
- currently selected item to be in the middle of the path, then set the
- highlight range to be 0.5,0.5 and highlightRangeMode to PathView.StrictlyEnforceRange.
- Then, when the path scrolls,
- the currently selected item will be the item at that position. This also applies to
- when the currently selected item changes - it will scroll to within the preferred
- highlight range. Furthermore, the behaviour of the current item index will occur
- whether or not a highlight exists.
-
- The default value is \e PathView.StrictlyEnforceRange.
-
- Note that a valid range requires preferredHighlightEnd to be greater
- than or equal to preferredHighlightBegin.
-*/
-qreal QQuickPathView::preferredHighlightBegin() const
-{
- Q_D(const QQuickPathView);
- return d->highlightRangeStart;
-}
-
-void QQuickPathView::setPreferredHighlightBegin(qreal start)
-{
- Q_D(QQuickPathView);
- if (d->highlightRangeStart == start || start < 0 || start > 1.0)
- return;
- d->highlightRangeStart = start;
- d->haveHighlightRange = d->highlightRangeMode != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd;
- refill();
- emit preferredHighlightBeginChanged();
-}
-
-qreal QQuickPathView::preferredHighlightEnd() const
-{
- Q_D(const QQuickPathView);
- return d->highlightRangeEnd;
-}
-
-void QQuickPathView::setPreferredHighlightEnd(qreal end)
-{
- Q_D(QQuickPathView);
- if (d->highlightRangeEnd == end || end < 0 || end > 1.0)
- return;
- d->highlightRangeEnd = end;
- d->haveHighlightRange = d->highlightRangeMode != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd;
- refill();
- emit preferredHighlightEndChanged();
-}
-
-QQuickPathView::HighlightRangeMode QQuickPathView::highlightRangeMode() const
-{
- Q_D(const QQuickPathView);
- return d->highlightRangeMode;
-}
-
-void QQuickPathView::setHighlightRangeMode(HighlightRangeMode mode)
-{
- Q_D(QQuickPathView);
- if (d->highlightRangeMode == mode)
- return;
- d->highlightRangeMode = mode;
- d->haveHighlightRange = d->highlightRangeMode != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd;
- if (d->haveHighlightRange) {
- d->regenerate();
- d->snapToCurrent();
- }
- emit highlightRangeModeChanged();
-}
-
-/*!
- \qmlproperty int QtQuick2::PathView::highlightMoveDuration
- This property holds the move animation duration of the highlight delegate.
-
- If the highlightRangeMode is StrictlyEnforceRange then this property
- determines the speed that the items move along the path.
-
- The default value for the duration is 300ms.
-*/
-int QQuickPathView::highlightMoveDuration() const
-{
- Q_D(const QQuickPathView);
- return d->highlightMoveDuration;
-}
-
-void QQuickPathView::setHighlightMoveDuration(int duration)
-{
- Q_D(QQuickPathView);
- if (d->highlightMoveDuration == duration)
- return;
- d->highlightMoveDuration = duration;
- emit highlightMoveDurationChanged();
-}
-
-/*!
- \qmlproperty real QtQuick2::PathView::dragMargin
- This property holds the maximum distance from the path that initiate mouse dragging.
-
- By default the path can only be dragged by clicking on an item. If
- dragMargin is greater than zero, a drag can be initiated by clicking
- within dragMargin pixels of the path.
-*/
-qreal QQuickPathView::dragMargin() const
-{
- Q_D(const QQuickPathView);
- return d->dragMargin;
-}
-
-void QQuickPathView::setDragMargin(qreal dragMargin)
-{
- Q_D(QQuickPathView);
- if (d->dragMargin == dragMargin)
- return;
- d->dragMargin = dragMargin;
- emit dragMarginChanged();
-}
-
-/*!
- \qmlproperty real QtQuick2::PathView::flickDeceleration
- This property holds the rate at which a flick will decelerate.
-
- The default is 100.
-*/
-qreal QQuickPathView::flickDeceleration() const
-{
- Q_D(const QQuickPathView);
- return d->deceleration;
-}
-
-void QQuickPathView::setFlickDeceleration(qreal dec)
-{
- Q_D(QQuickPathView);
- if (d->deceleration == dec)
- return;
- d->deceleration = dec;
- emit flickDecelerationChanged();
-}
-
-/*!
- \qmlproperty bool QtQuick2::PathView::interactive
-
- A user cannot drag or flick a PathView that is not interactive.
-
- This property is useful for temporarily disabling flicking. This allows
- special interaction with PathView's children.
-*/
-bool QQuickPathView::isInteractive() const
-{
- Q_D(const QQuickPathView);
- return d->interactive;
-}
-
-void QQuickPathView::setInteractive(bool interactive)
-{
- Q_D(QQuickPathView);
- if (interactive != d->interactive) {
- d->interactive = interactive;
- if (!interactive)
- d->tl.clear();
- emit interactiveChanged();
- }
-}
-
-/*!
- \qmlproperty bool QtQuick2::PathView::moving
-
- This property holds whether the view is currently moving
- due to the user either dragging or flicking the view.
-*/
-bool QQuickPathView::isMoving() const
-{
- Q_D(const QQuickPathView);
- return d->moving;
-}
-
-/*!
- \qmlproperty bool QtQuick2::PathView::flicking
-
- This property holds whether the view is currently moving
- due to the user flicking the view.
-*/
-bool QQuickPathView::isFlicking() const
-{
- Q_D(const QQuickPathView);
- return d->flicking;
-}
-
-/*!
- \qmlsignal QtQuick2::PathView::onMovementStarted()
-
- This handler is called when the view begins moving due to user
- interaction.
-*/
-
-/*!
- \qmlsignal QtQuick2::PathView::onMovementEnded()
-
- This handler is called when the view stops moving due to user
- interaction. If a flick was generated, this handler will
- be triggered once the flick stops. If a flick was not
- generated, the handler will be triggered when the
- user stops dragging - i.e. a mouse or touch release.
-*/
-
-/*!
- \qmlsignal QtQuick2::PathView::onFlickStarted()
-
- This handler is called when the view is flicked. A flick
- starts from the point that the mouse or touch is released,
- while still in motion.
-*/
-
-/*!
- \qmlsignal QtQuick2::PathView::onFlickEnded()
-
- This handler is called when the view stops moving due to a flick.
-*/
-
-/*!
- \qmlproperty Component QtQuick2::PathView::delegate
-
- The delegate provides a template defining each item instantiated by the view.
- The index is exposed as an accessible \c index property. Properties of the
- model are also available depending upon the type of \l {qmlmodels}{Data Model}.
-
- The number of elements in the delegate has a direct effect on the
- flicking performance of the view when pathItemCount is specified. If at all possible, place functionality
- that is not needed for the normal display of the delegate in a \l Loader which
- can load additional elements when needed.
-
- Note that the PathView will layout the items based on the size of the root
- item in the delegate.
-
- Here is an example delegate:
- \snippet doc/src/snippets/declarative/pathview/pathview.qml 1
-*/
-QDeclarativeComponent *QQuickPathView::delegate() const
-{
- Q_D(const QQuickPathView);
- if (d->model) {
- if (QQuickVisualDataModel *dataModel = qobject_cast<QQuickVisualDataModel*>(d->model))
- return dataModel->delegate();
- }
-
- return 0;
-}
-
-void QQuickPathView::setDelegate(QDeclarativeComponent *delegate)
-{
- Q_D(QQuickPathView);
- if (delegate == this->delegate())
- return;
- if (!d->ownModel) {
- d->model = new QQuickVisualDataModel(qmlContext(this));
- d->ownModel = true;
- }
- if (QQuickVisualDataModel *dataModel = qobject_cast<QQuickVisualDataModel*>(d->model)) {
- int oldCount = dataModel->count();
- dataModel->setDelegate(delegate);
- d->modelCount = dataModel->count();
- d->regenerate();
- if (oldCount != dataModel->count())
- emit countChanged();
- emit delegateChanged();
- }
-}
-
-/*!
- \qmlproperty int QtQuick2::PathView::pathItemCount
- This property holds the number of items visible on the path at any one time.
-*/
-int QQuickPathView::pathItemCount() const
-{
- Q_D(const QQuickPathView);
- return d->pathItems;
-}
-
-void QQuickPathView::setPathItemCount(int i)
-{
- Q_D(QQuickPathView);
- if (i == d->pathItems)
- return;
- if (i < 1)
- i = 1;
- d->pathItems = i;
- d->updateMappedRange();
- if (d->isValid() && isComponentComplete()) {
- d->regenerate();
- }
- emit pathItemCountChanged();
-}
-
-QPointF QQuickPathViewPrivate::pointNear(const QPointF &point, qreal *nearPercent) const
-{
- //XXX maybe do recursively at increasing resolution.
- qreal mindist = 1e10; // big number
- QPointF nearPoint = path->pointAt(0);
- qreal nearPc = 0;
- for (qreal i=1; i < 1000; i++) {
- QPointF pt = path->pointAt(i/1000.0);
- QPointF diff = pt - point;
- qreal dist = diff.x()*diff.x() + diff.y()*diff.y();
- if (dist < mindist) {
- nearPoint = pt;
- nearPc = i;
- mindist = dist;
- }
- }
-
- if (nearPercent)
- *nearPercent = nearPc / 1000.0;
-
- return nearPoint;
-}
-
-void QQuickPathView::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QQuickPathView);
- if (d->interactive) {
- d->handleMousePressEvent(event);
- event->accept();
- } else {
- QQuickItem::mousePressEvent(event);
- }
-}
-
-void QQuickPathViewPrivate::handleMousePressEvent(QMouseEvent *event)
-{
- Q_Q(QQuickPathView);
- if (!interactive || !items.count())
- return;
- QPointF scenePoint = q->mapToScene(event->localPos());
- int idx = 0;
- for (; idx < items.count(); ++idx) {
- QRectF rect = items.at(idx)->boundingRect();
- rect = items.at(idx)->mapRectToScene(rect);
- if (rect.contains(scenePoint))
- break;
- }
- if (idx == items.count() && dragMargin == 0.) // didn't click on an item
- return;
-
- startPoint = pointNear(event->localPos(), &startPc);
- if (idx == items.count()) {
- qreal distance = qAbs(event->localPos().x() - startPoint.x()) + qAbs(event->localPos().y() - startPoint.y());
- if (distance > dragMargin)
- return;
- }
-
- if (tl.isActive() && flicking)
- stealMouse = true; // If we've been flicked then steal the click.
- else
- stealMouse = false;
-
- lastElapsed = 0;
- lastDist = 0;
- QQuickItemPrivate::start(lastPosTime);
- tl.clear();
-}
-
-void QQuickPathView::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QQuickPathView);
- if (d->interactive) {
- d->handleMouseMoveEvent(event);
- if (d->stealMouse)
- setKeepMouseGrab(true);
- event->accept();
- } else {
- QQuickItem::mouseMoveEvent(event);
- }
-}
-
-void QQuickPathViewPrivate::handleMouseMoveEvent(QMouseEvent *event)
-{
- Q_Q(QQuickPathView);
- if (!interactive || !lastPosTime.isValid())
- return;
-
- qreal newPc;
- QPointF pathPoint = pointNear(event->localPos(), &newPc);
- if (!stealMouse) {
- QPointF delta = pathPoint - startPoint;
- if (qAbs(delta.x()) > qApp->styleHints()->startDragDistance() || qAbs(delta.y()) > qApp->styleHints()->startDragDistance()) {
- stealMouse = true;
- startPc = newPc;
- }
- }
-
- if (stealMouse) {
- moveReason = QQuickPathViewPrivate::Mouse;
- qreal diff = (newPc - startPc)*modelCount*mappedRange;
- if (diff) {
- q->setOffset(offset + diff);
-
- if (diff > modelCount/2)
- diff -= modelCount;
- else if (diff < -modelCount/2)
- diff += modelCount;
-
- lastElapsed = QQuickItemPrivate::restart(lastPosTime);
- lastDist = diff;
- startPc = newPc;
- }
- if (!moving) {
- moving = true;
- emit q->movingChanged();
- emit q->movementStarted();
- }
- }
-}
-
-void QQuickPathView::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QQuickPathView);
- if (d->interactive) {
- d->handleMouseReleaseEvent(event);
- event->accept();
- ungrabMouse();
- } else {
- QQuickItem::mouseReleaseEvent(event);
- }
-}
-
-void QQuickPathViewPrivate::handleMouseReleaseEvent(QMouseEvent *)
-{
- Q_Q(QQuickPathView);
- stealMouse = false;
- q->setKeepMouseGrab(false);
- if (!interactive || !lastPosTime.isValid())
- return;
-
- qreal elapsed = qreal(lastElapsed + QQuickItemPrivate::elapsed(lastPosTime)) / 1000.;
- qreal velocity = elapsed > 0. ? lastDist / elapsed : 0;
- if (model && modelCount && qAbs(velocity) > 1.) {
- qreal count = pathItems == -1 ? modelCount : pathItems;
- if (qAbs(velocity) > count * 2) // limit velocity
- velocity = (velocity > 0 ? count : -count) * 2;
- // Calculate the distance to be travelled
- qreal v2 = velocity*velocity;
- qreal accel = deceleration/10;
- // + 0.25 to encourage moving at least one item in the flick direction
- qreal dist = qMin(qreal(modelCount-1), qreal(v2 / (accel * 2.0) + 0.25));
- if (haveHighlightRange && highlightRangeMode == QQuickPathView::StrictlyEnforceRange) {
- // round to nearest item.
- if (velocity > 0.)
- dist = qRound(dist + offset) - offset;
- else
- dist = qRound(dist - offset) + offset;
- // Calculate accel required to stop on item boundary
- if (dist <= 0.) {
- dist = 0.;
- accel = 0.;
- } else {
- accel = v2 / (2.0f * qAbs(dist));
- }
- }
- offsetAdj = 0.0;
- moveOffset.setValue(offset);
- tl.accel(moveOffset, velocity, accel, dist);
- tl.callback(QDeclarativeTimeLineCallback(&moveOffset, fixOffsetCallback, this));
- if (!flicking) {
- flicking = true;
- emit q->flickingChanged();
- emit q->flickStarted();
- }
- } else {
- fixOffset();
- }
-
- lastPosTime.invalidate();
- if (!tl.isActive())
- q->movementEnding();
-}
-
-bool QQuickPathView::sendMouseEvent(QMouseEvent *event)
-{
- Q_D(QQuickPathView);
- QRectF myRect = mapRectToScene(QRectF(0, 0, width(), height()));
- QQuickCanvas *c = canvas();
- QQuickItem *grabber = c ? c->mouseGrabberItem() : 0;
- bool stealThisEvent = d->stealMouse;
- if ((stealThisEvent || myRect.contains(event->windowPos())) && (!grabber || !grabber->keepMouseGrab())) {
- QMouseEvent mouseEvent(event->type(), mapFromScene(event->windowPos()), event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers());
- mouseEvent.setAccepted(false);
-
- switch (mouseEvent.type()) {
- case QEvent::MouseMove:
- d->handleMouseMoveEvent(&mouseEvent);
- break;
- case QEvent::MouseButtonPress:
- d->handleMousePressEvent(&mouseEvent);
- stealThisEvent = d->stealMouse; // Update stealThisEvent in case changed by function call above
- break;
- case QEvent::MouseButtonRelease:
- d->handleMouseReleaseEvent(&mouseEvent);
- break;
- default:
- break;
- }
- grabber = c->mouseGrabberItem();
- if (grabber && stealThisEvent && !grabber->keepMouseGrab() && grabber != this)
- grabMouse();
-
- return d->stealMouse;
- } else if (d->lastPosTime.isValid()) {
- d->lastPosTime.invalidate();
- d->fixOffset();
- }
- if (event->type() == QEvent::MouseButtonRelease)
- d->stealMouse = false;
- return false;
-}
-
-bool QQuickPathView::childMouseEventFilter(QQuickItem *i, QEvent *e)
-{
- Q_D(QQuickPathView);
- if (!isVisible() || !d->interactive)
- return QQuickItem::childMouseEventFilter(i, e);
-
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease:
- return sendMouseEvent(static_cast<QMouseEvent *>(e));
- default:
- break;
- }
-
- return QQuickItem::childMouseEventFilter(i, e);
-}
-
-void QQuickPathView::mouseUngrabEvent()
-{
- Q_D(QQuickPathView);
- if (d->stealMouse) {
- // if our mouse grab has been removed (probably by a Flickable),
- // fix our state
- d->stealMouse = false;
- setKeepMouseGrab(false);
- d->lastPosTime.invalidate();
- }
-}
-
-void QQuickPathView::updatePolish()
-{
- QQuickItem::updatePolish();
- refill();
-}
-
-void QQuickPathView::componentComplete()
-{
- Q_D(QQuickPathView);
- if (d->model && d->ownModel)
- static_cast<QQuickVisualDataModel *>(d->model.data())->componentComplete();
-
- QQuickItem::componentComplete();
-
- d->createHighlight();
- // It is possible that a refill has already happended to to Path
- // bindings being handled in the componentComplete(). If so
- // don't do it again.
- if (d->items.count() == 0 && d->model) {
- d->modelCount = d->model->count();
- d->regenerate();
- }
- d->updateHighlight();
-
- if (d->modelCount)
- emit countChanged();
-}
-
-void QQuickPathView::refill()
-{
- Q_D(QQuickPathView);
- if (!d->isValid() || !isComponentComplete())
- return;
-
- d->layoutScheduled = false;
- bool currentVisible = false;
-
- // first move existing items and remove items off path
- int idx = d->firstIndex;
- QList<QQuickItem*>::iterator it = d->items.begin();
- while (it != d->items.end()) {
- qreal pos = d->positionOfIndex(idx);
- QQuickItem *item = *it;
- if (pos >= 0.0) {
- d->updateItem(item, pos);
- if (idx == d->currentIndex) {
- currentVisible = true;
- d->currentItemOffset = pos;
- }
- ++it;
- } else {
- // qDebug() << "release";
- d->updateItem(item, 1.0);
- d->releaseItem(item);
- if (it == d->items.begin()) {
- if (++d->firstIndex >= d->modelCount)
- d->firstIndex = 0;
- }
- it = d->items.erase(it);
- }
- ++idx;
- if (idx >= d->modelCount)
- idx = 0;
- }
- if (!d->items.count())
- d->firstIndex = -1;
-
- bool waiting = false;
- if (d->modelCount) {
- // add items to beginning and end
- int count = d->pathItems == -1 ? d->modelCount : qMin(d->pathItems, d->modelCount);
- if (d->items.count() < count) {
- int idx = qRound(d->modelCount - d->offset) % d->modelCount;
- qreal startPos = 0.0;
- if (d->haveHighlightRange && d->highlightRangeMode != QQuickPathView::NoHighlightRange)
- startPos = d->highlightRangeStart;
- if (d->firstIndex >= 0) {
- startPos = d->positionOfIndex(d->firstIndex);
- idx = (d->firstIndex + d->items.count()) % d->modelCount;
- }
- qreal pos = d->positionOfIndex(idx);
- while ((pos > startPos || !d->items.count()) && d->items.count() < count) {
-// qDebug() << "append" << idx;
- QQuickItem *item = d->getItem(idx, idx+1);
- if (!item) {
- waiting = true;
- break;
- }
- if (d->currentIndex == idx) {
- currentVisible = true;
- d->currentItemOffset = pos;
- }
- if (d->items.count() == 0)
- d->firstIndex = idx;
- d->items.append(item);
- d->updateItem(item, pos);
- ++idx;
- if (idx >= d->modelCount)
- idx = 0;
- pos = d->positionOfIndex(idx);
- }
-
- idx = d->firstIndex - 1;
- if (idx < 0)
- idx = d->modelCount - 1;
- pos = d->positionOfIndex(idx);
- while (!waiting && (pos >= 0.0 && pos < startPos) && d->items.count() < count) {
-// qDebug() << "prepend" << idx;
- QQuickItem *item = d->getItem(idx, idx+1);
- if (!item) {
- waiting = true;
- break;
- }
- if (d->currentIndex == idx) {
- currentVisible = true;
- d->currentItemOffset = pos;
- }
- d->items.prepend(item);
- d->updateItem(item, pos);
- d->firstIndex = idx;
- idx = d->firstIndex - 1;
- if (idx < 0)
- idx = d->modelCount - 1;
- pos = d->positionOfIndex(idx);
- }
- }
- }
-
- if (!currentVisible) {
- d->currentItemOffset = 1.0;
- if (d->currentItem) {
- if (QQuickPathViewAttached *att = d->attached(d->currentItem))
- att->setOnPath(false);
- } else if (!waiting && d->currentIndex >= 0 && d->currentIndex < d->modelCount) {
- if (d->currentItem = d->getItem(d->currentIndex, d->currentIndex, false)) {
- d->updateItem(d->currentItem, d->currentIndex < d->firstIndex ? 0.0 : 1.0);
- if (QQuickPathViewAttached *att = d->attached(d->currentItem))
- att->setIsCurrentItem(true);
- }
- }
- } else if (!waiting && !d->currentItem) {
- if (d->currentItem = d->getItem(d->currentIndex, d->currentIndex, true)) {
- d->currentItem->setFocus(true);
- if (QQuickPathViewAttached *att = d->attached(d->currentItem))
- att->setIsCurrentItem(true);
- }
- }
-
- if (d->highlightItem && d->haveHighlightRange && d->highlightRangeMode == QQuickPathView::StrictlyEnforceRange) {
- d->updateItem(d->highlightItem, d->highlightRangeStart);
- if (QQuickPathViewAttached *att = d->attached(d->highlightItem))
- att->setOnPath(true);
- } else if (d->highlightItem && d->moveReason != QQuickPathViewPrivate::SetIndex) {
- d->updateItem(d->highlightItem, d->currentItemOffset);
- if (QQuickPathViewAttached *att = d->attached(d->highlightItem))
- att->setOnPath(currentVisible);
- }
- while (d->itemCache.count())
- d->releaseItem(d->itemCache.takeLast());
-}
-
-void QQuickPathView::modelUpdated(const QDeclarativeChangeSet &changeSet, bool reset)
-{
- Q_D(QQuickPathView);
- if (!d->model || !d->model->isValid() || !d->path || !isComponentComplete())
- return;
-
- if (reset) {
- d->modelCount = d->model->count();
- d->regenerate();
- emit countChanged();
- return;
- }
-
- if (changeSet.removes().isEmpty() && changeSet.inserts().isEmpty())
- return;
-
- const int modelCount = d->modelCount;
- int moveId = -1;
- int moveOffset;
- bool currentChanged = false;
- bool changedOffset = false;
- foreach (const QDeclarativeChangeSet::Remove &r, changeSet.removes()) {
- if (moveId == -1 && d->currentIndex >= r.index + r.count) {
- d->currentIndex -= r.count;
- currentChanged = true;
- } else if (moveId == -1 && d->currentIndex >= r.index && d->currentIndex < r.index + r.count) {
- // current item has been removed.
- d->currentIndex = qMin(r.index, d->modelCount - r.count - 1);
- if (r.isMove()) {
- moveId = r.moveId;
- moveOffset = d->currentIndex - r.index;
- } else if (d->currentItem) {
- if (QQuickPathViewAttached *att = d->attached(d->currentItem))
- att->setIsCurrentItem(true);
- d->releaseItem(d->currentItem);
- d->currentItem = 0;
- }
- currentChanged = true;
- }
-
- if (r.index > d->currentIndex) {
- changedOffset = true;
- d->offset -= r.count;
- d->offsetAdj -= r.count;
- }
- d->modelCount -= r.count;
- }
- foreach (const QDeclarativeChangeSet::Insert &i, changeSet.inserts()) {
- if (d->modelCount) {
- if (moveId == -1 && i.index <= d->currentIndex) {
- d->currentIndex += i.count;
- currentChanged = true;
- } else {
- if (moveId != -1 && moveId == i.moveId) {
- d->currentIndex = i.index + moveOffset;
- currentChanged = true;
- }
- if (i.index > d->currentIndex) {
- d->offset += i.count;
- d->offsetAdj += i.count;
- changedOffset = true;
- }
- }
- }
- d->modelCount += i.count;
- }
-
- d->offset = qmlMod(d->offset, d->modelCount);
- if (d->offset < 0)
- d->offset += d->modelCount;
-
- d->itemCache += d->items;
- d->items.clear();
-
- if (!d->modelCount) {
- while (d->itemCache.count())
- d->releaseItem(d->itemCache.takeLast());
- d->offset = 0;
- changedOffset = true;
- d->tl.reset(d->moveOffset);
- } else {
- if (!d->flicking && !d->moving && d->haveHighlightRange && d->highlightRangeMode == QQuickPathView::StrictlyEnforceRange) {
- d->offset = qmlMod(d->modelCount - d->currentIndex, d->modelCount);
- changedOffset = true;
- }
- d->firstIndex = -1;
- d->updateMappedRange();
- d->scheduleLayout();
- }
- if (changedOffset)
- emit offsetChanged();
- if (currentChanged)
- emit currentIndexChanged();
- if (d->modelCount != modelCount)
- emit countChanged();
-}
-
-void QQuickPathView::destroyingItem(QQuickItem *item)
-{
- Q_UNUSED(item);
-}
-
-void QQuickPathView::ticked()
-{
- Q_D(QQuickPathView);
- d->updateCurrent();
-}
-
-void QQuickPathView::movementEnding()
-{
- Q_D(QQuickPathView);
- if (d->flicking) {
- d->flicking = false;
- emit flickingChanged();
- emit flickEnded();
- }
- if (d->moving && !d->stealMouse) {
- d->moving = false;
- emit movingChanged();
- emit movementEnded();
- }
-}
-
-// find the item closest to the snap position
-int QQuickPathViewPrivate::calcCurrentIndex()
-{
- int current = -1;
- if (modelCount && model && items.count()) {
- offset = qmlMod(offset, modelCount);
- if (offset < 0)
- offset += modelCount;
- current = qRound(qAbs(qmlMod(modelCount - offset, modelCount)));
- current = current % modelCount;
- }
-
- return current;
-}
-
-void QQuickPathViewPrivate::createCurrentItem()
-{
- if (requestedIndex != -1)
- return;
- int itemIndex = (currentIndex - firstIndex + modelCount) % modelCount;
- if (itemIndex < items.count()) {
- if (currentItem = getItem(currentIndex, currentIndex, true)) {
- currentItem->setFocus(true);
- if (QQuickPathViewAttached *att = attached(currentItem))
- att->setIsCurrentItem(true);
- }
- } else if (currentIndex >= 0 && currentIndex < modelCount) {
- if (currentItem = getItem(currentIndex, currentIndex, false)) {
- updateItem(currentItem, currentIndex < firstIndex ? 0.0 : 1.0);
- if (QQuickPathViewAttached *att = attached(currentItem))
- att->setIsCurrentItem(true);
- }
- }
-}
-
-void QQuickPathViewPrivate::updateCurrent()
-{
- Q_Q(QQuickPathView);
- if (moveReason != Mouse)
- return;
- if (!modelCount || !haveHighlightRange || highlightRangeMode != QQuickPathView::StrictlyEnforceRange)
- return;
-
- int idx = calcCurrentIndex();
- if (model && idx != currentIndex) {
- if (currentItem) {
- if (QQuickPathViewAttached *att = attached(currentItem))
- att->setIsCurrentItem(false);
- releaseItem(currentItem);
- }
- currentIndex = idx;
- currentItem = 0;
- createCurrentItem();
- emit q->currentIndexChanged();
- }
-}
-
-void QQuickPathViewPrivate::fixOffsetCallback(void *d)
-{
- ((QQuickPathViewPrivate *)d)->fixOffset();
-}
-
-void QQuickPathViewPrivate::fixOffset()
-{
- Q_Q(QQuickPathView);
- if (model && items.count()) {
- if (haveHighlightRange && highlightRangeMode == QQuickPathView::StrictlyEnforceRange) {
- int curr = calcCurrentIndex();
- if (curr != currentIndex)
- q->setCurrentIndex(curr);
- else
- snapToCurrent();
- }
- }
-}
-
-void QQuickPathViewPrivate::snapToCurrent()
-{
- if (!model || modelCount <= 0)
- return;
-
- qreal targetOffset = qmlMod(modelCount - currentIndex, modelCount);
-
- if (offset == targetOffset)
- return;
-
- moveReason = Other;
- offsetAdj = 0.0;
- tl.reset(moveOffset);
- moveOffset.setValue(offset);
-
- const int duration = highlightMoveDuration;
-
- if (!duration) {
- tl.set(moveOffset, targetOffset);
- } else if (moveDirection == Positive || (moveDirection == Shortest && targetOffset - offset > modelCount/2)) {
- qreal distance = modelCount - targetOffset + offset;
- if (targetOffset > moveOffset) {
- tl.move(moveOffset, 0.0, QEasingCurve(QEasingCurve::InQuad), int(duration * offset / distance));
- tl.set(moveOffset, modelCount);
- tl.move(moveOffset, targetOffset, QEasingCurve(offset == 0.0 ? QEasingCurve::InOutQuad : QEasingCurve::OutQuad), int(duration * (modelCount-targetOffset) / distance));
- } else {
- tl.move(moveOffset, targetOffset, QEasingCurve(QEasingCurve::InOutQuad), duration);
- }
- } else if (moveDirection == Negative || targetOffset - offset <= -modelCount/2) {
- qreal distance = modelCount - offset + targetOffset;
- if (targetOffset < moveOffset) {
- tl.move(moveOffset, modelCount, QEasingCurve(targetOffset == 0 ? QEasingCurve::InOutQuad : QEasingCurve::InQuad), int(duration * (modelCount-offset) / distance));
- tl.set(moveOffset, 0.0);
- tl.move(moveOffset, targetOffset, QEasingCurve(QEasingCurve::OutQuad), int(duration * targetOffset / distance));
- } else {
- tl.move(moveOffset, targetOffset, QEasingCurve(QEasingCurve::InOutQuad), duration);
- }
- } else {
- tl.move(moveOffset, targetOffset, QEasingCurve(QEasingCurve::InOutQuad), duration);
- }
- moveDirection = Shortest;
-}
-
-QQuickPathViewAttached *QQuickPathView::qmlAttachedProperties(QObject *obj)
-{
- return new QQuickPathViewAttached(obj);
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/items/qquickpathview_p.h b/src/declarative/items/qquickpathview_p.h
deleted file mode 100644
index ebc1587b09..0000000000
--- a/src/declarative/items/qquickpathview_p.h
+++ /dev/null
@@ -1,259 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKPATHVIEW_P_H
-#define QQUICKPATHVIEW_P_H
-
-#include "qquickitem.h"
-
-#include <private/qdeclarativepath_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeChangeSet;
-
-class QQuickPathViewPrivate;
-class QQuickPathViewAttached;
-class Q_AUTOTEST_EXPORT QQuickPathView : public QQuickItem
-{
- Q_OBJECT
-
- Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged)
- Q_PROPERTY(QDeclarativePath *path READ path WRITE setPath NOTIFY pathChanged)
- Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
- Q_PROPERTY(QQuickItem *currentItem READ currentItem NOTIFY currentItemChanged)
- Q_PROPERTY(qreal offset READ offset WRITE setOffset NOTIFY offsetChanged)
-
- Q_PROPERTY(QDeclarativeComponent *highlight READ highlight WRITE setHighlight NOTIFY highlightChanged)
- Q_PROPERTY(QQuickItem *highlightItem READ highlightItem NOTIFY highlightItemChanged)
-
- Q_PROPERTY(qreal preferredHighlightBegin READ preferredHighlightBegin WRITE setPreferredHighlightBegin NOTIFY preferredHighlightBeginChanged)
- Q_PROPERTY(qreal preferredHighlightEnd READ preferredHighlightEnd WRITE setPreferredHighlightEnd NOTIFY preferredHighlightEndChanged)
- Q_PROPERTY(HighlightRangeMode highlightRangeMode READ highlightRangeMode WRITE setHighlightRangeMode NOTIFY highlightRangeModeChanged)
- Q_PROPERTY(int highlightMoveDuration READ highlightMoveDuration WRITE setHighlightMoveDuration NOTIFY highlightMoveDurationChanged)
-
- Q_PROPERTY(qreal dragMargin READ dragMargin WRITE setDragMargin NOTIFY dragMarginChanged)
- Q_PROPERTY(qreal flickDeceleration READ flickDeceleration WRITE setFlickDeceleration NOTIFY flickDecelerationChanged)
- Q_PROPERTY(bool interactive READ isInteractive WRITE setInteractive NOTIFY interactiveChanged)
-
- Q_PROPERTY(bool moving READ isMoving NOTIFY movingChanged)
- Q_PROPERTY(bool flicking READ isFlicking NOTIFY flickingChanged)
-
- Q_PROPERTY(int count READ count NOTIFY countChanged)
- Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged)
- Q_PROPERTY(int pathItemCount READ pathItemCount WRITE setPathItemCount NOTIFY pathItemCountChanged)
-
- Q_ENUMS(HighlightRangeMode)
-
-public:
- QQuickPathView(QQuickItem *parent=0);
- virtual ~QQuickPathView();
-
- QVariant model() const;
- void setModel(const QVariant &);
-
- QDeclarativePath *path() const;
- void setPath(QDeclarativePath *);
-
- int currentIndex() const;
- void setCurrentIndex(int idx);
-
- QQuickItem *currentItem() const;
-
- qreal offset() const;
- void setOffset(qreal offset);
-
- QDeclarativeComponent *highlight() const;
- void setHighlight(QDeclarativeComponent *highlight);
- QQuickItem *highlightItem();
-
- enum HighlightRangeMode { NoHighlightRange, ApplyRange, StrictlyEnforceRange };
- HighlightRangeMode highlightRangeMode() const;
- void setHighlightRangeMode(HighlightRangeMode mode);
-
- qreal preferredHighlightBegin() const;
- void setPreferredHighlightBegin(qreal);
-
- qreal preferredHighlightEnd() const;
- void setPreferredHighlightEnd(qreal);
-
- int highlightMoveDuration() const;
- void setHighlightMoveDuration(int);
-
- qreal dragMargin() const;
- void setDragMargin(qreal margin);
-
- qreal flickDeceleration() const;
- void setFlickDeceleration(qreal dec);
-
- bool isInteractive() const;
- void setInteractive(bool);
-
- bool isMoving() const;
- bool isFlicking() const;
-
- int count() const;
-
- QDeclarativeComponent *delegate() const;
- void setDelegate(QDeclarativeComponent *);
-
- int pathItemCount() const;
- void setPathItemCount(int);
-
- static QQuickPathViewAttached *qmlAttachedProperties(QObject *);
-
-public Q_SLOTS:
- void incrementCurrentIndex();
- void decrementCurrentIndex();
-
-Q_SIGNALS:
- void currentIndexChanged();
- void currentItemChanged();
- void offsetChanged();
- void modelChanged();
- void countChanged();
- void pathChanged();
- void preferredHighlightBeginChanged();
- void preferredHighlightEndChanged();
- void highlightRangeModeChanged();
- void dragMarginChanged();
- void snapPositionChanged();
- void delegateChanged();
- void pathItemCountChanged();
- void flickDecelerationChanged();
- void interactiveChanged();
- void movingChanged();
- void flickingChanged();
- void highlightChanged();
- void highlightItemChanged();
- void highlightMoveDurationChanged();
- void movementStarted();
- void movementEnded();
- void flickStarted();
- void flickEnded();
-
-protected:
- virtual void updatePolish();
- void mousePressEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *);
- bool sendMouseEvent(QMouseEvent *event);
- bool childMouseEventFilter(QQuickItem *, QEvent *);
- void mouseUngrabEvent();
- void componentComplete();
-
-private Q_SLOTS:
- void refill();
- void ticked();
- void movementEnding();
- void modelUpdated(const QDeclarativeChangeSet &changeSet, bool reset);
- void createdItem(int index, QQuickItem *item);
- void initItem(int index, QQuickItem *item);
- void destroyingItem(QQuickItem *item);
- void pathUpdated();
-
-private:
- friend class QQuickPathViewAttached;
- Q_DISABLE_COPY(QQuickPathView)
- Q_DECLARE_PRIVATE(QQuickPathView)
-};
-
-class QDeclarativeOpenMetaObject;
-class QQuickPathViewAttached : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QQuickPathView *view READ view CONSTANT)
- Q_PROPERTY(bool isCurrentItem READ isCurrentItem NOTIFY currentItemChanged)
- Q_PROPERTY(bool onPath READ isOnPath NOTIFY pathChanged)
-
-public:
- QQuickPathViewAttached(QObject *parent);
- ~QQuickPathViewAttached();
-
- QQuickPathView *view() { return m_view; }
-
- bool isCurrentItem() const { return m_isCurrent; }
- void setIsCurrentItem(bool c) {
- if (m_isCurrent != c) {
- m_isCurrent = c;
- emit currentItemChanged();
- }
- }
-
- QVariant value(const QByteArray &name) const;
- void setValue(const QByteArray &name, const QVariant &val);
-
- bool isOnPath() const { return m_onPath; }
- void setOnPath(bool on) {
- if (on != m_onPath) {
- m_onPath = on;
- emit pathChanged();
- }
- }
- qreal m_percent;
-
-Q_SIGNALS:
- void currentItemChanged();
- void pathChanged();
-
-private:
- friend class QQuickPathViewPrivate;
- friend class QQuickPathView;
- QQuickPathView *m_view;
- QDeclarativeOpenMetaObject *m_metaobject;
- bool m_onPath : 1;
- bool m_isCurrent : 1;
-};
-
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickPathView)
-QML_DECLARE_TYPEINFO(QQuickPathView, QML_HAS_ATTACHED_PROPERTIES)
-QT_END_HEADER
-
-#endif // QQUICKPATHVIEW_P_H
diff --git a/src/declarative/items/qquickpathview_p_p.h b/src/declarative/items/qquickpathview_p_p.h
deleted file mode 100644
index 9bf329dab5..0000000000
--- a/src/declarative/items/qquickpathview_p_p.h
+++ /dev/null
@@ -1,199 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKPATHVIEW_P_P_H
-#define QQUICKPATHVIEW_P_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 "qquickpathview_p.h"
-#include "qquickitem_p.h"
-#include "qquickvisualdatamodel_p.h"
-
-#include <QtDeclarative/qdeclarative.h>
-#include <QtCore/qdatetime.h>
-#include <QtCore/qcoreapplication.h>
-
-#include <private/qdeclarativeanimation_p_p.h>
-#include <private/qdeclarativeguard_p.h>
-#include <private/qdeclarativetimeline_p_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeOpenMetaObjectType;
-class QQuickPathViewAttached;
-class QQuickPathViewPrivate : public QQuickItemPrivate, public QQuickItemChangeListener
-{
- Q_DECLARE_PUBLIC(QQuickPathView)
-
-public:
- QQuickPathViewPrivate()
- : path(0), currentIndex(0), currentItemOffset(0.0), startPc(0), lastDist(0)
- , lastElapsed(0), offset(0.0), offsetAdj(0.0), mappedRange(1.0)
- , stealMouse(false), ownModel(false), interactive(true), haveHighlightRange(true)
- , autoHighlight(true), highlightUp(false), layoutScheduled(false)
- , moving(false), flicking(false), requestedOnPath(false), inRequest(false)
- , dragMargin(0), deceleration(100)
- , moveOffset(this, &QQuickPathViewPrivate::setAdjustedOffset)
- , firstIndex(-1), pathItems(-1), requestedIndex(-1), requestedZ(0)
- , moveReason(Other), moveDirection(Shortest), attType(0), highlightComponent(0), highlightItem(0)
- , moveHighlight(this, &QQuickPathViewPrivate::setHighlightPosition)
- , highlightPosition(0)
- , highlightRangeStart(0), highlightRangeEnd(0)
- , highlightRangeMode(QQuickPathView::StrictlyEnforceRange)
- , highlightMoveDuration(300), modelCount(0)
- {
- }
-
- void init();
-
- void itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry) {
- if ((newGeometry.size() != oldGeometry.size())
- && (!highlightItem || item != highlightItem)) {
- if (QQuickPathViewAttached *att = attached(item))
- att->m_percent = -1;
- scheduleLayout();
- }
- }
-
- void scheduleLayout() {
- Q_Q(QQuickPathView);
- if (!layoutScheduled) {
- layoutScheduled = true;
- q->polish();
- }
- }
-
- QQuickItem *getItem(int modelIndex, qreal z = 0, bool onPath=true);
- void releaseItem(QQuickItem *item);
- QQuickPathViewAttached *attached(QQuickItem *item);
- QDeclarativeOpenMetaObjectType *attachedType();
- void clear();
- void updateMappedRange();
- qreal positionOfIndex(qreal index) const;
- void createHighlight();
- void updateHighlight();
- void setHighlightPosition(qreal pos);
- bool isValid() const {
- return model && model->count() > 0 && model->isValid() && path;
- }
-
- void handleMousePressEvent(QMouseEvent *event);
- void handleMouseMoveEvent(QMouseEvent *event);
- void handleMouseReleaseEvent(QMouseEvent *);
-
- int calcCurrentIndex();
- void createCurrentItem();
- void updateCurrent();
- static void fixOffsetCallback(void*);
- void fixOffset();
- void setOffset(qreal offset);
- void setAdjustedOffset(qreal offset);
- void regenerate();
- void updateItem(QQuickItem *, qreal);
- void snapToCurrent();
- QPointF pointNear(const QPointF &point, qreal *nearPercent=0) const;
-
- QDeclarativePath *path;
- int currentIndex;
- QDeclarativeGuard<QQuickItem> currentItem;
- qreal currentItemOffset;
- qreal startPc;
- QPointF startPoint;
- qreal lastDist;
- int lastElapsed;
- qreal offset;
- qreal offsetAdj;
- qreal mappedRange;
- bool stealMouse : 1;
- bool ownModel : 1;
- bool interactive : 1;
- bool haveHighlightRange : 1;
- bool autoHighlight : 1;
- bool highlightUp : 1;
- bool layoutScheduled : 1;
- bool moving : 1;
- bool flicking : 1;
- bool requestedOnPath : 1;
- bool inRequest : 1;
- QElapsedTimer lastPosTime;
- QPointF lastPos;
- qreal dragMargin;
- qreal deceleration;
- QDeclarativeTimeLine tl;
- QDeclarativeTimeLineValueProxy<QQuickPathViewPrivate> moveOffset;
- int firstIndex;
- int pathItems;
- int requestedIndex;
- qreal requestedZ;
- QList<QQuickItem *> items;
- QList<QQuickItem *> itemCache;
- QDeclarativeGuard<QQuickVisualModel> model;
- QVariant modelVariant;
- enum MovementReason { Other, SetIndex, Mouse };
- MovementReason moveReason;
- enum MovementDirection { Shortest, Negative, Positive };
- MovementDirection moveDirection;
- QDeclarativeOpenMetaObjectType *attType;
- QDeclarativeComponent *highlightComponent;
- QQuickItem *highlightItem;
- QDeclarativeTimeLineValueProxy<QQuickPathViewPrivate> moveHighlight;
- qreal highlightPosition;
- qreal highlightRangeStart;
- qreal highlightRangeEnd;
- QQuickPathView::HighlightRangeMode highlightRangeMode;
- int highlightMoveDuration;
- int modelCount;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/declarative/items/qquickpincharea.cpp b/src/declarative/items/qquickpincharea.cpp
deleted file mode 100644
index beacbe32bf..0000000000
--- a/src/declarative/items/qquickpincharea.cpp
+++ /dev/null
@@ -1,600 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtSG module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickpincharea_p_p.h"
-#include "qquickcanvas.h"
-
-#include <QtGui/qevent.h>
-#include <QtGui/qguiapplication.h>
-#include <QtGui/qstylehints.h>
-
-#include <float.h>
-#include <math.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass PinchEvent QQuickPinchEvent
- \inqmlmodule QtQuick 2
- \ingroup qml-event-elements
- \brief The PinchEvent object provides information about a pinch event.
-
- \bold {The PinchEvent element was added in QtQuick 1.1}
-
- The \c center, \c startCenter, \c previousCenter properties provide the center position between the two touch points.
-
- The \c scale and \c previousScale properties provide the scale factor.
-
- The \c angle, \c previousAngle and \c rotation properties provide the angle between the two points and the amount of rotation.
-
- The \c point1, \c point2, \c startPoint1, \c startPoint2 properties provide the positions of the touch points.
-
- The \c accepted property may be set to false in the \c onPinchStarted handler if the gesture should not
- be handled.
-
- \sa PinchArea
-*/
-
-/*!
- \qmlproperty QPointF QtQuick2::PinchEvent::center
- \qmlproperty QPointF QtQuick2::PinchEvent::startCenter
- \qmlproperty QPointF QtQuick2::PinchEvent::previousCenter
-
- These properties hold the position of the center point between the two touch points.
-
- \list
- \o \c center is the current center point
- \o \c previousCenter is the center point of the previous event.
- \o \c startCenter is the center point when the gesture began
- \endlist
-*/
-
-/*!
- \qmlproperty real QtQuick2::PinchEvent::scale
- \qmlproperty real QtQuick2::PinchEvent::previousScale
-
- These properties hold the scale factor determined by the change in distance between the two touch points.
-
- \list
- \o \c scale is the current scale factor.
- \o \c previousScale is the scale factor of the previous event.
- \endlist
-
- When a pinch gesture is started, the scale is 1.0.
-*/
-
-/*!
- \qmlproperty real QtQuick2::PinchEvent::angle
- \qmlproperty real QtQuick2::PinchEvent::previousAngle
- \qmlproperty real QtQuick2::PinchEvent::rotation
-
- These properties hold the angle between the two touch points.
-
- \list
- \o \c angle is the current angle between the two points in the range -180 to 180.
- \o \c previousAngle is the angle of the previous event.
- \o \c rotation is the total rotation since the pinch gesture started.
- \endlist
-
- When a pinch gesture is started, the rotation is 0.0.
-*/
-
-/*!
- \qmlproperty QPointF QtQuick2::PinchEvent::point1
- \qmlproperty QPointF QtQuick2::PinchEvent::startPoint1
- \qmlproperty QPointF QtQuick2::PinchEvent::point2
- \qmlproperty QPointF QtQuick2::PinchEvent::startPoint2
-
- These properties provide the actual touch points generating the pinch.
-
- \list
- \o \c point1 and \c point2 hold the current positions of the points.
- \o \c startPoint1 and \c startPoint2 hold the positions of the points when the second point was touched.
- \endlist
-*/
-
-/*!
- \qmlproperty bool QtQuick2::PinchEvent::accepted
-
- Setting this property to false in the \c PinchArea::onPinchStarted handler
- will result in no further pinch events being generated, and the gesture
- ignored.
-*/
-
-/*!
- \qmlproperty int QtQuick2::PinchEvent::pointCount
-
- Holds the number of points currently touched. The PinchArea will not react
- until two touch points have initited a gesture, but will remain active until
- all touch points have been released.
-*/
-
-QQuickPinch::QQuickPinch()
- : m_target(0), m_minScale(1.0), m_maxScale(1.0)
- , m_minRotation(0.0), m_maxRotation(0.0)
- , m_axis(NoDrag), m_xmin(-FLT_MAX), m_xmax(FLT_MAX)
- , m_ymin(-FLT_MAX), m_ymax(FLT_MAX), m_active(false)
-{
-}
-
-QQuickPinchAreaPrivate::~QQuickPinchAreaPrivate()
-{
- delete pinch;
-}
-
-/*!
- \qmlclass PinchArea QQuickPinchArea
- \inqmlmodule QtQuick 2
- \brief The PinchArea item enables simple pinch gesture handling.
- \inherits Item
-
- \bold {The PinchArea element was added in QtQuick 1.1}
-
- A PinchArea is an invisible item that is typically used in conjunction with
- a visible item in order to provide pinch gesture handling for that item.
-
- The \l enabled property is used to enable and disable pinch handling for
- the proxied item. When disabled, the pinch area becomes transparent to
- mouse/touch events.
-
- PinchArea can be used in two ways:
-
- \list
- \o setting a \c pinch.target to provide automatic interaction with an element
- \o using the onPinchStarted, onPinchUpdated and onPinchFinished handlers
- \endlist
-
- \sa PinchEvent
-*/
-
-/*!
- \qmlsignal QtQuick2::PinchArea::onPinchStarted()
-
- This handler is called when the pinch area detects that a pinch gesture has started.
-
- The \l {PinchEvent}{pinch} parameter provides information about the pinch gesture,
- including the scale, center and angle of the pinch.
-
- To ignore this gesture set the \c pinch.accepted property to false. The gesture
- will be canceled and no further events will be sent.
-*/
-
-/*!
- \qmlsignal QtQuick2::PinchArea::onPinchUpdated()
-
- This handler is called when the pinch area detects that a pinch gesture has changed.
-
- The \l {PinchEvent}{pinch} parameter provides information about the pinch gesture,
- including the scale, center and angle of the pinch.
-*/
-
-/*!
- \qmlsignal QtQuick2::PinchArea::onPinchFinished()
-
- This handler is called when the pinch area detects that a pinch gesture has finished.
-
- The \l {PinchEvent}{pinch} parameter provides information about the pinch gesture,
- including the scale, center and angle of the pinch.
-*/
-
-
-/*!
- \qmlproperty Item QtQuick2::PinchArea::pinch.target
- \qmlproperty bool QtQuick2::PinchArea::pinch.active
- \qmlproperty real QtQuick2::PinchArea::pinch.minimumScale
- \qmlproperty real QtQuick2::PinchArea::pinch.maximumScale
- \qmlproperty real QtQuick2::PinchArea::pinch.minimumRotation
- \qmlproperty real QtQuick2::PinchArea::pinch.maximumRotation
- \qmlproperty enumeration QtQuick2::PinchArea::pinch.dragAxis
- \qmlproperty real QtQuick2::PinchArea::pinch.minimumX
- \qmlproperty real QtQuick2::PinchArea::pinch.maximumX
- \qmlproperty real QtQuick2::PinchArea::pinch.minimumY
- \qmlproperty real QtQuick2::PinchArea::pinch.maximumY
-
- \c pinch provides a convenient way to make an item react to pinch gestures.
-
- \list
- \i \c pinch.target specifies the id of the item to drag.
- \i \c pinch.active specifies if the target item is currently being dragged.
- \i \c pinch.minimumScale and \c pinch.maximumScale limit the range of the Item::scale property.
- \i \c pinch.minimumRotation and \c pinch.maximumRotation limit the range of the Item::rotation property.
- \i \c pinch.dragAxis specifies whether dragging in not allowed (\c Pinch.NoDrag), can be done horizontally (\c Pinch.XAxis), vertically (\c Pinch.YAxis), or both (\c Pinch.XandYAxis)
- \i \c pinch.minimum and \c pinch.maximum limit how far the target can be dragged along the corresponding axes.
- \endlist
-*/
-
-QQuickPinchArea::QQuickPinchArea(QQuickItem *parent)
- : QQuickItem(*(new QQuickPinchAreaPrivate), parent)
-{
- Q_D(QQuickPinchArea);
- d->init();
-}
-
-QQuickPinchArea::~QQuickPinchArea()
-{
-}
-/*!
- \qmlproperty bool QtQuick2::PinchArea::enabled
- This property holds whether the item accepts pinch gestures.
-
- This property defaults to true.
-*/
-bool QQuickPinchArea::isEnabled() const
-{
- Q_D(const QQuickPinchArea);
- return d->absorb;
-}
-
-void QQuickPinchArea::setEnabled(bool a)
-{
- Q_D(QQuickPinchArea);
- if (a != d->absorb) {
- d->absorb = a;
- emit enabledChanged();
- }
-}
-
-void QQuickPinchArea::touchEvent(QTouchEvent *event)
-{
- Q_D(QQuickPinchArea);
- if (!d->absorb || !isVisible()) {
- QQuickItem::event(event);
- return;
- }
-
- switch (event->type()) {
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- d->touchPoints.clear();
- for (int i = 0; i < event->touchPoints().count(); ++i) {
- if (!(event->touchPoints().at(i).state() & Qt::TouchPointReleased)) {
- d->touchPoints << event->touchPoints().at(i);
- }
- }
- updatePinch();
- break;
- case QEvent::TouchEnd:
- d->touchPoints.clear();
- updatePinch();
- break;
- default:
- QQuickItem::event(event);
- }
-}
-
-void QQuickPinchArea::updatePinch()
-{
- Q_D(QQuickPinchArea);
- if (d->touchPoints.count() == 0) {
- if (d->inPinch) {
- d->inPinch = false;
- QPointF pinchCenter = mapFromScene(d->sceneLastCenter);
- QQuickPinchEvent pe(pinchCenter, d->pinchLastScale, d->pinchLastAngle, d->pinchRotation);
- pe.setStartCenter(d->pinchStartCenter);
- pe.setPreviousCenter(pinchCenter);
- pe.setPreviousAngle(d->pinchLastAngle);
- pe.setPreviousScale(d->pinchLastScale);
- pe.setStartPoint1(mapFromScene(d->sceneStartPoint1));
- pe.setStartPoint2(mapFromScene(d->sceneStartPoint2));
- pe.setPoint1(mapFromScene(d->lastPoint1));
- pe.setPoint2(mapFromScene(d->lastPoint2));
- emit pinchFinished(&pe);
- d->pinchStartDist = 0;
- d->pinchActivated = false;
- if (d->pinch && d->pinch->target())
- d->pinch->setActive(false);
- }
- d->initPinch = false;
- d->pinchRejected = false;
- d->stealMouse = false;
- setKeepMouseGrab(false);
- QQuickCanvas *c = canvas();
- if (c && c->mouseGrabberItem() == this)
- ungrabMouse();
- return;
- }
- QTouchEvent::TouchPoint touchPoint1 = d->touchPoints.at(0);
- QTouchEvent::TouchPoint touchPoint2 = d->touchPoints.at(d->touchPoints. count() >= 2 ? 1 : 0);
- if (d->touchPoints.count() == 2
- && (touchPoint1.state() & Qt::TouchPointPressed || touchPoint2.state() & Qt::TouchPointPressed)) {
- d->id1 = touchPoint1.id();
- d->sceneStartPoint1 = touchPoint1.scenePos();
- d->sceneStartPoint2 = touchPoint2.scenePos();
- d->pinchActivated = true;
- d->initPinch = true;
- }
- if (d->pinchActivated && !d->pinchRejected){
- const int dragThreshold = qApp->styleHints()->startDragDistance();
- QPointF p1 = touchPoint1.scenePos();
- QPointF p2 = touchPoint2.scenePos();
- qreal dx = p1.x() - p2.x();
- qreal dy = p1.y() - p2.y();
- qreal dist = sqrt(dx*dx + dy*dy);
- QPointF sceneCenter = (p1 + p2)/2;
- qreal angle = QLineF(p1, p2).angle();
- if (d->touchPoints.count() == 1) {
- // If we only have one point then just move the center
- if (d->id1 == touchPoint1.id())
- sceneCenter = d->sceneLastCenter + touchPoint1.scenePos() - d->lastPoint1;
- else
- sceneCenter = d->sceneLastCenter + touchPoint2.scenePos() - d->lastPoint2;
- angle = d->pinchLastAngle;
- }
- d->id1 = touchPoint1.id();
- if (angle > 180)
- angle -= 360;
- if (!d->inPinch || d->initPinch) {
- if (d->touchPoints.count() >= 2
- && (qAbs(p1.x()-d->sceneStartPoint1.x()) > dragThreshold
- || qAbs(p1.y()-d->sceneStartPoint1.y()) > dragThreshold
- || qAbs(p2.x()-d->sceneStartPoint2.x()) > dragThreshold
- || qAbs(p2.y()-d->sceneStartPoint2.y()) > dragThreshold)) {
- d->initPinch = false;
- d->sceneStartCenter = sceneCenter;
- d->sceneLastCenter = sceneCenter;
- d->pinchStartCenter = mapFromScene(sceneCenter);
- d->pinchStartDist = dist;
- d->pinchStartAngle = angle;
- d->pinchLastScale = 1.0;
- d->pinchLastAngle = angle;
- d->pinchRotation = 0.0;
- d->lastPoint1 = p1;
- d->lastPoint2 = p2;
- QQuickPinchEvent pe(d->pinchStartCenter, 1.0, angle, 0.0);
- pe.setStartCenter(d->pinchStartCenter);
- pe.setPreviousCenter(d->pinchStartCenter);
- pe.setPreviousAngle(d->pinchLastAngle);
- pe.setPreviousScale(d->pinchLastScale);
- pe.setStartPoint1(mapFromScene(d->sceneStartPoint1));
- pe.setStartPoint2(mapFromScene(d->sceneStartPoint2));
- pe.setPoint1(mapFromScene(d->lastPoint1));
- pe.setPoint2(mapFromScene(d->lastPoint2));
- pe.setPointCount(d->touchPoints.count());
- emit pinchStarted(&pe);
- if (pe.accepted()) {
- d->inPinch = true;
- d->stealMouse = true;
- QQuickCanvas *c = canvas();
- if (c && c->mouseGrabberItem() != this)
- grabMouse();
- setKeepMouseGrab(true);
- if (d->pinch && d->pinch->target()) {
- d->pinchStartPos = pinch()->target()->pos();
- d->pinchStartScale = d->pinch->target()->scale();
- d->pinchStartRotation = d->pinch->target()->rotation();
- d->pinch->setActive(true);
- }
- } else {
- d->pinchRejected = true;
- }
- }
- } else if (d->pinchStartDist > 0) {
- qreal scale = dist ? dist / d->pinchStartDist : d->pinchLastScale;
- qreal da = d->pinchLastAngle - angle;
- if (da > 180)
- da -= 360;
- else if (da < -180)
- da += 360;
- d->pinchRotation += da;
- QPointF pinchCenter = mapFromScene(sceneCenter);
- QQuickPinchEvent pe(pinchCenter, scale, angle, d->pinchRotation);
- pe.setStartCenter(d->pinchStartCenter);
- pe.setPreviousCenter(mapFromScene(d->sceneLastCenter));
- pe.setPreviousAngle(d->pinchLastAngle);
- pe.setPreviousScale(d->pinchLastScale);
- pe.setStartPoint1(mapFromScene(d->sceneStartPoint1));
- pe.setStartPoint2(mapFromScene(d->sceneStartPoint2));
- pe.setPoint1(touchPoint1.pos());
- pe.setPoint2(touchPoint2.pos());
- pe.setPointCount(d->touchPoints.count());
- d->pinchLastScale = scale;
- d->sceneLastCenter = sceneCenter;
- d->pinchLastAngle = angle;
- d->lastPoint1 = touchPoint1.scenePos();
- d->lastPoint2 = touchPoint2.scenePos();
- emit pinchUpdated(&pe);
- if (d->pinch && d->pinch->target()) {
- qreal s = d->pinchStartScale * scale;
- s = qMin(qMax(pinch()->minimumScale(),s), pinch()->maximumScale());
- pinch()->target()->setScale(s);
- QPointF pos = sceneCenter - d->sceneStartCenter + d->pinchStartPos;
- if (pinch()->axis() & QQuickPinch::XAxis) {
- qreal x = pos.x();
- if (x < pinch()->xmin())
- x = pinch()->xmin();
- else if (x > pinch()->xmax())
- x = pinch()->xmax();
- pinch()->target()->setX(x);
- }
- if (pinch()->axis() & QQuickPinch::YAxis) {
- qreal y = pos.y();
- if (y < pinch()->ymin())
- y = pinch()->ymin();
- else if (y > pinch()->ymax())
- y = pinch()->ymax();
- pinch()->target()->setY(y);
- }
- if (d->pinchStartRotation >= pinch()->minimumRotation()
- && d->pinchStartRotation <= pinch()->maximumRotation()) {
- qreal r = d->pinchRotation + d->pinchStartRotation;
- r = qMin(qMax(pinch()->minimumRotation(),r), pinch()->maximumRotation());
- pinch()->target()->setRotation(r);
- }
- }
- }
- }
-}
-
-void QQuickPinchArea::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QQuickPinchArea);
- d->stealMouse = false;
- if (!d->absorb)
- QQuickItem::mousePressEvent(event);
- else {
- setKeepMouseGrab(false);
- event->setAccepted(true);
- }
-}
-
-void QQuickPinchArea::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QQuickPinchArea);
- if (!d->absorb) {
- QQuickItem::mouseMoveEvent(event);
- return;
- }
-}
-
-void QQuickPinchArea::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QQuickPinchArea);
- d->stealMouse = false;
- if (!d->absorb) {
- QQuickItem::mouseReleaseEvent(event);
- } else {
- QQuickCanvas *c = canvas();
- if (c && c->mouseGrabberItem() == this)
- ungrabMouse();
- setKeepMouseGrab(false);
- }
-}
-
-void QQuickPinchArea::mouseUngrabEvent()
-{
- setKeepMouseGrab(false);
-}
-
-bool QQuickPinchArea::sendMouseEvent(QMouseEvent *event)
-{
- Q_D(QQuickPinchArea);
- QRectF myRect = mapRectToScene(QRectF(0, 0, width(), height()));
-
- QQuickCanvas *c = canvas();
- QQuickItem *grabber = c ? c->mouseGrabberItem() : 0;
- bool stealThisEvent = d->stealMouse;
- if ((stealThisEvent || myRect.contains(event->windowPos())) && (!grabber || !grabber->keepMouseGrab())) {
- QMouseEvent mouseEvent(event->type(), mapFromScene(event->windowPos()), event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers());
- mouseEvent.setAccepted(false);
-
- switch (mouseEvent.type()) {
- case QEvent::MouseMove:
- mouseMoveEvent(&mouseEvent);
- break;
- case QEvent::MouseButtonPress:
- mousePressEvent(&mouseEvent);
- break;
- case QEvent::MouseButtonRelease:
- mouseReleaseEvent(&mouseEvent);
- break;
- default:
- break;
- }
- grabber = c->mouseGrabberItem();
- if (grabber && stealThisEvent && !grabber->keepMouseGrab() && grabber != this)
- grabMouse();
-
- return stealThisEvent;
- }
- if (event->type() == QEvent::MouseButtonRelease) {
- d->stealMouse = false;
- if (c && c->mouseGrabberItem() == this)
- ungrabMouse();
- setKeepMouseGrab(false);
- }
- return false;
-}
-
-bool QQuickPinchArea::childMouseEventFilter(QQuickItem *i, QEvent *e)
-{
- Q_D(QQuickPinchArea);
- if (!d->absorb || !isVisible())
- return QQuickItem::childMouseEventFilter(i, e);
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease:
- return sendMouseEvent(static_cast<QMouseEvent *>(e));
- break;
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate: {
- QTouchEvent *touch = static_cast<QTouchEvent*>(e);
- d->touchPoints.clear();
- for (int i = 0; i < touch->touchPoints().count(); ++i)
- if (!(touch->touchPoints().at(i).state() & Qt::TouchPointReleased))
- d->touchPoints << touch->touchPoints().at(i);
- updatePinch();
- }
- return d->inPinch;
- case QEvent::TouchEnd:
- d->touchPoints.clear();
- updatePinch();
- break;
- default:
- break;
- }
-
- return QQuickItem::childMouseEventFilter(i, e);
-}
-
-void QQuickPinchArea::geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry)
-{
- QQuickItem::geometryChanged(newGeometry, oldGeometry);
-}
-
-void QQuickPinchArea::itemChange(ItemChange change, const ItemChangeData &value)
-{
- QQuickItem::itemChange(change, value);
-}
-
-QQuickPinch *QQuickPinchArea::pinch()
-{
- Q_D(QQuickPinchArea);
- if (!d->pinch)
- d->pinch = new QQuickPinch;
- return d->pinch;
-}
-
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/items/qquickpincharea_p.h b/src/declarative/items/qquickpincharea_p.h
deleted file mode 100644
index c98a1fdd9e..0000000000
--- a/src/declarative/items/qquickpincharea_p.h
+++ /dev/null
@@ -1,315 +0,0 @@
-// Commit: f707672eb4c51ea82fbd98e1da16ece61a74c690
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtSG module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKPINCHAREA_H
-#define QQUICKPINCHAREA_H
-
-#include "qquickitem.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class Q_AUTOTEST_EXPORT QQuickPinch : public QObject
-{
- Q_OBJECT
-
- Q_ENUMS(Axis)
- Q_PROPERTY(QQuickItem *target READ target WRITE setTarget RESET resetTarget)
- Q_PROPERTY(qreal minimumScale READ minimumScale WRITE setMinimumScale NOTIFY minimumScaleChanged)
- Q_PROPERTY(qreal maximumScale READ maximumScale WRITE setMaximumScale NOTIFY maximumScaleChanged)
- Q_PROPERTY(qreal minimumRotation READ minimumRotation WRITE setMinimumRotation NOTIFY minimumRotationChanged)
- Q_PROPERTY(qreal maximumRotation READ maximumRotation WRITE setMaximumRotation NOTIFY maximumRotationChanged)
- Q_PROPERTY(Axis dragAxis READ axis WRITE setAxis NOTIFY dragAxisChanged)
- Q_PROPERTY(qreal minimumX READ xmin WRITE setXmin NOTIFY minimumXChanged)
- Q_PROPERTY(qreal maximumX READ xmax WRITE setXmax NOTIFY maximumXChanged)
- Q_PROPERTY(qreal minimumY READ ymin WRITE setYmin NOTIFY minimumYChanged)
- Q_PROPERTY(qreal maximumY READ ymax WRITE setYmax NOTIFY maximumYChanged)
- Q_PROPERTY(bool active READ active NOTIFY activeChanged)
-
-public:
- QQuickPinch();
-
- QQuickItem *target() const { return m_target; }
- void setTarget(QQuickItem *target) {
- if (target == m_target)
- return;
- m_target = target;
- emit targetChanged();
- }
- void resetTarget() {
- if (!m_target)
- return;
- m_target = 0;
- emit targetChanged();
- }
-
- qreal minimumScale() const { return m_minScale; }
- void setMinimumScale(qreal s) {
- if (s == m_minScale)
- return;
- m_minScale = s;
- emit minimumScaleChanged();
- }
- qreal maximumScale() const { return m_maxScale; }
- void setMaximumScale(qreal s) {
- if (s == m_maxScale)
- return;
- m_maxScale = s;
- emit maximumScaleChanged();
- }
-
- qreal minimumRotation() const { return m_minRotation; }
- void setMinimumRotation(qreal r) {
- if (r == m_minRotation)
- return;
- m_minRotation = r;
- emit minimumRotationChanged();
- }
- qreal maximumRotation() const { return m_maxRotation; }
- void setMaximumRotation(qreal r) {
- if (r == m_maxRotation)
- return;
- m_maxRotation = r;
- emit maximumRotationChanged();
- }
-
- enum Axis { NoDrag=0x00, XAxis=0x01, YAxis=0x02, XandYAxis=0x03 };
- Axis axis() const { return m_axis; }
- void setAxis(Axis a) {
- if (a == m_axis)
- return;
- m_axis = a;
- emit dragAxisChanged();
- }
-
- qreal xmin() const { return m_xmin; }
- void setXmin(qreal x) {
- if (x == m_xmin)
- return;
- m_xmin = x;
- emit minimumXChanged();
- }
- qreal xmax() const { return m_xmax; }
- void setXmax(qreal x) {
- if (x == m_xmax)
- return;
- m_xmax = x;
- emit maximumXChanged();
- }
- qreal ymin() const { return m_ymin; }
- void setYmin(qreal y) {
- if (y == m_ymin)
- return;
- m_ymin = y;
- emit minimumYChanged();
- }
- qreal ymax() const { return m_ymax; }
- void setYmax(qreal y) {
- if (y == m_ymax)
- return;
- m_ymax = y;
- emit maximumYChanged();
- }
-
- bool active() const { return m_active; }
- void setActive(bool a) {
- if (a == m_active)
- return;
- m_active = a;
- emit activeChanged();
- }
-
-signals:
- void targetChanged();
- void minimumScaleChanged();
- void maximumScaleChanged();
- void minimumRotationChanged();
- void maximumRotationChanged();
- void dragAxisChanged();
- void minimumXChanged();
- void maximumXChanged();
- void minimumYChanged();
- void maximumYChanged();
- void activeChanged();
-
-private:
- QQuickItem *m_target;
- qreal m_minScale;
- qreal m_maxScale;
- qreal m_minRotation;
- qreal m_maxRotation;
- Axis m_axis;
- qreal m_xmin;
- qreal m_xmax;
- qreal m_ymin;
- qreal m_ymax;
- bool m_active;
-};
-
-class Q_AUTOTEST_EXPORT QQuickPinchEvent : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QPointF center READ center)
- Q_PROPERTY(QPointF startCenter READ startCenter)
- Q_PROPERTY(QPointF previousCenter READ previousCenter)
- Q_PROPERTY(qreal scale READ scale)
- Q_PROPERTY(qreal previousScale READ previousScale)
- Q_PROPERTY(qreal angle READ angle)
- Q_PROPERTY(qreal previousAngle READ previousAngle)
- Q_PROPERTY(qreal rotation READ rotation)
- Q_PROPERTY(QPointF point1 READ point1)
- Q_PROPERTY(QPointF startPoint1 READ startPoint1)
- Q_PROPERTY(QPointF point2 READ point2)
- Q_PROPERTY(QPointF startPoint2 READ startPoint2)
- Q_PROPERTY(int pointCount READ pointCount)
- Q_PROPERTY(bool accepted READ accepted WRITE setAccepted)
-
-public:
- QQuickPinchEvent(QPointF c, qreal s, qreal a, qreal r)
- : QObject(), m_center(c), m_scale(s), m_angle(a), m_rotation(r)
- , m_pointCount(0), m_accepted(true) {}
-
- QPointF center() const { return m_center; }
- QPointF startCenter() const { return m_startCenter; }
- void setStartCenter(QPointF c) { m_startCenter = c; }
- QPointF previousCenter() const { return m_lastCenter; }
- void setPreviousCenter(QPointF c) { m_lastCenter = c; }
- qreal scale() const { return m_scale; }
- qreal previousScale() const { return m_lastScale; }
- void setPreviousScale(qreal s) { m_lastScale = s; }
- qreal angle() const { return m_angle; }
- qreal previousAngle() const { return m_lastAngle; }
- void setPreviousAngle(qreal a) { m_lastAngle = a; }
- qreal rotation() const { return m_rotation; }
- QPointF point1() const { return m_point1; }
- void setPoint1(QPointF p) { m_point1 = p; }
- QPointF startPoint1() const { return m_startPoint1; }
- void setStartPoint1(QPointF p) { m_startPoint1 = p; }
- QPointF point2() const { return m_point2; }
- void setPoint2(QPointF p) { m_point2 = p; }
- QPointF startPoint2() const { return m_startPoint2; }
- void setStartPoint2(QPointF p) { m_startPoint2 = p; }
- int pointCount() const { return m_pointCount; }
- void setPointCount(int count) { m_pointCount = count; }
-
- bool accepted() const { return m_accepted; }
- void setAccepted(bool a) { m_accepted = a; }
-
-private:
- QPointF m_center;
- QPointF m_startCenter;
- QPointF m_lastCenter;
- qreal m_scale;
- qreal m_lastScale;
- qreal m_angle;
- qreal m_lastAngle;
- qreal m_rotation;
- QPointF m_point1;
- QPointF m_point2;
- QPointF m_startPoint1;
- QPointF m_startPoint2;
- int m_pointCount;
- bool m_accepted;
-};
-
-
-class QQuickMouseEvent;
-class QQuickPinchAreaPrivate;
-class Q_AUTOTEST_EXPORT QQuickPinchArea : public QQuickItem
-{
- Q_OBJECT
-
- Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged)
- Q_PROPERTY(QQuickPinch *pinch READ pinch CONSTANT)
-
-public:
- QQuickPinchArea(QQuickItem *parent=0);
- ~QQuickPinchArea();
-
- bool isEnabled() const;
- void setEnabled(bool);
-
- QQuickPinch *pinch();
-
-Q_SIGNALS:
- void enabledChanged();
- void pinchStarted(QQuickPinchEvent *pinch);
- void pinchUpdated(QQuickPinchEvent *pinch);
- void pinchFinished(QQuickPinchEvent *pinch);
-
-protected:
- virtual void mousePressEvent(QMouseEvent *event);
- virtual void mouseReleaseEvent(QMouseEvent *event);
- virtual void mouseMoveEvent(QMouseEvent *event);
- virtual void mouseUngrabEvent();
- virtual bool sendMouseEvent(QMouseEvent *event);
- virtual bool childMouseEventFilter(QQuickItem *i, QEvent *e);
- virtual void touchEvent(QTouchEvent *event);
-
- virtual void geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry);
- virtual void itemChange(ItemChange change, const ItemChangeData& value);
-
-private:
- void updatePinch();
- void handlePress();
- void handleRelease();
-
-private:
- Q_DISABLE_COPY(QQuickPinchArea)
- Q_DECLARE_PRIVATE(QQuickPinchArea)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickPinch)
-QML_DECLARE_TYPE(QQuickPinchEvent)
-QML_DECLARE_TYPE(QQuickPinchArea)
-
-QT_END_HEADER
-
-#endif // QQUICKPINCHAREA_H
-
diff --git a/src/declarative/items/qquickpincharea_p_p.h b/src/declarative/items/qquickpincharea_p_p.h
deleted file mode 100644
index 1c9d5c5ba4..0000000000
--- a/src/declarative/items/qquickpincharea_p_p.h
+++ /dev/null
@@ -1,116 +0,0 @@
-// Commit: f707672eb4c51ea82fbd98e1da16ece61a74c690
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtSG module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKPINCHAREA_P_H
-#define QQUICKPINCHAREA_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 <qevent.h>
-
-#include "qquickitem_p.h"
-#include "qquickpincharea_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QQuickPinch;
-class QQuickPinchAreaPrivate : public QQuickItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickPinchArea)
-public:
- QQuickPinchAreaPrivate()
- : absorb(true), stealMouse(false), inPinch(false)
- , pinchRejected(false), pinchActivated(false), initPinch(false)
- , pinch(0), pinchStartDist(0), pinchStartScale(1.0)
- , pinchLastScale(1.0), pinchStartRotation(0.0), pinchStartAngle(0.0)
- , pinchLastAngle(0.0), pinchRotation(0.0)
- {
- }
-
- ~QQuickPinchAreaPrivate();
-
- void init()
- {
- Q_Q(QQuickPinchArea);
- q->setAcceptedMouseButtons(Qt::LeftButton);
- q->setFiltersChildMouseEvents(true);
- }
-
- bool absorb : 1;
- bool stealMouse : 1;
- bool inPinch : 1;
- bool pinchRejected : 1;
- bool pinchActivated : 1;
- bool initPinch : 1;
- QQuickPinch *pinch;
- QPointF sceneStartPoint1;
- QPointF sceneStartPoint2;
- QPointF lastPoint1;
- QPointF lastPoint2;
- qreal pinchStartDist;
- qreal pinchStartScale;
- qreal pinchLastScale;
- qreal pinchStartRotation;
- qreal pinchStartAngle;
- qreal pinchLastAngle;
- qreal pinchRotation;
- QPointF sceneStartCenter;
- QPointF pinchStartCenter;
- QPointF sceneLastCenter;
- QPointF pinchStartPos;
- QList<QTouchEvent::TouchPoint> touchPoints;
- int id1;
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKPINCHAREA_P_H
-
diff --git a/src/declarative/items/qquickpositioners.cpp b/src/declarative/items/qquickpositioners.cpp
deleted file mode 100644
index 08fa4b1724..0000000000
--- a/src/declarative/items/qquickpositioners.cpp
+++ /dev/null
@@ -1,1532 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickpositioners_p.h"
-#include "qquickpositioners_p_p.h"
-
-#include <QtDeclarative/qdeclarative.h>
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtCore/qmath.h>
-#include <QtCore/qcoreapplication.h>
-
-#include <private/qdeclarativestate_p.h>
-#include <private/qdeclarativestategroup_p.h>
-#include <private/qdeclarativestateoperations_p.h>
-#include <private/qdeclarativetransition_p.h>
-
-QT_BEGIN_NAMESPACE
-
-static const QQuickItemPrivate::ChangeTypes watchedChanges
- = QQuickItemPrivate::Geometry
- | QQuickItemPrivate::SiblingOrder
- | QQuickItemPrivate::Visibility
- | QQuickItemPrivate::Destroyed;
-
-void QQuickBasePositionerPrivate::watchChanges(QQuickItem *other)
-{
- QQuickItemPrivate *otherPrivate = QQuickItemPrivate::get(other);
- otherPrivate->addItemChangeListener(this, watchedChanges);
-}
-
-void QQuickBasePositionerPrivate::unwatchChanges(QQuickItem* other)
-{
- QQuickItemPrivate *otherPrivate = QQuickItemPrivate::get(other);
- otherPrivate->removeItemChangeListener(this, watchedChanges);
-}
-
-QQuickBasePositioner::QQuickBasePositioner(PositionerType at, QQuickItem *parent)
- : QQuickImplicitSizeItem(*(new QQuickBasePositionerPrivate), parent)
-{
- Q_D(QQuickBasePositioner);
- d->init(at);
-}
-/*!
- \internal
- \class QQuickBasePositioner
- \brief The QQuickBasePositioner class provides a base for QQuickGraphics layouts.
-
- To create a QQuickGraphics Positioner, simply subclass QQuickBasePositioner and implement
- doLayout(), which is automatically called when the layout might need
- updating. In doLayout() use the setX and setY functions from QQuickBasePositioner, and the
- base class will apply the positions along with the appropriate transitions. The items to
- position are provided in order as the protected member positionedItems.
-
- You also need to set a PositionerType, to declare whether you are positioning the x, y or both
- for the child items. Depending on the chosen type, only x or y changes will be applied.
-
- Note that the subclass is responsible for adding the spacing in between items.
-
- Positioning is usually delayed until before a frame is rendered, to batch multiple repositioning
- changes into one calculation.
-*/
-
-QQuickBasePositioner::QQuickBasePositioner(QQuickBasePositionerPrivate &dd, PositionerType at, QQuickItem *parent)
- : QQuickImplicitSizeItem(dd, parent)
-{
- Q_D(QQuickBasePositioner);
- d->init(at);
-}
-
-QQuickBasePositioner::~QQuickBasePositioner()
-{
- Q_D(QQuickBasePositioner);
- for (int i = 0; i < positionedItems.count(); ++i)
- d->unwatchChanges(positionedItems.at(i).item);
- positionedItems.clear();
-}
-
-void QQuickBasePositioner::updatePolish()
-{
- Q_D(QQuickBasePositioner);
- if (d->positioningDirty)
- prePositioning();
-}
-
-int QQuickBasePositioner::spacing() const
-{
- Q_D(const QQuickBasePositioner);
- return d->spacing;
-}
-
-void QQuickBasePositioner::setSpacing(int s)
-{
- Q_D(QQuickBasePositioner);
- if (s==d->spacing)
- return;
- d->spacing = s;
- d->setPositioningDirty();
- emit spacingChanged();
-}
-
-QDeclarativeTransition *QQuickBasePositioner::move() const
-{
- Q_D(const QQuickBasePositioner);
- return d->moveTransition;
-}
-
-void QQuickBasePositioner::setMove(QDeclarativeTransition *mt)
-{
- Q_D(QQuickBasePositioner);
- if (mt == d->moveTransition)
- return;
- d->moveTransition = mt;
- emit moveChanged();
-}
-
-QDeclarativeTransition *QQuickBasePositioner::add() const
-{
- Q_D(const QQuickBasePositioner);
- return d->addTransition;
-}
-
-void QQuickBasePositioner::setAdd(QDeclarativeTransition *add)
-{
- Q_D(QQuickBasePositioner);
- if (add == d->addTransition)
- return;
-
- d->addTransition = add;
- emit addChanged();
-}
-
-void QQuickBasePositioner::componentComplete()
-{
- QQuickItem::componentComplete();
- positionedItems.reserve(childItems().count());
- prePositioning();
- reportConflictingAnchors();
-}
-
-void QQuickBasePositioner::itemChange(ItemChange change, const ItemChangeData &value)
-{
- Q_D(QQuickBasePositioner);
- if (change == ItemChildAddedChange){
- d->setPositioningDirty();
- } else if (change == ItemChildRemovedChange) {
- QQuickItem *child = value.item;
- QQuickBasePositioner::PositionedItem posItem(child);
- int idx = positionedItems.find(posItem);
- if (idx >= 0) {
- d->unwatchChanges(child);
- positionedItems.remove(idx);
- }
- d->setPositioningDirty();
- }
-
- QQuickItem::itemChange(change, value);
-}
-
-void QQuickBasePositioner::prePositioning()
-{
- Q_D(QQuickBasePositioner);
- if (!isComponentComplete())
- return;
-
- if (d->doingPositioning)
- return;
-
- d->positioningDirty = false;
- d->doingPositioning = true;
- //Need to order children by creation order modified by stacking order
- QList<QQuickItem *> children = childItems();
-
- QPODVector<PositionedItem,8> oldItems;
- positionedItems.copyAndClear(oldItems);
- for (int ii = 0; ii < children.count(); ++ii) {
- QQuickItem *child = children.at(ii);
- QQuickItemPrivate *childPrivate = QQuickItemPrivate::get(child);
- PositionedItem *item = 0;
- PositionedItem posItem(child);
- int wIdx = oldItems.find(posItem);
- if (wIdx < 0) {
- d->watchChanges(child);
- positionedItems.append(posItem);
- item = &positionedItems[positionedItems.count()-1];
- item->isNew = true;
- if (!childPrivate->explicitVisible || !child->width() || !child->height())
- item->isVisible = false;
- } else {
- item = &oldItems[wIdx];
- // Items are only omitted from positioning if they are explicitly hidden
- // i.e. their positioning is not affected if an ancestor is hidden.
- if (!childPrivate->explicitVisible || !child->width() || !child->height()) {
- item->isVisible = false;
- } else if (!item->isVisible) {
- item->isVisible = true;
- item->isNew = true;
- } else {
- item->isNew = false;
- }
- positionedItems.append(*item);
- }
- }
- QSizeF contentSize(0,0);
- doPositioning(&contentSize);
- updateAttachedProperties();
- if (!d->addActions.isEmpty() || !d->moveActions.isEmpty())
- finishApplyTransitions();
- d->doingPositioning = false;
- //Set implicit size to the size of its children
- setImplicitSize(contentSize.width(), contentSize.height());
-}
-
-void QQuickBasePositioner::positionX(int x, const PositionedItem &target)
-{
- Q_D(QQuickBasePositioner);
- if (d->type == Horizontal || d->type == Both) {
- if (target.isNew) {
- if (!d->addTransition || !d->addTransition->enabled())
- target.item->setX(x);
- else
- d->addActions << QDeclarativeAction(target.item, QLatin1String("x"), QVariant(x));
- } else if (x != target.item->x()) {
- if (!d->moveTransition || !d->moveTransition->enabled())
- target.item->setX(x);
- else
- d->moveActions << QDeclarativeAction(target.item, QLatin1String("x"), QVariant(x));
- }
- }
-}
-
-void QQuickBasePositioner::positionY(int y, const PositionedItem &target)
-{
- Q_D(QQuickBasePositioner);
- if (d->type == Vertical || d->type == Both) {
- if (target.isNew) {
- if (!d->addTransition || !d->addTransition->enabled())
- target.item->setY(y);
- else
- d->addActions << QDeclarativeAction(target.item, QLatin1String("y"), QVariant(y));
- } else if (y != target.item->y()) {
- if (!d->moveTransition || !d->moveTransition->enabled())
- target.item->setY(y);
- else
- d->moveActions << QDeclarativeAction(target.item, QLatin1String("y"), QVariant(y));
- }
- }
-}
-
-void QQuickBasePositioner::finishApplyTransitions()
-{
- Q_D(QQuickBasePositioner);
- // Note that if a transition is not set the transition manager will
- // apply the changes directly, in the case add/move aren't set
- d->addTransitionManager.transition(d->addActions, d->addTransition);
- d->moveTransitionManager.transition(d->moveActions, d->moveTransition);
- d->addActions.clear();
- d->moveActions.clear();
-}
-
-QQuickPositionerAttached *QQuickBasePositioner::qmlAttachedProperties(QObject *obj)
-{
- return new QQuickPositionerAttached(obj);
-}
-
-void QQuickBasePositioner::updateAttachedProperties(QQuickPositionerAttached *specificProperty, QQuickItem *specificPropertyOwner) const
-{
- // If this function is deemed too expensive or shows up in profiles, it could
- // be changed to run only when there are attached properties present. This
- // could be a flag in the positioner that is set by the attached property
- // constructor.
- QQuickPositionerAttached *prevLastProperty = 0;
- QQuickPositionerAttached *lastProperty = 0;
-
- int visibleItemIndex = 0;
- for (int ii = 0; ii < positionedItems.count(); ++ii) {
- const PositionedItem &child = positionedItems.at(ii);
- if (!child.item)
- continue;
-
- QQuickPositionerAttached *property = 0;
-
- if (specificProperty) {
- if (specificPropertyOwner == child.item) {
- property = specificProperty;
- }
- } else {
- property = static_cast<QQuickPositionerAttached *>(qmlAttachedPropertiesObject<QQuickBasePositioner>(child.item, false));
- }
-
- if (child.isVisible) {
- if (property) {
- property->setIndex(visibleItemIndex);
- property->setIsFirstItem(visibleItemIndex == 0);
-
- if (property->isLastItem())
- prevLastProperty = property;
- }
-
- lastProperty = property;
- ++visibleItemIndex;
- } else if (property) {
- property->setIndex(-1);
- property->setIsFirstItem(false);
- property->setIsLastItem(false);
- }
- }
-
- if (prevLastProperty && prevLastProperty != lastProperty)
- prevLastProperty->setIsLastItem(false);
- if (lastProperty)
- lastProperty->setIsLastItem(true);
-}
-
-/*!
- \qmlclass Positioner QQuickPositionerAttached
- \inqmlmodule QtQuick 2
- \ingroup qml-positioning-elements
- \brief The Positioner type provides attached properties that contain details on where an item exists in a positioner.
-
- Positioner items (such as Column, Row, Flow and Grid) provide automatic layout
- for child items. Attaching this property allows a child item to determine
- where it exists within the positioner.
-*/
-
-QQuickPositionerAttached::QQuickPositionerAttached(QObject *parent) : QObject(parent), m_index(-1), m_isFirstItem(false), m_isLastItem(false)
-{
- QQuickItem *attachedItem = qobject_cast<QQuickItem *>(parent);
- if (attachedItem) {
- QQuickBasePositioner *positioner = qobject_cast<QQuickBasePositioner *>(attachedItem->parent());
- if (positioner) {
- positioner->updateAttachedProperties(this, attachedItem);
- }
- }
-}
-
-/*!
- \qmlattachedproperty Item QtQuick2::Positioner::index
-
- This property allows the item to determine
- its index within the positioner.
-*/
-void QQuickPositionerAttached::setIndex(int index)
-{
- if (m_index == index)
- return;
- m_index = index;
- emit indexChanged();
-}
-
-/*!
- \qmlattachedproperty Item QtQuick2::Positioner::isFirstItem
- \qmlattachedproperty Item QtQuick2::Positioner::isLastItem
-
- These properties allow the item to determine if it
- is the first or last item in the positioner, respectively.
-*/
-void QQuickPositionerAttached::setIsFirstItem(bool isFirstItem)
-{
- if (m_isFirstItem == isFirstItem)
- return;
- m_isFirstItem = isFirstItem;
- emit isFirstItemChanged();
-}
-
-void QQuickPositionerAttached::setIsLastItem(bool isLastItem)
-{
- if (m_isLastItem == isLastItem)
- return;
- m_isLastItem = isLastItem;
- emit isLastItemChanged();
-}
-
-/*!
- \qmlclass Column QQuickColumn
- \inqmlmodule QtQuick 2
- \ingroup qml-positioning-elements
- \brief The Column item arranges its children vertically.
- \inherits Item
-
- The Column item positions its child items so that they are vertically
- aligned and not overlapping.
-
- Spacing between items can be added using the \l spacing property.
- Transitions can be used for cases where items managed by a Column are
- added or moved. These are stored in the \l add and \l move properties
- respectively.
-
- See \l{Using QML Positioner and Repeater Items} for more details about this item and other
- related items.
-
- \section1 Example Usage
-
- The following example positions differently shaped rectangles using a Column
- item.
-
- \image verticalpositioner_example.png
-
- \snippet doc/src/snippets/declarative/column/vertical-positioner.qml document
-
- \section1 Using Transitions
-
- Transitions can be used to animate items that are added to, moved within,
- or removed from a Column item. The \l add and \l move properties can be set to
- the transitions that will be applied when items are added to, removed from,
- or re-positioned within a Column item.
-
- The use of transitions with positioners is described in more detail in the
- \l{Using QML Positioner and Repeater Items#Using Transitions}{Using QML
- Positioner and Repeater Items} document.
-
- \image verticalpositioner_transition.gif
-
- \qml
- Column {
- spacing: 2
- add: Transition {
- // Define an animation for adding a new item...
- }
- move: Transition {
- // Define an animation for moving items within the column...
- }
- // ...
- }
- \endqml
-
- \section1 Limitations
-
- Note that the positioner assumes that the x and y positions of its children
- will not change. If you manually change the x or y properties in script, bind
- the x or y properties, use anchors on a child of a positioner, or have the
- height of a child depend on the position of a child, then the
- positioner may exhibit strange behavior. If you need to perform any of these
- actions, consider positioning the items without the use of a Column.
-
- Items with a width or height of 0 will not be positioned.
-
- Positioning is batched and syncronized with painting to reduce the number of
- calculations needed. This means that positioners may not reposition items immediately
- when changes occur, but it will have moved by the next frame.
-
- \sa Row, Grid, Flow, Positioner, {declarative/positioners}{Positioners example}
-*/
-/*!
- \qmlproperty Transition QtQuick2::Column::add
-
- This property holds the transition to be applied when adding an
- item to the positioner. The transition will only be applied to the
- added item(s). Positioner transitions will only affect the
- position (x, y) of items.
-
- For a positioner, adding an item can mean that either the object
- has been created or reparented, and thus is now a child or the
- positioner, or that the object has had its opacity increased from
- zero, and thus is now visible.
-
- \sa move
-*/
-/*!
- \qmlproperty Transition QtQuick2::Column::move
-
- This property holds the transition to apply when moving an item
- within the positioner. Positioner transitions will only affect
- the position (x, y) of items.
-
- This transition can be performed when other items are added or removed
- from the positioner, or when items resize themselves.
-
- \image positioner-move.gif
-
- \qml
- Column {
- move: Transition {
- NumberAnimation {
- properties: "y"
- duration: 1000
- }
- }
- }
- \endqml
-
- \sa add, {declarative/positioners}{Positioners example}
-*/
-/*!
- \qmlproperty int QtQuick2::Column::spacing
-
- The spacing is the amount in pixels left empty between adjacent
- items. The default spacing is 0.
-
- \sa Grid::spacing
-*/
-QQuickColumn::QQuickColumn(QQuickItem *parent)
-: QQuickBasePositioner(Vertical, parent)
-{
-}
-
-void QQuickColumn::doPositioning(QSizeF *contentSize)
-{
- int voffset = 0;
-
- for (int ii = 0; ii < positionedItems.count(); ++ii) {
- const PositionedItem &child = positionedItems.at(ii);
- if (!child.item || !child.isVisible)
- continue;
-
- if (child.item->y() != voffset)
- positionY(voffset, child);
-
- contentSize->setWidth(qMax(contentSize->width(), child.item->width()));
-
- voffset += child.item->height();
- voffset += spacing();
- }
-
- if (voffset != 0)//If we positioned any items, undo the spacing from the last item
- voffset -= spacing();
- contentSize->setHeight(voffset);
-}
-
-void QQuickColumn::reportConflictingAnchors()
-{
- QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate*>(QQuickBasePositionerPrivate::get(this));
- for (int ii = 0; ii < positionedItems.count(); ++ii) {
- const PositionedItem &child = positionedItems.at(ii);
- if (child.item) {
- QQuickAnchors *anchors = QQuickItemPrivate::get(static_cast<QQuickItem *>(child.item))->_anchors;
- if (anchors) {
- QQuickAnchors::Anchors usedAnchors = anchors->usedAnchors();
- if (usedAnchors & QQuickAnchors::TopAnchor ||
- usedAnchors & QQuickAnchors::BottomAnchor ||
- usedAnchors & QQuickAnchors::VCenterAnchor ||
- anchors->fill() || anchors->centerIn()) {
- d->anchorConflict = true;
- break;
- }
- }
- }
- }
- if (d->anchorConflict) {
- qmlInfo(this) << "Cannot specify top, bottom, verticalCenter, fill or centerIn anchors for items inside Column";
- }
-}
-/*!
- \qmlclass Row QQuickRow
- \inqmlmodule QtQuick 2
- \ingroup qml-positioning-elements
- \brief The Row item arranges its children horizontally.
- \inherits Item
-
- The Row item positions its child items so that they are horizontally
- aligned and not overlapping.
-
- Use \l spacing to set the spacing between items in a Row, and use the
- \l add and \l move properties to set the transitions that should be applied
- when items are added to, removed from, or re-positioned within the Row.
-
- See \l{Using QML Positioner and Repeater Items} for more details about this item and other
- related items.
-
- \section1 Example Usage
-
- The following example lays out differently shaped rectangles using a Row.
-
- \image horizontalpositioner_example.png
-
- \snippet doc/src/snippets/declarative/row/row.qml document
-
- \section1 Using Transitions
-
- Transitions can be used to animate items that are added to, moved within,
- or removed from a Grid item. The \l add and \l move properties can be set to
- the transitions that will be applied when items are added to, removed from,
- or re-positioned within a Row item.
-
- \section1 Limitations
-
- Note that the positioner assumes that the x and y positions of its children
- will not change. If you manually change the x or y properties in script, bind
- the x or y properties, use anchors on a child of a positioner, or have the
- width of a child depend on the position of a child, then the
- positioner may exhibit strange behavior. If you need to perform any of these
- actions, consider positioning the items without the use of a Row.
-
- Items with a width or height of 0 will not be positioned.
-
- Positioning is batched and syncronized with painting to reduce the number of
- calculations needed. This means that positioners may not reposition items immediately
- when changes occur, but it will have moved by the next frame.
-
- \sa Column, Grid, Flow, Positioner, {declarative/positioners}{Positioners example}
-*/
-/*!
- \qmlproperty Transition QtQuick2::Row::add
-
- This property holds the transition to be applied when adding an
- item to the positioner. The transition will only be applied to the
- added item(s). Positioner transitions will only affect the
- position (x, y) of items.
-
- For a positioner, adding an item can mean that either the object
- has been created or reparented, and thus is now a child or the
- positioner, or that the object has had its opacity increased from
- zero, and thus is now visible.
-
- \sa move
-*/
-/*!
- \qmlproperty Transition QtQuick2::Row::move
-
- This property holds the transition to be applied when moving an
- item within the positioner. Positioner transitions will only affect
- the position (x, y) of items.
-
- This transition can be performed when other items are added or removed
- from the positioner, or when items resize themselves.
-
- \qml
- Row {
- id: positioner
- move: Transition {
- NumberAnimation {
- properties: "x"
- duration: 1000
- }
- }
- }
- \endqml
-
- \sa add, {declarative/positioners}{Positioners example}
-*/
-/*!
- \qmlproperty int QtQuick2::Row::spacing
-
- The spacing is the amount in pixels left empty between adjacent
- items. The default spacing is 0.
-
- \sa Grid::spacing
-*/
-
-QQuickRow::QQuickRow(QQuickItem *parent)
-: QQuickBasePositioner(Horizontal, parent)
-{
-}
-/*!
- \qmlproperty enumeration QtQuick2::Row::layoutDirection
-
- This property holds the layoutDirection of the row.
-
- Possible values:
-
- \list
- \o Qt.LeftToRight (default) - Items are laid out from left to right. If the width of the row is explicitly set,
- the left anchor remains to the left of the row.
- \o Qt.RightToLeft - Items are laid out from right to left. If the width of the row is explicitly set,
- the right anchor remains to the right of the row.
- \endlist
-
- \sa Grid::layoutDirection, Flow::layoutDirection, {declarative/righttoleft/layoutdirection}{Layout directions example}
-*/
-
-Qt::LayoutDirection QQuickRow::layoutDirection() const
-{
- return QQuickBasePositionerPrivate::getLayoutDirection(this);
-}
-
-void QQuickRow::setLayoutDirection(Qt::LayoutDirection layoutDirection)
-{
- QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate* >(QQuickBasePositionerPrivate::get(this));
- if (d->layoutDirection != layoutDirection) {
- d->layoutDirection = layoutDirection;
- // For RTL layout the positioning changes when the width changes.
- if (d->layoutDirection == Qt::RightToLeft)
- d->addItemChangeListener(d, QQuickItemPrivate::Geometry);
- else
- d->removeItemChangeListener(d, QQuickItemPrivate::Geometry);
- prePositioning();
- emit layoutDirectionChanged();
- emit effectiveLayoutDirectionChanged();
- }
-}
-/*!
- \qmlproperty enumeration QtQuick2::Row::effectiveLayoutDirection
- This property holds the effective layout direction of the row positioner.
-
- When using the attached property \l {LayoutMirroring::enabled}{LayoutMirroring::enabled} for locale layouts,
- the visual layout direction of the row positioner will be mirrored. However, the
- property \l {Row::layoutDirection}{layoutDirection} will remain unchanged.
-
- \sa Row::layoutDirection, {LayoutMirroring}{LayoutMirroring}
-*/
-
-Qt::LayoutDirection QQuickRow::effectiveLayoutDirection() const
-{
- return QQuickBasePositionerPrivate::getEffectiveLayoutDirection(this);
-}
-
-void QQuickRow::doPositioning(QSizeF *contentSize)
-{
- QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate* >(QQuickBasePositionerPrivate::get(this));
- int hoffset = 0;
-
- QList<int> hoffsets;
- for (int ii = 0; ii < positionedItems.count(); ++ii) {
- const PositionedItem &child = positionedItems.at(ii);
- if (!child.item || !child.isVisible)
- continue;
-
- if (d->isLeftToRight()) {
- if (child.item->x() != hoffset)
- positionX(hoffset, child);
- } else {
- hoffsets << hoffset;
- }
-
- contentSize->setHeight(qMax(contentSize->height(), child.item->height()));
-
- hoffset += child.item->width();
- hoffset += spacing();
- }
-
- if (hoffset != 0)//If we positioned any items, undo the extra spacing from the last item
- hoffset -= spacing();
- contentSize->setWidth(hoffset);
-
- if (d->isLeftToRight())
- return;
-
- //Right to Left layout
- int end = 0;
- if (!widthValid())
- end = contentSize->width();
- else
- end = width();
-
- int acc = 0;
- for (int ii = 0; ii < positionedItems.count(); ++ii) {
- const PositionedItem &child = positionedItems.at(ii);
- if (!child.item || !child.isVisible)
- continue;
- hoffset = end - hoffsets[acc++] - child.item->width();
- if (child.item->x() != hoffset)
- positionX(hoffset, child);
- }
-}
-
-void QQuickRow::reportConflictingAnchors()
-{
- QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate*>(QQuickBasePositionerPrivate::get(this));
- for (int ii = 0; ii < positionedItems.count(); ++ii) {
- const PositionedItem &child = positionedItems.at(ii);
- if (child.item) {
- QQuickAnchors *anchors = QQuickItemPrivate::get(static_cast<QQuickItem *>(child.item))->_anchors;
- if (anchors) {
- QQuickAnchors::Anchors usedAnchors = anchors->usedAnchors();
- if (usedAnchors & QQuickAnchors::LeftAnchor ||
- usedAnchors & QQuickAnchors::RightAnchor ||
- usedAnchors & QQuickAnchors::HCenterAnchor ||
- anchors->fill() || anchors->centerIn()) {
- d->anchorConflict = true;
- break;
- }
- }
- }
- }
- if (d->anchorConflict)
- qmlInfo(this) << "Cannot specify left, right, horizontalCenter, fill or centerIn anchors for items inside Row";
-}
-
-/*!
- \qmlclass Grid QQuickGrid
- \inqmlmodule QtQuick 2
- \ingroup qml-positioning-elements
- \brief The Grid item positions its children in a grid.
- \inherits Item
-
- The Grid item positions its child items so that they are
- aligned in a grid and are not overlapping.
-
- The grid positioner calculates a grid of rectangular cells of sufficient
- size to hold all items, placing the items in the cells, from left to right
- and top to bottom. Each item is positioned in the top-left corner of its
- cell with position (0, 0).
-
- A Grid defaults to four columns, and as many rows as are necessary to
- fit all child items. The number of rows and columns can be constrained
- by setting the \l rows and \l columns properties.
-
- Spacing can be added between child items by setting the \l spacing
- property. The amount of spacing applied will be the same in the
- horizontal and vertical directions.
-
- See \l{Using QML Positioner and Repeater Items} for more details about this item and other
- related items.
-
- \section1 Example Usage
-
- The following example demonstrates this.
-
- \image gridLayout_example.png
-
- \snippet doc/src/snippets/declarative/grid/grid.qml document
-
- \section1 Using Transitions
-
- Transitions can be used to animate items that are added to, moved within,
- or removed from a Grid item. The \l add and \l move properties can be set to
- the transitions that will be applied when items are added to, removed from,
- or re-positioned within a Grid item.
-
- \section1 Limitations
-
- Note that the positioner assumes that the x and y positions of its children
- will not change. If you manually change the x or y properties in script, bind
- the x or y properties, use anchors on a child of a positioner, or have the
- width or height of a child depend on the position of a child, then the
- positioner may exhibit strange behavior. If you need to perform any of these
- actions, consider positioning the items without the use of a Grid.
-
- Items with a width or height of 0 will not be positioned.
-
- Positioning is batched and syncronized with painting to reduce the number of
- calculations needed. This means that positioners may not reposition items immediately
- when changes occur, but it will have moved by the next frame.
-
- \sa Flow, Row, Column, Positioner, {declarative/positioners}{Positioners example}
-*/
-/*!
- \qmlproperty Transition QtQuick2::Grid::add
-
- This property holds the transition to be applied when adding an
- item to the positioner. The transition will only be applied to the
- added item(s). Positioner transitions will only affect the
- position (x, y) of items.
-
- For a positioner, adding an item can mean that either the object
- has been created or reparented, and thus is now a child or the
- positioner, or that the object has had its opacity increased from
- zero, and thus is now visible.
-
- \sa move
-*/
-/*!
- \qmlproperty Transition QtQuick2::Grid::move
-
- This property holds the transition to be applied when moving an
- item within the positioner. Positioner transitions will only affect
- the position (x, y) of items.
-
- This transition can be performed when other items are added or removed
- from the positioner, or when items resize themselves.
-
- \qml
- Grid {
- move: Transition {
- NumberAnimation {
- properties: "x,y"
- duration: 1000
- }
- }
- }
- \endqml
-
- \sa add, {declarative/positioners}{Positioners example}
-*/
-/*!
- \qmlproperty int QtQuick2::Grid::spacing
-
- The spacing is the amount in pixels left empty between adjacent
- items. The default spacing is 0.
-
- The below example places a Grid containing a red, a blue and a
- green rectangle on a gray background. The area the grid positioner
- occupies is colored white. The positioner on the left has the
- no spacing (the default), and the positioner on the right has
- a spacing of 6.
-
- \inlineimage qml-grid-no-spacing.png
- \inlineimage qml-grid-spacing.png
-
- \sa rows, columns
-*/
-QQuickGrid::QQuickGrid(QQuickItem *parent) :
- QQuickBasePositioner(Both, parent), m_rows(-1), m_columns(-1), m_rowSpacing(-1), m_columnSpacing(-1), m_flow(LeftToRight)
-{
-}
-
-/*!
- \qmlproperty int QtQuick2::Grid::columns
-
- This property holds the number of columns in the grid. The default
- number of columns is 4.
-
- If the grid does not have enough items to fill the specified
- number of columns, some columns will be of zero width.
-*/
-
-/*!
- \qmlproperty int QtQuick2::Grid::rows
- This property holds the number of rows in the grid.
-
- If the grid does not have enough items to fill the specified
- number of rows, some rows will be of zero width.
-*/
-
-void QQuickGrid::setColumns(const int columns)
-{
- if (columns == m_columns)
- return;
- m_columns = columns;
- prePositioning();
- emit columnsChanged();
-}
-
-void QQuickGrid::setRows(const int rows)
-{
- if (rows == m_rows)
- return;
- m_rows = rows;
- prePositioning();
- emit rowsChanged();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Grid::flow
- This property holds the flow of the layout.
-
- Possible values are:
-
- \list
- \o Grid.LeftToRight (default) - Items are positioned next to
- each other in the \l layoutDirection, then wrapped to the next line.
- \o Grid.TopToBottom - Items are positioned next to each
- other from top to bottom, then wrapped to the next column.
- \endlist
-*/
-QQuickGrid::Flow QQuickGrid::flow() const
-{
- return m_flow;
-}
-
-void QQuickGrid::setFlow(Flow flow)
-{
- if (m_flow != flow) {
- m_flow = flow;
- prePositioning();
- emit flowChanged();
- }
-}
-
-/*!
- \qmlproperty int QtQuick2::Grid::rowSpacing
-
- This property holds the spacing in pixels between rows.
-
- \sa columnSpacing
- \since QtQuick2.0
-*/
-void QQuickGrid::setRowSpacing(const int rowSpacing)
-{
- if (rowSpacing == m_rowSpacing)
- return;
- m_rowSpacing = rowSpacing;
- prePositioning();
- emit rowSpacingChanged();
-}
-
-/*!
- \qmlproperty int QtQuick2::Grid::columnSpacing
-
- This property holds the spacing in pixels between columns.
-
- \sa rowSpacing
- \since QtQuick2.0
-*/
-void QQuickGrid::setColumnSpacing(const int columnSpacing)
-{
- if (columnSpacing == m_columnSpacing)
- return;
- m_columnSpacing = columnSpacing;
- prePositioning();
- emit columnSpacingChanged();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Grid::layoutDirection
-
- This property holds the layout direction of the layout.
-
- Possible values are:
-
- \list
- \o Qt.LeftToRight (default) - Items are positioned from the top to bottom,
- and left to right. The flow direction is dependent on the
- \l Grid::flow property.
- \o Qt.RightToLeft - Items are positioned from the top to bottom,
- and right to left. The flow direction is dependent on the
- \l Grid::flow property.
- \endlist
-
- \sa Flow::layoutDirection, Row::layoutDirection, {declarative/righttoleft/layoutdirection}{Layout directions example}
-*/
-Qt::LayoutDirection QQuickGrid::layoutDirection() const
-{
- return QQuickBasePositionerPrivate::getLayoutDirection(this);
-}
-
-void QQuickGrid::setLayoutDirection(Qt::LayoutDirection layoutDirection)
-{
- QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate*>(QQuickBasePositionerPrivate::get(this));
- if (d->layoutDirection != layoutDirection) {
- d->layoutDirection = layoutDirection;
- // For RTL layout the positioning changes when the width changes.
- if (d->layoutDirection == Qt::RightToLeft)
- d->addItemChangeListener(d, QQuickItemPrivate::Geometry);
- else
- d->removeItemChangeListener(d, QQuickItemPrivate::Geometry);
- prePositioning();
- emit layoutDirectionChanged();
- emit effectiveLayoutDirectionChanged();
- }
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Grid::effectiveLayoutDirection
- This property holds the effective layout direction of the grid positioner.
-
- When using the attached property \l {LayoutMirroring::enabled}{LayoutMirroring::enabled} for locale layouts,
- the visual layout direction of the grid positioner will be mirrored. However, the
- property \l {Grid::layoutDirection}{layoutDirection} will remain unchanged.
-
- \sa Grid::layoutDirection, {LayoutMirroring}{LayoutMirroring}
-*/
-Qt::LayoutDirection QQuickGrid::effectiveLayoutDirection() const
-{
- return QQuickBasePositionerPrivate::getEffectiveLayoutDirection(this);
-}
-
-void QQuickGrid::doPositioning(QSizeF *contentSize)
-{
- QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate*>(QQuickBasePositionerPrivate::get(this));
- int c = m_columns;
- int r = m_rows;
- //Is allocating the extra QPODVector too much overhead?
- QPODVector<PositionedItem, 8> visibleItems;//we aren't concerned with invisible items
- visibleItems.reserve(positionedItems.count());
- for (int i=0; i<positionedItems.count(); i++)
- if (positionedItems[i].item && positionedItems[i].isVisible)
- visibleItems.append(positionedItems[i]);
-
- int numVisible = visibleItems.count();
- if (m_columns <= 0 && m_rows <= 0){
- c = 4;
- r = (numVisible+3)/4;
- } else if (m_rows <= 0){
- r = (numVisible+(m_columns-1))/m_columns;
- } else if (m_columns <= 0){
- c = (numVisible+(m_rows-1))/m_rows;
- }
-
- if (r==0 || c==0)
- return; //Nothing to do
-
- QList<int> maxColWidth;
- QList<int> maxRowHeight;
- int childIndex =0;
- if (m_flow == LeftToRight) {
- for (int i=0; i < r; i++){
- for (int j=0; j < c; j++){
- if (j==0)
- maxRowHeight << 0;
- if (i==0)
- maxColWidth << 0;
-
- if (childIndex == visibleItems.count())
- break;
-
- const PositionedItem &child = visibleItems.at(childIndex++);
- if (child.item->width() > maxColWidth[j])
- maxColWidth[j] = child.item->width();
- if (child.item->height() > maxRowHeight[i])
- maxRowHeight[i] = child.item->height();
- }
- }
- } else {
- for (int j=0; j < c; j++){
- for (int i=0; i < r; i++){
- if (j==0)
- maxRowHeight << 0;
- if (i==0)
- maxColWidth << 0;
-
- if (childIndex == visibleItems.count())
- break;
-
- const PositionedItem &child = visibleItems.at(childIndex++);
- if (child.item->width() > maxColWidth[j])
- maxColWidth[j] = child.item->width();
- if (child.item->height() > maxRowHeight[i])
- maxRowHeight[i] = child.item->height();
- }
- }
- }
-
- int columnSpacing = m_columnSpacing;
- if (columnSpacing == -1)
- columnSpacing = spacing();
-
- int rowSpacing = m_rowSpacing;
- if (rowSpacing == -1)
- rowSpacing = spacing();
-
- int widthSum = 0;
- for (int j=0; j < maxColWidth.size(); j++){
- if (j)
- widthSum += columnSpacing;
- widthSum += maxColWidth[j];
- }
-
- int heightSum = 0;
- for (int i=0; i < maxRowHeight.size(); i++){
- if (i)
- heightSum += rowSpacing;
- heightSum += maxRowHeight[i];
- }
-
- contentSize->setHeight(heightSum);
- contentSize->setWidth(widthSum);
-
- int end = 0;
- if (widthValid())
- end = width();
- else
- end = widthSum;
-
- int xoffset=0;
- if (!d->isLeftToRight())
- xoffset = end;
- int yoffset=0;
- int curRow =0;
- int curCol =0;
- for (int i = 0; i < visibleItems.count(); ++i) {
- const PositionedItem &child = visibleItems.at(i);
- int childXOffset = xoffset;
- if (!d->isLeftToRight())
- childXOffset -= child.item->width();
- if ((child.item->x() != childXOffset) || (child.item->y() != yoffset)){
- positionX(childXOffset, child);
- positionY(yoffset, child);
- }
-
- if (m_flow == LeftToRight) {
- if (d->isLeftToRight())
- xoffset += maxColWidth[curCol]+columnSpacing;
- else
- xoffset -= maxColWidth[curCol]+columnSpacing;
- curCol++;
- curCol%=c;
- if (!curCol){
- yoffset += maxRowHeight[curRow]+rowSpacing;
- if (d->isLeftToRight())
- xoffset = 0;
- else
- xoffset = end;
- curRow++;
- if (curRow>=r)
- break;
- }
- } else {
- yoffset+=maxRowHeight[curRow]+rowSpacing;
- curRow++;
- curRow%=r;
- if (!curRow){
- if (d->isLeftToRight())
- xoffset += maxColWidth[curCol]+columnSpacing;
- else
- xoffset -= maxColWidth[curCol]+columnSpacing;
- yoffset=0;
- curCol++;
- if (curCol>=c)
- break;
- }
- }
- }
-}
-
-void QQuickGrid::reportConflictingAnchors()
-{
- QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate*>(QQuickBasePositionerPrivate::get(this));
- for (int ii = 0; ii < positionedItems.count(); ++ii) {
- const PositionedItem &child = positionedItems.at(ii);
- if (child.item) {
- QQuickAnchors *anchors = QQuickItemPrivate::get(static_cast<QQuickItem *>(child.item))->_anchors;
- if (anchors && (anchors->usedAnchors() || anchors->fill() || anchors->centerIn())) {
- d->anchorConflict = true;
- break;
- }
- }
- }
- if (d->anchorConflict)
- qmlInfo(this) << "Cannot specify anchors for items inside Grid";
-}
-
-/*!
- \qmlclass Flow QQuickFlow
- \inqmlmodule QtQuick 2
- \ingroup qml-positioning-elements
- \brief The Flow item arranges its children side by side, wrapping as necessary.
- \inherits Item
-
- The Flow item positions its child items like words on a page, wrapping them
- to create rows or columns of items that do not overlap.
-
- Spacing between items can be added using the \l spacing property.
- Transitions can be used for cases where items managed by a Column are
- added or moved. These are stored in the \l add and \l move properties
- respectively.
-
- See \l{Using QML Positioner and Repeater Items} for more details about this item and other
- related items.
-
- \section1 Example Usage
-
- The following example positions \l Text items within a parent item using
- a Flow item.
-
- \image qml-flow-snippet.png
-
- \snippet doc/src/snippets/declarative/flow.qml flow item
-
- \section1 Using Transitions
-
- Transitions can be used to animate items that are added to, moved within,
- or removed from a Flow item. The \l add and \l move properties can be set to
- the transitions that will be applied when items are added to, removed from,
- or re-positioned within a Flow item.
-
- The use of transitions with positioners is described in more detail in the
- \l{Using QML Positioner and Repeater Items#Using Transitions}{Using QML
- Positioner and Repeater Items} document.
-
- \section1 Limitations
-
- Note that the positioner assumes that the x and y positions of its children
- will not change. If you manually change the x or y properties in script, bind
- the x or y properties, use anchors on a child of a positioner, or have the
- width or height of a child depend on the position of a child, then the
- positioner may exhibit strange behavior. If you need to perform any of these
- actions, consider positioning the items without the use of a Flow.
-
- Items with a width or height of 0 will not be positioned.
-
- Positioning is batched and syncronized with painting to reduce the number of
- calculations needed. This means that positioners may not reposition items immediately
- when changes occur, but it will have moved by the next frame.
-
- \sa Column, Row, Grid, Positioner, {declarative/positioners}{Positioners example}
-*/
-/*!
- \qmlproperty Transition QtQuick2::Flow::add
-
- This property holds the transition to be applied when adding an
- item to the positioner. The transition will only be applied to the
- added item(s). Positioner transitions will only affect the
- position (x, y) of items.
-
- For a positioner, adding an item can mean that either the object
- has been created or reparented, and thus is now a child or the
- positioner, or that the object has had its opacity increased from
- zero, and thus is now visible.
-
- \sa move
-*/
-/*!
- \qmlproperty Transition QtQuick2::Flow::move
-
- This property holds the transition to be applied when moving an
- item within the positioner. Positioner transitions will only affect
- the position (x, y) of items.
-
- This transition can be performed when other items are added or removed
- from the positioner, or when items resize themselves.
-
- \qml
- Flow {
- id: positioner
- move: Transition {
- NumberAnimation {
- properties: "x,y"
- ease: "easeOutBounce"
- }
- }
- }
- \endqml
-
- \sa add, {declarative/positioners}{Positioners example}
-*/
-/*!
- \qmlproperty int QtQuick2::Flow::spacing
-
- spacing is the amount in pixels left empty between each adjacent
- item, and defaults to 0.
-
- \sa Grid::spacing
-*/
-
-class QQuickFlowPrivate : public QQuickBasePositionerPrivate
-{
- Q_DECLARE_PUBLIC(QQuickFlow)
-
-public:
- QQuickFlowPrivate()
- : QQuickBasePositionerPrivate(), flow(QQuickFlow::LeftToRight)
- {}
-
- QQuickFlow::Flow flow;
-};
-
-QQuickFlow::QQuickFlow(QQuickItem *parent)
-: QQuickBasePositioner(*(new QQuickFlowPrivate), Both, parent)
-{
- Q_D(QQuickFlow);
- // Flow layout requires relayout if its own size changes too.
- d->addItemChangeListener(d, QQuickItemPrivate::Geometry);
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Flow::flow
- This property holds the flow of the layout.
-
- Possible values are:
-
- \list
- \o Flow.LeftToRight (default) - Items are positioned next to
- to each other according to the \l layoutDirection until the width of the Flow
- is exceeded, then wrapped to the next line.
- \o Flow.TopToBottom - Items are positioned next to each
- other from top to bottom until the height of the Flow is exceeded,
- then wrapped to the next column.
- \endlist
-*/
-QQuickFlow::Flow QQuickFlow::flow() const
-{
- Q_D(const QQuickFlow);
- return d->flow;
-}
-
-void QQuickFlow::setFlow(Flow flow)
-{
- Q_D(QQuickFlow);
- if (d->flow != flow) {
- d->flow = flow;
- prePositioning();
- emit flowChanged();
- }
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Flow::layoutDirection
-
- This property holds the layout direction of the layout.
-
- Possible values are:
-
- \list
- \o Qt.LeftToRight (default) - Items are positioned from the top to bottom,
- and left to right. The flow direction is dependent on the
- \l Flow::flow property.
- \o Qt.RightToLeft - Items are positioned from the top to bottom,
- and right to left. The flow direction is dependent on the
- \l Flow::flow property.
- \endlist
-
- \sa Grid::layoutDirection, Row::layoutDirection, {declarative/righttoleft/layoutdirection}{Layout directions example}
-*/
-
-Qt::LayoutDirection QQuickFlow::layoutDirection() const
-{
- Q_D(const QQuickFlow);
- return d->layoutDirection;
-}
-
-void QQuickFlow::setLayoutDirection(Qt::LayoutDirection layoutDirection)
-{
- Q_D(QQuickFlow);
- if (d->layoutDirection != layoutDirection) {
- d->layoutDirection = layoutDirection;
- prePositioning();
- emit layoutDirectionChanged();
- emit effectiveLayoutDirectionChanged();
- }
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Flow::effectiveLayoutDirection
- This property holds the effective layout direction of the flow positioner.
-
- When using the attached property \l {LayoutMirroring::enabled}{LayoutMirroring::enabled} for locale layouts,
- the visual layout direction of the grid positioner will be mirrored. However, the
- property \l {Flow::layoutDirection}{layoutDirection} will remain unchanged.
-
- \sa Flow::layoutDirection, {LayoutMirroring}{LayoutMirroring}
-*/
-
-Qt::LayoutDirection QQuickFlow::effectiveLayoutDirection() const
-{
- return QQuickBasePositionerPrivate::getEffectiveLayoutDirection(this);
-}
-
-void QQuickFlow::doPositioning(QSizeF *contentSize)
-{
- Q_D(QQuickFlow);
-
- int hoffset = 0;
- int voffset = 0;
- int linemax = 0;
- QList<int> hoffsets;
-
- for (int i = 0; i < positionedItems.count(); ++i) {
- const PositionedItem &child = positionedItems.at(i);
- if (!child.item || !child.isVisible)
- continue;
-
- if (d->flow == LeftToRight) {
- if (widthValid() && hoffset && hoffset + child.item->width() > width()) {
- hoffset = 0;
- voffset += linemax + spacing();
- linemax = 0;
- }
- } else {
- if (heightValid() && voffset && voffset + child.item->height() > height()) {
- voffset = 0;
- hoffset += linemax + spacing();
- linemax = 0;
- }
- }
-
- if (d->isLeftToRight()) {
- if (child.item->x() != hoffset)
- positionX(hoffset, child);
- } else {
- hoffsets << hoffset;
- }
- if (child.item->y() != voffset)
- positionY(voffset, child);
-
- contentSize->setWidth(qMax(contentSize->width(), hoffset + child.item->width()));
- contentSize->setHeight(qMax(contentSize->height(), voffset + child.item->height()));
-
- if (d->flow == LeftToRight) {
- hoffset += child.item->width();
- hoffset += spacing();
- linemax = qMax(linemax, qCeil(child.item->height()));
- } else {
- voffset += child.item->height();
- voffset += spacing();
- linemax = qMax(linemax, qCeil(child.item->width()));
- }
- }
- if (d->isLeftToRight())
- return;
-
- int end;
- if (widthValid())
- end = width();
- else
- end = contentSize->width();
- int acc = 0;
- for (int i = 0; i < positionedItems.count(); ++i) {
- const PositionedItem &child = positionedItems.at(i);
- if (!child.item || !child.isVisible)
- continue;
- hoffset = end - hoffsets[acc++] - child.item->width();
- if (child.item->x() != hoffset)
- positionX(hoffset, child);
- }
-}
-
-void QQuickFlow::reportConflictingAnchors()
-{
- Q_D(QQuickFlow);
- for (int ii = 0; ii < positionedItems.count(); ++ii) {
- const PositionedItem &child = positionedItems.at(ii);
- if (child.item) {
- QQuickAnchors *anchors = QQuickItemPrivate::get(static_cast<QQuickItem *>(child.item))->_anchors;
- if (anchors && (anchors->usedAnchors() || anchors->fill() || anchors->centerIn())) {
- d->anchorConflict = true;
- break;
- }
- }
- }
- if (d->anchorConflict)
- qmlInfo(this) << "Cannot specify anchors for items inside Flow";
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickpositioners_p.h b/src/declarative/items/qquickpositioners_p.h
deleted file mode 100644
index b8e8879205..0000000000
--- a/src/declarative/items/qquickpositioners_p.h
+++ /dev/null
@@ -1,295 +0,0 @@
-// Commit: 2c7cab4172f1acc86fd49345a2847417e162f2c3
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKPOSITIONERS_P_H
-#define QQUICKPOSITIONERS_P_H
-
-#include "qquickimplicitsizeitem_p.h"
-
-#include <private/qdeclarativestate_p.h>
-#include <private/qpodvector_p.h>
-
-#include <QtCore/qobject.h>
-#include <QtCore/qstring.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickBasePositionerPrivate;
-
-class QQuickPositionerAttached : public QObject
-{
- Q_OBJECT
-
-public:
- QQuickPositionerAttached(QObject *parent);
-
- Q_PROPERTY(int index READ index NOTIFY indexChanged)
- Q_PROPERTY(bool isFirstItem READ isFirstItem NOTIFY isFirstItemChanged)
- Q_PROPERTY(bool isLastItem READ isLastItem NOTIFY isLastItemChanged)
-
- int index() const { return m_index; }
- void setIndex(int index);
-
- bool isFirstItem() const { return m_isFirstItem; }
- void setIsFirstItem(bool isFirstItem);
-
- bool isLastItem() const { return m_isLastItem; }
- void setIsLastItem(bool isLastItem);
-
-Q_SIGNALS:
- void indexChanged();
- void isFirstItemChanged();
- void isLastItemChanged();
-
-private:
- int m_index;
- bool m_isFirstItem;
- bool m_isLastItem;
-};
-
-class Q_DECLARATIVE_PRIVATE_EXPORT QQuickBasePositioner : public QQuickImplicitSizeItem
-{
- Q_OBJECT
-
- Q_PROPERTY(int spacing READ spacing WRITE setSpacing NOTIFY spacingChanged)
- Q_PROPERTY(QDeclarativeTransition *move READ move WRITE setMove NOTIFY moveChanged)
- Q_PROPERTY(QDeclarativeTransition *add READ add WRITE setAdd NOTIFY addChanged)
-public:
- enum PositionerType { None = 0x0, Horizontal = 0x1, Vertical = 0x2, Both = 0x3 };
- QQuickBasePositioner(PositionerType, QQuickItem *parent);
- ~QQuickBasePositioner();
-
- int spacing() const;
- void setSpacing(int);
-
- QDeclarativeTransition *move() const;
- void setMove(QDeclarativeTransition *);
-
- QDeclarativeTransition *add() const;
- void setAdd(QDeclarativeTransition *);
-
- static QQuickPositionerAttached *qmlAttachedProperties(QObject *obj);
-
- void updateAttachedProperties(QQuickPositionerAttached *specificProperty = 0, QQuickItem *specificPropertyOwner = 0) const;
-
-protected:
- QQuickBasePositioner(QQuickBasePositionerPrivate &dd, PositionerType at, QQuickItem *parent);
- virtual void componentComplete();
- virtual void itemChange(ItemChange, const ItemChangeData &);
- void finishApplyTransitions();
-
- virtual void updatePolish();
-
-Q_SIGNALS:
- void spacingChanged();
- void moveChanged();
- void addChanged();
-
-protected Q_SLOTS:
- void prePositioning();
-
-protected:
- virtual void doPositioning(QSizeF *contentSize)=0;
- virtual void reportConflictingAnchors()=0;
- class PositionedItem {
- public :
- PositionedItem(QQuickItem *i) : item(i), isNew(false), isVisible(true) {}
- bool operator==(const PositionedItem &other) const { return other.item == item; }
- QQuickItem *item;
- bool isNew;
- bool isVisible;
- };
-
- QPODVector<PositionedItem,8> positionedItems;
- void positionX(int,const PositionedItem &target);
- void positionY(int,const PositionedItem &target);
-
-private:
- Q_DISABLE_COPY(QQuickBasePositioner)
- Q_DECLARE_PRIVATE(QQuickBasePositioner)
-};
-
-class Q_AUTOTEST_EXPORT QQuickColumn : public QQuickBasePositioner
-{
- Q_OBJECT
-public:
- QQuickColumn(QQuickItem *parent=0);
-
-protected:
- virtual void doPositioning(QSizeF *contentSize);
- virtual void reportConflictingAnchors();
-private:
- Q_DISABLE_COPY(QQuickColumn)
-};
-
-class Q_AUTOTEST_EXPORT QQuickRow: public QQuickBasePositioner
-{
- Q_OBJECT
- Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection NOTIFY layoutDirectionChanged)
- Q_PROPERTY(Qt::LayoutDirection effectiveLayoutDirection READ effectiveLayoutDirection NOTIFY effectiveLayoutDirectionChanged)
-public:
- QQuickRow(QQuickItem *parent=0);
-
- Qt::LayoutDirection layoutDirection() const;
- void setLayoutDirection (Qt::LayoutDirection);
- Qt::LayoutDirection effectiveLayoutDirection() const;
-
-Q_SIGNALS:
- void layoutDirectionChanged();
- void effectiveLayoutDirectionChanged();
-
-protected:
- virtual void doPositioning(QSizeF *contentSize);
- virtual void reportConflictingAnchors();
-private:
- Q_DISABLE_COPY(QQuickRow)
-};
-
-class Q_AUTOTEST_EXPORT QQuickGrid : public QQuickBasePositioner
-{
- Q_OBJECT
- Q_PROPERTY(int rows READ rows WRITE setRows NOTIFY rowsChanged)
- Q_PROPERTY(int columns READ columns WRITE setColumns NOTIFY columnsChanged)
- Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing NOTIFY rowSpacingChanged)
- Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing NOTIFY columnSpacingChanged)
- Q_PROPERTY(Flow flow READ flow WRITE setFlow NOTIFY flowChanged)
- Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection NOTIFY layoutDirectionChanged)
- Q_PROPERTY(Qt::LayoutDirection effectiveLayoutDirection READ effectiveLayoutDirection NOTIFY effectiveLayoutDirectionChanged)
-
-public:
- QQuickGrid(QQuickItem *parent=0);
-
- int rows() const {return m_rows;}
- void setRows(const int rows);
-
- int columns() const {return m_columns;}
- void setColumns(const int columns);
-
- int rowSpacing() const { return m_rowSpacing; }
- void setRowSpacing(int);
-
- int columnSpacing() const { return m_columnSpacing; }
- void setColumnSpacing(int);
-
- Q_ENUMS(Flow)
- enum Flow { LeftToRight, TopToBottom };
- Flow flow() const;
- void setFlow(Flow);
-
- Qt::LayoutDirection layoutDirection() const;
- void setLayoutDirection (Qt::LayoutDirection);
- Qt::LayoutDirection effectiveLayoutDirection() const;
-
-Q_SIGNALS:
- void rowsChanged();
- void columnsChanged();
- void flowChanged();
- void layoutDirectionChanged();
- void effectiveLayoutDirectionChanged();
- void rowSpacingChanged();
- void columnSpacingChanged();
-
-protected:
- virtual void doPositioning(QSizeF *contentSize);
- virtual void reportConflictingAnchors();
-
-private:
- int m_rows;
- int m_columns;
- int m_rowSpacing;
- int m_columnSpacing;
- Flow m_flow;
- Q_DISABLE_COPY(QQuickGrid)
-};
-
-class QQuickFlowPrivate;
-class Q_AUTOTEST_EXPORT QQuickFlow: public QQuickBasePositioner
-{
- Q_OBJECT
- Q_PROPERTY(Flow flow READ flow WRITE setFlow NOTIFY flowChanged)
- Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection NOTIFY layoutDirectionChanged)
- Q_PROPERTY(Qt::LayoutDirection effectiveLayoutDirection READ effectiveLayoutDirection NOTIFY effectiveLayoutDirectionChanged)
-public:
- QQuickFlow(QQuickItem *parent=0);
-
- Q_ENUMS(Flow)
- enum Flow { LeftToRight, TopToBottom };
- Flow flow() const;
- void setFlow(Flow);
-
- Qt::LayoutDirection layoutDirection() const;
- void setLayoutDirection (Qt::LayoutDirection);
- Qt::LayoutDirection effectiveLayoutDirection() const;
-
-Q_SIGNALS:
- void flowChanged();
- void layoutDirectionChanged();
- void effectiveLayoutDirectionChanged();
-
-protected:
- virtual void doPositioning(QSizeF *contentSize);
- virtual void reportConflictingAnchors();
-protected:
- QQuickFlow(QQuickFlowPrivate &dd, QQuickItem *parent);
-private:
- Q_DISABLE_COPY(QQuickFlow)
- Q_DECLARE_PRIVATE(QQuickFlow)
-};
-
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickColumn)
-QML_DECLARE_TYPE(QQuickRow)
-QML_DECLARE_TYPE(QQuickGrid)
-QML_DECLARE_TYPE(QQuickFlow)
-
-QML_DECLARE_TYPE(QQuickBasePositioner)
-QML_DECLARE_TYPEINFO(QQuickBasePositioner, QML_HAS_ATTACHED_PROPERTIES)
-
-QT_END_HEADER
-
-#endif // QQUICKPOSITIONERS_P_H
diff --git a/src/declarative/items/qquickpositioners_p_p.h b/src/declarative/items/qquickpositioners_p_p.h
deleted file mode 100644
index 86c6c74ba6..0000000000
--- a/src/declarative/items/qquickpositioners_p_p.h
+++ /dev/null
@@ -1,164 +0,0 @@
-// Commit: 2c7cab4172f1acc86fd49345a2847417e162f2c3
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKPOSITIONERS_P_P_H
-#define QQUICKPOSITIONERS_P_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 "qquickpositioners_p.h"
-#include "qquickimplicitsizeitem_p_p.h"
-
-#include <private/qdeclarativestate_p.h>
-#include <private/qdeclarativetransitionmanager_p_p.h>
-#include <private/qdeclarativestateoperations_p.h>
-
-#include <QtCore/qobject.h>
-#include <QtCore/qstring.h>
-#include <QtCore/qtimer.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickBasePositionerPrivate : public QQuickImplicitSizeItemPrivate, public QQuickItemChangeListener
-{
- Q_DECLARE_PUBLIC(QQuickBasePositioner)
-
-public:
- QQuickBasePositionerPrivate()
- : spacing(0), type(QQuickBasePositioner::None)
- , moveTransition(0), addTransition(0), positioningDirty(false)
- , doingPositioning(false), anchorConflict(false), layoutDirection(Qt::LeftToRight)
- {
- }
-
- void init(QQuickBasePositioner::PositionerType at)
- {
- type = at;
- childrenDoNotOverlap = true;
- }
-
- int spacing;
-
- QQuickBasePositioner::PositionerType type;
- QDeclarativeTransition *moveTransition;
- QDeclarativeTransition *addTransition;
- QDeclarativeStateOperation::ActionList addActions;
- QDeclarativeStateOperation::ActionList moveActions;
- QDeclarativeTransitionManager addTransitionManager;
- QDeclarativeTransitionManager moveTransitionManager;
-
- void watchChanges(QQuickItem *other);
- void unwatchChanges(QQuickItem* other);
- void setPositioningDirty() {
- Q_Q(QQuickBasePositioner);
- if (!positioningDirty) {
- positioningDirty = true;
- q->polish();
- }
- }
-
- bool positioningDirty : 1;
- bool doingPositioning : 1;
- bool anchorConflict : 1;
-
- Qt::LayoutDirection layoutDirection;
-
- void mirrorChange() {
- if (type != QQuickBasePositioner::Vertical)
- setPositioningDirty();
- }
- bool isLeftToRight() const {
- if (type == QQuickBasePositioner::Vertical)
- return true;
- else
- return effectiveLayoutMirror ? layoutDirection == Qt::RightToLeft : layoutDirection == Qt::LeftToRight;
- }
-
- virtual void itemSiblingOrderChanged(QQuickItem* other)
- {
- Q_UNUSED(other);
- setPositioningDirty();
- }
-
- void itemGeometryChanged(QQuickItem *, const QRectF &newGeometry, const QRectF &oldGeometry)
- {
- if (newGeometry.size() != oldGeometry.size())
- setPositioningDirty();
- }
-
- virtual void itemVisibilityChanged(QQuickItem *)
- {
- setPositioningDirty();
- }
-
- void itemDestroyed(QQuickItem *item)
- {
- Q_Q(QQuickBasePositioner);
- q->positionedItems.removeOne(QQuickBasePositioner::PositionedItem(item));
- }
-
- static Qt::LayoutDirection getLayoutDirection(const QQuickBasePositioner *positioner)
- {
- return positioner->d_func()->layoutDirection;
- }
-
- static Qt::LayoutDirection getEffectiveLayoutDirection(const QQuickBasePositioner *positioner)
- {
- if (positioner->d_func()->effectiveLayoutMirror)
- return positioner->d_func()->layoutDirection == Qt::RightToLeft ? Qt::LeftToRight : Qt::RightToLeft;
- else
- return positioner->d_func()->layoutDirection;
- }
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKPOSITIONERS_P_P_H
diff --git a/src/declarative/items/qquickrectangle.cpp b/src/declarative/items/qquickrectangle.cpp
deleted file mode 100644
index c3cbaaa00e..0000000000
--- a/src/declarative/items/qquickrectangle.cpp
+++ /dev/null
@@ -1,556 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickrectangle_p.h"
-#include "qquickrectangle_p_p.h"
-
-#include <private/qsgcontext_p.h>
-#include <private/qsgadaptationlayer_p.h>
-
-#include <QtGui/qpixmapcache.h>
-#include <QtCore/qstringbuilder.h>
-#include <QtCore/qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-// XXX todo - should we change rectangle to draw entirely within its width/height?
-/*!
- \internal
- \class QQuickPen
- \brief The QQuickPen class provides a pen used for drawing rectangle borders on a QQuickView.
-
- By default, the pen is invalid and nothing is drawn. You must either set a color (then the default
- width is 1) or a width (then the default color is black).
-
- A width of 1 indicates is a single-pixel line on the border of the item being painted.
-
- Example:
- \qml
- Rectangle {
- border.width: 2
- border.color: "red"
- }
- \endqml
-*/
-
-QQuickPen::QQuickPen(QObject *parent)
- : QObject(parent)
- , m_width(1)
- , m_color("#000000")
- , m_aligned(true)
- , m_valid(false)
-{
-}
-
-qreal QQuickPen::width() const
-{
- return m_width;
-}
-
-void QQuickPen::setWidth(qreal w)
-{
- if (m_width == w && m_valid)
- return;
-
- m_width = w;
- m_valid = m_color.alpha() && (qRound(m_width) >= 1 || (!m_aligned && m_width > 0));
- emit penChanged();
-}
-
-QColor QQuickPen::color() const
-{
- return m_color;
-}
-
-void QQuickPen::setColor(const QColor &c)
-{
- m_color = c;
- m_valid = m_color.alpha() && (qRound(m_width) >= 1 || (!m_aligned && m_width > 0));
- emit penChanged();
-}
-
-bool QQuickPen::aligned() const
-{
- return m_aligned;
-}
-
-void QQuickPen::setAligned(bool aligned)
-{
- if (aligned == m_aligned)
- return;
- m_aligned = aligned;
- m_valid = m_color.alpha() && (qRound(m_width) >= 1 || (!m_aligned && m_width > 0));
- emit penChanged();
-}
-
-bool QQuickPen::isValid() const
-{
- return m_valid;
-}
-
-/*!
- \qmlclass GradientStop QQuickGradientStop
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
- \brief The GradientStop item defines the color at a position in a Gradient.
-
- \sa Gradient
-*/
-
-/*!
- \qmlproperty real QtQuick2::GradientStop::position
- \qmlproperty color QtQuick2::GradientStop::color
-
- The position and color properties describe the color used at a given
- position in a gradient, as represented by a gradient stop.
-
- The default position is 0.0; the default color is black.
-
- \sa Gradient
-*/
-QQuickGradientStop::QQuickGradientStop(QObject *parent)
- : QObject(parent)
-{
-}
-
-qreal QQuickGradientStop::position() const
-{
- return m_position;
-}
-
-void QQuickGradientStop::setPosition(qreal position)
-{
- m_position = position; updateGradient();
-}
-
-QColor QQuickGradientStop::color() const
-{
- return m_color;
-}
-
-void QQuickGradientStop::setColor(const QColor &color)
-{
- m_color = color; updateGradient();
-}
-
-void QQuickGradientStop::updateGradient()
-{
- if (QQuickGradient *grad = qobject_cast<QQuickGradient*>(parent()))
- grad->doUpdate();
-}
-
-/*!
- \qmlclass Gradient QQuickGradient
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
- \brief The Gradient item defines a gradient fill.
-
- A gradient is defined by two or more colors, which will be blended seamlessly.
-
- The colors are specified as a set of GradientStop child items, each of
- which defines a position on the gradient from 0.0 to 1.0 and a color.
- The position of each GradientStop is defined by setting its
- \l{GradientStop::}{position} property; its color is defined using its
- \l{GradientStop::}{color} property.
-
- A gradient without any gradient stops is rendered as a solid white fill.
-
- Note that this item is not a visual representation of a gradient. To display a
- gradient, use a visual element (like \l Rectangle) which supports the use
- of gradients.
-
- \section1 Example Usage
-
- \div {class="float-right"}
- \inlineimage qml-gradient.png
- \enddiv
-
- The following example declares a \l Rectangle item with a gradient starting
- with red, blending to yellow at one third of the height of the rectangle,
- and ending with green:
-
- \snippet doc/src/snippets/declarative/gradient.qml code
-
- \clearfloat
- \section1 Performance and Limitations
-
- Calculating gradients can be computationally expensive compared to the use
- of solid color fills or images. Consider using gradients for static items
- in a user interface.
-
- In Qt 4.7, only vertical, linear gradients can be applied to items. If you
- need to apply different orientations of gradients, a combination of rotation
- and clipping will need to be applied to the relevant items. This can
- introduce additional performance requirements for your application.
-
- The use of animations involving gradient stops may not give the desired
- result. An alternative way to animate gradients is to use pre-generated
- images or SVG drawings containing gradients.
-
- \sa GradientStop
-*/
-
-/*!
- \qmlproperty list<GradientStop> QtQuick2::Gradient::stops
- \default
-
- This property holds the gradient stops describing the gradient.
-
- By default, this property contains an empty list.
-
- To set the gradient stops, define them as children of the Gradient element.
-*/
-QQuickGradient::QQuickGradient(QObject *parent)
-: QObject(parent), m_gradient(0)
-{
-}
-
-QQuickGradient::~QQuickGradient()
-{
- delete m_gradient;
-}
-
-QDeclarativeListProperty<QQuickGradientStop> QQuickGradient::stops()
-{
- return QDeclarativeListProperty<QQuickGradientStop>(this, m_stops);
-}
-
-const QGradient *QQuickGradient::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 QQuickGradientStop *stop = m_stops.at(i);
- m_gradient->setCoordinateMode(QGradient::ObjectBoundingMode);
- m_gradient->setColorAt(stop->position(), stop->color());
- }
- }
-
- return m_gradient;
-}
-
-void QQuickGradient::doUpdate()
-{
- delete m_gradient;
- m_gradient = 0;
- emit updated();
-}
-
-int QQuickRectanglePrivate::doUpdateSlotIdx = -1;
-
-/*!
- \qmlclass Rectangle QQuickRectangle
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
- \brief The Rectangle item provides a filled rectangle with an optional border.
- \inherits Item
-
- Rectangle items are used to fill areas with solid color or gradients, and are
- often used to hold other items.
-
- \section1 Appearance
-
- Each Rectangle item is painted using either a solid fill color, specified using
- the \l color property, or a gradient, defined using a Gradient element and set
- using the \l gradient property. If both a color and a gradient are specified,
- the gradient is used.
-
- You can add an optional border to a rectangle with its own color and thickness
- by setting the \l border.color and \l border.width properties.
-
- You can also create rounded rectangles using the \l radius property. Since this
- introduces curved edges to the corners of a rectangle, it may be appropriate to
- set the \l smooth property to improve its appearance.
-
- \section1 Example Usage
-
- \div {class="float-right"}
- \inlineimage declarative-rect.png
- \enddiv
-
- The following example shows the effects of some of the common properties on a
- Rectangle item, which in this case is used to create a square:
-
- \snippet doc/src/snippets/declarative/rectangle/rectangle.qml document
-
- \clearfloat
- \section1 Performance
-
- Using the \l smooth property improves the appearance of a rounded rectangle at
- the cost of rendering performance. You should consider unsetting this property
- for rectangles in motion, and only set it when they are stationary.
-
- \sa Image
-*/
-
-QQuickRectangle::QQuickRectangle(QQuickItem *parent)
-: QQuickItem(*(new QQuickRectanglePrivate), parent)
-{
- setFlag(ItemHasContents);
-}
-
-void QQuickRectangle::doUpdate()
-{
- Q_D(QQuickRectangle);
- qreal penMargin = 0;
- qreal penOffset = 0;
- if (d->pen && d->pen->isValid()) {
- if (d->pen->aligned()) {
- const int pw = qRound(d->pen->width());
- penMargin = qreal(0.5) * pw;
- penOffset = (pw & 1) * qreal(0.5);
- } else {
- penMargin = qreal(0.5) * d->pen->width();
- }
- }
- if (penMargin != d->penMargin || penOffset != d->penOffset) {
- d->penMargin = penMargin;
- d->penOffset = penOffset;
- d->dirty(QQuickItemPrivate::Size); // update clip
- }
- update();
-}
-
-/*!
- \qmlproperty int QtQuick2::Rectangle::border.width
- \qmlproperty color QtQuick2::Rectangle::border.color
-
- The width and color used to draw the border of the rectangle.
-
- A width of 1 creates a thin line. For no line, use a width of 0 or a transparent color.
-
- \note The width of the rectangle's border does not affect the geometry of the
- rectangle itself or its position relative to other items if anchors are used.
-
- If \c border.width is an odd number, the rectangle is painted at a half-pixel offset to retain
- border smoothness. Also, the border is rendered evenly on either side of the
- rectangle's boundaries, and the spare pixel is rendered to the right and below the
- rectangle (as documented for QRect rendering). This can cause unintended effects if
- \c border.width is 1 and the rectangle is \l{Item::clip}{clipped} by a parent item:
-
- \div {class="float-right"}
- \inlineimage rect-border-width.png
- \enddiv
-
- \snippet doc/src/snippets/declarative/rectangle/rect-border-width.qml 0
-
- \clearfloat
- Here, the innermost rectangle's border is clipped on the bottom and right edges by its
- parent. To avoid this, the border width can be set to two instead of one.
-*/
-QQuickPen *QQuickRectangle::border()
-{
- Q_D(QQuickRectangle);
- return d->getPen();
-}
-
-/*!
- \qmlproperty Gradient QtQuick2::Rectangle::gradient
-
- The gradient to use to fill the rectangle.
-
- This property allows for the construction of simple vertical gradients.
- Other gradients may by formed by adding rotation to the rectangle.
-
- \div {class="float-left"}
- \inlineimage declarative-rect_gradient.png
- \enddiv
-
- \snippet doc/src/snippets/declarative/rectangle/rectangle-gradient.qml rectangles
- \clearfloat
-
- If both a gradient and a color are specified, the gradient will be used.
-
- \sa Gradient, color
-*/
-QQuickGradient *QQuickRectangle::gradient() const
-{
- Q_D(const QQuickRectangle);
- return d->gradient;
-}
-
-void QQuickRectangle::setGradient(QQuickGradient *gradient)
-{
- Q_D(QQuickRectangle);
- if (d->gradient == gradient)
- return;
- static int updatedSignalIdx = -1;
- if (updatedSignalIdx < 0)
- updatedSignalIdx = QQuickGradient::staticMetaObject.indexOfSignal("updated()");
- if (d->doUpdateSlotIdx < 0)
- d->doUpdateSlotIdx = QQuickRectangle::staticMetaObject.indexOfSlot("doUpdate()");
- if (d->gradient)
- QMetaObject::disconnect(d->gradient, updatedSignalIdx, this, d->doUpdateSlotIdx);
- d->gradient = gradient;
- if (d->gradient)
- QMetaObject::connect(d->gradient, updatedSignalIdx, this, d->doUpdateSlotIdx);
- update();
-}
-
-/*!
- \qmlproperty real QtQuick2::Rectangle::radius
- This property holds the corner radius used to draw a rounded rectangle.
-
- If radius is non-zero, the rectangle will be painted as a rounded rectangle, otherwise it will be
- painted as a normal rectangle. The same radius is used by all 4 corners; there is currently
- no way to specify different radii for different corners.
-*/
-qreal QQuickRectangle::radius() const
-{
- Q_D(const QQuickRectangle);
- return d->radius;
-}
-
-void QQuickRectangle::setRadius(qreal radius)
-{
- Q_D(QQuickRectangle);
- if (d->radius == radius)
- return;
-
- d->radius = radius;
- update();
- emit radiusChanged();
-}
-
-/*!
- \qmlproperty color QtQuick2::Rectangle::color
- This property holds the color used to fill the rectangle.
-
- The default color is white.
-
- \div {class="float-right"}
- \inlineimage rect-color.png
- \enddiv
-
- The following example shows rectangles with colors specified
- using hexadecimal and named color notation:
-
- \snippet doc/src/snippets/declarative/rectangle/rectangle-colors.qml rectangles
-
- \clearfloat
- If both a gradient and a color are specified, the gradient will be used.
-
- \sa gradient
-*/
-QColor QQuickRectangle::color() const
-{
- Q_D(const QQuickRectangle);
- return d->color;
-}
-
-void QQuickRectangle::setColor(const QColor &c)
-{
- Q_D(QQuickRectangle);
- if (d->color == c)
- return;
-
- d->color = c;
- update();
- emit colorChanged();
-}
-
-QSGNode *QQuickRectangle::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
-{
- Q_UNUSED(data);
- Q_D(QQuickRectangle);
-
- if (width() <= 0 || height() <= 0
- || (d->color.alpha() == 0 && (!d->pen || d->pen->width() == 0 || d->pen->color().alpha() == 0))) {
- delete oldNode;
- return 0;
- }
-
- QSGRectangleNode *rectangle = static_cast<QSGRectangleNode *>(oldNode);
- if (!rectangle) rectangle = d->sceneGraphContext()->createRectangleNode();
-
- rectangle->setRect(QRectF(0, 0, width(), height()));
- rectangle->setColor(d->color);
-
- if (d->pen && d->pen->isValid()) {
- rectangle->setPenColor(d->pen->color());
- rectangle->setPenWidth(d->pen->width());
- rectangle->setAligned(d->pen->aligned());
- } else {
- rectangle->setPenWidth(0);
- }
-
- rectangle->setRadius(d->radius);
-
- QGradientStops stops;
- if (d->gradient) {
- QList<QQuickGradientStop *> qxstops = d->gradient->m_stops;
- for (int i = 0; i < qxstops.size(); ++i){
- int j = 0;
- while (j < stops.size() && stops.at(j).first < qxstops[i]->position())
- j++;
- stops.insert(j, QGradientStop(qxstops.at(i)->position(), qxstops.at(i)->color()));
- }
- }
- rectangle->setGradientStops(stops);
-
- rectangle->update();
-
- return rectangle;
-}
-/*!
- \qmlproperty bool QtQuick2::Rectangle::smooth
-
- Set this property if you want the item to be smoothly scaled or
- transformed. Smooth filtering gives better visual quality, but is slower. If
- the item is displayed at its natural size, this property has no visual or
- performance effect.
-
- \note Generally scaling artifacts are only visible if the item is stationary on
- the screen. A common pattern when animating an item is to disable smooth
- filtering at the beginning of the animation and reenable it at the conclusion.
-
- \image rect-smooth.png
- On this image, smooth is turned off for the top half and on for the bottom half.
-*/
-
-QRectF QQuickRectangle::boundingRect() const
-{
- Q_D(const QQuickRectangle);
- return QRectF(d->penOffset - d->penMargin, d->penOffset - d->penMargin,
- d->width + 2 * d->penMargin, d->height + 2 * d->penMargin);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickrectangle_p.h b/src/declarative/items/qquickrectangle_p.h
deleted file mode 100644
index 838b944c62..0000000000
--- a/src/declarative/items/qquickrectangle_p.h
+++ /dev/null
@@ -1,189 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKRECTANGLE_P_H
-#define QQUICKRECTANGLE_P_H
-
-#include "qquickitem.h"
-
-#include <QtGui/qbrush.h>
-
-#include <private/qdeclarativeglobal_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-class Q_DECLARATIVE_PRIVATE_EXPORT QQuickPen : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(qreal width READ width WRITE setWidth NOTIFY penChanged)
- Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY penChanged)
- Q_PROPERTY(bool aligned READ aligned WRITE setAligned NOTIFY penChanged)
-public:
- QQuickPen(QObject *parent=0);
-
- qreal width() const;
- void setWidth(qreal w);
-
- QColor color() const;
- void setColor(const QColor &c);
-
- bool aligned() const;
- void setAligned(bool aligned);
-
- bool isValid() const;
-
-Q_SIGNALS:
- void penChanged();
-
-private:
- qreal m_width;
- QColor m_color;
- bool m_aligned : 1;
- bool m_valid : 1;
-};
-
-class Q_AUTOTEST_EXPORT QQuickGradientStop : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(qreal position READ position WRITE setPosition)
- Q_PROPERTY(QColor color READ color WRITE setColor)
-
-public:
- QQuickGradientStop(QObject *parent=0);
-
- qreal position() const;
- void setPosition(qreal position);
-
- QColor color() const;
- void setColor(const QColor &color);
-
-private:
- void updateGradient();
-
-private:
- qreal m_position;
- QColor m_color;
-};
-
-class Q_AUTOTEST_EXPORT QQuickGradient : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QDeclarativeListProperty<QQuickGradientStop> stops READ stops)
- Q_CLASSINFO("DefaultProperty", "stops")
-
-public:
- QQuickGradient(QObject *parent=0);
- ~QQuickGradient();
-
- QDeclarativeListProperty<QQuickGradientStop> stops();
-
- const QGradient *gradient() const;
-
-Q_SIGNALS:
- void updated();
-
-private:
- void doUpdate();
-
-private:
- QList<QQuickGradientStop *> m_stops;
- mutable QGradient *m_gradient;
- friend class QQuickRectangle;
- friend class QQuickGradientStop;
-};
-
-class QQuickRectanglePrivate;
-class Q_DECLARATIVE_PRIVATE_EXPORT QQuickRectangle : public QQuickItem
-{
- Q_OBJECT
-
- Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
- Q_PROPERTY(QQuickGradient *gradient READ gradient WRITE setGradient)
- Q_PROPERTY(QQuickPen * border READ border CONSTANT)
- Q_PROPERTY(qreal radius READ radius WRITE setRadius NOTIFY radiusChanged)
-public:
- QQuickRectangle(QQuickItem *parent=0);
-
- QColor color() const;
- void setColor(const QColor &);
-
- QQuickPen *border();
-
- QQuickGradient *gradient() const;
- void setGradient(QQuickGradient *gradient);
-
- qreal radius() const;
- void setRadius(qreal radius);
-
- virtual QRectF boundingRect() const;
-
-Q_SIGNALS:
- void colorChanged();
- void radiusChanged();
-
-protected:
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
-
-private Q_SLOTS:
- void doUpdate();
-
-private:
- Q_DISABLE_COPY(QQuickRectangle)
- Q_DECLARE_PRIVATE(QQuickRectangle)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickPen)
-QML_DECLARE_TYPE(QQuickGradientStop)
-QML_DECLARE_TYPE(QQuickGradient)
-QML_DECLARE_TYPE(QQuickRectangle)
-
-QT_END_HEADER
-
-#endif // QQUICKRECTANGLE_P_H
diff --git a/src/declarative/items/qquickrectangle_p_p.h b/src/declarative/items/qquickrectangle_p_p.h
deleted file mode 100644
index 93140ce75a..0000000000
--- a/src/declarative/items/qquickrectangle_p_p.h
+++ /dev/null
@@ -1,103 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKRECTANGLE_P_P_H
-#define QQUICKRECTANGLE_P_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 "qquickitem_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QQuickGradient;
-class QQuickRectangle;
-class QQuickRectanglePrivate : public QQuickItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickRectangle)
-
-public:
- QQuickRectanglePrivate() :
- color(Qt::white), gradient(0), pen(0), radius(0), penMargin(0), penOffset(0)
- {
- }
-
- ~QQuickRectanglePrivate()
- {
- delete pen;
- }
-
- QColor color;
- QQuickGradient *gradient;
- QQuickPen *pen;
- qreal radius;
- qreal penMargin;
- qreal penOffset;
- static int doUpdateSlotIdx;
-
- QQuickPen *getPen() {
- if (!pen) {
- Q_Q(QQuickRectangle);
- pen = new QQuickPen;
- static int penChangedSignalIdx = -1;
- if (penChangedSignalIdx < 0)
- penChangedSignalIdx = QQuickPen::staticMetaObject.indexOfSignal("penChanged()");
- if (doUpdateSlotIdx < 0)
- doUpdateSlotIdx = QQuickRectangle::staticMetaObject.indexOfSlot("doUpdate()");
- QMetaObject::connect(pen, penChangedSignalIdx, q, doUpdateSlotIdx);
- }
- return pen;
- }
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKRECTANGLE_P_P_H
diff --git a/src/declarative/items/qquickrepeater.cpp b/src/declarative/items/qquickrepeater.cpp
deleted file mode 100644
index efa83eec38..0000000000
--- a/src/declarative/items/qquickrepeater.cpp
+++ /dev/null
@@ -1,476 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickrepeater_p.h"
-#include "qquickrepeater_p_p.h"
-#include "qquickvisualdatamodel_p.h"
-
-#include <private/qdeclarativeglobal_p.h>
-#include <private/qdeclarativelistaccessor_p.h>
-#include <private/qlistmodelinterface_p.h>
-#include <private/qdeclarativechangeset_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QQuickRepeaterPrivate::QQuickRepeaterPrivate()
- : model(0), ownModel(false), inRequest(false), itemCount(0), createFrom(-1)
-{
-}
-
-QQuickRepeaterPrivate::~QQuickRepeaterPrivate()
-{
- if (ownModel)
- delete model;
-}
-
-/*!
- \qmlclass Repeater QQuickRepeater
- \inqmlmodule QtQuick 2
- \ingroup qml-utility-elements
- \inherits Item
-
- \brief The Repeater element allows you to repeat an Item-based component using a model.
-
- The Repeater element is used to create a large number of
- similar items. Like other view elements, a Repeater has a \l model and a \l delegate:
- for each entry in the model, the delegate is instantiated
- in a context seeded with data from the model. A Repeater item is usually
- enclosed in a positioner element such as \l Row or \l Column to visually
- position the multiple delegate items created by the Repeater.
-
- The following Repeater creates three instances of a \l Rectangle item within
- a \l Row:
-
- \snippet doc/src/snippets/declarative/repeaters/repeater.qml import
- \codeline
- \snippet doc/src/snippets/declarative/repeaters/repeater.qml simple
-
- \image repeater-simple.png
-
- A Repeater's \l model can be any of the supported \l {qmlmodels}{data models}.
- Additionally, like delegates for other views, a Repeater delegate can access
- its index within the repeater, as well as the model data relevant to the
- delegate. See the \l delegate property documentation for details.
-
- Items instantiated by the Repeater are inserted, in order, as
- children of the Repeater's parent. The insertion starts immediately after
- the repeater's position in its parent stacking list. This allows
- a Repeater to be used inside a layout. For example, the following Repeater's
- items are stacked between a red rectangle and a blue rectangle:
-
- \snippet doc/src/snippets/declarative/repeaters/repeater.qml layout
-
- \image repeater.png
-
-
- \note A Repeater item owns all items it instantiates. Removing or dynamically destroying
- an item created by a Repeater results in unpredictable behavior.
-
-
- \section2 Considerations when using Repeater
-
- The Repeater element creates all of its delegate items when the repeater is first
- created. This can be inefficient if there are a large number of delegate items and
- not all of the items are required to be visible at the same time. If this is the case,
- consider using other view elements like ListView (which only creates delegate items
- when they are scrolled into view) or use the \l {Dynamic Object Creation} methods to
- create items as they are required.
-
- Also, note that Repeater is \l {Item}-based, and can only repeat \l {Item}-derived objects.
- For example, it cannot be used to repeat QtObjects:
- \badcode
- Item {
- //XXX does not work! Can't repeat QtObject as it doesn't derive from Item.
- Repeater {
- model: 10
- QtObject {}
- }
- }
- \endcode
- */
-
-/*!
- \qmlsignal QtQuick2::Repeater::onItemAdded(int index, Item item)
-
- This handler is called when an item is added to the repeater. The \a index
- parameter holds the index at which the item has been inserted within the
- repeater, and the \a item parameter holds the \l Item that has been added.
-*/
-
-/*!
- \qmlsignal QtQuick2::Repeater::onItemRemoved(int index, Item item)
-
- This handler is called when an item is removed from the repeater. The \a index
- parameter holds the index at which the item was removed from the repeater,
- and the \a item parameter holds the \l Item that was removed.
-
- Do not keep a reference to \a item if it was created by this repeater, as
- in these cases it will be deleted shortly after the handler is called.
-*/
-QQuickRepeater::QQuickRepeater(QQuickItem *parent)
- : QQuickItem(*(new QQuickRepeaterPrivate), parent)
-{
-}
-
-QQuickRepeater::~QQuickRepeater()
-{
-}
-
-/*!
- \qmlproperty any QtQuick2::Repeater::model
-
- The model providing data for the repeater.
-
- This property can be set to any of the supported \l {qmlmodels}{data models}:
-
- \list
- \o A number that indicates the number of delegates to be created by the repeater
- \o A model (e.g. a ListModel item, or a QAbstractItemModel subclass)
- \o A string list
- \o An object list
- \endlist
-
- The type of model affects the properties that are exposed to the \l delegate.
-
- \sa {qmlmodels}{Data Models}
-*/
-QVariant QQuickRepeater::model() const
-{
- Q_D(const QQuickRepeater);
- return d->dataSource;
-}
-
-void QQuickRepeater::setModel(const QVariant &model)
-{
- Q_D(QQuickRepeater);
- if (d->dataSource == model)
- return;
-
- clear();
- if (d->model) {
- disconnect(d->model, SIGNAL(modelUpdated(QDeclarativeChangeSet,bool)),
- this, SLOT(modelUpdated(QDeclarativeChangeSet,bool)));
- disconnect(d->model, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(createdItem(int,QQuickItem*)));
- disconnect(d->model, SIGNAL(initItem(int,QQuickItem*)), this, SLOT(initItem(int,QQuickItem*)));
-// disconnect(d->model, SIGNAL(destroyingItem(QQuickItem*)), this, SLOT(destroyingItem(QQuickItem*)));
- }
- d->dataSource = model;
- QObject *object = qvariant_cast<QObject*>(model);
- QQuickVisualModel *vim = 0;
- if (object && (vim = qobject_cast<QQuickVisualModel *>(object))) {
- if (d->ownModel) {
- delete d->model;
- d->ownModel = false;
- }
- d->model = vim;
- } else {
- if (!d->ownModel) {
- d->model = new QQuickVisualDataModel(qmlContext(this));
- d->ownModel = true;
- if (isComponentComplete())
- static_cast<QQuickVisualDataModel *>(d->model)->componentComplete();
- }
- if (QQuickVisualDataModel *dataModel = qobject_cast<QQuickVisualDataModel*>(d->model))
- dataModel->setModel(model);
- }
- if (d->model) {
- connect(d->model, SIGNAL(modelUpdated(QDeclarativeChangeSet,bool)),
- this, SLOT(modelUpdated(QDeclarativeChangeSet,bool)));
- connect(d->model, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(createdItem(int,QQuickItem*)));
- connect(d->model, SIGNAL(initItem(int,QQuickItem*)), this, SLOT(initItem(int,QQuickItem*)));
-// connect(d->model, SIGNAL(destroyingItem(QQuickItem*)), this, SLOT(destroyingItem(QQuickItem*)));
- regenerate();
- }
- emit modelChanged();
- emit countChanged();
-}
-
-/*!
- \qmlproperty Component QtQuick2::Repeater::delegate
- \default
-
- The delegate provides a template defining each item instantiated by the repeater.
-
- Delegates are exposed to a read-only \c index property that indicates the index
- of the delegate within the repeater. For example, the following \l Text delegate
- displays the index of each repeated item:
-
- \table
- \row
- \o \snippet doc/src/snippets/declarative/repeaters/repeater.qml index
- \o \image repeater-index.png
- \endtable
-
- If the \l model is a \l{QStringList-based model}{string list} or
- \l{QObjectList-based model}{object list}, the delegate is also exposed to
- a read-only \c modelData property that holds the string or object data. For
- example:
-
- \table
- \row
- \o \snippet doc/src/snippets/declarative/repeaters/repeater.qml modeldata
- \o \image repeater-modeldata.png
- \endtable
-
- If the \l model is a model object (such as a \l ListModel) the delegate
- can access all model roles as named properties, in the same way that delegates
- do for view classes like ListView.
-
- \sa {QML Data Models}
- */
-QDeclarativeComponent *QQuickRepeater::delegate() const
-{
- Q_D(const QQuickRepeater);
- if (d->model) {
- if (QQuickVisualDataModel *dataModel = qobject_cast<QQuickVisualDataModel*>(d->model))
- return dataModel->delegate();
- }
-
- return 0;
-}
-
-void QQuickRepeater::setDelegate(QDeclarativeComponent *delegate)
-{
- Q_D(QQuickRepeater);
- if (QQuickVisualDataModel *dataModel = qobject_cast<QQuickVisualDataModel*>(d->model))
- if (delegate == dataModel->delegate())
- return;
-
- if (!d->ownModel) {
- d->model = new QQuickVisualDataModel(qmlContext(this));
- d->ownModel = true;
- }
- if (QQuickVisualDataModel *dataModel = qobject_cast<QQuickVisualDataModel*>(d->model)) {
- dataModel->setDelegate(delegate);
- regenerate();
- emit delegateChanged();
- }
-}
-
-/*!
- \qmlproperty int QtQuick2::Repeater::count
-
- This property holds the number of items in the repeater.
-*/
-int QQuickRepeater::count() const
-{
- Q_D(const QQuickRepeater);
- if (d->model)
- return d->model->count();
- return 0;
-}
-
-/*!
- \qmlmethod Item QtQuick2::Repeater::itemAt(index)
-
- Returns the \l Item that has been created at the given \a index, or \c null
- if no item exists at \a index.
-*/
-QQuickItem *QQuickRepeater::itemAt(int index) const
-{
- Q_D(const QQuickRepeater);
- if (index >= 0 && index < d->deletables.count())
- return d->deletables[index];
- return 0;
-}
-
-void QQuickRepeater::componentComplete()
-{
- Q_D(QQuickRepeater);
- if (d->model && d->ownModel)
- static_cast<QQuickVisualDataModel *>(d->model)->componentComplete();
- QQuickItem::componentComplete();
- regenerate();
- if (d->model && d->model->count())
- emit countChanged();
-}
-
-void QQuickRepeater::itemChange(ItemChange change, const ItemChangeData &value)
-{
- QQuickItem::itemChange(change, value);
- if (change == ItemParentHasChanged) {
- regenerate();
- }
-}
-
-void QQuickRepeater::clear()
-{
- Q_D(QQuickRepeater);
- bool complete = isComponentComplete();
-
- if (d->model) {
- for (int i = 0; i < d->deletables.count(); ++i) {
- QQuickItem *item = d->deletables.at(i);
- if (complete)
- emit itemRemoved(i, item);
- d->model->release(item);
- }
- }
- d->deletables.clear();
- d->itemCount = 0;
-}
-
-void QQuickRepeater::regenerate()
-{
- Q_D(QQuickRepeater);
- if (!isComponentComplete())
- return;
-
- clear();
-
- if (!d->model || !d->model->count() || !d->model->isValid() || !parentItem() || !isComponentComplete())
- return;
-
- d->itemCount = count();
- d->deletables.resize(d->itemCount);
- d->createFrom = 0;
- d->createItems();
-}
-
-void QQuickRepeaterPrivate::createItems()
-{
- Q_Q(QQuickRepeater);
- if (createFrom == -1)
- return;
- inRequest = true;
- for (int ii = createFrom; ii < itemCount; ++ii) {
- if (!deletables.at(ii)) {
- QQuickItem *item = model->item(ii, false);
- if (!item) {
- createFrom = ii;
- break;
- }
- deletables[ii] = item;
- QDeclarative_setParent_noEvent(item, q->parentItem());
- item->setParentItem(q->parentItem());
- if (ii > 0 && deletables.at(ii-1)) {
- item->stackAfter(deletables.at(ii-1));
- } else {
- QQuickItem *after = q;
- for (int si = ii+1; si < itemCount; ++si) {
- if (deletables.at(si)) {
- after = deletables.at(si);
- break;
- }
- }
- item->stackBefore(after);
- }
- emit q->itemAdded(ii, item);
- }
- }
- inRequest = false;
-}
-
-void QQuickRepeater::createdItem(int, QQuickItem *)
-{
- Q_D(QQuickRepeater);
- if (!d->inRequest)
- d->createItems();
-}
-
-void QQuickRepeater::initItem(int, QQuickItem *item)
-{
- QDeclarative_setParent_noEvent(item, parentItem());
- item->setParentItem(parentItem());
-}
-
-void QQuickRepeater::modelUpdated(const QDeclarativeChangeSet &changeSet, bool reset)
-{
- Q_D(QQuickRepeater);
-
- if (!isComponentComplete())
- return;
-
- if (reset) {
- regenerate();
- emit countChanged();
- }
-
- int difference = 0;
- QHash<int, QVector<QPointer<QQuickItem> > > moved;
- foreach (const QDeclarativeChangeSet::Remove &remove, changeSet.removes()) {
- int index = qMin(remove.index, d->deletables.count());
- int count = qMin(remove.index + remove.count, d->deletables.count()) - index;
- if (remove.isMove()) {
- moved.insert(remove.moveId, d->deletables.mid(index, count));
- d->deletables.erase(
- d->deletables.begin() + index,
- d->deletables.begin() + index + count);
- } else while (count--) {
- QQuickItem *item = d->deletables.at(index);
- d->deletables.remove(index);
- emit itemRemoved(index, item);
- if (item)
- d->model->release(item);
- --d->itemCount;
- }
-
- difference -= remove.count;
- }
-
- d->createFrom = -1;
- foreach (const QDeclarativeChangeSet::Insert &insert, changeSet.inserts()) {
- int index = qMin(insert.index, d->deletables.count());
- if (insert.isMove()) {
- QVector<QPointer<QQuickItem> > items = moved.value(insert.moveId);
- d->deletables = d->deletables.mid(0, index) + items + d->deletables.mid(index);
- QQuickItem *stackBefore = index + items.count() < d->deletables.count()
- ? d->deletables.at(index + items.count())
- : this;
- for (int i = index; i < index + items.count(); ++i)
- d->deletables.at(i)->stackBefore(stackBefore);
- } else for (int i = 0; i < insert.count; ++i) {
- int modelIndex = index + i;
- ++d->itemCount;
- d->deletables.insert(modelIndex, 0);
- if (d->createFrom == -1)
- d->createFrom = modelIndex;
- }
- difference += insert.count;
- }
-
- d->createItems();
-
- if (difference != 0)
- emit countChanged();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickrepeater_p.h b/src/declarative/items/qquickrepeater_p.h
deleted file mode 100644
index 5b90d74e65..0000000000
--- a/src/declarative/items/qquickrepeater_p.h
+++ /dev/null
@@ -1,112 +0,0 @@
-// Commit: ebd4bc73c46c2962742a682b6a391fb68c482aec
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKREPEATER_P_H
-#define QQUICKREPEATER_P_H
-
-#include "qquickitem.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeChangeSet;
-
-class QQuickRepeaterPrivate;
-class Q_AUTOTEST_EXPORT QQuickRepeater : public QQuickItem
-{
- Q_OBJECT
-
- Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged)
- Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged)
- Q_PROPERTY(int count READ count NOTIFY countChanged)
- Q_CLASSINFO("DefaultProperty", "delegate")
-
-public:
- QQuickRepeater(QQuickItem *parent=0);
- virtual ~QQuickRepeater();
-
- QVariant model() const;
- void setModel(const QVariant &);
-
- QDeclarativeComponent *delegate() const;
- void setDelegate(QDeclarativeComponent *);
-
- int count() const;
-
- Q_INVOKABLE QQuickItem *itemAt(int index) const;
-
-Q_SIGNALS:
- void modelChanged();
- void delegateChanged();
- void countChanged();
-
- void itemAdded(int index, QQuickItem *item);
- void itemRemoved(int index, QQuickItem *item);
-
-private:
- void clear();
- void regenerate();
-
-protected:
- virtual void componentComplete();
- void itemChange(ItemChange change, const ItemChangeData &value);
-
-private Q_SLOTS:
- void createdItem(int index, QQuickItem *item);
- void initItem(int, QQuickItem *item);
- void modelUpdated(const QDeclarativeChangeSet &changeSet, bool reset);
-
-private:
- Q_DISABLE_COPY(QQuickRepeater)
- Q_DECLARE_PRIVATE(QQuickRepeater)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickRepeater)
-
-QT_END_HEADER
-
-#endif // QQUICKREPEATER_P_H
diff --git a/src/declarative/items/qquickrepeater_p_p.h b/src/declarative/items/qquickrepeater_p_p.h
deleted file mode 100644
index 962d177494..0000000000
--- a/src/declarative/items/qquickrepeater_p_p.h
+++ /dev/null
@@ -1,89 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKREPEATER_P_P_H
-#define QQUICKREPEATER_P_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 "qquickrepeater_p.h"
-#include "qquickitem_p.h"
-
-#include <QtCore/qpointer.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeContext;
-class QQuickVisualModel;
-class QQuickRepeaterPrivate : public QQuickItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickRepeater)
-
-public:
- QQuickRepeaterPrivate();
- ~QQuickRepeaterPrivate();
-
-private:
- void createItems();
-
- QQuickVisualModel *model;
- QVariant dataSource;
- bool ownModel : 1;
- bool inRequest : 1;
- int itemCount;
- int createFrom;
-
- QVector<QPointer<QQuickItem> > deletables;
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKREPEATER_P_P_H
diff --git a/src/declarative/items/qquickscalegrid.cpp b/src/declarative/items/qquickscalegrid.cpp
deleted file mode 100644
index 9a8f652a9b..0000000000
--- a/src/declarative/items/qquickscalegrid.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickscalegrid_p_p.h"
-
-#include <QtDeclarative/qdeclarative.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \internal
- \class QQuickScaleGrid
- \brief The QQuickScaleGrid class allows you to specify a 3x3 grid to use in scaling an image.
-*/
-
-QQuickScaleGrid::QQuickScaleGrid(QObject *parent) : QObject(parent), _left(0), _top(0), _right(0), _bottom(0)
-{
-}
-
-QQuickScaleGrid::~QQuickScaleGrid()
-{
-}
-
-bool QQuickScaleGrid::isNull() const
-{
- return !_left && !_top && !_right && !_bottom;
-}
-
-void QQuickScaleGrid::setLeft(int pos)
-{
- if (_left != pos) {
- _left = pos;
- emit borderChanged();
- }
-}
-
-void QQuickScaleGrid::setTop(int pos)
-{
- if (_top != pos) {
- _top = pos;
- emit borderChanged();
- }
-}
-
-void QQuickScaleGrid::setRight(int pos)
-{
- if (_right != pos) {
- _right = pos;
- emit borderChanged();
- }
-}
-
-void QQuickScaleGrid::setBottom(int pos)
-{
- if (_bottom != pos) {
- _bottom = pos;
- emit borderChanged();
- }
-}
-
-QQuickGridScaledImage::QQuickGridScaledImage()
-: _l(-1), _r(-1), _t(-1), _b(-1),
- _h(QQuickBorderImage::Stretch), _v(QQuickBorderImage::Stretch)
-{
-}
-
-QQuickGridScaledImage::QQuickGridScaledImage(const QQuickGridScaledImage &o)
-: _l(o._l), _r(o._r), _t(o._t), _b(o._b), _h(o._h), _v(o._v), _pix(o._pix)
-{
-}
-
-QQuickGridScaledImage &QQuickGridScaledImage::operator=(const QQuickGridScaledImage &o)
-{
- _l = o._l;
- _r = o._r;
- _t = o._t;
- _b = o._b;
- _h = o._h;
- _v = o._v;
- _pix = o._pix;
- return *this;
-}
-
-QQuickGridScaledImage::QQuickGridScaledImage(QIODevice *data)
-: _l(-1), _r(-1), _t(-1), _b(-1), _h(QQuickBorderImage::Stretch), _v(QQuickBorderImage::Stretch)
-{
- int l = -1;
- int r = -1;
- int t = -1;
- int b = -1;
- QString imgFile;
-
- QByteArray raw;
- while (raw = data->readLine(), !raw.isEmpty()) {
- QString line = QString::fromUtf8(raw.trimmed());
- if (line.isEmpty() || line.startsWith(QLatin1Char('#')))
- continue;
-
- int colonId = line.indexOf(QLatin1Char(':'));
- if (colonId <= 0)
- return;
-
- QStringList list;
- list.append(line.left(colonId).trimmed());
- list.append(line.mid(colonId+1).trimmed());
-
- if (list[0] == QLatin1String("border.left"))
- l = list[1].toInt();
- else if (list[0] == QLatin1String("border.right"))
- r = list[1].toInt();
- else if (list[0] == QLatin1String("border.top"))
- t = list[1].toInt();
- else if (list[0] == QLatin1String("border.bottom"))
- b = list[1].toInt();
- else if (list[0] == QLatin1String("source"))
- imgFile = list[1];
- else if (list[0] == QLatin1String("horizontalTileRule"))
- _h = stringToRule(list[1]);
- else if (list[0] == QLatin1String("verticalTileRule"))
- _v = stringToRule(list[1]);
- }
-
- if (l < 0 || r < 0 || t < 0 || b < 0 || imgFile.isEmpty())
- return;
-
- _l = l; _r = r; _t = t; _b = b;
-
- _pix = imgFile;
- if (_pix.startsWith(QLatin1Char('"')) && _pix.endsWith(QLatin1Char('"')))
- _pix = _pix.mid(1, _pix.size() - 2); // remove leading/trailing quotes.
-}
-
-QQuickBorderImage::TileMode QQuickGridScaledImage::stringToRule(const QString &s)
-{
- if (s == QLatin1String("Stretch"))
- return QQuickBorderImage::Stretch;
- if (s == QLatin1String("Repeat"))
- return QQuickBorderImage::Repeat;
- if (s == QLatin1String("Round"))
- return QQuickBorderImage::Round;
-
- qWarning("QQuickGridScaledImage: Invalid tile rule specified. Using Stretch.");
- return QQuickBorderImage::Stretch;
-}
-
-bool QQuickGridScaledImage::isValid() const
-{
- return _l >= 0;
-}
-
-int QQuickGridScaledImage::gridLeft() const
-{
- return _l;
-}
-
-int QQuickGridScaledImage::gridRight() const
-{
- return _r;
-}
-
-int QQuickGridScaledImage::gridTop() const
-{
- return _t;
-}
-
-int QQuickGridScaledImage::gridBottom() const
-{
- return _b;
-}
-
-QString QQuickGridScaledImage::pixmapUrl() const
-{
- return _pix;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickscalegrid_p_p.h b/src/declarative/items/qquickscalegrid_p_p.h
deleted file mode 100644
index 8d93c3b1c9..0000000000
--- a/src/declarative/items/qquickscalegrid_p_p.h
+++ /dev/null
@@ -1,134 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKSCALEGRID_P_P_H
-#define QQUICKSCALEGRID_P_P_H
-
-#include "qquickborderimage_p.h"
-
-#include <QtDeclarative/qdeclarative.h>
-#include <QtCore/qobject.h>
-
-#include <private/qdeclarativepixmapcache_p.h>
-#include <private/qdeclarativeglobal_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class Q_DECLARATIVE_PRIVATE_EXPORT QQuickScaleGrid : public QObject
-{
- Q_OBJECT
- Q_ENUMS(TileRule)
-
- Q_PROPERTY(int left READ left WRITE setLeft NOTIFY borderChanged)
- Q_PROPERTY(int top READ top WRITE setTop NOTIFY borderChanged)
- Q_PROPERTY(int right READ right WRITE setRight NOTIFY borderChanged)
- Q_PROPERTY(int bottom READ bottom WRITE setBottom NOTIFY borderChanged)
-
-public:
- QQuickScaleGrid(QObject *parent=0);
- ~QQuickScaleGrid();
-
- bool isNull() const;
-
- int left() const { return _left; }
- void setLeft(int);
-
- int top() const { return _top; }
- void setTop(int);
-
- int right() const { return _right; }
- void setRight(int);
-
- int bottom() const { return _bottom; }
- void setBottom(int);
-
-Q_SIGNALS:
- void borderChanged();
-
-private:
- int _left;
- int _top;
- int _right;
- int _bottom;
-};
-
-class Q_DECLARATIVE_PRIVATE_EXPORT QQuickGridScaledImage
-{
-public:
- QQuickGridScaledImage();
- QQuickGridScaledImage(const QQuickGridScaledImage &);
- QQuickGridScaledImage(QIODevice*);
- QQuickGridScaledImage &operator=(const QQuickGridScaledImage &);
- bool isValid() const;
- int gridLeft() const;
- int gridRight() const;
- int gridTop() const;
- int gridBottom() const;
- QQuickBorderImage::TileMode horizontalTileRule() const { return _h; }
- QQuickBorderImage::TileMode verticalTileRule() const { return _v; }
-
- QString pixmapUrl() const;
-
-private:
- static QQuickBorderImage::TileMode stringToRule(const QString &);
-
-private:
- int _l;
- int _r;
- int _t;
- int _b;
- QQuickBorderImage::TileMode _h;
- QQuickBorderImage::TileMode _v;
- QString _pix;
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickScaleGrid)
-
-QT_END_HEADER
-
-#endif // QQUICKSCALEGRID_P_P_H
diff --git a/src/declarative/items/qquickshadereffect.cpp b/src/declarative/items/qquickshadereffect.cpp
deleted file mode 100644
index bdef980440..0000000000
--- a/src/declarative/items/qquickshadereffect.cpp
+++ /dev/null
@@ -1,763 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <private/qquickshadereffect_p.h>
-#include <private/qquickshadereffectnode_p.h>
-
-#include "qsgmaterial.h"
-#include "qquickitem_p.h"
-
-#include <private/qsgcontext_p.h>
-#include <private/qsgtextureprovider_p.h>
-#include "qquickcanvas.h"
-
-#include "qquickimage_p.h"
-#include "qquickshadereffectsource_p.h"
-
-#include <QtCore/qsignalmapper.h>
-#include <QtGui/qopenglframebufferobject.h>
-
-QT_BEGIN_NAMESPACE
-
-static const char qt_default_vertex_code[] =
- "uniform highp mat4 qt_Matrix; \n"
- "attribute highp vec4 qt_Vertex; \n"
- "attribute highp vec2 qt_MultiTexCoord0; \n"
- "varying highp vec2 qt_TexCoord0; \n"
- "void main() { \n"
- " qt_TexCoord0 = qt_MultiTexCoord0; \n"
- " gl_Position = qt_Matrix * qt_Vertex; \n"
- "}";
-
-static const char qt_default_fragment_code[] =
- "varying highp vec2 qt_TexCoord0; \n"
- "uniform sampler2D source; \n"
- "uniform lowp float qt_Opacity; \n"
- "void main() { \n"
- " gl_FragColor = texture2D(source, qt_TexCoord0) * qt_Opacity; \n"
- "}";
-
-static const char qt_position_attribute_name[] = "qt_Vertex";
-static const char qt_texcoord_attribute_name[] = "qt_MultiTexCoord0";
-
-const char *qtPositionAttributeName()
-{
- return qt_position_attribute_name;
-}
-
-const char *qtTexCoordAttributeName()
-{
- return qt_texcoord_attribute_name;
-}
-
-/*!
- \qmlclass ShaderEffect QQuickShaderEffect
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
- \brief The ShaderEffect element applies custom shaders to a rectangle.
- \inherits Item
-
- The ShaderEffect element applies a custom OpenGL
- \l{vertexShader}{vertex} and \l{fragmentShader}{fragment} shader to a
- rectangle. It allows you to write effects such as drop shadow, blur,
- colorize and page curl directly in QML.
-
- There are two types of input to the \l vertexShader:
- uniform variables and attributes. Some are predefined:
- \list
- \o uniform mat4 qt_Matrix - combined transformation
- matrix, the product of the matrices from the root item to this
- ShaderEffect, and an orthogonal projection.
- \o uniform float qt_Opacity - combined opacity, the product of the
- opacities from the root item to this ShaderEffect.
- \o attribute vec4 qt_Vertex - vertex position, the top-left vertex has
- position (0, 0), the bottom-right (\l{Item::width}{width},
- \l{Item::height}{height}).
- \o attribute vec2 qt_MultiTexCoord0 - texture coordinate, the top-left
- coordinate is (0, 0), the bottom-right (1, 1).
- \endlist
-
- In addition, any property that can be mapped to an OpenGL Shading Language
- (GLSL) type is available as a uniform variable. The following list shows
- how properties are mapped to GLSL uniform variables:
- \list
- \o bool, int, qreal -> bool, int, float - If the type in the shader is not
- the same as in QML, the value is converted automatically.
- \o QColor -> vec4 - When colors are passed to the shader, they are first
- premultiplied. Thus Qt.rgba(0.2, 0.6, 1.0, 0.5) becomes
- vec4(0.1, 0.3, 0.5, 0.5) in the shader, for example.
- \o QRect, QRectF -> vec4 - Qt.rect(x, y, w, h) becomes vec4(x, y, w, h) in
- the shader.
- \o QPoint, QPointF, QSize, QSizeF -> vec2
- \o QVector3D -> vec3
- \o QTransform -> mat4
- \o \l Image, \l ShaderEffectSource -> sampler2D - Origin is in the top-left
- corner, and the color values are premultiplied.
- \endlist
-
- The output from the \l fragmentShader should be premultiplied. If
- \l blending is enabled, source-over blending is used. However, additive
- blending can be achieved by outputting zero in the alpha channel.
-
- \row
- \o \image declarative-shadereffectitem.png
- \o \qml
- import QtQuick 2.0
-
- Rectangle {
- width: 200; height: 100
- Row {
- Image { id: img; sourceSize { width: 100; height: 100 } source: "qt-logo.png" }
- ShaderEffect {
- width: 100; height: 100
- property variant src: img
- vertexShader: "
- uniform highp mat4 qt_Matrix;
- attribute highp vec4 qt_Vertex;
- attribute highp vec2 qt_MultiTexCoord0;
- varying highp vec2 coord;
- void main() {
- coord = qt_MultiTexCoord0;
- gl_Position = qt_Matrix * qt_Vertex;
- }"
- fragmentShader: "
- varying highp vec2 coord;
- uniform sampler2D src;
- uniform lowp float qt_Opacity;
- void main() {
- lowp vec4 tex = texture2D(src, coord);
- gl_FragColor = vec4(vec3(dot(tex.rgb, vec3(0.344, 0.5, 0.156))), tex.a) * qt_Opacity;
- }"
- }
- }
- }
- \endqml
- \endrow
-
- By default, the ShaderEffect consists of four vertices, one for each
- corner. For non-linear vertex transformations, like page curl, you can
- specify a fine grid of vertices by specifying a \l mesh resolution.
-
- \note Scene Graph textures have origin in the top-left corner rather than
- bottom-left which is common in OpenGL.
-*/
-
-QQuickShaderEffect::QQuickShaderEffect(QQuickItem *parent)
- : QQuickItem(parent)
- , m_meshResolution(1, 1)
- , m_mesh(0)
- , m_cullMode(NoCulling)
- , m_blending(true)
- , m_dirtyData(true)
- , m_programDirty(true)
- , m_dirtyMesh(true)
- , m_dirtyGeometry(true)
-{
- setFlag(QQuickItem::ItemHasContents);
-}
-
-QQuickShaderEffect::~QQuickShaderEffect()
-{
- reset();
-}
-
-void QQuickShaderEffect::componentComplete()
-{
- updateProperties();
- QQuickItem::componentComplete();
-}
-
-/*!
- \qmlproperty string QtQuick2::ShaderEffect::fragmentShader
-
- This property holds the fragment shader's GLSL source code.
- The default shader passes the texture coordinate along to the fragment
- shader as "varying highp vec2 qt_TexCoord0".
-*/
-
-void QQuickShaderEffect::setFragmentShader(const QByteArray &code)
-{
- if (m_source.fragmentCode.constData() == code.constData())
- return;
- m_source.fragmentCode = code;
- if (isComponentComplete()) {
- reset();
- updateProperties();
- update();
- }
- emit fragmentShaderChanged();
-}
-
-/*!
- \qmlproperty string QtQuick2::ShaderEffect::vertexShader
-
- This property holds the vertex shader's GLSL source code.
- The default shader expects the texture coordinate to be passed from the
- vertex shader as "varying highp vec2 qt_TexCoord0", and it samples from a
- sampler2D named "source".
-*/
-
-void QQuickShaderEffect::setVertexShader(const QByteArray &code)
-{
- if (m_source.vertexCode.constData() == code.constData())
- return;
- m_source.vertexCode = code;
- if (isComponentComplete()) {
- reset();
- updateProperties();
- update();
- }
- emit vertexShaderChanged();
-}
-
-/*!
- \qmlproperty bool QtQuick2::ShaderEffect::blending
-
- If this property is true, the output from the \l fragmentShader is blended
- with the background using source-over blend mode. If false, the background
- is disregarded. Blending decreases the performance, so you should set this
- property to false when blending is not needed. The default value is true.
-*/
-
-void QQuickShaderEffect::setBlending(bool enable)
-{
- if (blending() == enable)
- return;
-
- m_blending = enable;
- update();
-
- emit blendingChanged();
-}
-
-/*!
- \qmlproperty variant QtQuick2::ShaderEffect::mesh
-
- This property defines the mesh used to draw the ShaderEffect. It can hold
- any mesh object deriving from \l QQuickShaderEffectMesh, such as \l GridMesh.
- If a size value is assigned to this property, the ShaderEffect implicitly
- uses a \l GridMesh with the value as
- \l{GridMesh::resolution}{mesh resolution}. By default, this property is
- the size 1x1.
-
- \sa GridMesh
-*/
-
-QVariant QQuickShaderEffect::mesh() const
-{
- return m_mesh ? qVariantFromValue(static_cast<QObject *>(m_mesh))
- : qVariantFromValue(m_meshResolution);
-}
-
-void QQuickShaderEffect::setMesh(const QVariant &mesh)
-{
- QQuickShaderEffectMesh *newMesh = qobject_cast<QQuickShaderEffectMesh *>(qVariantValue<QObject *>(mesh));
- if (newMesh && newMesh == m_mesh)
- return;
- if (m_mesh)
- disconnect(m_mesh, SIGNAL(geometryChanged()), this, 0);
- m_mesh = newMesh;
- if (m_mesh) {
- connect(m_mesh, SIGNAL(geometryChanged()), this, SLOT(updateGeometry()));
- } else {
- if (qVariantCanConvert<QSize>(mesh)) {
- m_meshResolution = mesh.toSize();
- } else {
- QList<QByteArray> res = mesh.toByteArray().split('x');
- bool ok = res.size() == 2;
- if (ok) {
- int w = res.at(0).toInt(&ok);
- if (ok) {
- int h = res.at(1).toInt(&ok);
- if (ok)
- m_meshResolution = QSize(w, h);
- }
- }
- if (!ok)
- qWarning("ShaderEffect: mesh property must be size or object deriving from QQuickShaderEffectMesh.");
- }
- m_defaultMesh.setResolution(m_meshResolution);
- }
-
- m_dirtyMesh = true;
- update();
- emit meshChanged();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::ShaderEffect::cullMode
-
- This property defines which sides of the element should be visible.
-
- \list
- \o ShaderEffect.NoCulling - Both sides are visible
- \o ShaderEffect.BackFaceCulling - only front side is visible
- \o ShaderEffect.FrontFaceCulling - only back side is visible
- \endlist
-
- The default is NoCulling.
-*/
-
-void QQuickShaderEffect::setCullMode(CullMode face)
-{
- if (face == m_cullMode)
- return;
- m_cullMode = face;
- update();
- emit cullModeChanged();
-}
-
-void QQuickShaderEffect::changeSource(int index)
-{
- Q_ASSERT(index >= 0 && index < m_sources.size());
- QVariant v = property(m_sources.at(index).name.constData());
- setSource(v, index);
-}
-
-void QQuickShaderEffect::updateData()
-{
- m_dirtyData = true;
- update();
-}
-
-void QQuickShaderEffect::updateGeometry()
-{
- m_dirtyGeometry = true;
- update();
-}
-
-void QQuickShaderEffect::setSource(const QVariant &var, int index)
-{
- Q_ASSERT(index >= 0 && index < m_sources.size());
-
- SourceData &source = m_sources[index];
-
- source.sourceObject = 0;
- if (var.isNull()) {
- return;
- } else if (!qVariantCanConvert<QObject *>(var)) {
- qWarning("Could not assign source of type '%s' to property '%s'.", var.typeName(), source.name.constData());
- return;
- }
-
- QObject *obj = qVariantValue<QObject *>(var);
- QQuickItem *item = qobject_cast<QQuickItem *>(obj);
- if (!item || !item->isTextureProvider()) {
- qWarning("ShaderEffect: source uniform [%s] is not assigned a valid texture provider: %s [%s]",
- source.name.constData(), qPrintable(obj->objectName()), obj->metaObject()->className());
- return;
- }
-
- source.sourceObject = item;
-
-
- // TODO: Find better solution.
- // 'item' needs a canvas to get a scenegraph node.
- // The easiest way to make sure it gets a canvas is to
- // make it a part of the same item tree as 'this'.
- if (item && item->parentItem() == 0) {
- item->setParentItem(this);
- item->setVisible(false);
- }
-}
-
-void QQuickShaderEffect::disconnectPropertySignals()
-{
- disconnect(this, 0, this, SLOT(updateData()));
- for (int i = 0; i < m_sources.size(); ++i) {
- SourceData &source = m_sources[i];
- disconnect(this, 0, source.mapper, 0);
- disconnect(source.mapper, 0, this, 0);
- }
-}
-
-void QQuickShaderEffect::connectPropertySignals()
-{
- QSet<QByteArray>::const_iterator it;
- for (it = m_source.uniformNames.begin(); it != m_source.uniformNames.end(); ++it) {
- int pi = metaObject()->indexOfProperty(it->constData());
- if (pi >= 0) {
- QMetaProperty mp = metaObject()->property(pi);
- if (!mp.hasNotifySignal())
- qWarning("QQuickShaderEffect: property '%s' does not have notification method!", it->constData());
- QByteArray signalName("2");
- signalName.append(mp.notifySignal().signature());
- connect(this, signalName, this, SLOT(updateData()));
- } else {
- qWarning("QQuickShaderEffect: '%s' does not have a matching property!", it->constData());
- }
- }
- for (int i = 0; i < m_sources.size(); ++i) {
- SourceData &source = m_sources[i];
- int pi = metaObject()->indexOfProperty(source.name.constData());
- if (pi >= 0) {
- QMetaProperty mp = metaObject()->property(pi);
- QByteArray signalName("2");
- signalName.append(mp.notifySignal().signature());
- connect(this, signalName, source.mapper, SLOT(map()));
- source.mapper->setMapping(this, i);
- connect(source.mapper, SIGNAL(mapped(int)), this, SLOT(changeSource(int)));
- } else {
- qWarning("QQuickShaderEffect: '%s' does not have a matching source!", source.name.constData());
- }
- }
-}
-
-void QQuickShaderEffect::reset()
-{
- disconnectPropertySignals();
-
- m_source.attributeNames.clear();
- m_source.uniformNames.clear();
- m_source.respectsOpacity = false;
- m_source.respectsMatrix = false;
- m_source.className = metaObject()->className();
-
- for (int i = 0; i < m_sources.size(); ++i) {
- const SourceData &source = m_sources.at(i);
- delete source.mapper;
- QQuickItem *item = qobject_cast<QQuickItem *>(source.sourceObject);
- if (item && item->parentItem() == this)
- item->setParentItem(0);
- }
- m_sources.clear();
-
- m_programDirty = true;
- m_dirtyMesh = true;
-}
-
-void QQuickShaderEffect::updateProperties()
-{
- if (m_source.vertexCode.isEmpty()) {
- m_source.attributeNames.append(QByteArray(qt_position_attribute_name));
- m_source.attributeNames.append(QByteArray(qt_texcoord_attribute_name));
- m_source.respectsMatrix = true;
- } else {
- lookThroughShaderCode(m_source.vertexCode);
- }
- if (m_source.fragmentCode.isEmpty()) {
- m_source.respectsOpacity = true;
- QByteArray name("source");
- m_source.uniformNames.insert(name);
- SourceData d;
- d.mapper = new QSignalMapper;
- d.name = name;
- d.sourceObject = 0;
- m_sources.append(d);
- } else {
- lookThroughShaderCode(m_source.fragmentCode);
- }
-
- if (!m_mesh && !m_source.attributeNames.contains(qt_position_attribute_name))
- qWarning("QQuickShaderEffect: Missing reference to \'%s\'.", qt_position_attribute_name);
- if (!m_mesh && !m_source.attributeNames.contains(qt_texcoord_attribute_name))
- qWarning("QQuickShaderEffect: Missing reference to \'%s\'.", qt_texcoord_attribute_name);
- if (!m_source.respectsMatrix)
- qWarning("QQuickShaderEffect: Missing reference to \'qt_Matrix\'.");
- if (!m_source.respectsOpacity)
- qWarning("QQuickShaderEffect: Missing reference to \'qt_Opacity\'.");
-
- for (int i = 0; i < m_sources.size(); ++i) {
- QVariant v = property(m_sources.at(i).name);
- setSource(v, i);
- }
-
- connectPropertySignals();
-}
-
-namespace {
-
- enum VariableQualifier {
- AttributeQualifier,
- UniformQualifier
- };
-
- inline bool qt_isalpha(char c)
- {
- char ch = c | 0x20;
- return (ch >= 'a' && ch <= 'z') || c == '_';
- }
-
- inline bool qt_isalnum(char c)
- {
- return qt_isalpha(c) || (c >= '0' && c <= '9');
- }
-
- inline bool qt_isspace(char c)
- {
- return c == ' ' || (c >= 0x09 && c <= 0x0d);
- }
-
- // Returns -1 if not found, returns index to first character after the name if found.
- int qt_search_for_variable(const char *s, int length, int index, VariableQualifier &decl,
- int &typeIndex, int &typeLength,
- int &nameIndex, int &nameLength)
- {
- enum Identifier {
- QualifierIdentifier, // Base state
- PrecisionIdentifier,
- TypeIdentifier,
- NameIdentifier
- };
- Identifier expected = QualifierIdentifier;
- bool compilerDirectiveExpected = index == 0;
-
- while (index < length) {
- // Skip whitespace.
- while (qt_isspace(s[index])) {
- compilerDirectiveExpected |= s[index] == '\n';
- ++index;
- }
-
- if (qt_isalpha(s[index])) {
- // Read identifier.
- int idIndex = index;
- ++index;
- while (qt_isalnum(s[index]))
- ++index;
- int idLength = index - idIndex;
-
- const int attrLen = sizeof("attribute") - 1;
- const int uniLen = sizeof("uniform") - 1;
- const int loLen = sizeof("lowp") - 1;
- const int medLen = sizeof("mediump") - 1;
- const int hiLen = sizeof("highp") - 1;
-
- switch (expected) {
- case QualifierIdentifier:
- if (idLength == attrLen && qstrncmp("attribute", s + idIndex, attrLen) == 0) {
- decl = AttributeQualifier;
- expected = PrecisionIdentifier;
- } else if (idLength == uniLen && qstrncmp("uniform", s + idIndex, uniLen) == 0) {
- decl = UniformQualifier;
- expected = PrecisionIdentifier;
- }
- break;
- case PrecisionIdentifier:
- if ((idLength == loLen && qstrncmp("lowp", s + idIndex, loLen) == 0)
- || (idLength == medLen && qstrncmp("mediump", s + idIndex, medLen) == 0)
- || (idLength == hiLen && qstrncmp("highp", s + idIndex, hiLen) == 0))
- {
- expected = TypeIdentifier;
- break;
- }
- // Fall through.
- case TypeIdentifier:
- typeIndex = idIndex;
- typeLength = idLength;
- expected = NameIdentifier;
- break;
- case NameIdentifier:
- nameIndex = idIndex;
- nameLength = idLength;
- return index; // Attribute or uniform declaration found. Return result.
- default:
- break;
- }
- } else if (s[index] == '#' && compilerDirectiveExpected) {
- // Skip compiler directives.
- ++index;
- while (index < length && (s[index] != '\n' || s[index - 1] == '\\'))
- ++index;
- } else if (s[index] == '/' && s[index + 1] == '/') {
- // Skip comments.
- index += 2;
- while (index < length && s[index] != '\n')
- ++index;
- } else if (s[index] == '/' && s[index + 1] == '*') {
- // Skip comments.
- index += 2;
- while (index < length && (s[index] != '*' || s[index + 1] != '/'))
- ++index;
- if (index < length)
- index += 2; // Skip star-slash.
- } else {
- expected = QualifierIdentifier;
- ++index;
- }
- compilerDirectiveExpected = false;
- }
- return -1;
- }
-}
-
-void QQuickShaderEffect::lookThroughShaderCode(const QByteArray &code)
-{
- int index = 0;
- int typeIndex, typeLength, nameIndex, nameLength;
- const char *s = code.constData();
- VariableQualifier decl;
- while ((index = qt_search_for_variable(s, code.size(), index, decl, typeIndex, typeLength,
- nameIndex, nameLength)) != -1)
- {
- if (decl == AttributeQualifier) {
- m_source.attributeNames.append(QByteArray(s + nameIndex, nameLength));
- } else {
- Q_ASSERT(decl == UniformQualifier);
-
- const int matLen = sizeof("qt_Matrix") - 1;
- const int opLen = sizeof("qt_Opacity") - 1;
- const int sampLen = sizeof("sampler2D") - 1;
-
- if (nameLength == matLen && qstrncmp("qt_Matrix", s + nameIndex, matLen) == 0) {
- m_source.respectsMatrix = true;
- } else if (nameLength == opLen && qstrncmp("qt_Opacity", s + nameIndex, opLen) == 0) {
- m_source.respectsOpacity = true;
- } else {
- QByteArray name(s + nameIndex, nameLength);
- m_source.uniformNames.insert(name);
- if (typeLength == sampLen && qstrncmp("sampler2D", s + typeIndex, sampLen) == 0) {
- SourceData d;
- d.mapper = new QSignalMapper;
- d.name = name;
- d.sourceObject = 0;
- m_sources.append(d);
- }
- }
- }
- }
-}
-
-void QQuickShaderEffect::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- m_dirtyGeometry = true;
- QQuickItem::geometryChanged(newGeometry, oldGeometry);
-}
-
-QSGNode *QQuickShaderEffect::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
-{
- QQuickShaderEffectNode *node = static_cast<QQuickShaderEffectNode *>(oldNode);
-
- // In the case of a bad vertex shader, don't try to create a node...
- if (m_source.attributeNames.isEmpty()) {
- if (node)
- delete node;
- return 0;
- }
-
- if (!node) {
- node = new QQuickShaderEffectNode;
- m_programDirty = true;
- m_dirtyData = true;
- m_dirtyGeometry = true;
- }
-
- QQuickShaderEffectMaterial *material = node->shaderMaterial();
-
- if (m_dirtyMesh) {
- node->setGeometry(0);
- m_dirtyMesh = false;
- m_dirtyGeometry = true;
- }
-
- if (m_dirtyGeometry) {
- node->setFlag(QSGNode::OwnsGeometry, false);
- QSGGeometry *geometry = node->geometry();
- QRectF rect(0, 0, width(), height());
- QQuickShaderEffectMesh *mesh = m_mesh ? m_mesh : &m_defaultMesh;
-
- geometry = mesh->updateGeometry(geometry, m_source.attributeNames, rect);
- if (!geometry) {
- delete node;
- return 0;
- }
-
- node->setGeometry(geometry);
- node->setFlag(QSGNode::OwnsGeometry, true);
-
- m_dirtyGeometry = false;
- }
-
- if (m_programDirty) {
- QQuickShaderEffectProgram s = m_source;
- if (s.fragmentCode.isEmpty())
- s.fragmentCode = qt_default_fragment_code;
- if (s.vertexCode.isEmpty())
- s.vertexCode = qt_default_vertex_code;
- s.className = metaObject()->className();
-
- material->setProgramSource(s);
- node->markDirty(QSGNode::DirtyMaterial);
- m_programDirty = false;
- }
-
- // Update blending
- if (bool(material->flags() & QSGMaterial::Blending) != m_blending) {
- material->setFlag(QSGMaterial::Blending, m_blending);
- node->markDirty(QSGNode::DirtyMaterial);
- }
-
- if (int(material->cullMode()) != int(m_cullMode)) {
- material->setCullMode(QQuickShaderEffectMaterial::CullMode(m_cullMode));
- node->markDirty(QSGNode::DirtyMaterial);
- }
-
- if (m_dirtyData) {
- QVector<QPair<QByteArray, QVariant> > values;
- QVector<QPair<QByteArray, QSGTextureProvider *> > textures;
- const QVector<QPair<QByteArray, QSGTextureProvider *> > &oldTextures = material->textureProviders();
-
- for (QSet<QByteArray>::const_iterator it = m_source.uniformNames.begin();
- it != m_source.uniformNames.end(); ++it) {
- values.append(qMakePair(*it, property(*it)));
- }
- for (int i = 0; i < oldTextures.size(); ++i) {
- QSGTextureProvider *t = oldTextures.at(i).second;
- if (t)
- disconnect(t, SIGNAL(textureChanged()), node, SLOT(markDirtyTexture()));
- }
- for (int i = 0; i < m_sources.size(); ++i) {
- const SourceData &source = m_sources.at(i);
- QSGTextureProvider *t = source.sourceObject ? source.sourceObject->textureProvider() : 0;
- textures.append(qMakePair(source.name, t));
- if (t)
- connect(t, SIGNAL(textureChanged()), node, SLOT(markDirtyTexture()), Qt::DirectConnection);
- }
- material->setUniforms(values);
- material->setTextureProviders(textures);
- node->markDirty(QSGNode::DirtyMaterial);
- m_dirtyData = false;
- }
-
- return node;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickshadereffect_p.h b/src/declarative/items/qquickshadereffect_p.h
deleted file mode 100644
index 1910f43195..0000000000
--- a/src/declarative/items/qquickshadereffect_p.h
+++ /dev/null
@@ -1,158 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKSHADEREFFECT_P_H
-#define QQUICKSHADEREFFECT_P_H
-
-#include "qquickitem.h"
-
-#include "qsgmaterial.h"
-#include <private/qsgadaptationlayer_p.h>
-#include <private/qquickshadereffectnode_p.h>
-#include "qquickshadereffectmesh_p.h"
-
-#include <QtCore/qpointer.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-const char *qtPositionAttributeName();
-const char *qtTexCoordAttributeName();
-
-class QSGContext;
-class QSignalMapper;
-class QQuickCustomMaterialShader;
-
-class Q_AUTOTEST_EXPORT QQuickShaderEffect : public QQuickItem
-{
- Q_OBJECT
- Q_PROPERTY(QByteArray fragmentShader READ fragmentShader WRITE setFragmentShader NOTIFY fragmentShaderChanged)
- Q_PROPERTY(QByteArray vertexShader READ vertexShader WRITE setVertexShader NOTIFY vertexShaderChanged)
- Q_PROPERTY(bool blending READ blending WRITE setBlending NOTIFY blendingChanged)
- Q_PROPERTY(QVariant mesh READ mesh WRITE setMesh NOTIFY meshChanged)
- Q_PROPERTY(CullMode culling READ cullMode WRITE setCullMode NOTIFY cullModeChanged)
- Q_ENUMS(CullMode)
-
-public:
- enum CullMode
- {
- NoCulling = QQuickShaderEffectMaterial::NoCulling,
- BackFaceCulling = QQuickShaderEffectMaterial::BackFaceCulling,
- FrontFaceCulling = QQuickShaderEffectMaterial::FrontFaceCulling
- };
-
- QQuickShaderEffect(QQuickItem *parent = 0);
- ~QQuickShaderEffect();
-
- virtual void componentComplete();
-
- QByteArray fragmentShader() const { return m_source.fragmentCode; }
- void setFragmentShader(const QByteArray &code);
-
- QByteArray vertexShader() const { return m_source.vertexCode; }
- void setVertexShader(const QByteArray &code);
-
- bool blending() const { return m_blending; }
- void setBlending(bool enable);
-
- QVariant mesh() const;
- void setMesh(const QVariant &mesh);
-
- CullMode cullMode() const { return m_cullMode; }
- void setCullMode(CullMode face);
-
-Q_SIGNALS:
- void fragmentShaderChanged();
- void vertexShaderChanged();
- void blendingChanged();
- void meshChanged();
- void cullModeChanged();
-
-protected:
- virtual void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry);
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
-
-private Q_SLOTS:
- void changeSource(int index);
- void updateData();
- void updateGeometry();
-
-private:
- friend class QQuickCustomMaterialShader;
- friend class QQuickShaderEffectNode;
-
- void setSource(const QVariant &var, int index);
- void disconnectPropertySignals();
- void connectPropertySignals();
- void reset();
- void updateProperties();
- void lookThroughShaderCode(const QByteArray &code);
-
- QQuickShaderEffectProgram m_source;
- QSize m_meshResolution;
- QQuickShaderEffectMesh *m_mesh;
- QQuickGridMesh m_defaultMesh;
- CullMode m_cullMode;
-
- struct SourceData
- {
- QSignalMapper *mapper;
- QPointer<QQuickItem> sourceObject;
- QByteArray name;
- };
- QVector<SourceData> m_sources;
-
- uint m_blending : 1;
- uint m_dirtyData : 1;
-
- uint m_programDirty : 1;
- uint m_dirtyMesh : 1;
- uint m_dirtyGeometry : 1;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKSHADEREFFECT_P_H
diff --git a/src/declarative/items/qquickshadereffectmesh.cpp b/src/declarative/items/qquickshadereffectmesh.cpp
deleted file mode 100644
index 7709bed614..0000000000
--- a/src/declarative/items/qquickshadereffectmesh.cpp
+++ /dev/null
@@ -1,216 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickshadereffectmesh_p.h"
-#include "qsggeometry.h"
-#include "qquickshadereffect_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QQuickShaderEffectMesh::QQuickShaderEffectMesh(QObject *parent)
- : QObject(parent)
-{
-}
-
-/*!
- \qmlclass GridMesh QQuickGridMesh
- \inqmlmodule QtQuick 2
- \ingroup qml-utility-elements
- \brief GridMesh defines a mesh with vertices arranged in a grid.
-
- GridMesh defines a rectangular mesh consisting of vertices arranged in an
- evenly spaced grid. It is used to generate \l{QSGGeometry}{geometry}.
- The grid resolution is specified with the \l resolution property.
-*/
-
-QQuickGridMesh::QQuickGridMesh(QObject *parent)
- : QQuickShaderEffectMesh(parent)
- , m_resolution(1, 1)
-{
- connect(this, SIGNAL(resolutionChanged()), this, SIGNAL(geometryChanged()));
-}
-
-QSGGeometry *QQuickGridMesh::updateGeometry(QSGGeometry *geometry, const QVector<QByteArray> &attributes, const QRectF &dstRect) const
-{
- int vmesh = m_resolution.height();
- int hmesh = m_resolution.width();
- int attrCount = attributes.count();
-
- if (!geometry) {
- bool error = true;
- Q_UNUSED(error)
- switch (attrCount) {
- case 0:
- qWarning("QQuickGridMesh:: No attributes specified.");
- break;
- case 1:
- if (attributes.at(0) == qtPositionAttributeName()) {
- error = false;
- break;
- }
- qWarning("QQuickGridMesh:: Missing \'%s\' attribute.",
- qtPositionAttributeName());
- break;
- case 2:
- if (attributes.contains(qtPositionAttributeName())
- && attributes.contains(qtTexCoordAttributeName()))
- {
- error = false;
- break;
- }
- qWarning("QQuickGridMesh:: Missing \'%s\' or \'%s\' attribute.",
- qtPositionAttributeName(), qtTexCoordAttributeName());
- break;
- default:
- qWarning("QQuickGridMesh:: Too many attributes specified.");
- break;
- }
-
- geometry = new QSGGeometry(attrCount == 1
- ? QSGGeometry::defaultAttributes_Point2D()
- : QSGGeometry::defaultAttributes_TexturedPoint2D(),
- (vmesh + 1) * (hmesh + 1), vmesh * 2 * (hmesh + 2),
- GL_UNSIGNED_SHORT);
-
- } else {
- geometry->allocate((vmesh + 1) * (hmesh + 1), vmesh * 2 * (hmesh + 2));
- }
-
- QSGGeometry::Point2D *vdata = static_cast<QSGGeometry::Point2D *>(geometry->vertexData());
-
- bool positionFirst = attributes.at(0) == qtPositionAttributeName();
-
- QRectF srcRect(0, 0, 1, 1);
- for (int iy = 0; iy <= vmesh; ++iy) {
- float fy = iy / float(vmesh);
- float y = float(dstRect.top()) + fy * float(dstRect.height());
- float ty = float(srcRect.top()) + fy * float(srcRect.height());
- for (int ix = 0; ix <= hmesh; ++ix) {
- float fx = ix / float(hmesh);
- for (int ia = 0; ia < attrCount; ++ia) {
- if (positionFirst == (ia == 0)) {
- vdata->x = float(dstRect.left()) + fx * float(dstRect.width());
- vdata->y = y;
- ++vdata;
- } else {
- vdata->x = float(srcRect.left()) + fx * float(srcRect.width());
- vdata->y = ty;
- ++vdata;
- }
- }
- }
- }
-
- quint16 *indices = (quint16 *)geometry->indexDataAsUShort();
- int i = 0;
- for (int iy = 0; iy < vmesh; ++iy) {
- *(indices++) = i + hmesh + 1;
- for (int ix = 0; ix <= hmesh; ++ix, ++i) {
- *(indices++) = i + hmesh + 1;
- *(indices++) = i;
- }
- *(indices++) = i - 1;
- }
-
- return geometry;
-}
-
-/*!
- \qmlproperty size QtQuick2::GridMesh::resolution
-
- This property holds the grid resolution. The resolution's width and height
- specify the number of cells or spacings between vertices horizontally and
- vertically respectively. The minimum and default is 1x1, which corresponds
- to four vertices in total, one in each corner.
- For non-linear vertex transformations, you probably want to set the
- resolution higher.
-
- \row
- \o \image declarative-gridmesh.png
- \o \qml
- import QtQuick 2.0
-
- ShaderEffect {
- width: 200
- height: 200
- mesh: GridMesh {
- resolution: Qt.size(20, 20)
- }
- property variant source: Image {
- source: "qt-logo.png"
- sourceSize { width: 200; height: 200 }
- smooth: true
- }
- vertexShader: "
- uniform highp mat4 qt_Matrix;
- attribute highp vec4 qt_Vertex;
- attribute highp vec2 qt_MultiTexCoord0;
- varying highp vec2 qt_TexCoord0;
- uniform highp float width;
- void main() {
- highp vec4 pos = qt_Vertex;
- highp float d = .5 * smoothstep(0., 1., qt_MultiTexCoord0.y);
- pos.x = width * mix(d, 1.0 - d, qt_MultiTexCoord0.x);
- gl_Position = qt_Matrix * pos;
- qt_TexCoord0 = qt_MultiTexCoord0;
- }"
- }
- \endqml
- \endrow
-*/
-
-void QQuickGridMesh::setResolution(const QSize &res)
-{
- if (res == m_resolution)
- return;
- if (res.width() < 1 || res.height() < 1) {
- return;
- }
- m_resolution = res;
- emit resolutionChanged();
-}
-
-QSize QQuickGridMesh::resolution() const
-{
- return m_resolution;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickshadereffectmesh_p.h b/src/declarative/items/qquickshadereffectmesh_p.h
deleted file mode 100644
index 40549f73a8..0000000000
--- a/src/declarative/items/qquickshadereffectmesh_p.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativeparserstatus.h"
-
-#include <QtGui/qcolor.h>
-#include <QtCore/qobject.h>
-#include <QtCore/qsize.h>
-#include <QtCore/qvariant.h>
-#include <QtGui/qopenglfunctions.h>
-
-#ifndef QQUICKSHADEREFFECTMESH_P_H
-#define QQUICKSHADEREFFECTMESH_P_H
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGGeometry;
-class QRectF;
-
-class Q_DECLARATIVE_EXPORT QQuickShaderEffectMesh : public QObject
-{
- Q_OBJECT
-public:
- QQuickShaderEffectMesh(QObject *parent = 0);
- // If 'geometry' != 0, 'attributes' is the same as last time the function was called.
- virtual QSGGeometry *updateGeometry(QSGGeometry *geometry, const QVector<QByteArray> &attributes, const QRectF &rect) const = 0;
-
-Q_SIGNALS:
- // Emitted when the geometry needs to be updated.
- void geometryChanged();
-};
-
-class QQuickGridMesh : public QQuickShaderEffectMesh
-{
- Q_OBJECT
- Q_PROPERTY(QSize resolution READ resolution WRITE setResolution NOTIFY resolutionChanged)
-public:
- QQuickGridMesh(QObject *parent = 0);
- virtual QSGGeometry *updateGeometry(QSGGeometry *geometry, const QVector<QByteArray> &attributes, const QRectF &rect) const;
-
- void setResolution(const QSize &res);
- QSize resolution() const;
-
-Q_SIGNALS:
- void resolutionChanged();
-
-private:
- QSize m_resolution;
-};
-
-inline QColor qt_premultiply_color(const QColor &c)
-{
- return QColor::fromRgbF(c.redF() * c.alphaF(), c.greenF() * c.alphaF(), c.blueF() * c.alphaF(), c.alphaF());
-}
-
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKSHADEREFFECTMESH_P_H
diff --git a/src/declarative/items/qquickshadereffectnode.cpp b/src/declarative/items/qquickshadereffectnode.cpp
deleted file mode 100644
index 43c891e497..0000000000
--- a/src/declarative/items/qquickshadereffectnode.cpp
+++ /dev/null
@@ -1,317 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <private/qquickshadereffectnode_p.h>
-
-#include "qquickshadereffectmesh_p.h"
-#include <private/qsgtextureprovider_p.h>
-#include <private/qsgrenderer_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickCustomMaterialShader : public QSGMaterialShader
-{
-public:
- QQuickCustomMaterialShader(const QQuickShaderEffectMaterialKey &key, const QVector<QByteArray> &attributes);
- virtual void deactivate();
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
- virtual char const *const *attributeNames() const;
-
-protected:
- friend class QQuickShaderEffectNode;
-
- virtual void initialize();
- virtual const char *vertexShader() const;
- virtual const char *fragmentShader() const;
-
- const QQuickShaderEffectMaterialKey m_key;
- QVector<const char *> m_attributeNames;
- const QVector<QByteArray> m_attributes;
-
- QVector<int> m_uniformLocs;
- int m_opacityLoc;
- int m_matrixLoc;
- uint m_textureIndicesSet;
-};
-
-QQuickCustomMaterialShader::QQuickCustomMaterialShader(const QQuickShaderEffectMaterialKey &key, const QVector<QByteArray> &attributes)
- : m_key(key)
- , m_attributes(attributes)
- , m_textureIndicesSet(false)
-{
- for (int i = 0; i < attributes.count(); ++i)
- m_attributeNames.append(attributes.at(i).constData());
- m_attributeNames.append(0);
-}
-
-void QQuickCustomMaterialShader::deactivate()
-{
- QSGMaterialShader::deactivate();
- glDisable(GL_CULL_FACE);
-}
-
-void QQuickCustomMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
-{
- Q_ASSERT(newEffect != 0);
-
- const QQuickShaderEffectMaterial *material = static_cast<const QQuickShaderEffectMaterial *>(newEffect);
-
- if (!m_textureIndicesSet) {
- for (int i = 0; i < material->m_textures.size(); ++i)
- program()->setUniformValue(material->m_textures.at(i).first.constData(), i);
- m_textureIndicesSet = true;
- }
-
- if (m_uniformLocs.size() != material->m_uniformValues.size()) {
- m_uniformLocs.reserve(material->m_uniformValues.size());
- for (int i = 0; i < material->m_uniformValues.size(); ++i) {
- const QByteArray &name = material->m_uniformValues.at(i).first;
- m_uniformLocs.append(program()->uniformLocation(name.constData()));
- }
- }
-
- QOpenGLFunctions *functions = state.context()->functions();
- for (int i = material->m_textures.size() - 1; i >= 0; --i) {
- functions->glActiveTexture(GL_TEXTURE0 + i);
- if (QSGTextureProvider *provider = material->m_textures.at(i).second) {
- if (QSGTexture *texture = provider->texture()) {
- texture->bind();
- continue;
- }
- }
- qWarning("ShaderEffect: source or provider missing when binding textures");
- glBindTexture(GL_TEXTURE_2D, 0);
- }
-
- if (material->m_source.respectsOpacity)
- program()->setUniformValue(m_opacityLoc, state.opacity());
-
- for (int i = 0; i < material->m_uniformValues.count(); ++i) {
- const QVariant &v = material->m_uniformValues.at(i).second;
-
- switch (v.type()) {
- case QVariant::Color:
- program()->setUniformValue(m_uniformLocs.at(i), qt_premultiply_color(qvariant_cast<QColor>(v)));
- break;
- case QVariant::Double:
- program()->setUniformValue(m_uniformLocs.at(i), (float) qvariant_cast<double>(v));
- break;
- case QVariant::Transform:
- program()->setUniformValue(m_uniformLocs.at(i), qvariant_cast<QTransform>(v));
- break;
- case QVariant::Int:
- program()->setUniformValue(m_uniformLocs.at(i), v.toInt());
- break;
- case QVariant::Bool:
- program()->setUniformValue(m_uniformLocs.at(i), GLint(v.toBool()));
- break;
- case QVariant::Size:
- case QVariant::SizeF:
- program()->setUniformValue(m_uniformLocs.at(i), v.toSizeF());
- break;
- case QVariant::Point:
- case QVariant::PointF:
- program()->setUniformValue(m_uniformLocs.at(i), v.toPointF());
- break;
- case QVariant::Rect:
- case QVariant::RectF:
- {
- QRectF r = v.toRectF();
- program()->setUniformValue(m_uniformLocs.at(i), r.x(), r.y(), r.width(), r.height());
- }
- break;
- case QVariant::Vector3D:
- program()->setUniformValue(m_uniformLocs.at(i), qvariant_cast<QVector3D>(v));
- break;
- default:
- break;
- }
- }
-
- const QQuickShaderEffectMaterial *oldMaterial = static_cast<const QQuickShaderEffectMaterial *>(oldEffect);
- if (oldEffect == 0 || material->cullMode() != oldMaterial->cullMode()) {
- switch (material->cullMode()) {
- case QQuickShaderEffectMaterial::FrontFaceCulling:
- glEnable(GL_CULL_FACE);
- glCullFace(GL_FRONT);
- break;
- case QQuickShaderEffectMaterial::BackFaceCulling:
- glEnable(GL_CULL_FACE);
- glCullFace(GL_BACK);
- break;
- default:
- glDisable(GL_CULL_FACE);
- break;
- }
- }
-
- if ((state.isMatrixDirty()) && material->m_source.respectsMatrix)
- program()->setUniformValue(m_matrixLoc, state.combinedMatrix());
-}
-
-char const *const *QQuickCustomMaterialShader::attributeNames() const
-{
- return m_attributeNames.constData();
-}
-
-void QQuickCustomMaterialShader::initialize()
-{
- m_opacityLoc = program()->uniformLocation("qt_Opacity");
- m_matrixLoc = program()->uniformLocation("qt_Matrix");
-}
-
-const char *QQuickCustomMaterialShader::vertexShader() const
-{
- return m_key.vertexCode.constData();
-}
-
-const char *QQuickCustomMaterialShader::fragmentShader() const
-{
- return m_key.fragmentCode.constData();
-}
-
-
-bool QQuickShaderEffectMaterialKey::operator == (const QQuickShaderEffectMaterialKey &other) const
-{
- return vertexCode == other.vertexCode && fragmentCode == other.fragmentCode && className == other.className;
-}
-
-uint qHash(const QQuickShaderEffectMaterialKey &key)
-{
- return qHash(qMakePair(qMakePair(key.vertexCode, key.fragmentCode), key.className));
-}
-
-
-QHash<QQuickShaderEffectMaterialKey, QSharedPointer<QSGMaterialType> > QQuickShaderEffectMaterial::materialMap;
-
-QQuickShaderEffectMaterial::QQuickShaderEffectMaterial()
- : m_cullMode(NoCulling)
-{
- setFlag(Blending, true);
-}
-
-QSGMaterialType *QQuickShaderEffectMaterial::type() const
-{
- return m_type.data();
-}
-
-QSGMaterialShader *QQuickShaderEffectMaterial::createShader() const
-{
- return new QQuickCustomMaterialShader(m_source, m_source.attributeNames);
-}
-
-int QQuickShaderEffectMaterial::compare(const QSGMaterial *other) const
-{
- return this - static_cast<const QQuickShaderEffectMaterial *>(other);
-}
-
-void QQuickShaderEffectMaterial::setCullMode(QQuickShaderEffectMaterial::CullMode face)
-{
- m_cullMode = face;
-}
-
-QQuickShaderEffectMaterial::CullMode QQuickShaderEffectMaterial::cullMode() const
-{
- return m_cullMode;
-}
-
-void QQuickShaderEffectMaterial::setProgramSource(const QQuickShaderEffectProgram &source)
-{
- m_source = source;
- m_type = materialMap.value(m_source);
- if (m_type.isNull()) {
- m_type = QSharedPointer<QSGMaterialType>(new QSGMaterialType);
- materialMap.insert(m_source, m_type);
- }
-}
-
-void QQuickShaderEffectMaterial::setUniforms(const QVector<QPair<QByteArray, QVariant> > &uniformValues)
-{
- m_uniformValues = uniformValues;
-}
-
-void QQuickShaderEffectMaterial::setTextureProviders(const QVector<QPair<QByteArray, QSGTextureProvider *> > &textures)
-{
- m_textures = textures;
-}
-
-const QVector<QPair<QByteArray, QSGTextureProvider *> > &QQuickShaderEffectMaterial::textureProviders() const
-{
- return m_textures;
-}
-
-void QQuickShaderEffectMaterial::updateTextures() const
-{
- for (int i = 0; i < m_textures.size(); ++i) {
- if (QSGTextureProvider *provider = m_textures.at(i).second) {
- if (QSGDynamicTexture *texture = qobject_cast<QSGDynamicTexture *>(provider->texture()))
- texture->updateTexture();
- }
- }
-}
-
-
-QQuickShaderEffectNode::QQuickShaderEffectNode()
-{
- QSGNode::setFlag(UsePreprocess, true);
- setMaterial(&m_material);
-
-#ifdef QML_RUNTIME_TESTING
- description = QLatin1String("shadereffect");
-#endif
-}
-
-QQuickShaderEffectNode::~QQuickShaderEffectNode()
-{
-}
-
-void QQuickShaderEffectNode::markDirtyTexture()
-{
- markDirty(DirtyMaterial);
-}
-
-void QQuickShaderEffectNode::preprocess()
-{
- Q_ASSERT(material());
- static_cast<QQuickShaderEffectMaterial *>(material())->updateTextures();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickshadereffectnode_p.h b/src/declarative/items/qquickshadereffectnode_p.h
deleted file mode 100644
index 50213ff396..0000000000
--- a/src/declarative/items/qquickshadereffectnode_p.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKSHADEREFFECTNODE_P_H
-#define QQUICKSHADEREFFECTNODE_P_H
-
-#include "qsgnode.h"
-#include "qsgmaterial.h"
-#include <private/qsgtextureprovider_p.h>
-#include <qquickitem.h>
-
-#include <QtCore/qsharedpointer.h>
-#include <QtCore/qpointer.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-struct QQuickShaderEffectMaterialKey {
- QByteArray vertexCode;
- QByteArray fragmentCode;
- const char *className;
-
- bool operator == (const QQuickShaderEffectMaterialKey &other) const;
-};
-
-uint qHash(const QQuickShaderEffectMaterialKey &key);
-
-// TODO: Implement support for multisampling.
-struct QQuickShaderEffectProgram : public QQuickShaderEffectMaterialKey
-{
- QQuickShaderEffectProgram() : respectsOpacity(false), respectsMatrix(false) {}
-
- QVector<QByteArray> attributeNames;
- QSet<QByteArray> uniformNames;
-
- uint respectsOpacity : 1;
- uint respectsMatrix : 1;
-};
-
-
-class QQuickCustomMaterialShader;
-class QQuickShaderEffectMaterial : public QSGMaterial
-{
-public:
- enum CullMode
- {
- NoCulling,
- BackFaceCulling,
- FrontFaceCulling
- };
-
- QQuickShaderEffectMaterial();
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
- virtual int compare(const QSGMaterial *other) const;
-
- void setCullMode(CullMode face);
- CullMode cullMode() const;
-
- void setProgramSource(const QQuickShaderEffectProgram &);
- void setUniforms(const QVector<QPair<QByteArray, QVariant> > &uniformValues);
- void setTextureProviders(const QVector<QPair<QByteArray, QSGTextureProvider *> > &textures);
- const QVector<QPair<QByteArray, QSGTextureProvider *> > &textureProviders() const;
- void updateTextures() const;
-
-protected:
- friend class QQuickCustomMaterialShader;
-
- // The type pointer needs to be unique. It is not safe to let the type object be part of the
- // QQuickShaderEffectMaterial, since it can be deleted and a new one constructed on top of the old
- // one. The new QQuickShaderEffectMaterial would then get the same type pointer as the old one, and
- // CustomMaterialShaders based on the old one would incorrectly be used together with the new
- // one. To guarantee that the type pointer is unique, the type object must live as long as
- // there are any CustomMaterialShaders of that type.
- QSharedPointer<QSGMaterialType> m_type;
-
- QQuickShaderEffectProgram m_source;
- QVector<QPair<QByteArray, QVariant> > m_uniformValues;
- QVector<QPair<QByteArray, QSGTextureProvider *> > m_textures;
- CullMode m_cullMode;
-
- static QHash<QQuickShaderEffectMaterialKey, QSharedPointer<QSGMaterialType> > materialMap;
-};
-
-
-class QSGShaderEffectMesh;
-
-class QQuickShaderEffectNode : public QObject, public QSGGeometryNode
-{
- Q_OBJECT
-public:
- QQuickShaderEffectNode();
- virtual ~QQuickShaderEffectNode();
-
- virtual void preprocess();
-
- QQuickShaderEffectMaterial *shaderMaterial() { return &m_material; }
-
-private Q_SLOTS:
- void markDirtyTexture();
-
-private:
- QQuickShaderEffectMaterial m_material;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKSHADEREFFECTNODE_P_H
diff --git a/src/declarative/items/qquickshadereffectsource.cpp b/src/declarative/items/qquickshadereffectsource.cpp
deleted file mode 100644
index 952f240cd3..0000000000
--- a/src/declarative/items/qquickshadereffectsource.cpp
+++ /dev/null
@@ -1,921 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickshadereffectsource_p.h"
-
-#include "qquickitem_p.h"
-#include "qquickcanvas_p.h"
-#include <private/qsgadaptationlayer_p.h>
-#include <private/qsgrenderer_p.h>
-
-#include "qopenglframebufferobject.h"
-#include "qmath.h"
-#include <private/qsgtexture_p.h>
-
-QT_BEGIN_NAMESPACE
-
-DEFINE_BOOL_CONFIG_OPTION(qmlFboOverlay, QML_FBO_OVERLAY)
-
-class QQuickShaderEffectSourceTextureProvider : public QSGTextureProvider
-{
- Q_OBJECT
-public:
- QQuickShaderEffectSourceTextureProvider()
- : sourceTexture(0)
- {
- }
-
- QSGTexture *texture() const {
- sourceTexture->setMipmapFiltering(mipmapFiltering);
- sourceTexture->setFiltering(filtering);
- sourceTexture->setHorizontalWrapMode(horizontalWrap);
- sourceTexture->setVerticalWrapMode(verticalWrap);
- return sourceTexture;
- }
-
- QQuickShaderEffectTexture *sourceTexture;
-
- QSGTexture::Filtering mipmapFiltering;
- QSGTexture::Filtering filtering;
- QSGTexture::WrapMode horizontalWrap;
- QSGTexture::WrapMode verticalWrap;
-};
-#include "qquickshadereffectsource.moc"
-
-
-QQuickShaderEffectSourceNode::QQuickShaderEffectSourceNode()
-{
- setFlag(UsePreprocess, true);
-}
-
-void QQuickShaderEffectSourceNode::markDirtyTexture()
-{
- markDirty(DirtyMaterial);
-}
-
-
-QQuickShaderEffectTexture::QQuickShaderEffectTexture(QQuickItem *shaderSource)
- : QSGDynamicTexture()
- , m_item(0)
- , m_format(GL_RGBA)
- , m_shaderSource(shaderSource)
- , m_renderer(0)
- , m_fbo(0)
- , m_secondaryFbo(0)
-#ifdef QSG_DEBUG_FBO_OVERLAY
- , m_debugOverlay(0)
-#endif
- , m_context(QQuickItemPrivate::get(shaderSource)->sceneGraphContext())
- , m_mipmap(false)
- , m_live(true)
- , m_recursive(false)
- , m_dirtyTexture(true)
- , m_multisamplingSupportChecked(false)
- , m_multisampling(false)
- , m_grab(false)
-{
-}
-
-QQuickShaderEffectTexture::~QQuickShaderEffectTexture()
-{
- if (m_renderer)
- disconnect(m_renderer, SIGNAL(sceneGraphChanged()), this, SLOT(markDirtyTexture()));
- delete m_renderer;
- delete m_fbo;
- delete m_secondaryFbo;
-#ifdef QSG_DEBUG_FBO_OVERLAY
- delete m_debugOverlay;
-#endif
-}
-
-int QQuickShaderEffectTexture::textureId() const
-{
- return m_fbo ? m_fbo->texture() : 0;
-}
-
-bool QQuickShaderEffectTexture::hasAlphaChannel() const
-{
- return m_format != GL_RGB;
-}
-
-bool QQuickShaderEffectTexture::hasMipmaps() const
-{
- return m_mipmap;
-}
-
-
-void QQuickShaderEffectTexture::bind()
-{
-#ifndef QT_NO_DEBUG
- if (!m_recursive && m_fbo && ((m_multisampling && m_secondaryFbo->isBound()) || m_fbo->isBound()))
- qWarning("ShaderEffectSource: \'recursive\' must be set to true when rendering recursively.");
-#endif
- glBindTexture(GL_TEXTURE_2D, m_fbo ? m_fbo->texture() : 0);
- updateBindOptions();
-}
-
-bool QQuickShaderEffectTexture::updateTexture()
-{
- if ((m_live || m_grab) && m_dirtyTexture) {
- grab();
- m_grab = false;
- return true;
- }
- return false;
-}
-
-void QQuickShaderEffectTexture::setHasMipmaps(bool mipmap)
-{
- if (mipmap == m_mipmap)
- return;
- m_mipmap = mipmap;
- if (m_mipmap && m_fbo && !m_fbo->format().mipmap())
- markDirtyTexture();
-}
-
-
-void QQuickShaderEffectTexture::setItem(QSGNode *item)
-{
- if (item == m_item)
- return;
- m_item = item;
- markDirtyTexture();
-}
-
-void QQuickShaderEffectTexture::setRect(const QRectF &rect)
-{
- if (rect == m_rect)
- return;
- m_rect = rect;
- markDirtyTexture();
-}
-
-void QQuickShaderEffectTexture::setSize(const QSize &size)
-{
- if (size == m_size)
- return;
- m_size = size;
- markDirtyTexture();
-}
-
-void QQuickShaderEffectTexture::setFormat(GLenum format)
-{
- if (format == m_format)
- return;
- m_format = format;
- markDirtyTexture();
-}
-
-void QQuickShaderEffectTexture::setLive(bool live)
-{
- if (live == m_live)
- return;
- m_live = live;
- markDirtyTexture();
-}
-
-void QQuickShaderEffectTexture::scheduleUpdate()
-{
- if (m_grab)
- return;
- m_grab = true;
- if (m_dirtyTexture)
- emit updateRequested();
-}
-
-void QQuickShaderEffectTexture::setRecursive(bool recursive)
-{
- m_recursive = recursive;
-}
-
-void QQuickShaderEffectTexture::markDirtyTexture()
-{
- m_dirtyTexture = true;
- if (m_live || m_grab)
- emit updateRequested();
-}
-
-void QQuickShaderEffectTexture::grab()
-{
- if (!m_item || m_size.isNull()) {
- delete m_fbo;
- delete m_secondaryFbo;
- m_fbo = m_secondaryFbo = 0;
- m_dirtyTexture = false;
- if (m_grab)
- emit scheduledUpdateCompleted();
- return;
- }
- QSGNode *root = m_item;
- while (root->firstChild() && root->type() != QSGNode::RootNodeType)
- root = root->firstChild();
- if (root->type() != QSGNode::RootNodeType)
- return;
-
- if (!m_renderer) {
- m_renderer = m_context->createRenderer();
- connect(m_renderer, SIGNAL(sceneGraphChanged()), this, SLOT(markDirtyTexture()));
- }
- m_renderer->setRootNode(static_cast<QSGRootNode *>(root));
-
- bool deleteFboLater = false;
- if (!m_fbo || m_fbo->size() != m_size || m_fbo->format().internalTextureFormat() != m_format
- || (!m_fbo->format().mipmap() && m_mipmap))
- {
- if (!m_multisamplingSupportChecked) {
- QList<QByteArray> extensions = QByteArray((const char *)glGetString(GL_EXTENSIONS)).split(' ');
- m_multisampling = extensions.contains("GL_EXT_framebuffer_multisample")
- && extensions.contains("GL_EXT_framebuffer_blit");
- m_multisamplingSupportChecked = true;
- }
- if (m_multisampling) {
- // Don't delete the FBO right away in case it is used recursively.
- deleteFboLater = true;
- delete m_secondaryFbo;
- QOpenGLFramebufferObjectFormat format;
-
- format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
- format.setInternalTextureFormat(m_format);
- format.setSamples(8);
- m_secondaryFbo = new QOpenGLFramebufferObject(m_size, format);
- } else {
- QOpenGLFramebufferObjectFormat format;
- format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
- format.setInternalTextureFormat(m_format);
- format.setMipmap(m_mipmap);
- if (m_recursive) {
- deleteFboLater = true;
- delete m_secondaryFbo;
- m_secondaryFbo = new QOpenGLFramebufferObject(m_size, format);
- glBindTexture(GL_TEXTURE_2D, m_secondaryFbo->texture());
- updateBindOptions(true);
- } else {
- delete m_fbo;
- delete m_secondaryFbo;
- m_fbo = new QOpenGLFramebufferObject(m_size, format);
- m_secondaryFbo = 0;
- glBindTexture(GL_TEXTURE_2D, m_fbo->texture());
- updateBindOptions(true);
- }
- }
- }
-
- if (m_recursive && !m_secondaryFbo) {
- // m_fbo already created, m_recursive was just set.
- Q_ASSERT(m_fbo);
- Q_ASSERT(!m_multisampling);
-
- m_secondaryFbo = new QOpenGLFramebufferObject(m_size, m_fbo->format());
- glBindTexture(GL_TEXTURE_2D, m_secondaryFbo->texture());
- updateBindOptions(true);
- }
-
- // Render texture.
- root->markDirty(QSGNode::DirtyForceUpdate); // Force matrix, clip and opacity update.
- m_renderer->nodeChanged(root, QSGNode::DirtyForceUpdate); // Force render list update.
-
-#ifdef QSG_DEBUG_FBO_OVERLAY
- if (qmlFboOverlay()) {
- if (!m_debugOverlay)
- m_debugOverlay = m_context->createRectangleNode();
- m_debugOverlay->setRect(QRectF(0, 0, m_size.width(), m_size.height()));
- m_debugOverlay->setColor(QColor(0xff, 0x00, 0x80, 0x40));
- m_debugOverlay->setPenColor(QColor());
- m_debugOverlay->setPenWidth(0);
- m_debugOverlay->setRadius(0);
- m_debugOverlay->update();
- root->appendChildNode(m_debugOverlay);
- }
-#endif
-
- m_dirtyTexture = false;
-
- QOpenGLContext *ctx = m_context->glContext();
- m_renderer->setDeviceRect(m_size);
- m_renderer->setViewportRect(m_size);
- QRectF mirrored(m_rect.left(), m_rect.bottom(), m_rect.width(), -m_rect.height());
- m_renderer->setProjectionMatrixToRect(mirrored);
- m_renderer->setClearColor(Qt::transparent);
-
- if (m_multisampling) {
- m_renderer->renderScene(QSGBindableFbo(m_secondaryFbo));
-
- if (deleteFboLater) {
- delete m_fbo;
- QOpenGLFramebufferObjectFormat format;
- format.setInternalTextureFormat(m_format);
- format.setAttachment(QOpenGLFramebufferObject::NoAttachment);
- format.setMipmap(m_mipmap);
- format.setSamples(0);
- m_fbo = new QOpenGLFramebufferObject(m_size, format);
- glBindTexture(GL_TEXTURE_2D, m_fbo->texture());
- updateBindOptions(true);
- }
-
- QRect r(QPoint(), m_size);
- QOpenGLFramebufferObject::blitFramebuffer(m_fbo, r, m_secondaryFbo, r);
- } else {
- if (m_recursive) {
- m_renderer->renderScene(QSGBindableFbo(m_secondaryFbo));
-
- if (deleteFboLater) {
- delete m_fbo;
- QOpenGLFramebufferObjectFormat format;
- format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
- format.setInternalTextureFormat(m_format);
- format.setMipmap(m_mipmap);
- m_fbo = new QOpenGLFramebufferObject(m_size, format);
- glBindTexture(GL_TEXTURE_2D, m_fbo->texture());
- updateBindOptions(true);
- }
- qSwap(m_fbo, m_secondaryFbo);
- } else {
- m_renderer->renderScene(QSGBindableFbo(m_fbo));
- }
- }
-
- if (m_mipmap) {
- glBindTexture(GL_TEXTURE_2D, textureId());
- ctx->functions()->glGenerateMipmap(GL_TEXTURE_2D);
- }
-
- root->markDirty(QSGNode::DirtyForceUpdate); // Force matrix, clip, opacity and render list update.
-
-#ifdef QSG_DEBUG_FBO_OVERLAY
- if (qmlFboOverlay())
- root->removeChildNode(m_debugOverlay);
-#endif
- if (m_recursive)
- markDirtyTexture(); // Continuously update if 'live' and 'recursive'.
-
- if (m_grab)
- emit scheduledUpdateCompleted();
-}
-
-QImage QQuickShaderEffectTexture::toImage() const
-{
- if (m_fbo)
- return m_fbo->toImage();
-
- return QImage();
-}
-
-/*!
- \qmlclass ShaderEffectSource QQuickShaderEffectSource
- \since 5.0
- \ingroup qml-basic-visual-elements
- \brief The ShaderEffectSource element renders a QML element into a texture
- and displays it.
- \inherits Item
-
- The ShaderEffectSource element renders \l sourceItem into a texture and
- displays it in the scene. \l sourceItem is drawn into the texture as though
- it was a fully opaque root element. Thus \l sourceItem itself can be
- invisible, but still appear in the texture.
-
- ShaderEffectSource can be used as:
- \list
- \o a texture source in a \l ShaderEffect.
- This allows you to apply custom shader effects to any QML element.
- \o a cache for a complex element.
- The complex element can be rendered once into the texture, which can
- then be animated freely without the need to render the complex element
- again every frame.
- \o an opacity layer.
- ShaderEffectSource allows you to apply an opacity to elements as a group
- rather than each element individually.
- \endlist
-
- \table
- \row
- \o \image declarative-shadereffectsource.png
- \o \qml
- import QtQuick 2.0
-
- Rectangle {
- width: 200
- height: 100
- gradient: Gradient {
- GradientStop { position: 0; color: "white" }
- GradientStop { position: 1; color: "black" }
- }
- Row {
- opacity: 0.5
- Item {
- id: foo
- width: 100; height: 100
- Rectangle { x: 5; y: 5; width: 60; height: 60; color: "red" }
- Rectangle { x: 20; y: 20; width: 60; height: 60; color: "orange" }
- Rectangle { x: 35; y: 35; width: 60; height: 60; color: "yellow" }
- }
- ShaderEffectSource {
- width: 100; height: 100
- sourceItem: foo
- }
- }
- }
- \endqml
- \endrow
- \endtable
-
- The ShaderEffectSource element does not redirect any mouse or keyboard
- input to \l sourceItem. If you hide the \l sourceItem by setting
- \l{Item::visible}{visible} to false or \l{Item::opacity}{opacity} to zero,
- it will no longer react to input. In cases where the ShaderEffectSource is
- meant to replace the \l sourceItem, you typically want to hide the
- \l sourceItem while still handling input. For this, you can use
- the \l hideSource property.
-
- \note If \l sourceItem is a \l Rectangle with border, by default half the
- border width falls outside the texture. To get the whole border, you can
- extend the \l sourceRect.
-
- \warning In most cases, using a ShaderEffectSource will decrease
- performance, and in all cases, it will increase video memory usage.
- Rendering through a ShaderEffectSource might also lead to lower quality
- since some OpenGL implementations support multisampled backbuffer,
- but not multisampled framebuffer objects.
-*/
-
-QQuickShaderEffectSource::QQuickShaderEffectSource(QQuickItem *parent)
- : QQuickItem(parent)
- , m_provider(0)
- , m_texture(0)
- , m_wrapMode(ClampToEdge)
- , m_sourceItem(0)
- , m_textureSize(0, 0)
- , m_format(RGBA)
- , m_live(true)
- , m_hideSource(false)
- , m_mipmap(false)
- , m_recursive(false)
- , m_grab(true)
-{
- setFlag(ItemHasContents);
-}
-
-QQuickShaderEffectSource::~QQuickShaderEffectSource()
-{
- if (m_texture)
- m_texture->deleteLater();
-
- if (m_provider)
- m_provider->deleteLater();
-
- if (m_sourceItem) {
- QQuickItemPrivate *sd = QQuickItemPrivate::get(m_sourceItem);
- sd->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
- sd->derefFromEffectItem(m_hideSource);
- }
-}
-
-void QQuickShaderEffectSource::ensureTexture()
-{
- if (m_texture)
- return;
-
- Q_ASSERT_X(QQuickItemPrivate::get(this)->canvas
- && QQuickItemPrivate::get(this)->sceneGraphContext()
- && QThread::currentThread() == QQuickItemPrivate::get(this)->sceneGraphContext()->thread(),
- "QQuickShaderEffectSource::ensureTexture",
- "Cannot be used outside the rendering thread");
-
- m_texture = new QQuickShaderEffectTexture(this);
- connect(m_texture, SIGNAL(updateRequested()), this, SLOT(update()));
- connect(m_texture, SIGNAL(scheduledUpdateCompleted()), this, SIGNAL(scheduledUpdateCompleted()));
-}
-
-QSGTextureProvider *QQuickShaderEffectSource::textureProvider() const
-{
- if (!m_provider) {
- // Make sure it gets thread affinity on the rendering thread so deletion works properly..
- Q_ASSERT_X(QQuickItemPrivate::get(this)->canvas
- && QQuickItemPrivate::get(this)->sceneGraphContext()
- && QThread::currentThread() == QQuickItemPrivate::get(this)->sceneGraphContext()->thread(),
- "QQuickShaderEffectSource::textureProvider",
- "Cannot be used outside the rendering thread");
- const_cast<QQuickShaderEffectSource *>(this)->m_provider = new QQuickShaderEffectSourceTextureProvider();
- const_cast<QQuickShaderEffectSource *>(this)->ensureTexture();
- connect(m_texture, SIGNAL(updateRequested()), m_provider, SIGNAL(textureChanged()));
- m_provider->sourceTexture = m_texture;
- }
- return m_provider;
-}
-
-/*!
- \qmlproperty enumeration ShaderEffectSource::wrapMode
-
- This property defines the OpenGL wrap modes associated with the texture.
- Modifying this property makes most sense when the element is used as a
- source texture of a \l ShaderEffect.
-
- \list
- \o ShaderEffectSource.ClampToEdge - GL_CLAMP_TO_EDGE both horizontally and vertically
- \o ShaderEffectSource.RepeatHorizontally - GL_REPEAT horizontally, GL_CLAMP_TO_EDGE vertically
- \o ShaderEffectSource.RepeatVertically - GL_CLAMP_TO_EDGE horizontally, GL_REPEAT vertically
- \o ShaderEffectSource.Repeat - GL_REPEAT both horizontally and vertically
- \endlist
-
- \note Some OpenGL ES 2 implementations do not support the GL_REPEAT
- wrap mode with non-power-of-two textures.
-*/
-
-QQuickShaderEffectSource::WrapMode QQuickShaderEffectSource::wrapMode() const
-{
- return m_wrapMode;
-}
-
-void QQuickShaderEffectSource::setWrapMode(WrapMode mode)
-{
- if (mode == m_wrapMode)
- return;
- m_wrapMode = mode;
- update();
- emit wrapModeChanged();
-}
-
-/*!
- \qmlproperty Item ShaderEffectSource::sourceItem
-
- This property holds the element to be rendered into the texture.
-*/
-
-QQuickItem *QQuickShaderEffectSource::sourceItem() const
-{
- return m_sourceItem;
-}
-
-void QQuickShaderEffectSource::itemGeometryChanged(QQuickItem *item, const QRectF &newRect, const QRectF &oldRect)
-{
- Q_ASSERT(item == m_sourceItem);
- Q_UNUSED(item);
- if (newRect.size() != oldRect.size())
- update();
-}
-
-void QQuickShaderEffectSource::setSourceItem(QQuickItem *item)
-{
- if (item == m_sourceItem)
- return;
- if (m_sourceItem) {
- QQuickItemPrivate *d = QQuickItemPrivate::get(m_sourceItem);
- d->derefFromEffectItem(m_hideSource);
- d->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
- }
- m_sourceItem = item;
- if (m_sourceItem) {
- // TODO: Find better solution.
- // 'm_sourceItem' needs a canvas to get a scenegraph node.
- // The easiest way to make sure it gets a canvas is to
- // make it a part of the same item tree as 'this'.
- if (m_sourceItem->parentItem() == 0) {
- m_sourceItem->setParentItem(this);
- m_sourceItem->setVisible(false);
- }
- QQuickItemPrivate *d = QQuickItemPrivate::get(m_sourceItem);
- d->refFromEffectItem(m_hideSource);
- d->addItemChangeListener(this, QQuickItemPrivate::Geometry);
- }
- update();
- emit sourceItemChanged();
-}
-
-/*!
- \qmlproperty rect ShaderEffectSource::sourceRect
-
- This property defines which rectangular area of the \l sourceItem to
- render into the texture. The source rectangle can be larger than
- \l sourceItem itself. If the rectangle is null, which is the default,
- the whole \l sourceItem is rendered to texture.
-*/
-
-QRectF QQuickShaderEffectSource::sourceRect() const
-{
- return m_sourceRect;
-}
-
-void QQuickShaderEffectSource::setSourceRect(const QRectF &rect)
-{
- if (rect == m_sourceRect)
- return;
- m_sourceRect = rect;
- update();
- emit sourceRectChanged();
-}
-
-/*!
- \qmlproperty size ShaderEffectSource::textureSize
-
- This property holds the requested size of the texture. If it is empty,
- which is the default, the size of the source rectangle is used.
-
- \note Some platforms have a limit on how small framebuffer objects can be,
- which means the actual texture size might be larger than the requested
- size.
-*/
-
-QSize QQuickShaderEffectSource::textureSize() const
-{
- return m_textureSize;
-}
-
-void QQuickShaderEffectSource::setTextureSize(const QSize &size)
-{
- if (size == m_textureSize)
- return;
- m_textureSize = size;
- update();
- emit textureSizeChanged();
-}
-
-/*!
- \qmlproperty enumeration ShaderEffectSource::format
-
- This property defines the internal OpenGL format of the texture.
- Modifying this property makes most sense when the element is used as a
- source texture of a \l ShaderEffect. Depending on the OpenGL
- implementation, this property might allow you to save some texture memory.
-
- \list
- \o ShaderEffectSource.Alpha - GL_ALPHA
- \o ShaderEffectSource.RGB - GL_RGB
- \o ShaderEffectSource.RGBA - GL_RGBA
- \endlist
-
- \note Some OpenGL implementations do not support the GL_ALPHA format.
-*/
-
-QQuickShaderEffectSource::Format QQuickShaderEffectSource::format() const
-{
- return m_format;
-}
-
-void QQuickShaderEffectSource::setFormat(QQuickShaderEffectSource::Format format)
-{
- if (format == m_format)
- return;
- m_format = format;
- update();
- emit formatChanged();
-}
-
-/*!
- \qmlproperty bool ShaderEffectSource::live
-
- If this property is true, the texture is updated whenever the
- \l sourceItem changes. Otherwise, it will be a frozen image of the
- \l sourceItem. The property is true by default.
-*/
-
-bool QQuickShaderEffectSource::live() const
-{
- return m_live;
-}
-
-void QQuickShaderEffectSource::setLive(bool live)
-{
- if (live == m_live)
- return;
- m_live = live;
- update();
- emit liveChanged();
-}
-
-/*!
- \qmlproperty bool ShaderEffectSource::hideSource
-
- If this property is true, the \l sourceItem is hidden, though it will still
- be rendered into the texture. As opposed to hiding the \l sourceItem by
- setting \l{Item::visible}{visible} to false, setting this property to true
- will not prevent mouse or keyboard input from reaching \l sourceItem.
- The property is useful when the ShaderEffectSource is anchored on top of,
- and meant to replace the \l sourceItem.
-*/
-
-bool QQuickShaderEffectSource::hideSource() const
-{
- return m_hideSource;
-}
-
-void QQuickShaderEffectSource::setHideSource(bool hide)
-{
- if (hide == m_hideSource)
- return;
- if (m_sourceItem) {
- QQuickItemPrivate::get(m_sourceItem)->refFromEffectItem(hide);
- QQuickItemPrivate::get(m_sourceItem)->derefFromEffectItem(m_hideSource);
- }
- m_hideSource = hide;
- update();
- emit hideSourceChanged();
-}
-
-/*!
- \qmlproperty bool ShaderEffectSource::mipmap
-
- If this property is true, mipmaps are generated for the texture.
-
- \note Some OpenGL ES 2 implementations do not support mipmapping of
- non-power-of-two textures.
-*/
-
-bool QQuickShaderEffectSource::mipmap() const
-{
- return m_mipmap;
-}
-
-void QQuickShaderEffectSource::setMipmap(bool enabled)
-{
- if (enabled == m_mipmap)
- return;
- m_mipmap = enabled;
- update();
- emit mipmapChanged();
-}
-
-/*!
- \qmlproperty bool ShaderEffectSource::recursive
-
- Set this property to true if the ShaderEffectSource has a dependency on
- itself. ShaderEffectSources form a dependency chain, where one
- ShaderEffectSource can be part of the \l sourceItem of another.
- If there is a loop in this chain, a ShaderEffectSource could end up trying
- to render into the same texture it is using as source, which is not allowed
- by OpenGL. When this property is set to true, an extra texture is allocated
- so that ShaderEffectSource can keep a copy of the texture from the previous
- frame. It can then render into one texture and use the texture from the
- previous frame as source.
-
- Setting both this property and \l live to true will cause the scene graph
- to render continuously. Since the ShaderEffectSource depends on itself,
- updating it means that it immediately becomes dirty again.
-*/
-
-bool QQuickShaderEffectSource::recursive() const
-{
- return m_recursive;
-}
-
-void QQuickShaderEffectSource::setRecursive(bool enabled)
-{
- if (enabled == m_recursive)
- return;
- m_recursive = enabled;
- emit recursiveChanged();
-}
-
-/*!
- \qmlmethod ShaderEffectSource::scheduleUpdate()
-
- Schedules a re-rendering of the texture for the next frame.
- Use this to update the texture when \l live is false.
-*/
-
-void QQuickShaderEffectSource::scheduleUpdate()
-{
- if (m_grab)
- return;
- m_grab = true;
- update();
-}
-
-static void get_wrap_mode(QQuickShaderEffectSource::WrapMode mode, QSGTexture::WrapMode *hWrap, QSGTexture::WrapMode *vWrap)
-{
- switch (mode) {
- case QQuickShaderEffectSource::RepeatHorizontally:
- *hWrap = QSGTexture::Repeat;
- *vWrap = QSGTexture::ClampToEdge;
- break;
- case QQuickShaderEffectSource::RepeatVertically:
- *vWrap = QSGTexture::Repeat;
- *hWrap = QSGTexture::ClampToEdge;
- break;
- case QQuickShaderEffectSource::Repeat:
- *hWrap = *vWrap = QSGTexture::Repeat;
- break;
- default:
- // QQuickShaderEffectSource::ClampToEdge
- *hWrap = *vWrap = QSGTexture::ClampToEdge;
- break;
- }
-}
-
-
-QSGNode *QQuickShaderEffectSource::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
-{
- if (!m_sourceItem || m_sourceItem->width() == 0 || m_sourceItem->height() == 0) {
- delete oldNode;
- return 0;
- }
-
- ensureTexture();
-
- QQuickShaderEffectTexture *tex = qobject_cast<QQuickShaderEffectTexture *>(m_texture);
- tex->setLive(m_live);
- tex->setItem(QQuickItemPrivate::get(m_sourceItem)->itemNode());
- QRectF sourceRect = m_sourceRect.width() == 0 || m_sourceRect.height() == 0
- ? QRectF(0, 0, m_sourceItem->width(), m_sourceItem->height())
- : m_sourceRect;
- tex->setRect(sourceRect);
- QSize textureSize = m_textureSize.isEmpty()
- ? QSize(qCeil(qAbs(sourceRect.width())), qCeil(qAbs(sourceRect.height())))
- : m_textureSize;
- Q_ASSERT(!textureSize.isEmpty());
- QQuickItemPrivate *d = static_cast<QQuickItemPrivate *>(QObjectPrivate::get(this));
- const QSize minTextureSize = d->sceneGraphContext()->minimumFBOSize();
- // Keep power-of-two by doubling the size.
- while (textureSize.width() < minTextureSize.width())
- textureSize.rwidth() *= 2;
- while (textureSize.height() < minTextureSize.height())
- textureSize.rheight() *= 2;
-
- tex->setSize(textureSize);
- tex->setRecursive(m_recursive);
- tex->setFormat(GLenum(m_format));
- tex->setHasMipmaps(m_mipmap);
-
- if (m_grab)
- tex->scheduleUpdate();
- m_grab = false;
-
- QSGTexture::Filtering filtering = QQuickItemPrivate::get(this)->smooth
- ? QSGTexture::Linear
- : QSGTexture::Nearest;
- QSGTexture::Filtering mmFiltering = m_mipmap ? filtering : QSGTexture::None;
- QSGTexture::WrapMode hWrap, vWrap;
- get_wrap_mode(m_wrapMode, &hWrap, &vWrap);
-
- if (m_provider) {
- m_provider->mipmapFiltering = mmFiltering;
- m_provider->filtering = filtering;
- m_provider->horizontalWrap = hWrap;
- m_provider->verticalWrap = vWrap;
- }
-
- // Don't create the paint node if we're not spanning any area
- if (width() == 0 || height() == 0) {
- delete oldNode;
- return 0;
- }
-
- QQuickShaderEffectSourceNode *node = static_cast<QQuickShaderEffectSourceNode *>(oldNode);
- if (!node) {
- node = new QQuickShaderEffectSourceNode;
- node->setTexture(m_texture);
- connect(m_texture, SIGNAL(updateRequested()), node, SLOT(markDirtyTexture()));
- }
-
- // If live and recursive, update continuously.
- if (m_live && m_recursive)
- node->markDirty(QSGNode::DirtyMaterial);
-
- node->setMipmapFiltering(mmFiltering);
- node->setFiltering(filtering);
- node->setHorizontalWrapMode(hWrap);
- node->setVerticalWrapMode(vWrap);
- node->setTargetRect(QRectF(0, 0, width(), height()));
- node->setSourceRect(QRectF(0, 0, 1, 1));
- node->update();
-
- return node;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickshadereffectsource_p.h b/src/declarative/items/qquickshadereffectsource_p.h
deleted file mode 100644
index fee361c27c..0000000000
--- a/src/declarative/items/qquickshadereffectsource_p.h
+++ /dev/null
@@ -1,259 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKSHADEREFFECTSOURCE_P_H
-#define QQUICKSHADEREFFECTSOURCE_P_H
-
-#include "qquickitem.h"
-#include <private/qsgtextureprovider_p.h>
-#include <private/qsgadaptationlayer_p.h>
-#include <private/qsgcontext_p.h>
-#include <private/qsgdefaultimagenode_p.h>
-#include <private/qquickitemchangelistener_p.h>
-
-#include "qpointer.h"
-#include "qsize.h"
-#include "qrect.h"
-
-#define QSG_DEBUG_FBO_OVERLAY
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGNode;
-class UpdatePaintNodeData;
-class QOpenGLFramebufferObject;
-
-class QQuickShaderEffectSourceTextureProvider;
-
-class QQuickShaderEffectSourceNode : public QObject, public QSGDefaultImageNode
-{
- Q_OBJECT
-
-public:
- QQuickShaderEffectSourceNode();
-
-private Q_SLOTS:
- void markDirtyTexture();
-};
-
-class Q_DECLARATIVE_EXPORT QQuickShaderEffectTexture : public QSGDynamicTexture
-{
- Q_OBJECT
-public:
- QQuickShaderEffectTexture(QQuickItem *shaderSource);
- ~QQuickShaderEffectTexture();
-
- virtual bool updateTexture();
-
- // The item's "paint node", not effect node.
- QSGNode *item() const { return m_item; }
- void setItem(QSGNode *item);
-
- QRectF rect() const { return m_rect; }
- void setRect(const QRectF &rect);
-
- QSize size() const { return m_size; }
- void setSize(const QSize &size);
-
- void setHasMipmaps(bool mipmap);
-
- void bind();
-
- bool hasAlphaChannel() const;
- bool hasMipmaps() const;
- int textureId() const;
- QSize textureSize() const { return m_size; }
-
- GLenum format() const { return m_format; }
- void setFormat(GLenum format);
-
- bool live() const { return bool(m_live); }
- void setLive(bool live);
-
- bool recursive() const { return bool(m_recursive); }
- void setRecursive(bool recursive);
-
- void scheduleUpdate();
-
- QImage toImage() const;
-
-Q_SIGNALS:
- void updateRequested();
- void scheduledUpdateCompleted();
-
-public Q_SLOTS:
- void markDirtyTexture();
-
-private:
- void grab();
-
- QSGNode *m_item;
- QRectF m_rect;
- QSize m_size;
- GLenum m_format;
-
- QQuickItem *m_shaderSource;
- QSGRenderer *m_renderer;
- QOpenGLFramebufferObject *m_fbo;
- QOpenGLFramebufferObject *m_secondaryFbo;
-
-#ifdef QSG_DEBUG_FBO_OVERLAY
- QSGRectangleNode *m_debugOverlay;
-#endif
-
- QSGContext *m_context;
-
- uint m_mipmap : 1;
- uint m_live : 1;
- uint m_recursive : 1;
- uint m_dirtyTexture : 1;
- uint m_multisamplingSupportChecked : 1;
- uint m_multisampling : 1;
- uint m_grab : 1;
-};
-
-class Q_DECLARATIVE_EXPORT QQuickShaderEffectSource : public QQuickItem, public QQuickItemChangeListener
-{
- Q_OBJECT
- Q_PROPERTY(WrapMode wrapMode READ wrapMode WRITE setWrapMode NOTIFY wrapModeChanged)
- Q_PROPERTY(QQuickItem *sourceItem READ sourceItem WRITE setSourceItem NOTIFY sourceItemChanged)
- Q_PROPERTY(QRectF sourceRect READ sourceRect WRITE setSourceRect NOTIFY sourceRectChanged)
- Q_PROPERTY(QSize textureSize READ textureSize WRITE setTextureSize NOTIFY textureSizeChanged)
- Q_PROPERTY(Format format READ format WRITE setFormat NOTIFY formatChanged)
- Q_PROPERTY(bool live READ live WRITE setLive NOTIFY liveChanged)
- Q_PROPERTY(bool hideSource READ hideSource WRITE setHideSource NOTIFY hideSourceChanged)
- Q_PROPERTY(bool mipmap READ mipmap WRITE setMipmap NOTIFY mipmapChanged)
- Q_PROPERTY(bool recursive READ recursive WRITE setRecursive NOTIFY recursiveChanged)
-
- Q_ENUMS(Format WrapMode)
-public:
- enum WrapMode {
- ClampToEdge,
- RepeatHorizontally,
- RepeatVertically,
- Repeat
- };
-
- enum Format {
- Alpha = GL_ALPHA,
- RGB = GL_RGB,
- RGBA = GL_RGBA
- };
-
- QQuickShaderEffectSource(QQuickItem *parent = 0);
- ~QQuickShaderEffectSource();
-
- WrapMode wrapMode() const;
- void setWrapMode(WrapMode mode);
-
- QQuickItem *sourceItem() const;
- void setSourceItem(QQuickItem *item);
-
- QRectF sourceRect() const;
- void setSourceRect(const QRectF &rect);
-
- QSize textureSize() const;
- void setTextureSize(const QSize &size);
-
- Format format() const;
- void setFormat(Format format);
-
- bool live() const;
- void setLive(bool live);
-
- bool hideSource() const;
- void setHideSource(bool hide);
-
- bool mipmap() const;
- void setMipmap(bool enabled);
-
- bool recursive() const;
- void setRecursive(bool enabled);
-
- bool isTextureProvider() const { return true; }
- QSGTextureProvider *textureProvider() const;
-
- Q_INVOKABLE void scheduleUpdate();
-
-Q_SIGNALS:
- void wrapModeChanged();
- void sourceItemChanged();
- void sourceRectChanged();
- void textureSizeChanged();
- void formatChanged();
- void liveChanged();
- void hideSourceChanged();
- void mipmapChanged();
- void recursiveChanged();
-
- void scheduledUpdateCompleted();
-
-protected:
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
-
- virtual void itemGeometryChanged(QQuickItem *item, const QRectF &newRect, const QRectF &oldRect);
-
-private:
- void ensureTexture();
-
- QQuickShaderEffectSourceTextureProvider *m_provider;
- QQuickShaderEffectTexture *m_texture;
- WrapMode m_wrapMode;
- QPointer<QQuickItem> m_sourceItem;
- QRectF m_sourceRect;
- QSize m_textureSize;
- Format m_format;
- uint m_live : 1;
- uint m_hideSource : 1;
- uint m_mipmap : 1;
- uint m_recursive : 1;
- uint m_grab : 1;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKSHADEREFFECTSOURCE_P_H
diff --git a/src/declarative/items/qquicksprite.cpp b/src/declarative/items/qquicksprite.cpp
deleted file mode 100644
index b476905269..0000000000
--- a/src/declarative/items/qquicksprite.cpp
+++ /dev/null
@@ -1,130 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquicksprite_p.h"
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass Sprite QQuickSprite
- \inqmlmodule QtQuick 2
- \brief The Sprite element represents a sprite animation
-
-*/
-/*!
- \qmlproperty int QtQuick2::Sprite::duration
-
- Time between frames.
-*/
-/*!
- \qmlproperty int QtQuick2::Sprite::durationVariation
-
- The time between frames can vary by up to this amount.
-
- Default is 0.
-*/
-
-/*!
- \qmlproperty string QtQuick2::Sprite::name
-
- The name of this sprite, for use in the to property of other sprites.
-*/
-/*!
- \qmlproperty QVariantMap QtQuick2::Sprite::to
-
- A list of other sprites and weighted transitions to them,
- for example {"a":1, "b":2, "c":0} would specify that one-third should
- transition to sprite "a" when this sprite is done, and two-thirds should
- transition to sprite "b" when this sprite is done. As the transitions are
- chosen randomly, these proportions will not be exact. With "c":0 in the list,
- no sprites will randomly transition to "c", but it wll be a valid path if a sprite
- goal is set.
-
- If no list is specified, or the sum of weights in the list is zero, then the sprite
- will repeat itself after completing.
-*/
-/*!
- \qmlproperty int QtQuick2::Sprite::frames
-
- Number of frames in this sprite.
-*/
-/*!
- \qmlproperty int QtQuick2::Sprite::frameHeight
-
- Height of a single frame in this sprite.
-*/
-/*!
- \qmlproperty int QtQuick2::Sprite::frameWidth
-
- Width of a single frame in this sprite.
-*/
-/*!
- \qmlproperty url QtQuick2::Sprite::source
-
- The image source for the animation.
-
- If frameHeight and frameWidth are not specified, it is assumed to be a single long row of square frames.
- Otherwise, it can be multiple contiguous rows or rectangluar frames, when one row runs out the next will be used.
-*/
- Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged)
- Q_PROPERTY(int durationVariation READ durationVariance WRITE setDurationVariance NOTIFY durationVarianceChanged)
- Q_PROPERTY(QVariantMap to READ to WRITE setTo NOTIFY toChanged)
- Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
- Q_PROPERTY(qreal speedModifiesDuration READ speedModifer WRITE setSpeedModifier NOTIFY speedModifierChanged)
- Q_PROPERTY(int frames READ frames WRITE setFrames NOTIFY framesChanged)
- Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
- //If frame height or width is not specified, it is assumed to be a single long row of square frames.
- //Otherwise, it can be multiple contiguous rows, when one row runs out the next will be used.
- Q_PROPERTY(int frameHeight READ frameHeight WRITE setFrameHeight NOTIFY frameHeightChanged)
- Q_PROPERTY(int frameWidth READ frameWidth WRITE setFrameWidth NOTIFY frameWidthChanged)
-
-QQuickSprite::QQuickSprite(QObject *parent) :
- QQuickStochasticState(parent)
- , m_generatedCount(0)
- , m_framesPerRow(0)
- , m_frameHeight(0)
- , m_frameWidth(0)
- , m_rowY(0)
-{
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquicksprite_p.h b/src/declarative/items/qquicksprite_p.h
deleted file mode 100644
index e7f3bbce80..0000000000
--- a/src/declarative/items/qquicksprite_p.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKSPRITE_P_H
-#define QQUICKSPRITE_P_H
-
-#include <QObject>
-#include <QUrl>
-#include <QVariantMap>
-#include <QDeclarativeListProperty>
-#include "qquickspriteengine_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QQuickSprite : public QQuickStochasticState
-{
- Q_OBJECT
- Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
- //If frame height or width is not specified, it is assumed to be a single long row of square frames.
- //Otherwise, it can be multiple contiguous rows, when one row runs out the next will be used.
- Q_PROPERTY(int frameHeight READ frameHeight WRITE setFrameHeight NOTIFY frameHeightChanged)
- Q_PROPERTY(int frameWidth READ frameWidth WRITE setFrameWidth NOTIFY frameWidthChanged)
-
-public:
- explicit QQuickSprite(QObject *parent = 0);
-
- QUrl source() const
- {
- return m_source;
- }
-
- int frameHeight() const
- {
- return m_frameHeight;
- }
-
- int frameWidth() const
- {
- return m_frameWidth;
- }
-
-
-signals:
-
- void sourceChanged(QUrl arg);
-
- void frameHeightChanged(int arg);
-
- void frameWidthChanged(int arg);
-
-public slots:
-
- void setSource(QUrl arg)
- {
- if (m_source != arg) {
- m_source = arg;
- emit sourceChanged(arg);
- }
- }
-
- void setFrameHeight(int arg)
- {
- if (m_frameHeight != arg) {
- m_frameHeight = arg;
- emit frameHeightChanged(arg);
- }
- }
-
- void setFrameWidth(int arg)
- {
- if (m_frameWidth != arg) {
- m_frameWidth = arg;
- emit frameWidthChanged(arg);
- }
- }
-
-
-private:
- friend class QSGImageParticle;
- friend class QQuickSpriteEngine;
- friend class QQuickStochasticEngine;
- int m_generatedCount;
- int m_framesPerRow;
- QUrl m_source;
- int m_frameHeight;
- int m_frameWidth;
- int m_rowY;
-
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // QQUICKSPRITE_P_H
diff --git a/src/declarative/items/qquickspriteengine.cpp b/src/declarative/items/qquickspriteengine.cpp
deleted file mode 100644
index c25ccf3487..0000000000
--- a/src/declarative/items/qquickspriteengine.cpp
+++ /dev/null
@@ -1,501 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickspriteengine_p.h"
-#include "qquicksprite_p.h"
-#include <QDebug>
-#include <QPainter>
-#include <QSet>
-#include <QtGui>
-
-QT_BEGIN_NAMESPACE
-
-/* TODO:
- make sharable?
- solve the state data initialization/transfer issue so as to not need to make friends
-*/
-
-QQuickStochasticEngine::QQuickStochasticEngine(QObject *parent) :
- QObject(parent), m_timeOffset(0)
-{
- //Default size 1
- setCount(1);
- m_advanceTime.start();
-}
-
-QQuickStochasticEngine::QQuickStochasticEngine(QList<QQuickStochasticState*> states, QObject *parent) :
- QObject(parent), m_states(states), m_timeOffset(0)
-{
- //Default size 1
- setCount(1);
- m_advanceTime.start();
-}
-
-QQuickStochasticEngine::~QQuickStochasticEngine()
-{
-}
-
-QQuickSpriteEngine::QQuickSpriteEngine(QObject *parent)
- : QQuickStochasticEngine(parent)
-{
-}
-
-QQuickSpriteEngine::QQuickSpriteEngine(QList<QQuickSprite*> sprites, QObject *parent)
- : QQuickStochasticEngine(parent)
-{
- foreach (QQuickSprite* sprite, sprites)
- m_states << (QQuickStochasticState*)sprite;
-}
-
-QQuickSpriteEngine::~QQuickSpriteEngine()
-{
-}
-
-
-int QQuickSpriteEngine::maxFrames()
-{
- return m_maxFrames;
-}
-
-/* States too large to fit in one row are split into multiple rows
- This is more efficient for the implementation, but should remain an implementation detail (invisible from QML)
- Therefore the below functions abstract sprite from the viewpoint of classes that pass the details onto shaders
- But States maintain their listed index for internal structures
-TODO: All these calculations should be pre-calculated and cached during initialization for a significant performance boost
-TODO: Above idea needs to have the varying duration offset added to it
-*/
-int QQuickSpriteEngine::spriteState(int sprite)
-{
- int state = m_things[sprite];
- if (!m_sprites[state]->m_generatedCount)
- return state;
- int rowDuration = m_duration[sprite] * m_sprites[state]->m_framesPerRow;
- int extra = (m_timeOffset - m_startTimes[sprite])/rowDuration;
- return state + extra;
-}
-
-int QQuickSpriteEngine::spriteStart(int sprite)
-{
- int state = m_things[sprite];
- if (!m_sprites[state]->m_generatedCount)
- return m_startTimes[sprite];
- int rowDuration = m_duration[sprite] * m_sprites[state]->m_framesPerRow;
- int extra = (m_timeOffset - m_startTimes[sprite])/rowDuration;
- return state + extra*rowDuration;
-}
-
-int QQuickSpriteEngine::spriteFrames(int sprite)
-{
- int state = m_things[sprite];
- if (!m_sprites[state]->m_generatedCount)
- return m_sprites[state]->frames();
- int rowDuration = m_duration[sprite] * m_sprites[state]->m_framesPerRow;
- int extra = (m_timeOffset - m_startTimes[sprite])/rowDuration;
- if (extra == m_sprites[state]->m_generatedCount - 1)//last state
- return m_sprites[state]->frames() % m_sprites[state]->m_framesPerRow;
- else
- return m_sprites[state]->m_framesPerRow;
-}
-
-int QQuickSpriteEngine::spriteDuration(int sprite)
-{
- int state = m_things[sprite];
- if (!m_sprites[state]->m_generatedCount)
- return m_duration[sprite];
- int rowDuration = m_duration[sprite] * m_sprites[state]->m_framesPerRow;
- int extra = (m_timeOffset - m_startTimes[sprite])/rowDuration;
- if (extra == m_sprites[state]->m_generatedCount - 1)//last state
- return (m_duration[sprite] * m_sprites[state]->frames()) % rowDuration;
- else
- return rowDuration;
-}
-
-int QQuickSpriteEngine::spriteY(int sprite)
-{
- int state = m_things[sprite];
- if (!m_sprites[state]->m_generatedCount)
- return m_sprites[state]->m_rowY;
- int rowDuration = m_duration[sprite] * m_sprites[state]->m_framesPerRow;
- int extra = (m_timeOffset - m_startTimes[sprite])/rowDuration;
- return m_sprites[state]->m_rowY + m_sprites[state]->m_frameHeight * extra;
-}
-
-int QQuickSpriteEngine::spriteWidth(int sprite)
-{
- int state = m_things[sprite];
- return m_sprites[state]->m_frameWidth;
-}
-
-int QQuickSpriteEngine::spriteHeight(int sprite)
-{
- int state = m_things[sprite];
- return m_sprites[state]->m_frameHeight;
-}
-
-int QQuickSpriteEngine::spriteCount()//TODO: Actually image state count, need to rename these things to make sense together
-{
- return m_imageStateCount;
-}
-
-void QQuickStochasticEngine::setGoal(int state, int sprite, bool jump)
-{
- if (sprite >= m_things.count() || state >= m_states.count()
- || sprite < 0 || state < 0)
- return;
- if (!jump){
- m_goals[sprite] = state;
- return;
- }
-
- if (m_things[sprite] == state)
- return;//Already there
- m_things[sprite] = state;
- m_duration[sprite] = m_states[state]->variedDuration();
- m_goals[sprite] = -1;
- restart(sprite);
- emit stateChanged(sprite);
- emit m_states[state]->entered();
- return;
-}
-
-QImage QQuickSpriteEngine::assembledImage()
-{
- int h = 0;
- int w = 0;
- m_maxFrames = 0;
- m_imageStateCount = 0;
- int maxSize = 0;
-
- glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize);
- foreach (QQuickStochasticState* s, m_states){
- QQuickSprite* sprite = qobject_cast<QQuickSprite*>(s);
- if (sprite)
- m_sprites << sprite;
- else
- qDebug() << "Error: Non-sprite in QQuickSpriteEngine";
- }
-
- foreach (QQuickSprite* state, m_sprites){
- if (state->frames() > m_maxFrames)
- m_maxFrames = state->frames();
-
- QImage img(state->source().toLocalFile());
- if (img.isNull()) {
- qWarning() << "SpriteEngine: loading image failed..." << state->source().toLocalFile();
- return QImage();
- }
-
- //Check that the frame sizes are the same within one engine
- if (!state->m_frameWidth)
- state->m_frameWidth = img.width() / state->frames();
-
- if (!state->m_frameHeight)
- state->m_frameHeight = img.height();
-
- if (state->frames() * state->frameWidth() > maxSize){
- struct helper{
- static int divRoundUp(int a, int b){return (a+b-1)/b;}
- };
- int rowsNeeded = helper::divRoundUp(state->frames(), helper::divRoundUp(maxSize, state->frameWidth()));
- if (rowsNeeded * state->frameHeight() > maxSize){
- qWarning() << "SpriteEngine: Animation too large to fit in one texture..." << state->source().toLocalFile();
- qWarning() << "SpriteEngine: Your texture max size today is " << maxSize;
- }
- state->m_generatedCount = rowsNeeded;
- h += state->frameHeight() * rowsNeeded;
- w = qMax(w, helper::divRoundUp(maxSize, state->frameWidth()));
- m_imageStateCount += rowsNeeded;
- }else{
- h += state->frameHeight();
- w = qMax(w, state->frameWidth() * state->frames());
- m_imageStateCount++;
- }
- }
-
- //maxFrames is max number in a line of the texture
- QImage image(w, h, QImage::Format_ARGB32);
- image.fill(0);
- QPainter p(&image);
- int y = 0;
- foreach (QQuickSprite* state, m_sprites){
- QImage img(state->source().toLocalFile());
- int frameWidth = state->m_frameWidth;
- int frameHeight = state->m_frameHeight;
- if (img.height() == frameHeight && img.width() < maxSize){//Simple case
- p.drawImage(0,y,img);
- state->m_rowY = y;
- y += frameHeight;
- }else{//Chopping up image case
- state->m_framesPerRow = image.width()/frameWidth;
- state->m_rowY = y;
- int x = 0;
- int curX = 0;
- int curY = 0;
- int framesLeft = state->frames();
- while (framesLeft > 0){
- if (image.width() - x + curX <= img.width()){//finish a row in image (dest)
- int copied = image.width() - x;
- Q_ASSERT(!(copied % frameWidth));//XXX: Just checking
- framesLeft -= copied/frameWidth;
- p.drawImage(x,y,img.copy(curX,curY,copied,frameHeight));
- y += frameHeight;
- curX += copied;
- x = 0;
- if (curX == img.width()){
- curX = 0;
- curY += frameHeight;
- }
- }else{//finish a row in img (src)
- int copied = img.width() - curX;
- Q_ASSERT(!(copied % frameWidth));//XXX: Just checking
- framesLeft -= copied/frameWidth;
- p.drawImage(x,y,img.copy(curX,curY,copied,frameHeight));
- curY += frameHeight;
- x += copied;
- curX = 0;
- }
- }
- if (x)
- y += frameHeight;
- }
- }
-
- if (image.height() > maxSize){
- qWarning() << "SpriteEngine: Too many animations to fit in one texture...";
- qWarning() << "SpriteEngine: Your texture max size today is " << maxSize;
- return QImage();
- }
- return image;
-}
-
-void QQuickStochasticEngine::setCount(int c)
-{
- m_things.resize(c);
- m_goals.resize(c);
- m_duration.resize(c);
- m_startTimes.resize(c);
-}
-
-void QQuickStochasticEngine::start(int index, int state)
-{
- if (index >= m_things.count())
- return;
- m_things[index] = state;
- m_duration[index] = m_states[state]->variedDuration();
- m_goals[index] = -1;
- restart(index);
-}
-
-void QQuickStochasticEngine::stop(int index)
-{
- if (index >= m_things.count())
- return;
- //Will never change until start is called again with a new state - this is not a 'pause'
- for (int i=0; i<m_stateUpdates.count(); i++)
- m_stateUpdates[i].second.removeAll(index);
-}
-
-void QQuickStochasticEngine::restart(int index)
-{
- m_startTimes[index] = m_timeOffset + m_advanceTime.elapsed();
- int time = m_duration[index] * m_states[m_things[index]]->frames() + m_startTimes[index];
- for (int i=0; i<m_stateUpdates.count(); i++)
- m_stateUpdates[i].second.removeAll(index);
- addToUpdateList(time, index);
-}
-
-uint QQuickStochasticEngine::updateSprites(uint time)//### would returning a list of changed idxs be faster than signals?
-{
- //Sprite State Update;
- QSet<int> changedIndexes;
- while (!m_stateUpdates.isEmpty() && time >= m_stateUpdates.first().first){
- foreach (int idx, m_stateUpdates.first().second){
- if (idx >= m_things.count())
- continue;//TODO: Proper fix(because this does happen and I'm just ignoring it)
- int stateIdx = m_things[idx];
- int nextIdx = -1;
- int goalPath = goalSeek(stateIdx, idx);
- if (goalPath == -1){//Random
- qreal r =(qreal) qrand() / (qreal) RAND_MAX;
- qreal total = 0.0;
- for (QVariantMap::const_iterator iter=m_states[stateIdx]->m_to.constBegin();
- iter!=m_states[stateIdx]->m_to.constEnd(); iter++)
- total += (*iter).toReal();
- r*=total;
- for (QVariantMap::const_iterator iter= m_states[stateIdx]->m_to.constBegin();
- iter!=m_states[stateIdx]->m_to.constEnd(); iter++){
- if (r < (*iter).toReal()){
- bool superBreak = false;
- for (int i=0; i<m_states.count(); i++){
- if (m_states[i]->name() == iter.key()){
- nextIdx = i;
- superBreak = true;
- break;
- }
- }
- if (superBreak)
- break;
- }
- r -= (*iter).toReal();
- }
- }else{//Random out of shortest paths to goal
- nextIdx = goalPath;
- }
- if (nextIdx == -1)//No to states means stay here
- nextIdx = stateIdx;
-
- m_things[idx] = nextIdx;
- m_duration[idx] = m_states[nextIdx]->variedDuration();
- m_startTimes[idx] = time;
- if (nextIdx != stateIdx){
- changedIndexes << idx;
- emit m_states[nextIdx]->entered();
- }
- addToUpdateList((m_duration[idx] * m_states[nextIdx]->frames()) + time, idx);
- }
- m_stateUpdates.pop_front();
- }
-
- m_timeOffset = time;
- m_advanceTime.start();
- //TODO: emit this when a psuedostate changes too
- foreach (int idx, changedIndexes){//Batched so that update list doesn't change midway
- emit stateChanged(idx);
- }
- if (m_stateUpdates.isEmpty())
- return -1;
- return m_stateUpdates.first().first;
-}
-
-int QQuickStochasticEngine::goalSeek(int curIdx, int spriteIdx, int dist)
-{
- QString goalName;
- if (m_goals[spriteIdx] != -1)
- goalName = m_states[m_goals[spriteIdx]]->name();
- else
- goalName = m_globalGoal;
- if (goalName.isEmpty())
- return -1;
- //TODO: caching instead of excessively redoing iterative deepening (which was chosen arbitarily anyways)
- // Paraphrased - implement in an *efficient* manner
- for (int i=0; i<m_states.count(); i++)
- if (m_states[curIdx]->name() == goalName)
- return curIdx;
- if (dist < 0)
- dist = m_states.count();
- QQuickStochasticState* curState = m_states[curIdx];
- for (QVariantMap::const_iterator iter = curState->m_to.constBegin();
- iter!=curState->m_to.constEnd(); iter++){
- if (iter.key() == goalName)
- for (int i=0; i<m_states.count(); i++)
- if (m_states[i]->name() == goalName)
- return i;
- }
- QSet<int> options;
- for (int i=1; i<dist; i++){
- for (QVariantMap::const_iterator iter = curState->m_to.constBegin();
- iter!=curState->m_to.constEnd(); iter++){
- int option = -1;
- for (int j=0; j<m_states.count(); j++)//One place that could be a lot more efficient...
- if (m_states[j]->name() == iter.key())
- if (goalSeek(j, spriteIdx, i) != -1)
- option = j;
- if (option != -1)
- options << option;
- }
- if (!options.isEmpty()){
- if (options.count()==1)
- return *(options.begin());
- int option = -1;
- qreal r =(qreal) qrand() / (qreal) RAND_MAX;
- qreal total = 0;
- for (QSet<int>::const_iterator iter=options.constBegin();
- iter!=options.constEnd(); iter++)
- total += curState->m_to.value(m_states[(*iter)]->name()).toReal();
- r *= total;
- for (QVariantMap::const_iterator iter = curState->m_to.constBegin();
- iter!=curState->m_to.constEnd(); iter++){
- bool superContinue = true;
- for (int j=0; j<m_states.count(); j++)
- if (m_states[j]->name() == iter.key())
- if (options.contains(j))
- superContinue = false;
- if (superContinue)
- continue;
- if (r < (*iter).toReal()){
- bool superBreak = false;
- for (int j=0; j<m_states.count(); j++){
- if (m_states[j]->name() == iter.key()){
- option = j;
- superBreak = true;
- break;
- }
- }
- if (superBreak)
- break;
- }
- r-=(*iter).toReal();
- }
- return option;
- }
- }
- return -1;
-}
-
-void QQuickStochasticEngine::addToUpdateList(uint t, int idx)
-{
- for (int i=0; i<m_stateUpdates.count(); i++){
- if (m_stateUpdates[i].first==t){
- m_stateUpdates[i].second << idx;
- return;
- }else if (m_stateUpdates[i].first > t){
- QList<int> tmpList;
- tmpList << idx;
- m_stateUpdates.insert(i, qMakePair(t, tmpList));
- return;
- }
- }
- QList<int> tmpList;
- tmpList << idx;
- m_stateUpdates << qMakePair(t, tmpList);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickspriteengine_p.h b/src/declarative/items/qquickspriteengine_p.h
deleted file mode 100644
index 1040140a28..0000000000
--- a/src/declarative/items/qquickspriteengine_p.h
+++ /dev/null
@@ -1,323 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKSPRITEENGINE_P_H
-#define QQUICKSPRITEENGINE_P_H
-
-#include <QObject>
-#include <QVector>
-#include <QTimer>
-#include <QTime>
-#include <QList>
-#include <QDeclarativeListProperty>
-#include <QImage>
-#include <QPair>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickSprite;
-class Q_AUTOTEST_EXPORT QQuickStochasticState : public QObject //For internal use
-{
- Q_OBJECT
- Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged)
- Q_PROPERTY(int durationVariation READ durationVariance WRITE setDurationVariance NOTIFY durationVarianceChanged)
- Q_PROPERTY(QVariantMap to READ to WRITE setTo NOTIFY toChanged)
- Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
- Q_PROPERTY(qreal speedModifiesDuration READ speedModifer WRITE setSpeedModifier NOTIFY speedModifierChanged)
- Q_PROPERTY(int frames READ frames WRITE setFrames NOTIFY framesChanged)
-
-public:
- QQuickStochasticState(QObject* parent = 0)
- : QObject(parent)
- , m_frames(1)
- , m_duration(1000)
- {
- }
-
- int duration() const
- {
- return m_duration;
- }
-
- QString name() const
- {
- return m_name;
- }
-
- QVariantMap to() const
- {
- return m_to;
- }
-
- qreal speedModifer() const
- {
- return m_speedModifier;
- }
-
- int durationVariance() const
- {
- return m_durationVariance;
- }
-
-
- int variedDuration() const
- {
- return m_duration
- + (m_durationVariance * ((qreal)qrand()/RAND_MAX) * 2)
- - m_durationVariance;
- }
-
- int frames() const
- {
- return m_frames;
- }
-
-signals:
- void durationChanged(int arg);
-
- void nameChanged(QString arg);
-
- void toChanged(QVariantMap arg);
-
- void speedModifierChanged(qreal arg);
-
- void durationVarianceChanged(int arg);
-
- void entered();//### Just playing around - don't expect full state API
- void framesChanged(int arg);
-
-public slots:
- void setDuration(int arg)
- {
- if (m_duration != arg) {
- m_duration = arg;
- emit durationChanged(arg);
- }
- }
-
- void setName(QString arg)
- {
- if (m_name != arg) {
- m_name = arg;
- emit nameChanged(arg);
- }
- }
-
- void setTo(QVariantMap arg)
- {
- if (m_to != arg) {
- m_to = arg;
- emit toChanged(arg);
- }
- }
-
- void setSpeedModifier(qreal arg)
- {
- if (m_speedModifier != arg) {
- m_speedModifier = arg;
- emit speedModifierChanged(arg);
- }
- }
-
- void setDurationVariance(int arg)
- {
- if (m_durationVariance != arg) {
- m_durationVariance = arg;
- emit durationVarianceChanged(arg);
- }
- }
-
- void setFrames(int arg)
- {
- if (m_frames != arg) {
- m_frames = arg;
- emit framesChanged(arg);
- }
- }
-
-private:
- QString m_name;
- int m_frames;
- QVariantMap m_to;
- int m_duration;
- qreal m_speedModifier;
- int m_durationVariance;
-
- friend class QQuickStochasticEngine;
-};
-
-class Q_AUTOTEST_EXPORT QQuickStochasticEngine : public QObject
-{
- Q_OBJECT
- //TODO: Optimize single state case?
- Q_PROPERTY(QString globalGoal READ globalGoal WRITE setGlobalGoal NOTIFY globalGoalChanged)
- Q_PROPERTY(QDeclarativeListProperty<QQuickStochasticState> states READ states)
-public:
- explicit QQuickStochasticEngine(QObject *parent = 0);
- QQuickStochasticEngine(QList<QQuickStochasticState*> states, QObject *parent=0);
- ~QQuickStochasticEngine();
-
- QDeclarativeListProperty<QQuickStochasticState> states()
- {
- return QDeclarativeListProperty<QQuickStochasticState>(this, m_states);
- }
-
- QString globalGoal() const
- {
- return m_globalGoal;
- }
-
- int count() const {return m_things.count();}
- void setCount(int c);
-
- void setGoal(int state, int sprite=0, bool jump=false);
- void start(int index=0, int state=0);
- void stop(int index=0);
- int curState(int index=0) {return m_things[index];}
-
- QQuickStochasticState* state(int idx){return m_states[idx];}
- int stateIndex(QQuickStochasticState* s){return m_states.indexOf(s);}
- int stateIndex(const QString& s) {
- for (int i=0; i<m_states.count(); i++)
- if (m_states[i]->name() == s)
- return i;
- return -1;
- }
-
- int stateCount() {return m_states.count();}
-private:
-signals:
-
- void globalGoalChanged(QString arg);
- void stateChanged(int idx);
-
-public slots:
- void setGlobalGoal(QString arg)
- {
- if (m_globalGoal != arg) {
- m_globalGoal = arg;
- emit globalGoalChanged(arg);
- }
- }
-
- uint updateSprites(uint time);
-
-protected:
- friend class QQuickParticleSystem;
- void restart(int index);
- void addToUpdateList(uint t, int idx);
- int goalSeek(int curState, int idx, int dist=-1);
- QList<QQuickStochasticState*> m_states;
- //### Consider struct or class for the four data variables?
- QVector<int> m_things;//int is the index in m_states of the current state
- QVector<int> m_goals;
- QVector<int> m_duration;
- QVector<int> m_startTimes;
- QList<QPair<uint, QList<int> > > m_stateUpdates;//### This could be done faster - priority queue?
-
- QTime m_advanceTime;
- uint m_timeOffset;
- QString m_globalGoal;
- int m_maxFrames;
- int m_imageStateCount;
-};
-
-class QQuickSpriteEngine : public QQuickStochasticEngine
-{
- Q_OBJECT
- Q_PROPERTY(QDeclarativeListProperty<QQuickSprite> sprites READ sprites)
-public:
- explicit QQuickSpriteEngine(QObject *parent = 0);
- QQuickSpriteEngine(QList<QQuickSprite*> sprites, QObject *parent=0);
- ~QQuickSpriteEngine();
- QDeclarativeListProperty<QQuickSprite> sprites()
- {
- return QDeclarativeListProperty<QQuickSprite>(this, m_sprites);
- }
-
-
- int spriteState(int sprite=0);
- int spriteStart(int sprite=0);
- int spriteFrames(int sprite=0);
- int spriteDuration(int sprite=0);
- int spriteX(int /* sprite */ = 0) { return 0; }//Currently all rows are 0 aligned, if we get more space efficient we might change this
- int spriteY(int sprite=0);
- int spriteWidth(int sprite=0);
- int spriteHeight(int sprite=0);
- int spriteCount();//Like state count, but for the image states
- int maxFrames();
- QImage assembledImage();
-private:
- QList<QQuickSprite*> m_sprites;
-};
-
-//Common use is to have your own list property which is transparently an engine
-inline void spriteAppend(QDeclarativeListProperty<QQuickSprite> *p, QQuickSprite* s)
-{
- reinterpret_cast<QList<QQuickSprite *> *>(p->data)->append(s);
- p->object->metaObject()->invokeMethod(p->object, "createEngine");
-}
-
-inline QQuickSprite* spriteAt(QDeclarativeListProperty<QQuickSprite> *p, int idx)
-{
- return reinterpret_cast<QList<QQuickSprite *> *>(p->data)->at(idx);
-}
-
-inline void spriteClear(QDeclarativeListProperty<QQuickSprite> *p)
-{
- reinterpret_cast<QList<QQuickSprite *> *>(p->data)->clear();
- p->object->metaObject()->invokeMethod(p->object, "createEngine");
-}
-
-inline int spriteCount(QDeclarativeListProperty<QQuickSprite> *p)
-{
- return reinterpret_cast<QList<QQuickSprite *> *>(p->data)->count();
-}
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKSPRITEENGINE_P_H
diff --git a/src/declarative/items/qquickspriteimage.cpp b/src/declarative/items/qquickspriteimage.cpp
deleted file mode 100644
index a18d0f95c7..0000000000
--- a/src/declarative/items/qquickspriteimage.cpp
+++ /dev/null
@@ -1,455 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickspriteimage_p.h"
-#include "qquicksprite_p.h"
-#include "qquickspriteengine_p.h"
-#include <private/qsgcontext_p.h>
-#include <private/qsgadaptationlayer_p.h>
-#include <qsgnode.h>
-#include <qsgengine.h>
-#include <qsgtexturematerial.h>
-#include <qsgtexture.h>
-#include <qquickcanvas.h>
-#include <QFile>
-#include <cmath>
-#include <qmath.h>
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-
-static const char vertexShaderCode[] =
- "attribute highp vec2 vTex;\n"
- "uniform highp vec4 animData;// interpolate(bool), duration, frameCount (this anim), timestamp (this anim)\n"
- "uniform highp vec4 animPos;//sheet x,y, width/height of this anim\n"
- "uniform highp vec4 animSheetSize; //width/height of whole sheet, width/height of element\n"
- "\n"
- "uniform highp mat4 qt_Matrix;\n"
- "uniform highp float timestamp;\n"
- "\n"
- "varying highp vec4 fTexS;\n"
- "varying lowp float progress;\n"
- "\n"
- "\n"
- "void main() {\n"
- " //Calculate frame location in texture\n"
- " highp float frameIndex = mod((((timestamp - animData.w)*1000.)/animData.y),animData.z);\n"
- " progress = mod((timestamp - animData.w)*1000., animData.y) / animData.y;\n"
- "\n"
- " frameIndex = floor(frameIndex);\n"
- " fTexS.xy = vec2(((frameIndex + vTex.x) * animPos.z / animSheetSize.x), ((animPos.y + vTex.y * animPos.w) / animSheetSize.y));\n"
- "\n"
- " //Next frame is also passed, for interpolation\n"
- " //### Should the next anim be precalculated to allow for interpolation there?\n"
- " if (animData.x == 1.0 && frameIndex != animData.z - 1.)//Can't do it for the last frame though, this anim may not loop\n"
- " frameIndex = mod(frameIndex+1., animData.z);\n"
- " fTexS.zw = vec2(((frameIndex + vTex.x) * animPos.z / animSheetSize.x), ((animPos.y + vTex.y * animPos.w) / animSheetSize.y));\n"
- "\n"
- " gl_Position = qt_Matrix * vec4(animSheetSize.z * vTex.x, animSheetSize.w * vTex.y, 0, 1);\n"
- "}\n";
-
-static const char fragmentShaderCode[] =
- "uniform sampler2D texture;\n"
- "uniform lowp float qt_Opacity;\n"
- "\n"
- "varying highp vec4 fTexS;\n"
- "varying lowp float progress;\n"
- "\n"
- "void main() {\n"
- " gl_FragColor = mix(texture2D(texture, fTexS.xy), texture2D(texture, fTexS.zw), progress) * qt_Opacity;\n"
- "}\n";
-
-class QQuickSpriteMaterial : public QSGMaterial
-{
-public:
- QQuickSpriteMaterial();
- virtual ~QQuickSpriteMaterial();
- virtual QSGMaterialType *type() const { static QSGMaterialType type; return &type; }
- virtual QSGMaterialShader *createShader() const;
- virtual int compare(const QSGMaterial *other) const
- {
- return this - static_cast<const QQuickSpriteMaterial *>(other);
- }
-
- QSGTexture *texture;
-
- qreal timestamp;
- float interpolate;
- float frameDuration;
- float frameCount;
- float animT;
- float animX;
- float animY;
- float animWidth;
- float animHeight;
- float sheetWidth;
- float sheetHeight;
- float elementWidth;
- float elementHeight;
-};
-
-QQuickSpriteMaterial::QQuickSpriteMaterial()
- : timestamp(0)
- , interpolate(1.0f)
- , frameDuration(1.0f)
- , frameCount(1.0f)
- , animT(0.0f)
- , animX(0.0f)
- , animY(0.0f)
- , animWidth(1.0f)
- , animHeight(1.0f)
- , sheetWidth(1.0f)
- , sheetHeight(1.0f)
- , elementWidth(1.0f)
- , elementHeight(1.0f)
-{
- setFlag(Blending, true);
-}
-
-QQuickSpriteMaterial::~QQuickSpriteMaterial()
-{
- delete texture;
-}
-
-class SpriteMaterialData : public QSGMaterialShader
-{
-public:
- SpriteMaterialData(const char * /* vertexFile */ = 0, const char * /* fragmentFile */ = 0)
- {
- }
-
- void deactivate() {
- QSGMaterialShader::deactivate();
-
- for (int i=0; i<8; ++i) {
- program()->setAttributeArray(i, GL_FLOAT, chunkOfBytes, 1, 0);
- }
- }
-
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *)
- {
- QQuickSpriteMaterial *m = static_cast<QQuickSpriteMaterial *>(newEffect);
- m->texture->bind();
-
- program()->setUniformValue(m_opacity_id, state.opacity());
- program()->setUniformValue(m_timestamp_id, (float) m->timestamp);
- program()->setUniformValue(m_animData_id, m->interpolate, m->frameDuration, m->frameCount, m->animT);
- program()->setUniformValue(m_animPos_id, m->animX, m->animY, m->animWidth, m->animHeight);
- program()->setUniformValue(m_animSheetSize_id, m->sheetWidth, m->sheetHeight, m->elementWidth, m->elementHeight);
-
- if (state.isMatrixDirty())
- program()->setUniformValue(m_matrix_id, state.combinedMatrix());
- }
-
- virtual void initialize() {
- m_matrix_id = program()->uniformLocation("qt_Matrix");
- m_opacity_id = program()->uniformLocation("qt_Opacity");
- m_timestamp_id = program()->uniformLocation("timestamp");
- m_animData_id = program()->uniformLocation("animData");
- m_animPos_id = program()->uniformLocation("animPos");
- m_animSheetSize_id = program()->uniformLocation("animSheetSize");
- }
-
- virtual const char *vertexShader() const { return vertexShaderCode; }
- virtual const char *fragmentShader() const { return fragmentShaderCode; }
-
- virtual char const *const *attributeNames() const {
- static const char *attr[] = {
- "vTex",
- 0
- };
- return attr;
- }
-
- int m_matrix_id;
- int m_opacity_id;
- int m_timestamp_id;
- int m_animData_id;
- int m_animPos_id;
- int m_animSheetSize_id;
-
- static float chunkOfBytes[1024];
-};
-
-float SpriteMaterialData::chunkOfBytes[1024];
-
-QSGMaterialShader *QQuickSpriteMaterial::createShader() const
-{
- return new SpriteMaterialData;
-}
-
-struct SpriteVertex {
- float tx;
- float ty;
-};
-
-struct SpriteVertices {
- SpriteVertex v1;
- SpriteVertex v2;
- SpriteVertex v3;
- SpriteVertex v4;
-};
-
-/*!
- \qmlclass SpriteImage QQuickSpriteImage
- \inqmlmodule QtQuick 2
- \inherits Item
- \brief The SpriteImage element draws a sprite animation
-
-*/
-/*!
- \qmlproperty bool QtQuick2::SpriteImage::running
-
- Whether the sprite is animating or not.
-
- Default is true
-*/
-/*!
- \qmlproperty bool QtQuick2::SpriteImage::interpolate
-
- If true, interpolation will occur between sprite frames to make the
- animation appear smoother.
-
- Default is true.
-*/
-/*!
- \qmlproperty string QtQuick2::SpriteImage::goalState
-
- The name of the Sprite which the animation should move to.
-
- Sprite states have defined durations and transitions between them, setting goalState
- will cause it to disregard any path weightings (including 0) and head down the path
- which will reach the goalState quickest (fewest animations). It will pass through
- intermediate states on that path, and animate them for their duration.
-
- If it is possible to return to the goalState from the starting point of the goalState
- it will continue to do so until goalState is set to "" or an unreachable state.
-*/
-/*! \qmlmethod void QtQuick2::SpriteImage::jumpTo(string sprite)
-
- This function causes the sprite to jump to the specified state immediately, intermediate
- states are not played.
-*/
-/*!
- \qmlproperty list<Sprite> QtQuick2::SpriteImage::sprites
-
- The sprite or sprites to draw. Sprites will be scaled to the size of this element.
-*/
-
-//TODO: Implicitly size element to size of first sprite?
-QQuickSpriteImage::QQuickSpriteImage(QQuickItem *parent) :
- QQuickItem(parent)
- , m_node(0)
- , m_material(0)
- , m_spriteEngine(0)
- , m_pleaseReset(false)
- , m_running(true)
- , m_interpolate(true)
-{
- setFlag(ItemHasContents);
- connect(this, SIGNAL(runningChanged(bool)),
- this, SLOT(update()));
-}
-
-void QQuickSpriteImage::jumpTo(const QString &sprite)
-{
- if (!m_spriteEngine)
- return;
- m_spriteEngine->setGoal(m_spriteEngine->stateIndex(sprite), 0, true);
-}
-
-void QQuickSpriteImage::setGoalState(const QString &sprite)
-{
- if (m_goalState != sprite){
- m_goalState = sprite;
- emit goalStateChanged(sprite);
- m_spriteEngine->setGoal(m_spriteEngine->stateIndex(sprite));
- }
-}
-
-QDeclarativeListProperty<QQuickSprite> QQuickSpriteImage::sprites()
-{
- return QDeclarativeListProperty<QQuickSprite>(this, &m_sprites, spriteAppend, spriteCount, spriteAt, spriteClear);
-}
-
-void QQuickSpriteImage::createEngine()
-{
- //TODO: delay until component complete
- if (m_spriteEngine)
- delete m_spriteEngine;
- if (m_sprites.count())
- m_spriteEngine = new QQuickSpriteEngine(m_sprites, this);
- else
- m_spriteEngine = 0;
- reset();
-}
-
-static QSGGeometry::Attribute SpriteImage_Attributes[] = {
- QSGGeometry::Attribute::create(0, 2, GL_FLOAT), // tex
-};
-
-static QSGGeometry::AttributeSet SpriteImage_AttributeSet =
-{
- 1, // Attribute Count
- 2 * sizeof(float),
- SpriteImage_Attributes
-};
-
-QSGGeometryNode* QQuickSpriteImage::buildNode()
-{
- if (!m_spriteEngine) {
- qWarning() << "SpriteImage: No sprite engine...";
- return 0;
- }
-
- m_material = new QQuickSpriteMaterial();
-
- QImage image = m_spriteEngine->assembledImage();
- if (image.isNull())
- return 0;
- m_material->texture = canvas()->createTextureFromImage(image);
- m_material->texture->setFiltering(QSGTexture::Linear);
- m_spriteEngine->start(0);
- m_material->interpolate = m_interpolate ? 1.0 : 0.0;
- m_material->frameCount = m_spriteEngine->spriteFrames();
- m_material->frameDuration = m_spriteEngine->spriteDuration();
- m_material->animT = 0;
- m_material->animX = m_spriteEngine->spriteX();
- m_material->animY = m_spriteEngine->spriteY();
- m_material->animWidth = m_spriteEngine->spriteWidth();
- m_material->animHeight = m_spriteEngine->spriteHeight();
- m_material->sheetWidth = image.width();
- m_material->sheetHeight = image.height();
- m_material->elementWidth = width();
- m_material->elementHeight = height();
-
- int vCount = 4;
- int iCount = 6;
- QSGGeometry *g = new QSGGeometry(SpriteImage_AttributeSet, vCount, iCount);
- g->setDrawingMode(GL_TRIANGLES);
-
- SpriteVertices *p = (SpriteVertices *) g->vertexData();
-
- p->v1.tx = 0;
- p->v1.ty = 0;
-
- p->v2.tx = 1.0;
- p->v2.ty = 0;
-
- p->v3.tx = 0;
- p->v3.ty = 1.0;
-
- p->v4.tx = 1.0;
- p->v4.ty = 1.0;
-
- quint16 *indices = g->indexDataAsUShort();
- indices[0] = 0;
- indices[1] = 1;
- indices[2] = 2;
- indices[3] = 1;
- indices[4] = 3;
- indices[5] = 2;
-
-
- m_timestamp.start();
- m_node = new QSGGeometryNode();
- m_node->setGeometry(g);
- m_node->setMaterial(m_material);
- m_node->setFlag(QSGGeometryNode::OwnsMaterial);
- return m_node;
-}
-
-void QQuickSpriteImage::reset()
-{
- m_pleaseReset = true;
-}
-
-QSGNode *QQuickSpriteImage::updatePaintNode(QSGNode *, UpdatePaintNodeData *)
-{
- if (m_pleaseReset) {
- delete m_node;
- delete m_material;
-
- m_node = 0;
- m_material = 0;
- m_pleaseReset = false;
- }
-
- prepareNextFrame();
-
- if (m_running) {
- update();
- if (m_node)
- m_node->markDirty(QSGNode::DirtyMaterial);
- }
-
- return m_node;
-}
-
-void QQuickSpriteImage::prepareNextFrame()
-{
- if (m_node == 0)
- m_node = buildNode();
- if (m_node == 0) //error creating node
- return;
-
- uint timeInt = m_timestamp.elapsed();
- qreal time = timeInt / 1000.;
- m_material->timestamp = time;
- m_material->elementHeight = height();
- m_material->elementWidth = width();
- m_material->interpolate = m_interpolate;
-
- //Advance State
- m_spriteEngine->updateSprites(timeInt);
- int curY = m_spriteEngine->spriteY();
- if (curY != m_material->animY){
- m_material->animT = m_spriteEngine->spriteStart()/1000.0;
- m_material->frameCount = m_spriteEngine->spriteFrames();
- m_material->frameDuration = m_spriteEngine->spriteDuration();
- m_material->animX = m_spriteEngine->spriteX();
- m_material->animY = m_spriteEngine->spriteY();
- m_material->animWidth = m_spriteEngine->spriteWidth();
- m_material->animHeight = m_spriteEngine->spriteHeight();
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickspriteimage_p.h b/src/declarative/items/qquickspriteimage_p.h
deleted file mode 100644
index 39384cedca..0000000000
--- a/src/declarative/items/qquickspriteimage_p.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKSPRITEIMAGE_P_H
-#define QQUICKSPRITEIMAGE_P_H
-
-#include <QQuickItem>
-#include <QTime>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGContext;
-class QQuickSprite;
-class QQuickSpriteEngine;
-class QSGGeometryNode;
-class QQuickSpriteMaterial;
-class Q_AUTOTEST_EXPORT QQuickSpriteImage : public QQuickItem
-{
- Q_OBJECT
- Q_PROPERTY(bool running READ running WRITE setRunning NOTIFY runningChanged)
- Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate NOTIFY interpolateChanged)
- Q_PROPERTY(QString goalState READ goalState WRITE setGoalState NOTIFY goalStateChanged)
- //###try to share similar spriteEngines for less overhead?
- Q_PROPERTY(QDeclarativeListProperty<QQuickSprite> sprites READ sprites)
- Q_CLASSINFO("DefaultProperty", "sprites")
-
-public:
- explicit QQuickSpriteImage(QQuickItem *parent = 0);
-
- QDeclarativeListProperty<QQuickSprite> sprites();
-
- bool running() const
- {
- return m_running;
- }
-
- bool interpolate() const
- {
- return m_interpolate;
- }
-
- QString goalState() const
- {
- return m_goalState;
- }
-
-signals:
-
- void runningChanged(bool arg);
- void interpolateChanged(bool arg);
- void goalStateChanged(QString arg);
-
-public slots:
-
- void jumpTo(const QString &sprite);
- void setGoalState(const QString &sprite);
-
- void setRunning(bool arg)
- {
- if (m_running != arg) {
- m_running = arg;
- emit runningChanged(arg);
- }
- }
-
- void setInterpolate(bool arg)
- {
- if (m_interpolate != arg) {
- m_interpolate = arg;
- emit interpolateChanged(arg);
- }
- }
-
-private slots:
- void createEngine();
-protected:
- void reset();
- QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
-private:
- void prepareNextFrame();
- QSGGeometryNode* buildNode();
- QSGGeometryNode *m_node;
- QQuickSpriteMaterial *m_material;
- QList<QQuickSprite*> m_sprites;
- QQuickSpriteEngine* m_spriteEngine;
- QTime m_timestamp;
- int m_maxFrames;
- bool m_pleaseReset;
- bool m_running;
- bool m_interpolate;
- QString m_goalState;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKSPRITEIMAGE_P_H
diff --git a/src/declarative/items/qquickstateoperations.cpp b/src/declarative/items/qquickstateoperations.cpp
deleted file mode 100644
index 8c53e0a63f..0000000000
--- a/src/declarative/items/qquickstateoperations.cpp
+++ /dev/null
@@ -1,1346 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickstateoperations_p.h"
-#include "qquickitem_p.h"
-
-#include <private/qdeclarativestate_p_p.h>
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtCore/qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickParentChangePrivate : public QDeclarativeStateOperationPrivate
-{
- Q_DECLARE_PUBLIC(QQuickParentChange)
-public:
- QQuickParentChangePrivate() : target(0), parent(0), origParent(0), origStackBefore(0),
- rewindParent(0), rewindStackBefore(0) {}
-
- QQuickItem *target;
- QDeclarativeGuard<QQuickItem> parent;
- QDeclarativeGuard<QQuickItem> origParent;
- QDeclarativeGuard<QQuickItem> origStackBefore;
- QQuickItem *rewindParent;
- QQuickItem *rewindStackBefore;
-
- QDeclarativeNullableValue<QDeclarativeScriptString> xString;
- QDeclarativeNullableValue<QDeclarativeScriptString> yString;
- QDeclarativeNullableValue<QDeclarativeScriptString> widthString;
- QDeclarativeNullableValue<QDeclarativeScriptString> heightString;
- QDeclarativeNullableValue<QDeclarativeScriptString> scaleString;
- QDeclarativeNullableValue<QDeclarativeScriptString> rotationString;
-
- void doChange(QQuickItem *targetParent, QQuickItem *stackBefore = 0);
-};
-
-void QQuickParentChangePrivate::doChange(QQuickItem *targetParent, QQuickItem *stackBefore)
-{
- if (targetParent && target && target->parentItem()) {
- Q_Q(QQuickParentChange);
- bool ok;
- const QTransform &transform = target->parentItem()->itemTransform(targetParent, &ok);
- if (transform.type() >= QTransform::TxShear || !ok) {
- qmlInfo(q) << QQuickParentChange::tr("Unable to preserve appearance under complex transform");
- ok = false;
- }
-
- qreal scale = 1;
- qreal rotation = 0;
- bool isRotate = (transform.type() == QTransform::TxRotate) || (transform.m11() < 0);
- if (ok && !isRotate) {
- if (transform.m11() == transform.m22())
- scale = transform.m11();
- else {
- qmlInfo(q) << QQuickParentChange::tr("Unable to preserve appearance under non-uniform scale");
- ok = false;
- }
- } else if (ok && isRotate) {
- if (transform.m11() == transform.m22())
- scale = qSqrt(transform.m11()*transform.m11() + transform.m12()*transform.m12());
- else {
- qmlInfo(q) << QQuickParentChange::tr("Unable to preserve appearance under non-uniform scale");
- ok = false;
- }
-
- if (scale != 0)
- rotation = atan2(transform.m12()/scale, transform.m11()/scale) * 180/M_PI;
- else {
- qmlInfo(q) << QQuickParentChange::tr("Unable to preserve appearance under scale of 0");
- ok = false;
- }
- }
-
- const QPointF &point = transform.map(QPointF(target->x(),target->y()));
- qreal x = point.x();
- qreal y = point.y();
-
- // setParentItem will update the transformOriginPoint if needed
- target->setParentItem(targetParent);
-
- if (ok && target->transformOrigin() != QQuickItem::TopLeft) {
- qreal tempxt = target->transformOriginPoint().x();
- qreal tempyt = target->transformOriginPoint().y();
- QTransform t;
- t.translate(-tempxt, -tempyt);
- t.rotate(rotation);
- t.scale(scale, scale);
- t.translate(tempxt, tempyt);
- const QPointF &offset = t.map(QPointF(0,0));
- x += offset.x();
- y += offset.y();
- }
-
- if (ok) {
- //qDebug() << x << y << rotation << scale;
- target->setX(x);
- target->setY(y);
- target->setRotation(target->rotation() + rotation);
- target->setScale(target->scale() * scale);
- }
- } else if (target) {
- target->setParentItem(targetParent);
- }
-
- //restore the original stack position.
- //### if stackBefore has also been reparented this won't work
- if (stackBefore)
- target->stackBefore(stackBefore);
-}
-
-QQuickParentChange::QQuickParentChange(QObject *parent)
- : QDeclarativeStateOperation(*(new QQuickParentChangePrivate), parent)
-{
-}
-
-QQuickParentChange::~QQuickParentChange()
-{
-}
-
-QDeclarativeScriptString QQuickParentChange::x() const
-{
- Q_D(const QQuickParentChange);
- return d->xString.value;
-}
-
-void QQuickParentChange::setX(QDeclarativeScriptString x)
-{
- Q_D(QQuickParentChange);
- d->xString = x;
-}
-
-bool QQuickParentChange::xIsSet() const
-{
- Q_D(const QQuickParentChange);
- return d->xString.isValid();
-}
-
-QDeclarativeScriptString QQuickParentChange::y() const
-{
- Q_D(const QQuickParentChange);
- return d->yString.value;
-}
-
-void QQuickParentChange::setY(QDeclarativeScriptString y)
-{
- Q_D(QQuickParentChange);
- d->yString = y;
-}
-
-bool QQuickParentChange::yIsSet() const
-{
- Q_D(const QQuickParentChange);
- return d->yString.isValid();
-}
-
-QDeclarativeScriptString QQuickParentChange::width() const
-{
- Q_D(const QQuickParentChange);
- return d->widthString.value;
-}
-
-void QQuickParentChange::setWidth(QDeclarativeScriptString width)
-{
- Q_D(QQuickParentChange);
- d->widthString = width;
-}
-
-bool QQuickParentChange::widthIsSet() const
-{
- Q_D(const QQuickParentChange);
- return d->widthString.isValid();
-}
-
-QDeclarativeScriptString QQuickParentChange::height() const
-{
- Q_D(const QQuickParentChange);
- return d->heightString.value;
-}
-
-void QQuickParentChange::setHeight(QDeclarativeScriptString height)
-{
- Q_D(QQuickParentChange);
- d->heightString = height;
-}
-
-bool QQuickParentChange::heightIsSet() const
-{
- Q_D(const QQuickParentChange);
- return d->heightString.isValid();
-}
-
-QDeclarativeScriptString QQuickParentChange::scale() const
-{
- Q_D(const QQuickParentChange);
- return d->scaleString.value;
-}
-
-void QQuickParentChange::setScale(QDeclarativeScriptString scale)
-{
- Q_D(QQuickParentChange);
- d->scaleString = scale;
-}
-
-bool QQuickParentChange::scaleIsSet() const
-{
- Q_D(const QQuickParentChange);
- return d->scaleString.isValid();
-}
-
-QDeclarativeScriptString QQuickParentChange::rotation() const
-{
- Q_D(const QQuickParentChange);
- return d->rotationString.value;
-}
-
-void QQuickParentChange::setRotation(QDeclarativeScriptString rotation)
-{
- Q_D(QQuickParentChange);
- d->rotationString = rotation;
-}
-
-bool QQuickParentChange::rotationIsSet() const
-{
- Q_D(const QQuickParentChange);
- return d->rotationString.isValid();
-}
-
-QQuickItem *QQuickParentChange::originalParent() const
-{
- Q_D(const QQuickParentChange);
- return d->origParent;
-}
-
-QQuickItem *QQuickParentChange::object() const
-{
- Q_D(const QQuickParentChange);
- return d->target;
-}
-
-void QQuickParentChange::setObject(QQuickItem *target)
-{
- Q_D(QQuickParentChange);
- d->target = target;
-}
-
-QQuickItem *QQuickParentChange::parent() const
-{
- Q_D(const QQuickParentChange);
- return d->parent;
-}
-
-void QQuickParentChange::setParent(QQuickItem *parent)
-{
- Q_D(QQuickParentChange);
- d->parent = parent;
-}
-
-QDeclarativeStateOperation::ActionList QQuickParentChange::actions()
-{
- Q_D(QQuickParentChange);
- if (!d->target || !d->parent)
- return ActionList();
-
- ActionList actions;
-
- QDeclarativeAction a;
- a.event = this;
- actions << a;
-
- if (d->xString.isValid()) {
- bool ok = false;
- QString script = d->xString.value.script();
- qreal x = script.toFloat(&ok);
- if (ok) {
- QDeclarativeAction xa(d->target, QLatin1String("x"), x);
- actions << xa;
- } else {
- QDeclarativeBinding *newBinding = new QDeclarativeBinding(script, d->target, qmlContext(this));
- newBinding->setTarget(QDeclarativeProperty(d->target, QLatin1String("x")));
- QDeclarativeAction xa;
- xa.property = newBinding->property();
- xa.toBinding = newBinding;
- xa.fromValue = xa.property.read();
- xa.deletableToBinding = true;
- actions << xa;
- }
- }
-
- if (d->yString.isValid()) {
- bool ok = false;
- QString script = d->yString.value.script();
- qreal y = script.toFloat(&ok);
- if (ok) {
- QDeclarativeAction ya(d->target, QLatin1String("y"), y);
- actions << ya;
- } else {
- QDeclarativeBinding *newBinding = new QDeclarativeBinding(script, d->target, qmlContext(this));
- newBinding->setTarget(QDeclarativeProperty(d->target, QLatin1String("y")));
- QDeclarativeAction ya;
- ya.property = newBinding->property();
- ya.toBinding = newBinding;
- ya.fromValue = ya.property.read();
- ya.deletableToBinding = true;
- actions << ya;
- }
- }
-
- if (d->scaleString.isValid()) {
- bool ok = false;
- QString script = d->scaleString.value.script();
- qreal scale = script.toFloat(&ok);
- if (ok) {
- QDeclarativeAction sa(d->target, QLatin1String("scale"), scale);
- actions << sa;
- } else {
- QDeclarativeBinding *newBinding = new QDeclarativeBinding(script, d->target, qmlContext(this));
- newBinding->setTarget(QDeclarativeProperty(d->target, QLatin1String("scale")));
- QDeclarativeAction sa;
- sa.property = newBinding->property();
- sa.toBinding = newBinding;
- sa.fromValue = sa.property.read();
- sa.deletableToBinding = true;
- actions << sa;
- }
- }
-
- if (d->rotationString.isValid()) {
- bool ok = false;
- QString script = d->rotationString.value.script();
- qreal rotation = script.toFloat(&ok);
- if (ok) {
- QDeclarativeAction ra(d->target, QLatin1String("rotation"), rotation);
- actions << ra;
- } else {
- QDeclarativeBinding *newBinding = new QDeclarativeBinding(script, d->target, qmlContext(this));
- newBinding->setTarget(QDeclarativeProperty(d->target, QLatin1String("rotation")));
- QDeclarativeAction ra;
- ra.property = newBinding->property();
- ra.toBinding = newBinding;
- ra.fromValue = ra.property.read();
- ra.deletableToBinding = true;
- actions << ra;
- }
- }
-
- if (d->widthString.isValid()) {
- bool ok = false;
- QString script = d->widthString.value.script();
- qreal width = script.toFloat(&ok);
- if (ok) {
- QDeclarativeAction wa(d->target, QLatin1String("width"), width);
- actions << wa;
- } else {
- QDeclarativeBinding *newBinding = new QDeclarativeBinding(script, d->target, qmlContext(this));
- newBinding->setTarget(QDeclarativeProperty(d->target, QLatin1String("width")));
- QDeclarativeAction wa;
- wa.property = newBinding->property();
- wa.toBinding = newBinding;
- wa.fromValue = wa.property.read();
- wa.deletableToBinding = true;
- actions << wa;
- }
- }
-
- if (d->heightString.isValid()) {
- bool ok = false;
- QString script = d->heightString.value.script();
- qreal height = script.toFloat(&ok);
- if (ok) {
- QDeclarativeAction ha(d->target, QLatin1String("height"), height);
- actions << ha;
- } else {
- QDeclarativeBinding *newBinding = new QDeclarativeBinding(script, d->target, qmlContext(this));
- newBinding->setTarget(QDeclarativeProperty(d->target, QLatin1String("height")));
- QDeclarativeAction ha;
- ha.property = newBinding->property();
- ha.toBinding = newBinding;
- ha.fromValue = ha.property.read();
- ha.deletableToBinding = true;
- actions << ha;
- }
- }
-
- return actions;
-}
-
-void QQuickParentChange::saveOriginals()
-{
- Q_D(QQuickParentChange);
- saveCurrentValues();
- d->origParent = d->rewindParent;
- d->origStackBefore = d->rewindStackBefore;
-}
-
-/*void QQuickParentChange::copyOriginals(QDeclarativeActionEvent *other)
-{
- Q_D(QQuickParentChange);
- QQuickParentChange *pc = static_cast<QQuickParentChange*>(other);
-
- d->origParent = pc->d_func()->rewindParent;
- d->origStackBefore = pc->d_func()->rewindStackBefore;
-
- saveCurrentValues();
-}*/
-
-void QQuickParentChange::execute(Reason)
-{
- Q_D(QQuickParentChange);
- d->doChange(d->parent);
-}
-
-bool QQuickParentChange::isReversable()
-{
- return true;
-}
-
-void QQuickParentChange::reverse(Reason)
-{
- Q_D(QQuickParentChange);
- d->doChange(d->origParent, d->origStackBefore);
-}
-
-QString QQuickParentChange::typeName() const
-{
- return QLatin1String("ParentChange");
-}
-
-bool QQuickParentChange::override(QDeclarativeActionEvent*other)
-{
- Q_D(QQuickParentChange);
- if (other->typeName() != QLatin1String("ParentChange"))
- return false;
- if (QQuickParentChange *otherPC = static_cast<QQuickParentChange*>(other))
- return (d->target == otherPC->object());
- return false;
-}
-
-void QQuickParentChange::saveCurrentValues()
-{
- Q_D(QQuickParentChange);
- if (!d->target) {
- d->rewindParent = 0;
- d->rewindStackBefore = 0;
- return;
- }
-
- d->rewindParent = d->target->parentItem();
- d->rewindStackBefore = 0;
-
- if (!d->rewindParent)
- return;
-
- QList<QQuickItem *> children = d->rewindParent->childItems();
- for (int ii = 0; ii < children.count() - 1; ++ii) {
- if (children.at(ii) == d->target) {
- d->rewindStackBefore = children.at(ii + 1);
- break;
- }
- }
-}
-
-void QQuickParentChange::rewind()
-{
- Q_D(QQuickParentChange);
- d->doChange(d->rewindParent, d->rewindStackBefore);
-}
-
-class QQuickAnchorSetPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QQuickAnchorSet)
-public:
- QQuickAnchorSetPrivate()
- : usedAnchors(0), resetAnchors(0), fill(0),
- centerIn(0)/*, leftMargin(0), rightMargin(0), topMargin(0), bottomMargin(0),
- margins(0), vCenterOffset(0), hCenterOffset(0), baselineOffset(0)*/
- {
- }
-
- QQuickAnchors::Anchors usedAnchors;
- QQuickAnchors::Anchors resetAnchors;
-
- QQuickItem *fill;
- QQuickItem *centerIn;
-
- QDeclarativeScriptString leftScript;
- QDeclarativeScriptString rightScript;
- QDeclarativeScriptString topScript;
- QDeclarativeScriptString bottomScript;
- QDeclarativeScriptString hCenterScript;
- QDeclarativeScriptString vCenterScript;
- QDeclarativeScriptString baselineScript;
-
- /*qreal leftMargin;
- qreal rightMargin;
- qreal topMargin;
- qreal bottomMargin;
- qreal margins;
- qreal vCenterOffset;
- qreal hCenterOffset;
- qreal baselineOffset;*/
-};
-
-QQuickAnchorSet::QQuickAnchorSet(QObject *parent)
- : QObject(*new QQuickAnchorSetPrivate, parent)
-{
-}
-
-QQuickAnchorSet::~QQuickAnchorSet()
-{
-}
-
-QDeclarativeScriptString QQuickAnchorSet::top() const
-{
- Q_D(const QQuickAnchorSet);
- return d->topScript;
-}
-
-void QQuickAnchorSet::setTop(const QDeclarativeScriptString &edge)
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors |= QQuickAnchors::TopAnchor;
- d->topScript = edge;
- if (edge.script() == QLatin1String("undefined"))
- resetTop();
-}
-
-void QQuickAnchorSet::resetTop()
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors &= ~QQuickAnchors::TopAnchor;
- d->topScript = QDeclarativeScriptString();
- d->resetAnchors |= QQuickAnchors::TopAnchor;
-}
-
-QDeclarativeScriptString QQuickAnchorSet::bottom() const
-{
- Q_D(const QQuickAnchorSet);
- return d->bottomScript;
-}
-
-void QQuickAnchorSet::setBottom(const QDeclarativeScriptString &edge)
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors |= QQuickAnchors::BottomAnchor;
- d->bottomScript = edge;
- if (edge.script() == QLatin1String("undefined"))
- resetBottom();
-}
-
-void QQuickAnchorSet::resetBottom()
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors &= ~QQuickAnchors::BottomAnchor;
- d->bottomScript = QDeclarativeScriptString();
- d->resetAnchors |= QQuickAnchors::BottomAnchor;
-}
-
-QDeclarativeScriptString QQuickAnchorSet::verticalCenter() const
-{
- Q_D(const QQuickAnchorSet);
- return d->vCenterScript;
-}
-
-void QQuickAnchorSet::setVerticalCenter(const QDeclarativeScriptString &edge)
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors |= QQuickAnchors::VCenterAnchor;
- d->vCenterScript = edge;
- if (edge.script() == QLatin1String("undefined"))
- resetVerticalCenter();
-}
-
-void QQuickAnchorSet::resetVerticalCenter()
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors &= ~QQuickAnchors::VCenterAnchor;
- d->vCenterScript = QDeclarativeScriptString();
- d->resetAnchors |= QQuickAnchors::VCenterAnchor;
-}
-
-QDeclarativeScriptString QQuickAnchorSet::baseline() const
-{
- Q_D(const QQuickAnchorSet);
- return d->baselineScript;
-}
-
-void QQuickAnchorSet::setBaseline(const QDeclarativeScriptString &edge)
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors |= QQuickAnchors::BaselineAnchor;
- d->baselineScript = edge;
- if (edge.script() == QLatin1String("undefined"))
- resetBaseline();
-}
-
-void QQuickAnchorSet::resetBaseline()
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors &= ~QQuickAnchors::BaselineAnchor;
- d->baselineScript = QDeclarativeScriptString();
- d->resetAnchors |= QQuickAnchors::BaselineAnchor;
-}
-
-QDeclarativeScriptString QQuickAnchorSet::left() const
-{
- Q_D(const QQuickAnchorSet);
- return d->leftScript;
-}
-
-void QQuickAnchorSet::setLeft(const QDeclarativeScriptString &edge)
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors |= QQuickAnchors::LeftAnchor;
- d->leftScript = edge;
- if (edge.script() == QLatin1String("undefined"))
- resetLeft();
-}
-
-void QQuickAnchorSet::resetLeft()
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors &= ~QQuickAnchors::LeftAnchor;
- d->leftScript = QDeclarativeScriptString();
- d->resetAnchors |= QQuickAnchors::LeftAnchor;
-}
-
-QDeclarativeScriptString QQuickAnchorSet::right() const
-{
- Q_D(const QQuickAnchorSet);
- return d->rightScript;
-}
-
-void QQuickAnchorSet::setRight(const QDeclarativeScriptString &edge)
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors |= QQuickAnchors::RightAnchor;
- d->rightScript = edge;
- if (edge.script() == QLatin1String("undefined"))
- resetRight();
-}
-
-void QQuickAnchorSet::resetRight()
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors &= ~QQuickAnchors::RightAnchor;
- d->rightScript = QDeclarativeScriptString();
- d->resetAnchors |= QQuickAnchors::RightAnchor;
-}
-
-QDeclarativeScriptString QQuickAnchorSet::horizontalCenter() const
-{
- Q_D(const QQuickAnchorSet);
- return d->hCenterScript;
-}
-
-void QQuickAnchorSet::setHorizontalCenter(const QDeclarativeScriptString &edge)
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors |= QQuickAnchors::HCenterAnchor;
- d->hCenterScript = edge;
- if (edge.script() == QLatin1String("undefined"))
- resetHorizontalCenter();
-}
-
-void QQuickAnchorSet::resetHorizontalCenter()
-{
- Q_D(QQuickAnchorSet);
- d->usedAnchors &= ~QQuickAnchors::HCenterAnchor;
- d->hCenterScript = QDeclarativeScriptString();
- d->resetAnchors |= QQuickAnchors::HCenterAnchor;
-}
-
-QQuickItem *QQuickAnchorSet::fill() const
-{
- Q_D(const QQuickAnchorSet);
- return d->fill;
-}
-
-void QQuickAnchorSet::setFill(QQuickItem *f)
-{
- Q_D(QQuickAnchorSet);
- d->fill = f;
-}
-
-void QQuickAnchorSet::resetFill()
-{
- setFill(0);
-}
-
-QQuickItem *QQuickAnchorSet::centerIn() const
-{
- Q_D(const QQuickAnchorSet);
- return d->centerIn;
-}
-
-void QQuickAnchorSet::setCenterIn(QQuickItem* c)
-{
- Q_D(QQuickAnchorSet);
- d->centerIn = c;
-}
-
-void QQuickAnchorSet::resetCenterIn()
-{
- setCenterIn(0);
-}
-
-
-class QQuickAnchorChangesPrivate : public QDeclarativeStateOperationPrivate
-{
-public:
- QQuickAnchorChangesPrivate()
- : target(0), anchorSet(new QQuickAnchorSet),
- leftBinding(0), rightBinding(0), hCenterBinding(0),
- topBinding(0), bottomBinding(0), vCenterBinding(0), baselineBinding(0),
- origLeftBinding(0), origRightBinding(0), origHCenterBinding(0),
- origTopBinding(0), origBottomBinding(0), origVCenterBinding(0),
- origBaselineBinding(0)
- {
-
- }
- ~QQuickAnchorChangesPrivate() { delete anchorSet; }
-
- QQuickItem *target;
- QQuickAnchorSet *anchorSet;
-
- QDeclarativeBinding *leftBinding;
- QDeclarativeBinding *rightBinding;
- QDeclarativeBinding *hCenterBinding;
- QDeclarativeBinding *topBinding;
- QDeclarativeBinding *bottomBinding;
- QDeclarativeBinding *vCenterBinding;
- QDeclarativeBinding *baselineBinding;
-
- QDeclarativeAbstractBinding *origLeftBinding;
- QDeclarativeAbstractBinding *origRightBinding;
- QDeclarativeAbstractBinding *origHCenterBinding;
- QDeclarativeAbstractBinding *origTopBinding;
- QDeclarativeAbstractBinding *origBottomBinding;
- QDeclarativeAbstractBinding *origVCenterBinding;
- QDeclarativeAbstractBinding *origBaselineBinding;
-
- QQuickAnchorLine rewindLeft;
- QQuickAnchorLine rewindRight;
- QQuickAnchorLine rewindHCenter;
- QQuickAnchorLine rewindTop;
- QQuickAnchorLine rewindBottom;
- QQuickAnchorLine rewindVCenter;
- QQuickAnchorLine rewindBaseline;
-
- qreal fromX;
- qreal fromY;
- qreal fromWidth;
- qreal fromHeight;
-
- qreal toX;
- qreal toY;
- qreal toWidth;
- qreal toHeight;
-
- qreal rewindX;
- qreal rewindY;
- qreal rewindWidth;
- qreal rewindHeight;
-
- bool applyOrigLeft;
- bool applyOrigRight;
- bool applyOrigHCenter;
- bool applyOrigTop;
- bool applyOrigBottom;
- bool applyOrigVCenter;
- bool applyOrigBaseline;
-
- QDeclarativeNullableValue<qreal> origWidth;
- QDeclarativeNullableValue<qreal> origHeight;
- qreal origX;
- qreal origY;
-
- QList<QDeclarativeAbstractBinding*> oldBindings;
-
- QDeclarativeProperty leftProp;
- QDeclarativeProperty rightProp;
- QDeclarativeProperty hCenterProp;
- QDeclarativeProperty topProp;
- QDeclarativeProperty bottomProp;
- QDeclarativeProperty vCenterProp;
- QDeclarativeProperty baselineProp;
-};
-
-QQuickAnchorChanges::QQuickAnchorChanges(QObject *parent)
- : QDeclarativeStateOperation(*(new QQuickAnchorChangesPrivate), parent)
-{
-}
-
-QQuickAnchorChanges::~QQuickAnchorChanges()
-{
-}
-
-QQuickAnchorChanges::ActionList QQuickAnchorChanges::actions()
-{
- Q_D(QQuickAnchorChanges);
- d->leftBinding = d->rightBinding = d->hCenterBinding = d->topBinding
- = d->bottomBinding = d->vCenterBinding = d->baselineBinding = 0;
-
- d->leftProp = QDeclarativeProperty(d->target, QLatin1String("anchors.left"));
- d->rightProp = QDeclarativeProperty(d->target, QLatin1String("anchors.right"));
- d->hCenterProp = QDeclarativeProperty(d->target, QLatin1String("anchors.horizontalCenter"));
- d->topProp = QDeclarativeProperty(d->target, QLatin1String("anchors.top"));
- d->bottomProp = QDeclarativeProperty(d->target, QLatin1String("anchors.bottom"));
- d->vCenterProp = QDeclarativeProperty(d->target, QLatin1String("anchors.verticalCenter"));
- d->baselineProp = QDeclarativeProperty(d->target, QLatin1String("anchors.baseline"));
-
- if (d->anchorSet->d_func()->usedAnchors & QQuickAnchors::LeftAnchor) {
- d->leftBinding = new QDeclarativeBinding(d->anchorSet->d_func()->leftScript.script(), d->target, qmlContext(this));
- d->leftBinding->setTarget(d->leftProp);
- }
- if (d->anchorSet->d_func()->usedAnchors & QQuickAnchors::RightAnchor) {
- d->rightBinding = new QDeclarativeBinding(d->anchorSet->d_func()->rightScript.script(), d->target, qmlContext(this));
- d->rightBinding->setTarget(d->rightProp);
- }
- if (d->anchorSet->d_func()->usedAnchors & QQuickAnchors::HCenterAnchor) {
- d->hCenterBinding = new QDeclarativeBinding(d->anchorSet->d_func()->hCenterScript.script(), d->target, qmlContext(this));
- d->hCenterBinding->setTarget(d->hCenterProp);
- }
- if (d->anchorSet->d_func()->usedAnchors & QQuickAnchors::TopAnchor) {
- d->topBinding = new QDeclarativeBinding(d->anchorSet->d_func()->topScript.script(), d->target, qmlContext(this));
- d->topBinding->setTarget(d->topProp);
- }
- if (d->anchorSet->d_func()->usedAnchors & QQuickAnchors::BottomAnchor) {
- d->bottomBinding = new QDeclarativeBinding(d->anchorSet->d_func()->bottomScript.script(), d->target, qmlContext(this));
- d->bottomBinding->setTarget(d->bottomProp);
- }
- if (d->anchorSet->d_func()->usedAnchors & QQuickAnchors::VCenterAnchor) {
- d->vCenterBinding = new QDeclarativeBinding(d->anchorSet->d_func()->vCenterScript.script(), d->target, qmlContext(this));
- d->vCenterBinding->setTarget(d->vCenterProp);
- }
- if (d->anchorSet->d_func()->usedAnchors & QQuickAnchors::BaselineAnchor) {
- d->baselineBinding = new QDeclarativeBinding(d->anchorSet->d_func()->baselineScript.script(), d->target, qmlContext(this));
- d->baselineBinding->setTarget(d->baselineProp);
- }
-
- QDeclarativeAction a;
- a.event = this;
- return ActionList() << a;
-}
-
-QQuickAnchorSet *QQuickAnchorChanges::anchors()
-{
- Q_D(QQuickAnchorChanges);
- return d->anchorSet;
-}
-
-QQuickItem *QQuickAnchorChanges::object() const
-{
- Q_D(const QQuickAnchorChanges);
- return d->target;
-}
-
-void QQuickAnchorChanges::setObject(QQuickItem *target)
-{
- Q_D(QQuickAnchorChanges);
- d->target = target;
-}
-
-void QQuickAnchorChanges::execute(Reason reason)
-{
- Q_D(QQuickAnchorChanges);
- if (!d->target)
- return;
-
- QQuickItemPrivate *targetPrivate = QQuickItemPrivate::get(d->target);
- //incorporate any needed "reverts"
- if (d->applyOrigLeft) {
- if (!d->origLeftBinding)
- targetPrivate->anchors()->resetLeft();
- QDeclarativePropertyPrivate::setBinding(d->leftProp, d->origLeftBinding);
- }
- if (d->applyOrigRight) {
- if (!d->origRightBinding)
- targetPrivate->anchors()->resetRight();
- QDeclarativePropertyPrivate::setBinding(d->rightProp, d->origRightBinding);
- }
- if (d->applyOrigHCenter) {
- if (!d->origHCenterBinding)
- targetPrivate->anchors()->resetHorizontalCenter();
- QDeclarativePropertyPrivate::setBinding(d->hCenterProp, d->origHCenterBinding);
- }
- if (d->applyOrigTop) {
- if (!d->origTopBinding)
- targetPrivate->anchors()->resetTop();
- QDeclarativePropertyPrivate::setBinding(d->topProp, d->origTopBinding);
- }
- if (d->applyOrigBottom) {
- if (!d->origBottomBinding)
- targetPrivate->anchors()->resetBottom();
- QDeclarativePropertyPrivate::setBinding(d->bottomProp, d->origBottomBinding);
- }
- if (d->applyOrigVCenter) {
- if (!d->origVCenterBinding)
- targetPrivate->anchors()->resetVerticalCenter();
- QDeclarativePropertyPrivate::setBinding(d->vCenterProp, d->origVCenterBinding);
- }
- if (d->applyOrigBaseline) {
- if (!d->origBaselineBinding)
- targetPrivate->anchors()->resetBaseline();
- QDeclarativePropertyPrivate::setBinding(d->baselineProp, d->origBaselineBinding);
- }
-
- //destroy old bindings
- if (reason == ActualChange) {
- for (int i = 0; i < d->oldBindings.size(); ++i) {
- QDeclarativeAbstractBinding *binding = d->oldBindings.at(i);
- if (binding)
- binding->destroy();
- }
- d->oldBindings.clear();
- }
-
- //reset any anchors that have been specified as "undefined"
- if (d->anchorSet->d_func()->resetAnchors & QQuickAnchors::LeftAnchor) {
- targetPrivate->anchors()->resetLeft();
- QDeclarativePropertyPrivate::setBinding(d->leftProp, 0);
- }
- if (d->anchorSet->d_func()->resetAnchors & QQuickAnchors::RightAnchor) {
- targetPrivate->anchors()->resetRight();
- QDeclarativePropertyPrivate::setBinding(d->rightProp, 0);
- }
- if (d->anchorSet->d_func()->resetAnchors & QQuickAnchors::HCenterAnchor) {
- targetPrivate->anchors()->resetHorizontalCenter();
- QDeclarativePropertyPrivate::setBinding(d->hCenterProp, 0);
- }
- if (d->anchorSet->d_func()->resetAnchors & QQuickAnchors::TopAnchor) {
- targetPrivate->anchors()->resetTop();
- QDeclarativePropertyPrivate::setBinding(d->topProp, 0);
- }
- if (d->anchorSet->d_func()->resetAnchors & QQuickAnchors::BottomAnchor) {
- targetPrivate->anchors()->resetBottom();
- QDeclarativePropertyPrivate::setBinding(d->bottomProp, 0);
- }
- if (d->anchorSet->d_func()->resetAnchors & QQuickAnchors::VCenterAnchor) {
- targetPrivate->anchors()->resetVerticalCenter();
- QDeclarativePropertyPrivate::setBinding(d->vCenterProp, 0);
- }
- if (d->anchorSet->d_func()->resetAnchors & QQuickAnchors::BaselineAnchor) {
- targetPrivate->anchors()->resetBaseline();
- QDeclarativePropertyPrivate::setBinding(d->baselineProp, 0);
- }
-
- //set any anchors that have been specified
- if (d->leftBinding)
- QDeclarativePropertyPrivate::setBinding(d->leftBinding->property(), d->leftBinding);
- if (d->rightBinding)
- QDeclarativePropertyPrivate::setBinding(d->rightBinding->property(), d->rightBinding);
- if (d->hCenterBinding)
- QDeclarativePropertyPrivate::setBinding(d->hCenterBinding->property(), d->hCenterBinding);
- if (d->topBinding)
- QDeclarativePropertyPrivate::setBinding(d->topBinding->property(), d->topBinding);
- if (d->bottomBinding)
- QDeclarativePropertyPrivate::setBinding(d->bottomBinding->property(), d->bottomBinding);
- if (d->vCenterBinding)
- QDeclarativePropertyPrivate::setBinding(d->vCenterBinding->property(), d->vCenterBinding);
- if (d->baselineBinding)
- QDeclarativePropertyPrivate::setBinding(d->baselineBinding->property(), d->baselineBinding);
-}
-
-bool QQuickAnchorChanges::isReversable()
-{
- return true;
-}
-
-void QQuickAnchorChanges::reverse(Reason reason)
-{
- Q_D(QQuickAnchorChanges);
- if (!d->target)
- return;
-
- QQuickItemPrivate *targetPrivate = QQuickItemPrivate::get(d->target);
- //reset any anchors set by the state
- if (d->leftBinding) {
- targetPrivate->anchors()->resetLeft();
- QDeclarativePropertyPrivate::setBinding(d->leftBinding->property(), 0);
- if (reason == ActualChange) {
- d->leftBinding->destroy(); d->leftBinding = 0;
- }
- }
- if (d->rightBinding) {
- targetPrivate->anchors()->resetRight();
- QDeclarativePropertyPrivate::setBinding(d->rightBinding->property(), 0);
- if (reason == ActualChange) {
- d->rightBinding->destroy(); d->rightBinding = 0;
- }
- }
- if (d->hCenterBinding) {
- targetPrivate->anchors()->resetHorizontalCenter();
- QDeclarativePropertyPrivate::setBinding(d->hCenterBinding->property(), 0);
- if (reason == ActualChange) {
- d->hCenterBinding->destroy(); d->hCenterBinding = 0;
- }
- }
- if (d->topBinding) {
- targetPrivate->anchors()->resetTop();
- QDeclarativePropertyPrivate::setBinding(d->topBinding->property(), 0);
- if (reason == ActualChange) {
- d->topBinding->destroy(); d->topBinding = 0;
- }
- }
- if (d->bottomBinding) {
- targetPrivate->anchors()->resetBottom();
- QDeclarativePropertyPrivate::setBinding(d->bottomBinding->property(), 0);
- if (reason == ActualChange) {
- d->bottomBinding->destroy(); d->bottomBinding = 0;
- }
- }
- if (d->vCenterBinding) {
- targetPrivate->anchors()->resetVerticalCenter();
- QDeclarativePropertyPrivate::setBinding(d->vCenterBinding->property(), 0);
- if (reason == ActualChange) {
- d->vCenterBinding->destroy(); d->vCenterBinding = 0;
- }
- }
- if (d->baselineBinding) {
- targetPrivate->anchors()->resetBaseline();
- QDeclarativePropertyPrivate::setBinding(d->baselineBinding->property(), 0);
- if (reason == ActualChange) {
- d->baselineBinding->destroy(); d->baselineBinding = 0;
- }
- }
-
- //restore previous anchors
- if (d->origLeftBinding)
- QDeclarativePropertyPrivate::setBinding(d->leftProp, d->origLeftBinding);
- if (d->origRightBinding)
- QDeclarativePropertyPrivate::setBinding(d->rightProp, d->origRightBinding);
- if (d->origHCenterBinding)
- QDeclarativePropertyPrivate::setBinding(d->hCenterProp, d->origHCenterBinding);
- if (d->origTopBinding)
- QDeclarativePropertyPrivate::setBinding(d->topProp, d->origTopBinding);
- if (d->origBottomBinding)
- QDeclarativePropertyPrivate::setBinding(d->bottomProp, d->origBottomBinding);
- if (d->origVCenterBinding)
- QDeclarativePropertyPrivate::setBinding(d->vCenterProp, d->origVCenterBinding);
- if (d->origBaselineBinding)
- QDeclarativePropertyPrivate::setBinding(d->baselineProp, d->origBaselineBinding);
-
- //restore any absolute geometry changed by the state's anchors
- QQuickAnchors::Anchors stateVAnchors = d->anchorSet->d_func()->usedAnchors & QQuickAnchors::Vertical_Mask;
- QQuickAnchors::Anchors origVAnchors = targetPrivate->anchors()->usedAnchors() & QQuickAnchors::Vertical_Mask;
- QQuickAnchors::Anchors stateHAnchors = d->anchorSet->d_func()->usedAnchors & QQuickAnchors::Horizontal_Mask;
- QQuickAnchors::Anchors origHAnchors = targetPrivate->anchors()->usedAnchors() & QQuickAnchors::Horizontal_Mask;
-
- bool stateSetWidth = (stateHAnchors &&
- stateHAnchors != QQuickAnchors::LeftAnchor &&
- stateHAnchors != QQuickAnchors::RightAnchor &&
- stateHAnchors != QQuickAnchors::HCenterAnchor);
- bool origSetWidth = (origHAnchors &&
- origHAnchors != QQuickAnchors::LeftAnchor &&
- origHAnchors != QQuickAnchors::RightAnchor &&
- origHAnchors != QQuickAnchors::HCenterAnchor);
- if (d->origWidth.isValid() && stateSetWidth && !origSetWidth)
- d->target->setWidth(d->origWidth.value);
-
- bool stateSetHeight = (stateVAnchors &&
- stateVAnchors != QQuickAnchors::TopAnchor &&
- stateVAnchors != QQuickAnchors::BottomAnchor &&
- stateVAnchors != QQuickAnchors::VCenterAnchor &&
- stateVAnchors != QQuickAnchors::BaselineAnchor);
- bool origSetHeight = (origVAnchors &&
- origVAnchors != QQuickAnchors::TopAnchor &&
- origVAnchors != QQuickAnchors::BottomAnchor &&
- origVAnchors != QQuickAnchors::VCenterAnchor &&
- origVAnchors != QQuickAnchors::BaselineAnchor);
- if (d->origHeight.isValid() && stateSetHeight && !origSetHeight)
- d->target->setHeight(d->origHeight.value);
-
- if (stateHAnchors && !origHAnchors)
- d->target->setX(d->origX);
-
- if (stateVAnchors && !origVAnchors)
- d->target->setY(d->origY);
-}
-
-QString QQuickAnchorChanges::typeName() const
-{
- return QLatin1String("AnchorChanges");
-}
-
-QList<QDeclarativeAction> QQuickAnchorChanges::additionalActions()
-{
- Q_D(QQuickAnchorChanges);
- QList<QDeclarativeAction> extra;
-
- QQuickAnchors::Anchors combined = d->anchorSet->d_func()->usedAnchors | d->anchorSet->d_func()->resetAnchors;
- bool hChange = combined & QQuickAnchors::Horizontal_Mask;
- bool vChange = combined & QQuickAnchors::Vertical_Mask;
-
- if (d->target) {
- QDeclarativeAction a;
- if (hChange && d->fromX != d->toX) {
- a.property = QDeclarativeProperty(d->target, QLatin1String("x"));
- a.toValue = d->toX;
- extra << a;
- }
- if (vChange && d->fromY != d->toY) {
- a.property = QDeclarativeProperty(d->target, QLatin1String("y"));
- a.toValue = d->toY;
- extra << a;
- }
- if (hChange && d->fromWidth != d->toWidth) {
- a.property = QDeclarativeProperty(d->target, QLatin1String("width"));
- a.toValue = d->toWidth;
- extra << a;
- }
- if (vChange && d->fromHeight != d->toHeight) {
- a.property = QDeclarativeProperty(d->target, QLatin1String("height"));
- a.toValue = d->toHeight;
- extra << a;
- }
- }
-
- return extra;
-}
-
-bool QQuickAnchorChanges::changesBindings()
-{
- return true;
-}
-
-void QQuickAnchorChanges::saveOriginals()
-{
- Q_D(QQuickAnchorChanges);
- if (!d->target)
- return;
-
- d->origLeftBinding = QDeclarativePropertyPrivate::binding(d->leftProp);
- d->origRightBinding = QDeclarativePropertyPrivate::binding(d->rightProp);
- d->origHCenterBinding = QDeclarativePropertyPrivate::binding(d->hCenterProp);
- d->origTopBinding = QDeclarativePropertyPrivate::binding(d->topProp);
- d->origBottomBinding = QDeclarativePropertyPrivate::binding(d->bottomProp);
- d->origVCenterBinding = QDeclarativePropertyPrivate::binding(d->vCenterProp);
- d->origBaselineBinding = QDeclarativePropertyPrivate::binding(d->baselineProp);
-
- QQuickItemPrivate *targetPrivate = QQuickItemPrivate::get(d->target);
- if (targetPrivate->widthValid)
- d->origWidth = d->target->width();
- if (targetPrivate->heightValid)
- d->origHeight = d->target->height();
- d->origX = d->target->x();
- d->origY = d->target->y();
-
- d->applyOrigLeft = d->applyOrigRight = d->applyOrigHCenter = d->applyOrigTop
- = d->applyOrigBottom = d->applyOrigVCenter = d->applyOrigBaseline = false;
-
- saveCurrentValues();
-}
-
-void QQuickAnchorChanges::copyOriginals(QDeclarativeActionEvent *other)
-{
- Q_D(QQuickAnchorChanges);
- QQuickAnchorChanges *ac = static_cast<QQuickAnchorChanges*>(other);
- QQuickAnchorChangesPrivate *acp = ac->d_func();
-
- QQuickAnchors::Anchors combined = acp->anchorSet->d_func()->usedAnchors |
- acp->anchorSet->d_func()->resetAnchors;
-
- //probably also need to revert some things
- d->applyOrigLeft = (combined & QQuickAnchors::LeftAnchor);
- d->applyOrigRight = (combined & QQuickAnchors::RightAnchor);
- d->applyOrigHCenter = (combined & QQuickAnchors::HCenterAnchor);
- d->applyOrigTop = (combined & QQuickAnchors::TopAnchor);
- d->applyOrigBottom = (combined & QQuickAnchors::BottomAnchor);
- d->applyOrigVCenter = (combined & QQuickAnchors::VCenterAnchor);
- d->applyOrigBaseline = (combined & QQuickAnchors::BaselineAnchor);
-
- d->origLeftBinding = acp->origLeftBinding;
- d->origRightBinding = acp->origRightBinding;
- d->origHCenterBinding = acp->origHCenterBinding;
- d->origTopBinding = acp->origTopBinding;
- d->origBottomBinding = acp->origBottomBinding;
- d->origVCenterBinding = acp->origVCenterBinding;
- d->origBaselineBinding = acp->origBaselineBinding;
-
- d->origWidth = acp->origWidth;
- d->origHeight = acp->origHeight;
- d->origX = acp->origX;
- d->origY = acp->origY;
-
- d->oldBindings.clear();
- d->oldBindings << acp->leftBinding << acp->rightBinding << acp->hCenterBinding
- << acp->topBinding << acp->bottomBinding << acp->baselineBinding;
-
- saveCurrentValues();
-}
-
-void QQuickAnchorChanges::clearBindings()
-{
- Q_D(QQuickAnchorChanges);
- if (!d->target)
- return;
-
- //### should this (saving "from" values) be moved to saveCurrentValues()?
- d->fromX = d->target->x();
- d->fromY = d->target->y();
- d->fromWidth = d->target->width();
- d->fromHeight = d->target->height();
-
- QQuickItemPrivate *targetPrivate = QQuickItemPrivate::get(d->target);
- //reset any anchors with corresponding reverts
- //reset any anchors that have been specified as "undefined"
- //reset any anchors that we'll be setting in the state
- QQuickAnchors::Anchors combined = d->anchorSet->d_func()->resetAnchors |
- d->anchorSet->d_func()->usedAnchors;
- if (d->applyOrigLeft || (combined & QQuickAnchors::LeftAnchor)) {
- targetPrivate->anchors()->resetLeft();
- QDeclarativePropertyPrivate::setBinding(d->leftProp, 0);
- }
- if (d->applyOrigRight || (combined & QQuickAnchors::RightAnchor)) {
- targetPrivate->anchors()->resetRight();
- QDeclarativePropertyPrivate::setBinding(d->rightProp, 0);
- }
- if (d->applyOrigHCenter || (combined & QQuickAnchors::HCenterAnchor)) {
- targetPrivate->anchors()->resetHorizontalCenter();
- QDeclarativePropertyPrivate::setBinding(d->hCenterProp, 0);
- }
- if (d->applyOrigTop || (combined & QQuickAnchors::TopAnchor)) {
- targetPrivate->anchors()->resetTop();
- QDeclarativePropertyPrivate::setBinding(d->topProp, 0);
- }
- if (d->applyOrigBottom || (combined & QQuickAnchors::BottomAnchor)) {
- targetPrivate->anchors()->resetBottom();
- QDeclarativePropertyPrivate::setBinding(d->bottomProp, 0);
- }
- if (d->applyOrigVCenter || (combined & QQuickAnchors::VCenterAnchor)) {
- targetPrivate->anchors()->resetVerticalCenter();
- QDeclarativePropertyPrivate::setBinding(d->vCenterProp, 0);
- }
- if (d->applyOrigBaseline || (combined & QQuickAnchors::BaselineAnchor)) {
- targetPrivate->anchors()->resetBaseline();
- QDeclarativePropertyPrivate::setBinding(d->baselineProp, 0);
- }
-}
-
-bool QQuickAnchorChanges::override(QDeclarativeActionEvent*other)
-{
- if (other->typeName() != QLatin1String("AnchorChanges"))
- return false;
- if (static_cast<QDeclarativeActionEvent*>(this) == other)
- return true;
- if (static_cast<QQuickAnchorChanges*>(other)->object() == object())
- return true;
- return false;
-}
-
-void QQuickAnchorChanges::rewind()
-{
- Q_D(QQuickAnchorChanges);
- if (!d->target)
- return;
-
- QQuickItemPrivate *targetPrivate = QQuickItemPrivate::get(d->target);
-
- //restore previous values (but not previous bindings, i.e. anchors)
- d->target->setX(d->rewindX);
- d->target->setY(d->rewindY);
- if (targetPrivate->widthValid) {
- d->target->setWidth(d->rewindWidth);
- }
- if (targetPrivate->heightValid) {
- d->target->setHeight(d->rewindHeight);
- }
-}
-
-void QQuickAnchorChanges::saveCurrentValues()
-{
- Q_D(QQuickAnchorChanges);
- if (!d->target)
- return;
-
- QQuickItemPrivate *targetPrivate = QQuickItemPrivate::get(d->target);
- d->rewindLeft = targetPrivate->anchors()->left();
- d->rewindRight = targetPrivate->anchors()->right();
- d->rewindHCenter = targetPrivate->anchors()->horizontalCenter();
- d->rewindTop = targetPrivate->anchors()->top();
- d->rewindBottom = targetPrivate->anchors()->bottom();
- d->rewindVCenter = targetPrivate->anchors()->verticalCenter();
- d->rewindBaseline = targetPrivate->anchors()->baseline();
-
- d->rewindX = d->target->x();
- d->rewindY = d->target->y();
- d->rewindWidth = d->target->width();
- d->rewindHeight = d->target->height();
-}
-
-void QQuickAnchorChanges::saveTargetValues()
-{
- Q_D(QQuickAnchorChanges);
- if (!d->target)
- return;
-
- d->toX = d->target->x();
- d->toY = d->target->y();
- d->toWidth = d->target->width();
- d->toHeight = d->target->height();
-}
-
-#include <moc_qquickstateoperations_p.cpp>
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/items/qquickstateoperations_p.h b/src/declarative/items/qquickstateoperations_p.h
deleted file mode 100644
index 7844c6d7dd..0000000000
--- a/src/declarative/items/qquickstateoperations_p.h
+++ /dev/null
@@ -1,275 +0,0 @@
-// Commit: 84c47bbb133304d7ef35642fa1fbb17619d4a43d
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKSTATEOPERATIONS_P_H
-#define QQUICKSTATEOPERATIONS_P_H
-
-#include "qquickitem.h"
-#include "qquickanchors_p.h"
-
-#include <private/qdeclarativestate_p.h>
-
-#include <QtDeclarative/qdeclarativescriptstring.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickParentChangePrivate;
-class Q_AUTOTEST_EXPORT QQuickParentChange : public QDeclarativeStateOperation, public QDeclarativeActionEvent
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickParentChange)
-
- Q_PROPERTY(QQuickItem *target READ object WRITE setObject)
- Q_PROPERTY(QQuickItem *parent READ parent WRITE setParent)
- Q_PROPERTY(QDeclarativeScriptString x READ x WRITE setX)
- Q_PROPERTY(QDeclarativeScriptString y READ y WRITE setY)
- Q_PROPERTY(QDeclarativeScriptString width READ width WRITE setWidth)
- Q_PROPERTY(QDeclarativeScriptString height READ height WRITE setHeight)
- Q_PROPERTY(QDeclarativeScriptString scale READ scale WRITE setScale)
- Q_PROPERTY(QDeclarativeScriptString rotation READ rotation WRITE setRotation)
-public:
- QQuickParentChange(QObject *parent=0);
- ~QQuickParentChange();
-
- QQuickItem *object() const;
- void setObject(QQuickItem *);
-
- QQuickItem *parent() const;
- void setParent(QQuickItem *);
-
- QQuickItem *originalParent() const;
-
- QDeclarativeScriptString x() const;
- void setX(QDeclarativeScriptString x);
- bool xIsSet() const;
-
- QDeclarativeScriptString y() const;
- void setY(QDeclarativeScriptString y);
- bool yIsSet() const;
-
- QDeclarativeScriptString width() const;
- void setWidth(QDeclarativeScriptString width);
- bool widthIsSet() const;
-
- QDeclarativeScriptString height() const;
- void setHeight(QDeclarativeScriptString height);
- bool heightIsSet() const;
-
- QDeclarativeScriptString scale() const;
- void setScale(QDeclarativeScriptString scale);
- bool scaleIsSet() const;
-
- QDeclarativeScriptString rotation() const;
- void setRotation(QDeclarativeScriptString rotation);
- bool rotationIsSet() const;
-
- virtual ActionList actions();
-
- virtual void saveOriginals();
- //virtual void copyOriginals(QDeclarativeActionEvent*);
- virtual void execute(Reason reason = ActualChange);
- virtual bool isReversable();
- virtual void reverse(Reason reason = ActualChange);
- virtual QString typeName() const;
- virtual bool override(QDeclarativeActionEvent*other);
- virtual void rewind();
- virtual void saveCurrentValues();
-};
-
-class QQuickAnchorChanges;
-class QQuickAnchorSetPrivate;
-class Q_AUTOTEST_EXPORT QQuickAnchorSet : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QDeclarativeScriptString left READ left WRITE setLeft RESET resetLeft)
- Q_PROPERTY(QDeclarativeScriptString right READ right WRITE setRight RESET resetRight)
- Q_PROPERTY(QDeclarativeScriptString horizontalCenter READ horizontalCenter WRITE setHorizontalCenter RESET resetHorizontalCenter)
- Q_PROPERTY(QDeclarativeScriptString top READ top WRITE setTop RESET resetTop)
- Q_PROPERTY(QDeclarativeScriptString bottom READ bottom WRITE setBottom RESET resetBottom)
- Q_PROPERTY(QDeclarativeScriptString verticalCenter READ verticalCenter WRITE setVerticalCenter RESET resetVerticalCenter)
- Q_PROPERTY(QDeclarativeScriptString baseline READ baseline WRITE setBaseline RESET resetBaseline)
- //Q_PROPERTY(QQuickItem *fill READ fill WRITE setFill RESET resetFill)
- //Q_PROPERTY(QQuickItem *centerIn READ centerIn WRITE setCenterIn RESET resetCenterIn)
-
- /*Q_PROPERTY(qreal margins READ margins WRITE setMargins NOTIFY marginsChanged)
- Q_PROPERTY(qreal leftMargin READ leftMargin WRITE setLeftMargin NOTIFY leftMarginChanged)
- Q_PROPERTY(qreal rightMargin READ rightMargin WRITE setRightMargin NOTIFY rightMarginChanged)
- Q_PROPERTY(qreal horizontalCenterOffset READ horizontalCenterOffset WRITE setHorizontalCenterOffset NOTIFY horizontalCenterOffsetChanged())
- Q_PROPERTY(qreal topMargin READ topMargin WRITE setTopMargin NOTIFY topMarginChanged)
- Q_PROPERTY(qreal bottomMargin READ bottomMargin WRITE setBottomMargin NOTIFY bottomMarginChanged)
- Q_PROPERTY(qreal verticalCenterOffset READ verticalCenterOffset WRITE setVerticalCenterOffset NOTIFY verticalCenterOffsetChanged())
- Q_PROPERTY(qreal baselineOffset READ baselineOffset WRITE setBaselineOffset NOTIFY baselineOffsetChanged())*/
-
-public:
- QQuickAnchorSet(QObject *parent=0);
- virtual ~QQuickAnchorSet();
-
- QDeclarativeScriptString left() const;
- void setLeft(const QDeclarativeScriptString &edge);
- void resetLeft();
-
- QDeclarativeScriptString right() const;
- void setRight(const QDeclarativeScriptString &edge);
- void resetRight();
-
- QDeclarativeScriptString horizontalCenter() const;
- void setHorizontalCenter(const QDeclarativeScriptString &edge);
- void resetHorizontalCenter();
-
- QDeclarativeScriptString top() const;
- void setTop(const QDeclarativeScriptString &edge);
- void resetTop();
-
- QDeclarativeScriptString bottom() const;
- void setBottom(const QDeclarativeScriptString &edge);
- void resetBottom();
-
- QDeclarativeScriptString verticalCenter() const;
- void setVerticalCenter(const QDeclarativeScriptString &edge);
- void resetVerticalCenter();
-
- QDeclarativeScriptString baseline() const;
- void setBaseline(const QDeclarativeScriptString &edge);
- void resetBaseline();
-
- QQuickItem *fill() const;
- void setFill(QQuickItem *);
- void resetFill();
-
- QQuickItem *centerIn() const;
- void setCenterIn(QQuickItem *);
- void resetCenterIn();
-
- /*qreal leftMargin() const;
- void setLeftMargin(qreal);
-
- qreal rightMargin() const;
- void setRightMargin(qreal);
-
- qreal horizontalCenterOffset() const;
- void setHorizontalCenterOffset(qreal);
-
- qreal topMargin() const;
- void setTopMargin(qreal);
-
- qreal bottomMargin() const;
- void setBottomMargin(qreal);
-
- qreal margins() const;
- void setMargins(qreal);
-
- qreal verticalCenterOffset() const;
- void setVerticalCenterOffset(qreal);
-
- qreal baselineOffset() const;
- void setBaselineOffset(qreal);*/
-
- QQuickAnchors::Anchors usedAnchors() const;
-
-/*Q_SIGNALS:
- void leftMarginChanged();
- void rightMarginChanged();
- void topMarginChanged();
- void bottomMarginChanged();
- void marginsChanged();
- void verticalCenterOffsetChanged();
- void horizontalCenterOffsetChanged();
- void baselineOffsetChanged();*/
-
-private:
- friend class QQuickAnchorChanges;
- Q_DISABLE_COPY(QQuickAnchorSet)
- Q_DECLARE_PRIVATE(QQuickAnchorSet)
-};
-
-class QQuickAnchorChangesPrivate;
-class Q_AUTOTEST_EXPORT QQuickAnchorChanges : public QDeclarativeStateOperation, public QDeclarativeActionEvent
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickAnchorChanges)
-
- Q_PROPERTY(QQuickItem *target READ object WRITE setObject)
- Q_PROPERTY(QQuickAnchorSet *anchors READ anchors CONSTANT)
-
-public:
- QQuickAnchorChanges(QObject *parent=0);
- ~QQuickAnchorChanges();
-
- virtual ActionList actions();
-
- QQuickAnchorSet *anchors();
-
- QQuickItem *object() const;
- void setObject(QQuickItem *);
-
- virtual void execute(Reason reason = ActualChange);
- virtual bool isReversable();
- virtual void reverse(Reason reason = ActualChange);
- virtual QString typeName() const;
- virtual bool override(QDeclarativeActionEvent*other);
- virtual bool changesBindings();
- virtual void saveOriginals();
- virtual bool needsCopy() { return true; }
- virtual void copyOriginals(QDeclarativeActionEvent*);
- virtual void clearBindings();
- virtual void rewind();
- virtual void saveCurrentValues();
-
- QList<QDeclarativeAction> additionalActions();
- virtual void saveTargetValues();
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickParentChange)
-QML_DECLARE_TYPE(QQuickAnchorSet)
-QML_DECLARE_TYPE(QQuickAnchorChanges)
-
-QT_END_HEADER
-
-#endif // QQUICKSTATEOPERATIONS_P_H
-
diff --git a/src/declarative/items/qquicktext.cpp b/src/declarative/items/qquicktext.cpp
deleted file mode 100644
index 630b466d80..0000000000
--- a/src/declarative/items/qquicktext.cpp
+++ /dev/null
@@ -1,1950 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquicktext_p.h"
-#include "qquicktext_p_p.h"
-
-#include <private/qsgcontext_p.h>
-#include <private/qsgadaptationlayer_p.h>
-#include "qquicktextnode_p.h"
-#include "qquickimage_p_p.h"
-#include <private/qsgtexture_p.h>
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qabstracttextdocumentlayout.h>
-#include <QtGui/qpainter.h>
-#include <QtGui/qtextdocument.h>
-#include <QtGui/qtextobject.h>
-#include <QtGui/qtextcursor.h>
-#include <QtGui/qguiapplication.h>
-
-#include <private/qdeclarativestyledtext_p.h>
-#include <private/qdeclarativepixmapcache_p.h>
-
-#include <qmath.h>
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-extern Q_GUI_EXPORT bool qt_applefontsmoothing_enabled;
-
-class QQuickTextDocumentWithImageResources : public QTextDocument {
- Q_OBJECT
-
-public:
- QQuickTextDocumentWithImageResources(QQuickText *parent);
- virtual ~QQuickTextDocumentWithImageResources();
-
- void setText(const QString &);
- int resourcesLoading() const { return outstanding; }
-
-protected:
- QVariant loadResource(int type, const QUrl &name);
-
-private slots:
- void requestFinished();
-
-private:
- QHash<QUrl, QDeclarativePixmap *> m_resources;
-
- int outstanding;
- static QSet<QUrl> errors;
-};
-
-DEFINE_BOOL_CONFIG_OPTION(qmlDisableDistanceField, QML_DISABLE_DISTANCEFIELD)
-DEFINE_BOOL_CONFIG_OPTION(enableImageCache, QML_ENABLE_TEXT_IMAGE_CACHE);
-
-QString QQuickTextPrivate::elideChar = QString(0x2026);
-
-QQuickTextPrivate::QQuickTextPrivate()
-: color((QRgb)0), style(QQuickText::Normal), hAlign(QQuickText::AlignLeft),
- vAlign(QQuickText::AlignTop), elideMode(QQuickText::ElideNone),
- format(QQuickText::AutoText), wrapMode(QQuickText::NoWrap), lineHeight(1),
- lineHeightMode(QQuickText::ProportionalHeight), lineCount(1), maximumLineCount(INT_MAX),
- maximumLineCountValid(false),
- texture(0),
- imageCacheDirty(false), updateOnComponentComplete(true),
- richText(false), styledText(false), singleline(false), cacheAllTextAsImage(true), internalWidthUpdate(false),
- requireImplicitWidth(false), truncated(false), hAlignImplicit(true), rightToLeftText(false),
- layoutTextElided(false), richTextAsImage(false), textureImageCacheDirty(false), textHasChanged(true),
- naturalWidth(0), doc(0), elipsisLayout(0), textLine(0), nodeType(NodeIsNull)
-
-#if defined(Q_OS_MAC)
-, layoutThread(0), paintingThread(0)
-#endif
-
-{
- cacheAllTextAsImage = enableImageCache();
-}
-
-void QQuickTextPrivate::init()
-{
- Q_Q(QQuickText);
- q->setAcceptedMouseButtons(Qt::LeftButton);
- q->setFlag(QQuickItem::ItemHasContents);
-}
-
-QQuickTextDocumentWithImageResources::QQuickTextDocumentWithImageResources(QQuickText *parent)
-: QTextDocument(parent), outstanding(0)
-{
- setUndoRedoEnabled(false);
-}
-
-QQuickTextDocumentWithImageResources::~QQuickTextDocumentWithImageResources()
-{
- if (!m_resources.isEmpty())
- qDeleteAll(m_resources);
-}
-
-QVariant QQuickTextDocumentWithImageResources::loadResource(int type, const QUrl &name)
-{
- QDeclarativeContext *context = qmlContext(parent());
- QUrl url = context->resolvedUrl(name);
-
- if (type == QTextDocument::ImageResource) {
- QHash<QUrl, QDeclarativePixmap *>::Iterator iter = m_resources.find(url);
-
- if (iter == m_resources.end()) {
- QDeclarativePixmap *p = new QDeclarativePixmap(context->engine(), url);
- iter = m_resources.insert(url, p);
-
- if (p->isLoading()) {
- p->connectFinished(this, SLOT(requestFinished()));
- outstanding++;
- }
- }
-
- QDeclarativePixmap *p = *iter;
- if (p->isReady()) {
- return p->image();
- } else if (p->isError()) {
- if (!errors.contains(url)) {
- errors.insert(url);
- qmlInfo(parent()) << p->error();
- }
- }
- }
-
- return QTextDocument::loadResource(type,url); // The *resolved* URL
-}
-
-void QQuickTextDocumentWithImageResources::requestFinished()
-{
- outstanding--;
- if (outstanding == 0) {
- QQuickText *textItem = static_cast<QQuickText*>(parent());
- QString text = textItem->text();
-#ifndef QT_NO_TEXTHTMLPARSER
- setHtml(text);
-#else
- setPlainText(text);
-#endif
- QQuickTextPrivate *d = QQuickTextPrivate::get(textItem);
- d->updateLayout();
- }
-}
-
-void QQuickTextDocumentWithImageResources::setText(const QString &text)
-{
- if (!m_resources.isEmpty()) {
- qDeleteAll(m_resources);
- m_resources.clear();
- outstanding = 0;
- }
-
-#ifndef QT_NO_TEXTHTMLPARSER
- setHtml(text);
-#else
- setPlainText(text);
-#endif
-}
-
-QSet<QUrl> QQuickTextDocumentWithImageResources::errors;
-
-QQuickTextPrivate::~QQuickTextPrivate()
-{
- delete elipsisLayout;
- delete textLine; textLine = 0;
-}
-
-qreal QQuickTextPrivate::getImplicitWidth() const
-{
- if (!requireImplicitWidth) {
- // We don't calculate implicitWidth unless it is required.
- // We need to force a size update now to ensure implicitWidth is calculated
- QQuickTextPrivate *me = const_cast<QQuickTextPrivate*>(this);
- me->requireImplicitWidth = true;
- me->updateSize();
- }
- return implicitWidth;
-}
-
-void QQuickTextPrivate::updateLayout()
-{
- Q_Q(QQuickText);
- if (!q->isComponentComplete()) {
- updateOnComponentComplete = true;
- return;
- }
- updateOnComponentComplete = false;
- layoutTextElided = false;
- // Setup instance of QTextLayout for all cases other than richtext
- if (!richText) {
- if (elipsisLayout) {
- delete elipsisLayout;
- elipsisLayout = 0;
- }
- layout.clearLayout();
- layout.setFont(font);
- if (!styledText) {
- QString tmp = text;
- tmp.replace(QLatin1Char('\n'), QChar::LineSeparator);
- singleline = !tmp.contains(QChar::LineSeparator);
- if (singleline && !maximumLineCountValid && elideMode != QQuickText::ElideNone && q->widthValid() && wrapMode == QQuickText::NoWrap) {
- QFontMetrics fm(font);
- tmp = fm.elidedText(tmp,(Qt::TextElideMode)elideMode,q->width());
- if (tmp != text) {
- layoutTextElided = true;
- if (!truncated) {
- truncated = true;
- emit q->truncatedChanged();
- }
- }
- }
- layout.setText(tmp);
- } else {
- singleline = false;
- if (textHasChanged) {
- QDeclarativeStyledText::parse(text, layout);
- textHasChanged = false;
- }
- }
- } else {
- ensureDoc();
- QTextBlockFormat::LineHeightTypes type;
- type = lineHeightMode == QQuickText::FixedHeight ? QTextBlockFormat::FixedHeight : QTextBlockFormat::ProportionalHeight;
- QTextBlockFormat blockFormat;
- blockFormat.setLineHeight((lineHeightMode == QQuickText::FixedHeight ? lineHeight : lineHeight * 100), type);
- for (QTextBlock it = doc->begin(); it != doc->end(); it = it.next()) {
- QTextCursor cursor(it);
- cursor.mergeBlockFormat(blockFormat);
- }
- }
-
- updateSize();
-}
-
-void QQuickTextPrivate::updateSize()
-{
- Q_Q(QQuickText);
-
- if (!q->isComponentComplete()) {
- updateOnComponentComplete = true;
- return;
- }
-
- if (!requireImplicitWidth) {
- emit q->implicitWidthChanged();
- // if the implicitWidth is used, then updateSize() has already been called (recursively)
- if (requireImplicitWidth)
- return;
- }
-
- invalidateImageCache();
-
- QFontMetrics fm(font);
- if (text.isEmpty()) {
- q->setImplicitSize(0, fm.height());
- paintedSize = QSize(0, fm.height());
- emit q->paintedSizeChanged();
- q->update();
- return;
- }
-
- int dy = q->height();
- QSize size(0, 0);
-
-#if defined(Q_OS_MAC)
- layoutThread = QThread::currentThread();
-#endif
-
- //setup instance of QTextLayout for all cases other than richtext
- if (!richText) {
- QRect textRect = setupTextLayout();
- layedOutTextRect = textRect;
- size = textRect.size();
- dy -= size.height();
- } else {
- singleline = false; // richtext can't elide or be optimized for single-line case
- ensureDoc();
- doc->setDefaultFont(font);
- QQuickText::HAlignment horizontalAlignment = q->effectiveHAlign();
- if (rightToLeftText) {
- if (horizontalAlignment == QQuickText::AlignLeft)
- horizontalAlignment = QQuickText::AlignRight;
- else if (horizontalAlignment == QQuickText::AlignRight)
- horizontalAlignment = QQuickText::AlignLeft;
- }
- QTextOption option;
- option.setAlignment((Qt::Alignment)int(horizontalAlignment | vAlign));
- option.setWrapMode(QTextOption::WrapMode(wrapMode));
- if (!cacheAllTextAsImage && !richTextAsImage && !qmlDisableDistanceField())
- option.setUseDesignMetrics(true);
- doc->setDefaultTextOption(option);
- if (requireImplicitWidth && q->widthValid()) {
- doc->setTextWidth(-1);
- naturalWidth = doc->idealWidth();
- }
- if (wrapMode != QQuickText::NoWrap && q->widthValid())
- doc->setTextWidth(q->width());
- else
- doc->setTextWidth(doc->idealWidth()); // ### Text does not align if width is not set (QTextDoc bug)
- dy -= (int)doc->size().height();
- QSize dsize = doc->size().toSize();
- layedOutTextRect = QRect(QPoint(0,0), dsize);
- size = QSize(int(doc->idealWidth()),dsize.height());
- }
- int yoff = 0;
-
- if (q->heightValid()) {
- if (vAlign == QQuickText::AlignBottom)
- yoff = dy;
- else if (vAlign == QQuickText::AlignVCenter)
- yoff = dy/2;
- }
- q->setBaselineOffset(fm.ascent() + yoff);
-
- //### need to comfirm cost of always setting these for richText
- internalWidthUpdate = true;
- qreal iWidth = -1;
- if (!q->widthValid())
- iWidth = size.width();
- else if (requireImplicitWidth)
- iWidth = naturalWidth;
- if (iWidth > -1)
- q->setImplicitSize(iWidth, size.height());
- internalWidthUpdate = false;
-
- if (iWidth == -1)
- q->setImplicitHeight(size.height());
- if (paintedSize != size) {
- paintedSize = size;
- emit q->paintedSizeChanged();
- }
- q->update();
-}
-
-QQuickTextLine::QQuickTextLine()
- : QObject(), m_line(0), m_height(0)
-{
-}
-
-void QQuickTextLine::setLine(QTextLine *line)
-{
- m_line = line;
-}
-
-int QQuickTextLine::number() const
-{
- if (m_line)
- return m_line->lineNumber();
- return 0;
-}
-
-qreal QQuickTextLine::width() const
-{
- if (m_line)
- return m_line->width();
- return 0;
-}
-
-void QQuickTextLine::setWidth(qreal width)
-{
- if (m_line)
- m_line->setLineWidth(width);
-}
-
-qreal QQuickTextLine::height() const
-{
- if (m_height)
- return m_height;
- if (m_line)
- return m_line->height();
- return 0;
-}
-
-void QQuickTextLine::setHeight(qreal height)
-{
- if (m_line)
- m_line->setPosition(QPointF(m_line->x(), m_line->y() - m_line->height() + height));
- m_height = height;
-}
-
-qreal QQuickTextLine::x() const
-{
- if (m_line)
- return m_line->x();
- return 0;
-}
-
-void QQuickTextLine::setX(qreal x)
-{
- if (m_line)
- m_line->setPosition(QPointF(x, m_line->y()));
-}
-
-qreal QQuickTextLine::y() const
-{
- if (m_line)
- return m_line->y();
- return 0;
-}
-
-void QQuickTextLine::setY(qreal y)
-{
- if (m_line)
- m_line->setPosition(QPointF(m_line->x(), y));
-}
-
-void QQuickText::doLayout()
-{
- Q_D(QQuickText);
- d->updateSize();
-}
-
-bool QQuickTextPrivate::isLineLaidOutConnected()
-{
- static int idx = this->signalIndex("lineLaidOut(QQuickTextLine*)");
- return this->isSignalConnected(idx);
-}
-
-void QQuickTextPrivate::setupCustomLineGeometry(QTextLine &line, qreal &height, qreal elideWidth = 0)
-{
- Q_Q(QQuickText);
-
-#if defined(Q_OS_MAC)
- if (QThread::currentThread() != paintingThread) {
-#endif
- if (!line.lineNumber())
- linesRects.clear();
-
- if (!textLine)
- textLine = new QQuickTextLine;
- textLine->setLine(&line);
- textLine->setY(height);
- textLine->setHeight(0);
-
- // use the text item's width by default if it has one and wrap is on
- if (q->widthValid() && q->wrapMode() != QQuickText::NoWrap)
- textLine->setWidth(q->width() - elideWidth);
- else
- textLine->setWidth(INT_MAX);
- if (lineHeight != 1.0)
- textLine->setHeight((lineHeightMode == QQuickText::FixedHeight) ? lineHeight : line.height() * lineHeight);
-
- emit q->lineLaidOut(textLine);
-
- linesRects << QRectF(textLine->x(), textLine->y(), textLine->width(), textLine->height());
- height += textLine->height();
-
-#if defined(Q_OS_MAC)
- } else {
- if (line.lineNumber() < linesRects.count()) {
- QRectF r = linesRects.at(line.lineNumber());
- line.setLineWidth(r.width());
- line.setPosition(r.topLeft());
- }
- }
-#endif
-}
-
-/*!
- Lays out the QQuickTextPrivate::layout QTextLayout in the constraints of the QQuickText.
-
- Returns the size of the final text. This can be used to position the text vertically (the text is
- already absolutely positioned horizontally).
-*/
-QRect QQuickTextPrivate::setupTextLayout()
-{
- // ### text layout handling should be profiled and optimized as needed
- // what about QStackTextEngine engine(tmp, d->font.font()); QTextLayout textLayout(&engine);
- Q_Q(QQuickText);
- layout.setCacheEnabled(true);
-
- qreal lineWidth = 0;
- int visibleCount = 0;
-
- //set manual width
- if (q->widthValid())
- lineWidth = q->width();
-
- QTextOption textOption = layout.textOption();
- textOption.setAlignment(Qt::Alignment(q->effectiveHAlign()));
- textOption.setWrapMode(QTextOption::WrapMode(wrapMode));
- if (!cacheAllTextAsImage && !richTextAsImage && !qmlDisableDistanceField())
- textOption.setUseDesignMetrics(true);
- layout.setTextOption(textOption);
-
- QFontMetrics fm(layout.font());
- elidePos = QPointF();
-
- if (requireImplicitWidth && q->widthValid()) {
- // requires an extra layout
- QString elidedText;
- if (layoutTextElided) {
- // We have provided elided text to the layout, but we must calculate unelided width.
- elidedText = layout.text();
- layout.setText(text);
- }
- layout.beginLayout();
- forever {
- QTextLine line = layout.createLine();
- if (!line.isValid())
- break;
- }
- layout.endLayout();
- QRectF br;
- for (int i = 0; i < layout.lineCount(); ++i) {
- QTextLine line = layout.lineAt(i);
- br = br.united(line.naturalTextRect());
- }
- naturalWidth = br.width();
- if (layoutTextElided)
- layout.setText(elidedText);
- }
-
- qreal height = 0;
- QRectF br;
-
- bool truncate = false;
- bool customLayout = isLineLaidOutConnected();
- bool elideEnabled = elideMode == QQuickText::ElideRight && q->widthValid();
-
- layout.beginLayout();
- if (!lineWidth)
- lineWidth = INT_MAX;
- int linesLeft = maximumLineCount;
- int visibleTextLength = 0;
- forever {
- QTextLine line = layout.createLine();
- if (!line.isValid())
- break;
-
- visibleCount++;
-
- qreal preLayoutHeight = height;
- if (customLayout) {
- setupCustomLineGeometry(line, height);
- } else if (lineWidth) {
- line.setLineWidth(lineWidth);
- line.setPosition(QPointF(line.position().x(), height));
- height += (lineHeightMode == QQuickText::FixedHeight) ? lineHeight : line.height() * lineHeight;
- }
-
- bool elide = false;
- if (elideEnabled && q->heightValid() && height > q->height()) {
- // This line does not fit in the remaining area.
- elide = true;
- if (visibleCount > 1) {
- --visibleCount;
- height = preLayoutHeight;
- line.setLineWidth(0.0);
- line.setPosition(QPointF(FLT_MAX,FLT_MAX));
- line = layout.lineAt(visibleCount-1);
- }
- } else {
- visibleTextLength += line.textLength();
- }
-
- if (elide || (maximumLineCountValid && --linesLeft == 0)) {
- if (visibleTextLength < text.length()) {
- truncate = true;
- if (elideEnabled) {
- qreal elideWidth = fm.width(elideChar);
- // Need to correct for alignment
- if (customLayout)
- setupCustomLineGeometry(line, height, elideWidth);
- else
- line.setLineWidth(lineWidth - elideWidth);
- if (layout.text().mid(line.textStart(), line.textLength()).isRightToLeft()) {
- line.setPosition(QPointF(line.position().x() + elideWidth, line.position().y()));
- elidePos.setX(line.naturalTextRect().left() - elideWidth);
- } else {
- elidePos.setX(line.naturalTextRect().right());
- }
- elidePos.setY(line.position().y());
- if (!elipsisLayout)
- elipsisLayout = new QTextLayout(elideChar, layout.font());
- elipsisLayout->beginLayout();
- QTextLine el = elipsisLayout->createLine();
- el.setPosition(elidePos);
- elipsisLayout->endLayout();
- br = br.united(el.naturalTextRect());
- }
- br = br.united(line.naturalTextRect());
- break;
- }
- }
- br = br.united(line.naturalTextRect());
- }
- layout.endLayout();
-
- //Update truncated
- if (truncated != truncate) {
- truncated = truncate;
- emit q->truncatedChanged();
- }
-
- if (!customLayout)
- br.setHeight(height);
-
- if (!q->widthValid())
- naturalWidth = br.width();
-
- //Update the number of visible lines
- if (lineCount != visibleCount) {
- lineCount = visibleCount;
- emit q->lineCountChanged();
- }
-
- return QRect(qRound(br.x()), qRound(br.y()), qCeil(br.width()), qCeil(br.height()));
-}
-
-/*!
- Returns a painted version of the QQuickTextPrivate::layout QTextLayout.
- If \a drawStyle is true, the style color overrides all colors in the document.
-*/
-QPixmap QQuickTextPrivate::textLayoutImage(bool drawStyle)
-{
- QSize size = layedOutTextRect.size();
-
- //paint text
- QPixmap img(size);
- if (!size.isEmpty()) {
- img.fill(Qt::transparent);
-/*#ifdef Q_OS_MAC // Fails on CocoaX64
- bool oldSmooth = qt_applefontsmoothing_enabled;
- qt_applefontsmoothing_enabled = false;
-#endif*/
- QPainter p(&img);
-/*#ifdef Q_OS_MAC // Fails on CocoaX64
- qt_applefontsmoothing_enabled = oldSmooth;
-#endif*/
- drawTextLayout(&p, QPointF(-layedOutTextRect.x(),0), drawStyle);
- }
- return img;
-}
-
-/*!
- Paints the QQuickTextPrivate::layout QTextLayout into \a painter at \a pos. If
- \a drawStyle is true, the style color overrides all colors in the document.
-*/
-void QQuickTextPrivate::drawTextLayout(QPainter *painter, const QPointF &pos, bool drawStyle)
-{
- if (drawStyle)
- painter->setPen(styleColor);
- else
- painter->setPen(color);
- painter->setFont(font);
- layout.draw(painter, pos);
- if (!elidePos.isNull())
- painter->drawText(pos + elidePos, elideChar);
-}
-
-/*!
- Returns a painted version of the QQuickTextPrivate::doc QTextDocument.
- If \a drawStyle is true, the style color overrides all colors in the document.
-*/
-QPixmap QQuickTextPrivate::textDocumentImage(bool drawStyle)
-{
- QSize size = doc->size().toSize();
-
- //paint text
- QPixmap img(size);
- img.fill(Qt::transparent);
-/*#ifdef Q_OS_MAC // Fails on CocoaX64
- bool oldSmooth = qt_applefontsmoothing_enabled;
- qt_applefontsmoothing_enabled = false;
-#endif*/
- QPainter p(&img);
-/*#ifdef Q_OS_MAC // Fails on CocoaX64
- qt_applefontsmoothing_enabled = oldSmooth;
-#endif*/
-
- QAbstractTextDocumentLayout::PaintContext context;
-
- QTextOption oldOption(doc->defaultTextOption());
- if (drawStyle) {
- context.palette.setColor(QPalette::Text, styleColor);
- QTextOption colorOption(doc->defaultTextOption());
- colorOption.setFlags(QTextOption::SuppressColors);
- doc->setDefaultTextOption(colorOption);
- } else {
- context.palette.setColor(QPalette::Text, color);
- }
- doc->documentLayout()->draw(&p, context);
- if (drawStyle)
- doc->setDefaultTextOption(oldOption);
- return img;
-}
-
-/*!
- Mark the image cache as dirty.
-*/
-void QQuickTextPrivate::invalidateImageCache()
-{
- Q_Q(QQuickText);
-
- if (richTextAsImage || cacheAllTextAsImage || (qmlDisableDistanceField() && style != QQuickText::Normal)) { // If actually using the image cache
- if (imageCacheDirty)
- return;
-
- imageCacheDirty = true;
-
- if (q->isComponentComplete())
- QCoreApplication::postEvent(q, new QEvent(QEvent::User));
- } else if (q->isComponentComplete())
- q->update();
-}
-
-/*!
- Tests if the image cache is dirty, and repaints it if it is.
-*/
-void QQuickTextPrivate::checkImageCache()
-{
- Q_Q(QQuickText);
-
- if (!imageCacheDirty)
- return;
-
- if (text.isEmpty()) {
-
- imageCache = QPixmap();
-
- } else {
-
- QPixmap textImage;
- QPixmap styledImage;
-
- if (richText) {
- textImage = textDocumentImage(false);
- if (style != QQuickText::Normal)
- styledImage = textDocumentImage(true); //### should use styleColor
- } else {
- textImage = textLayoutImage(false);
- if (style != QQuickText::Normal)
- styledImage = textLayoutImage(true); //### should use styleColor
- }
-
- switch (style) {
- case QQuickText::Outline:
- imageCache = drawOutline(textImage, styledImage);
- break;
- case QQuickText::Sunken:
- imageCache = drawOutline(textImage, styledImage, -1);
- break;
- case QQuickText::Raised:
- imageCache = drawOutline(textImage, styledImage, 1);
- break;
- default:
- imageCache = textImage;
- break;
- }
-
- }
-
- imageCacheDirty = false;
- textureImageCacheDirty = true;
- q->update();
-}
-
-/*!
- Ensures the QQuickTextPrivate::doc variable is set to a valid text document
-*/
-void QQuickTextPrivate::ensureDoc()
-{
- if (!doc) {
- Q_Q(QQuickText);
- doc = new QQuickTextDocumentWithImageResources(q);
- doc->setDocumentMargin(0);
- }
-}
-
-/*!
- Draw \a styleSource as an outline around \a source and return the new image.
-*/
-QPixmap QQuickTextPrivate::drawOutline(const QPixmap &source, const QPixmap &styleSource)
-{
- QPixmap img = QPixmap(styleSource.width() + 2, styleSource.height() + 2);
- img.fill(Qt::transparent);
-
- QPainter ppm(&img);
-
- QPoint pos(0, 0);
- pos += QPoint(-1, 0);
- ppm.drawPixmap(pos, styleSource);
- pos += QPoint(2, 0);
- ppm.drawPixmap(pos, styleSource);
- pos += QPoint(-1, -1);
- ppm.drawPixmap(pos, styleSource);
- pos += QPoint(0, 2);
- ppm.drawPixmap(pos, styleSource);
-
- pos += QPoint(0, -1);
- ppm.drawPixmap(pos, source);
- ppm.end();
-
- return img;
-}
-
-/*!
- Draw \a styleSource below \a source at \a yOffset and return the new image.
-*/
-QPixmap QQuickTextPrivate::drawOutline(const QPixmap &source, const QPixmap &styleSource, int yOffset)
-{
- QPixmap img = QPixmap(styleSource.width() + 2, styleSource.height() + 2);
- img.fill(Qt::transparent);
-
- QPainter ppm(&img);
-
- ppm.drawPixmap(QPoint(0, yOffset), styleSource);
- ppm.drawPixmap(0, 0, source);
-
- ppm.end();
-
- return img;
-}
-
-/*!
- \qmlclass Text QQuickText
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
- \brief The Text item allows you to add formatted text to a scene.
- \inherits Item
-
- Text items can display both plain and rich text. For example, red text with
- a specific font and size can be defined like this:
-
- \qml
- Text {
- text: "Hello World!"
- font.family: "Helvetica"
- font.pointSize: 24
- color: "red"
- }
- \endqml
-
- Rich text is defined using HTML-style markup:
-
- \qml
- Text {
- text: "<b>Hello</b> <i>World!</i>"
- }
- \endqml
-
- \image declarative-text.png
-
- If height and width are not explicitly set, Text will attempt to determine how
- much room is needed and set it accordingly. Unless \l wrapMode is set, it will always
- prefer width to height (all text will be placed on a single line).
-
- The \l elide property can alternatively be used to fit a single line of
- plain text to a set width.
-
- Note that the \l{Supported HTML Subset} is limited. Also, if the text contains
- HTML img tags that load remote images, the text is reloaded.
-
- Text provides read-only text. For editable text, see \l TextEdit.
-
- \sa {declarative/text/fonts}{Fonts example}
-*/
-QQuickText::QQuickText(QQuickItem *parent)
-: QQuickImplicitSizeItem(*(new QQuickTextPrivate), parent)
-{
- Q_D(QQuickText);
- d->init();
-}
-
-QQuickText::~QQuickText()
-{
-}
-
-/*!
- \qmlproperty bool QtQuick2::Text::clip
- This property holds whether the text is clipped.
-
- Note that if the text does not fit in the bounding rectangle it will be abruptly chopped.
-
- If you want to display potentially long text in a limited space, you probably want to use \c elide instead.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Text::smooth
-
- This property holds whether the text is smoothly scaled or transformed.
-
- Smooth filtering gives better visual quality, but is slower. If
- the item is displayed at its natural size, this property has no visual or
- performance effect.
-
- \note Generally scaling artifacts are only visible if the item is stationary on
- the screen. A common pattern when animating an item is to disable smooth
- filtering at the beginning of the animation and reenable it at the conclusion.
-*/
-
-/*!
- \qmlsignal QtQuick2::Text::onLineLaidOut(line)
-
- This handler is called for every line during the layout process.
- This gives the opportunity to position and resize a line as it is being laid out.
- It can for example be used to create columns or lay out text around objects.
-
- The properties of a line are:
- \list
- \o number (read-only)
- \o x
- \o y
- \o width
- \o height
- \endlist
-
- For example, this will move the first 5 lines of a text element by 100 pixels to the right:
- \code
- onLineLaidOut: {
- if (line.number < 5) {
- line.x = line.x + 100
- line.width = line.width - 100
- }
- }
- \endcode
-*/
-
-/*!
- \qmlsignal QtQuick2::Text::onLinkActivated(string link)
-
- This handler is called when the user clicks on a link embedded in the text.
- The link must be in rich text or HTML format and the
- \a link string provides access to the particular link.
-
- \snippet doc/src/snippets/declarative/text/onLinkActivated.qml 0
-
- The example code will display the text
- "The main website is at \l{http://qt.nokia.com}{Nokia Qt DF}."
-
- Clicking on the highlighted link will output
- \tt{http://qt.nokia.com link activated} to the console.
-*/
-
-/*!
- \qmlproperty string QtQuick2::Text::font.family
-
- Sets the family name of the font.
-
- The family name is case insensitive and may optionally include a foundry name, e.g. "Helvetica [Cronyx]".
- If the family is available from more than one foundry and the foundry isn't specified, an arbitrary foundry is chosen.
- If the family isn't available a family will be set using the font matching algorithm.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Text::font.bold
-
- Sets whether the font weight is bold.
-*/
-
-/*!
- \qmlproperty enumeration QtQuick2::Text::font.weight
-
- Sets the font's weight.
-
- The weight can be one of:
- \list
- \o Font.Light
- \o Font.Normal - the default
- \o Font.DemiBold
- \o Font.Bold
- \o Font.Black
- \endlist
-
- \qml
- Text { text: "Hello"; font.weight: Font.DemiBold }
- \endqml
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Text::font.italic
-
- Sets whether the font has an italic style.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Text::font.underline
-
- Sets whether the text is underlined.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::Text::font.strikeout
-
- Sets whether the font has a strikeout style.
-*/
-
-/*!
- \qmlproperty real QtQuick2::Text::font.pointSize
-
- Sets the font size in points. The point size must be greater than zero.
-*/
-
-/*!
- \qmlproperty int QtQuick2::Text::font.pixelSize
-
- Sets the font size in pixels.
-
- Using this function makes the font device dependent.
- Use \c pointSize to set the size of the font in a device independent manner.
-*/
-
-/*!
- \qmlproperty real QtQuick2::Text::font.letterSpacing
-
- Sets the letter spacing for the font.
-
- Letter spacing changes the default spacing between individual letters in the font.
- A positive value increases the letter spacing by the corresponding pixels; a negative value decreases the spacing.
-*/
-
-/*!
- \qmlproperty real QtQuick2::Text::font.wordSpacing
-
- Sets the word spacing for the font.
-
- Word spacing changes the default spacing between individual words.
- A positive value increases the word spacing by a corresponding amount of pixels,
- while a negative value decreases the inter-word spacing accordingly.
-*/
-
-/*!
- \qmlproperty enumeration QtQuick2::Text::font.capitalization
-
- Sets the capitalization for the text.
-
- \list
- \o Font.MixedCase - This is the normal text rendering option where no capitalization change is applied.
- \o Font.AllUppercase - This alters the text to be rendered in all uppercase type.
- \o Font.AllLowercase - This alters the text to be rendered in all lowercase type.
- \o Font.SmallCaps - This alters the text to be rendered in small-caps type.
- \o Font.Capitalize - This alters the text to be rendered with the first character of each word as an uppercase character.
- \endlist
-
- \qml
- Text { text: "Hello"; font.capitalization: Font.AllLowercase }
- \endqml
-*/
-QFont QQuickText::font() const
-{
- Q_D(const QQuickText);
- return d->sourceFont;
-}
-
-void QQuickText::setFont(const QFont &font)
-{
- Q_D(QQuickText);
- if (d->sourceFont == font)
- return;
-
- d->sourceFont = font;
- QFont oldFont = d->font;
- d->font = font;
-
- if (d->font.pointSizeF() != -1) {
- // 0.5pt resolution
- qreal size = qRound(d->font.pointSizeF()*2.0);
- d->font.setPointSizeF(size/2.0);
- }
-
- if (oldFont != d->font)
- d->updateLayout();
-
- emit fontChanged(d->sourceFont);
-}
-
-/*!
- \qmlproperty string QtQuick2::Text::text
-
- The text to display. Text supports both plain and rich text strings.
-
- The item will try to automatically determine whether the text should
- be treated as styled text. This determination is made using Qt::mightBeRichText().
-*/
-QString QQuickText::text() const
-{
- Q_D(const QQuickText);
- return d->text;
-}
-
-void QQuickText::setText(const QString &n)
-{
- Q_D(QQuickText);
- if (d->text == n)
- return;
-
- d->richText = d->format == RichText;
- d->styledText = d->format == StyledText || (d->format == AutoText && Qt::mightBeRichText(n));
- d->text = n;
- if (isComponentComplete()) {
- if (d->richText) {
- d->ensureDoc();
- d->doc->setText(n);
- d->rightToLeftText = d->doc->toPlainText().isRightToLeft();
- d->richTextAsImage = enableImageCache();
- } else {
- d->rightToLeftText = d->text.isRightToLeft();
- }
- d->determineHorizontalAlignment();
- }
- d->textHasChanged = true;
- d->updateLayout();
- emit textChanged(d->text);
-}
-
-/*!
- \qmlproperty color QtQuick2::Text::color
-
- The text color.
-
- An example of green text defined using hexadecimal notation:
- \qml
- Text {
- color: "#00FF00"
- text: "green text"
- }
- \endqml
-
- An example of steel blue text defined using an SVG color name:
- \qml
- Text {
- color: "steelblue"
- text: "blue text"
- }
- \endqml
-*/
-QColor QQuickText::color() const
-{
- Q_D(const QQuickText);
- return d->color;
-}
-
-void QQuickText::setColor(const QColor &color)
-{
- Q_D(QQuickText);
- if (d->color == color)
- return;
-
- d->color = color;
- d->invalidateImageCache();
- emit colorChanged(d->color);
-}
-/*!
- \qmlproperty enumeration QtQuick2::Text::style
-
- Set an additional text style.
-
- Supported text styles are:
- \list
- \o Text.Normal - the default
- \o Text.Outline
- \o Text.Raised
- \o Text.Sunken
- \endlist
-
- \qml
- Row {
- Text { font.pointSize: 24; text: "Normal" }
- Text { font.pointSize: 24; text: "Raised"; style: Text.Raised; styleColor: "#AAAAAA" }
- Text { font.pointSize: 24; text: "Outline";style: Text.Outline; styleColor: "red" }
- Text { font.pointSize: 24; text: "Sunken"; style: Text.Sunken; styleColor: "#AAAAAA" }
- }
- \endqml
-
- \image declarative-textstyle.png
-*/
-QQuickText::TextStyle QQuickText::style() const
-{
- Q_D(const QQuickText);
- return d->style;
-}
-
-void QQuickText::setStyle(QQuickText::TextStyle style)
-{
- Q_D(QQuickText);
- if (d->style == style)
- return;
-
- // changing to/from Normal requires the boundingRect() to change
- if (isComponentComplete() && (d->style == Normal || style == Normal))
- update();
- d->style = style;
- d->invalidateImageCache();
- emit styleChanged(d->style);
-}
-
-/*!
- \qmlproperty color QtQuick2::Text::styleColor
-
- Defines the secondary color used by text styles.
-
- \c styleColor is used as the outline color for outlined text, and as the
- shadow color for raised or sunken text. If no style has been set, it is not
- used at all.
-
- \qml
- Text { font.pointSize: 18; text: "hello"; style: Text.Raised; styleColor: "gray" }
- \endqml
-
- \sa style
- */
-QColor QQuickText::styleColor() const
-{
- Q_D(const QQuickText);
- return d->styleColor;
-}
-
-void QQuickText::setStyleColor(const QColor &color)
-{
- Q_D(QQuickText);
- if (d->styleColor == color)
- return;
-
- d->styleColor = color;
- d->invalidateImageCache();
- emit styleColorChanged(d->styleColor);
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Text::horizontalAlignment
- \qmlproperty enumeration QtQuick2::Text::verticalAlignment
- \qmlproperty enumeration QtQuick2::Text::effectiveHorizontalAlignment
-
- Sets the horizontal and vertical alignment of the text within the Text items
- width and height. By default, the text is vertically aligned to the top. Horizontal
- alignment follows the natural alignment of the text, for example text that is read
- from left to right will be aligned to the left.
-
- The valid values for \c horizontalAlignment are \c Text.AlignLeft, \c Text.AlignRight, \c Text.AlignHCenter and
- \c Text.AlignJustify. The valid values for \c verticalAlignment are \c Text.AlignTop, \c Text.AlignBottom
- and \c Text.AlignVCenter.
-
- Note that for a single line of text, the size of the text is the area of the text. In this common case,
- all alignments are equivalent. If you want the text to be, say, centered in its parent, then you will
- need to either modify the Item::anchors, or set horizontalAlignment to Text.AlignHCenter and bind the width to
- that of the parent.
-
- When using the attached property LayoutMirroring::enabled to mirror application
- layouts, the horizontal alignment of text will also be mirrored. However, the property
- \c horizontalAlignment will remain unchanged. To query the effective horizontal alignment
- of Text, use the read-only property \c effectiveHorizontalAlignment.
-*/
-QQuickText::HAlignment QQuickText::hAlign() const
-{
- Q_D(const QQuickText);
- return d->hAlign;
-}
-
-void QQuickText::setHAlign(HAlignment align)
-{
- Q_D(QQuickText);
- bool forceAlign = d->hAlignImplicit && d->effectiveLayoutMirror;
- d->hAlignImplicit = false;
- if (d->setHAlign(align, forceAlign) && isComponentComplete())
- d->updateLayout();
-}
-
-void QQuickText::resetHAlign()
-{
- Q_D(QQuickText);
- d->hAlignImplicit = true;
- if (isComponentComplete() && d->determineHorizontalAlignment())
- d->updateLayout();
-}
-
-QQuickText::HAlignment QQuickText::effectiveHAlign() const
-{
- Q_D(const QQuickText);
- QQuickText::HAlignment effectiveAlignment = d->hAlign;
- if (!d->hAlignImplicit && d->effectiveLayoutMirror) {
- switch (d->hAlign) {
- case QQuickText::AlignLeft:
- effectiveAlignment = QQuickText::AlignRight;
- break;
- case QQuickText::AlignRight:
- effectiveAlignment = QQuickText::AlignLeft;
- break;
- default:
- break;
- }
- }
- return effectiveAlignment;
-}
-
-bool QQuickTextPrivate::setHAlign(QQuickText::HAlignment alignment, bool forceAlign)
-{
- Q_Q(QQuickText);
- if (hAlign != alignment || forceAlign) {
- QQuickText::HAlignment oldEffectiveHAlign = q->effectiveHAlign();
- hAlign = alignment;
-
- emit q->horizontalAlignmentChanged(hAlign);
- if (oldEffectiveHAlign != q->effectiveHAlign())
- emit q->effectiveHorizontalAlignmentChanged();
- return true;
- }
- return false;
-}
-
-bool QQuickTextPrivate::determineHorizontalAlignment()
-{
- if (hAlignImplicit) {
- bool alignToRight = text.isEmpty() ? QGuiApplication::keyboardInputDirection() == Qt::RightToLeft : rightToLeftText;
- return setHAlign(alignToRight ? QQuickText::AlignRight : QQuickText::AlignLeft);
- }
- return false;
-}
-
-void QQuickTextPrivate::mirrorChange()
-{
- Q_Q(QQuickText);
- if (q->isComponentComplete()) {
- if (!hAlignImplicit && (hAlign == QQuickText::AlignRight || hAlign == QQuickText::AlignLeft)) {
- updateLayout();
- emit q->effectiveHorizontalAlignmentChanged();
- }
- }
-}
-
-QTextDocument *QQuickTextPrivate::textDocument()
-{
- return doc;
-}
-
-QQuickText::VAlignment QQuickText::vAlign() const
-{
- Q_D(const QQuickText);
- return d->vAlign;
-}
-
-void QQuickText::setVAlign(VAlignment align)
-{
- Q_D(QQuickText);
- if (d->vAlign == align)
- return;
-
- d->vAlign = align;
- emit verticalAlignmentChanged(align);
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Text::wrapMode
-
- Set this property to wrap the text to the Text item's width. The text will only
- wrap if an explicit width has been set. wrapMode can be one of:
-
- \list
- \o Text.NoWrap (default) - no wrapping will be performed. If the text contains insufficient newlines, then \l paintedWidth will exceed a set width.
- \o Text.WordWrap - wrapping is done on word boundaries only. If a word is too long, \l paintedWidth will exceed a set width.
- \o Text.WrapAnywhere - wrapping is done at any point on a line, even if it occurs in the middle of a word.
- \o Text.Wrap - if possible, wrapping occurs at a word boundary; otherwise it will occur at the appropriate point on the line, even in the middle of a word.
- \endlist
-*/
-QQuickText::WrapMode QQuickText::wrapMode() const
-{
- Q_D(const QQuickText);
- return d->wrapMode;
-}
-
-void QQuickText::setWrapMode(WrapMode mode)
-{
- Q_D(QQuickText);
- if (mode == d->wrapMode)
- return;
-
- d->wrapMode = mode;
- d->updateLayout();
-
- emit wrapModeChanged();
-}
-
-/*!
- \qmlproperty int QtQuick2::Text::lineCount
-
- Returns the number of lines visible in the text item.
-
- This property is not supported for rich text.
-
- \sa maximumLineCount
-*/
-int QQuickText::lineCount() const
-{
- Q_D(const QQuickText);
- return d->lineCount;
-}
-
-/*!
- \qmlproperty bool QtQuick2::Text::truncated
-
- Returns true if the text has been truncated due to \l maximumLineCount
- or \l elide.
-
- This property is not supported for rich text.
-
- \sa maximumLineCount, elide
-*/
-bool QQuickText::truncated() const
-{
- Q_D(const QQuickText);
- return d->truncated;
-}
-
-/*!
- \qmlproperty int QtQuick2::Text::maximumLineCount
-
- Set this property to limit the number of lines that the text item will show.
- If elide is set to Text.ElideRight, the text will be elided appropriately.
- By default, this is the value of the largest possible integer.
-
- This property is not supported for rich text.
-
- \sa lineCount, elide
-*/
-int QQuickText::maximumLineCount() const
-{
- Q_D(const QQuickText);
- return d->maximumLineCount;
-}
-
-void QQuickText::setMaximumLineCount(int lines)
-{
- Q_D(QQuickText);
-
- d->maximumLineCountValid = lines==INT_MAX ? false : true;
- if (d->maximumLineCount != lines) {
- d->maximumLineCount = lines;
- d->updateLayout();
- emit maximumLineCountChanged();
- }
-}
-
-void QQuickText::resetMaximumLineCount()
-{
- Q_D(QQuickText);
- setMaximumLineCount(INT_MAX);
- d->elidePos = QPointF();
- if (d->truncated != false) {
- d->truncated = false;
- emit truncatedChanged();
- }
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Text::textFormat
-
- The way the text property should be displayed.
-
- Supported text formats are:
-
- \list
- \o Text.AutoText (default)
- \o Text.PlainText
- \o Text.StyledText
- \o Text.RichText
- \endlist
-
- If the text format is \c Text.AutoText the text element
- will automatically determine whether the text should be treated as
- styled text. This determination is made using Qt::mightBeRichText().
-
- Text.StyledText is an optimized format supporting some basic text
- styling markup, in the style of html 3.2:
-
- \code
- <b></b> - bold
- <i></i> - italic
- <br> - new line
- <p> - paragraph
- <u> - underlined text
- <font color="color_name" size="1-7"></font>
- <h1> to <h6> - headers
- <a href=""> - anchor
- <ol type="">, <ul type=""> and <li> - ordered and unordered lists
- &gt; &lt; &amp;
- \endcode
-
- \c Text.StyledText parser is strict, requiring tags to be correctly nested.
-
- \table
- \row
- \o
- \qml
-Column {
- Text {
- font.pointSize: 24
- text: "<b>Hello</b> <i>World!</i>"
- }
- Text {
- font.pointSize: 24
- textFormat: Text.RichText
- text: "<b>Hello</b> <i>World!</i>"
- }
- Text {
- font.pointSize: 24
- textFormat: Text.PlainText
- text: "<b>Hello</b> <i>World!</i>"
- }
-}
- \endqml
- \o \image declarative-textformat.png
- \endtable
-*/
-QQuickText::TextFormat QQuickText::textFormat() const
-{
- Q_D(const QQuickText);
- return d->format;
-}
-
-void QQuickText::setTextFormat(TextFormat format)
-{
- Q_D(QQuickText);
- if (format == d->format)
- return;
- d->format = format;
- bool wasRich = d->richText;
- d->richText = format == RichText;
- d->styledText = format == StyledText || (format == AutoText && Qt::mightBeRichText(d->text));
-
- if (isComponentComplete()) {
- if (!wasRich && d->richText) {
- d->ensureDoc();
- d->doc->setText(d->text);
- d->rightToLeftText = d->doc->toPlainText().isRightToLeft();
- d->richTextAsImage = enableImageCache();
- } else {
- d->rightToLeftText = d->text.isRightToLeft();
- }
- d->determineHorizontalAlignment();
- }
- d->updateLayout();
-
- emit textFormatChanged(d->format);
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Text::elide
-
- Set this property to elide parts of the text fit to the Text item's width.
- The text will only elide if an explicit width has been set.
-
- This property cannot be used with rich text.
-
- Eliding can be:
- \list
- \o Text.ElideNone - the default
- \o Text.ElideLeft
- \o Text.ElideMiddle
- \o Text.ElideRight
- \endlist
-
- If this property is set to Text.ElideRight, it can be used with multiline
- text. The text will only elide if \c maximumLineCount, or \c height has been set.
- If both \c maximumLineCount and \c height are set, \c maximumLineCount will
- apply unless the lines do not fit in the height allowed.
-
- If the text is a multi-length string, and the mode is not \c Text.ElideNone,
- the first string that fits will be used, otherwise the last will be elided.
-
- Multi-length strings are ordered from longest to shortest, separated by the
- Unicode "String Terminator" character \c U009C (write this in QML with \c{"\u009C"} or \c{"\x9C"}).
-*/
-QQuickText::TextElideMode QQuickText::elideMode() const
-{
- Q_D(const QQuickText);
- return d->elideMode;
-}
-
-void QQuickText::setElideMode(QQuickText::TextElideMode mode)
-{
- Q_D(QQuickText);
- if (mode == d->elideMode)
- return;
-
- d->elideMode = mode;
- d->updateLayout();
-
- emit elideModeChanged(d->elideMode);
-}
-
-/*! \internal */
-QRectF QQuickText::boundingRect() const
-{
- Q_D(const QQuickText);
-
- QRect rect = d->layedOutTextRect;
- if (d->style != Normal)
- rect.adjust(-1, 0, 1, 2);
-
- // Could include font max left/right bearings to either side of rectangle.
-
- int h = height();
- switch (d->vAlign) {
- case AlignTop:
- break;
- case AlignBottom:
- rect.moveTop(h - rect.height());
- break;
- case AlignVCenter:
- rect.moveTop((h - rect.height()) / 2);
- break;
- }
-
- return QRectF(rect);
-}
-
-/*! \internal */
-void QQuickText::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_D(QQuickText);
- bool elide = d->elideMode != QQuickText::ElideNone && widthValid();
- if ((!d->internalWidthUpdate
- && (newGeometry.width() != oldGeometry.width() || (elide && newGeometry.height() != oldGeometry.height())))
- && (d->wrapMode != QQuickText::NoWrap
- || d->elideMode != QQuickText::ElideNone
- || d->hAlign != QQuickText::AlignLeft)) {
- if ((d->singleline || d->maximumLineCountValid || heightValid()) && elide) {
- // We need to re-elide
- d->updateLayout();
- } else {
- // We just need to re-layout
- d->updateSize();
- }
- }
-
- QQuickItem::geometryChanged(newGeometry, oldGeometry);
-}
-
-QSGNode *QQuickText::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
-{
- Q_UNUSED(data);
- Q_D(QQuickText);
-
- if (d->text.isEmpty()) {
- delete oldNode;
- return 0;
- }
-
- QRectF bounds = boundingRect();
-
- // We need to make sure the layout is done in the current thread
-#if defined(Q_OS_MAC)
- d->paintingThread = QThread::currentThread();
- if (d->layoutThread != d->paintingThread)
- d->updateLayout();
-#endif
-
- // XXX todo - some styled text can be done by the QQuickTextNode
- if (d->richTextAsImage || d->cacheAllTextAsImage || (qmlDisableDistanceField() && d->style != Normal)) {
- bool wasDirty = d->textureImageCacheDirty;
- d->textureImageCacheDirty = false;
-
- if (d->imageCache.isNull()) {
- delete oldNode;
- return 0;
- }
-
- QSGImageNode *node = 0;
- if (!oldNode || d->nodeType != QQuickTextPrivate::NodeIsTexture) {
- delete oldNode;
- node = QQuickItemPrivate::get(this)->sceneGraphContext()->createImageNode();
- d->texture = new QSGPlainTexture();
- wasDirty = true;
- d->nodeType = QQuickTextPrivate::NodeIsTexture;
- } else {
- node = static_cast<QSGImageNode *>(oldNode);
- Q_ASSERT(d->texture);
- }
-
- if (wasDirty) {
- qobject_cast<QSGPlainTexture *>(d->texture)->setImage(d->imageCache.toImage());
- node->setTexture(0);
- node->setTexture(d->texture);
- }
-
- node->setTargetRect(QRectF(bounds.x(), bounds.y(), d->imageCache.width(), d->imageCache.height()));
- node->setSourceRect(QRectF(0, 0, 1, 1));
- node->setHorizontalWrapMode(QSGTexture::ClampToEdge);
- node->setVerticalWrapMode(QSGTexture::ClampToEdge);
- node->setFiltering(QSGTexture::Linear); // Nonsmooth text just ugly, so don't do that..
- node->update();
-
- return node;
-
- } else {
- QQuickTextNode *node = 0;
- if (!oldNode || d->nodeType != QQuickTextPrivate::NodeIsText) {
- delete oldNode;
- node = new QQuickTextNode(QQuickItemPrivate::get(this)->sceneGraphContext());
- d->nodeType = QQuickTextPrivate::NodeIsText;
- } else {
- node = static_cast<QQuickTextNode *>(oldNode);
- }
-
- node->deleteContent();
- node->setMatrix(QMatrix4x4());
-
- if (d->richText) {
- d->ensureDoc();
- node->addTextDocument(bounds.topLeft(), d->doc, d->color, d->style, d->styleColor);
-
- } else {
- node->addTextLayout(QPoint(0, bounds.y()), &d->layout, d->color, d->style, d->styleColor);
- if (d->elipsisLayout)
- node->addTextLayout(QPoint(0, bounds.y()), d->elipsisLayout, d->color, d->style, d->styleColor);
- }
-
- return node;
- }
-}
-
-bool QQuickText::event(QEvent *e)
-{
- Q_D(QQuickText);
- if (e->type() == QEvent::User) {
- d->checkImageCache();
- return true;
- } else {
- return QQuickImplicitSizeItem::event(e);
- }
-}
-
-/*!
- \qmlproperty real QtQuick2::Text::paintedWidth
-
- Returns the width of the text, including width past the width
- which is covered due to insufficient wrapping if WrapMode is set.
-*/
-qreal QQuickText::paintedWidth() const
-{
- Q_D(const QQuickText);
- return d->paintedSize.width();
-}
-
-/*!
- \qmlproperty real QtQuick2::Text::paintedHeight
-
- Returns the height of the text, including height past the height
- which is covered due to there being more text than fits in the set height.
-*/
-qreal QQuickText::paintedHeight() const
-{
- Q_D(const QQuickText);
- return d->paintedSize.height();
-}
-
-/*!
- \qmlproperty real QtQuick2::Text::lineHeight
-
- Sets the line height for the text.
- The value can be in pixels or a multiplier depending on lineHeightMode.
-
- The default value is a multiplier of 1.0.
- The line height must be a positive value.
-*/
-qreal QQuickText::lineHeight() const
-{
- Q_D(const QQuickText);
- return d->lineHeight;
-}
-
-void QQuickText::setLineHeight(qreal lineHeight)
-{
- Q_D(QQuickText);
-
- if ((d->lineHeight == lineHeight) || (lineHeight < 0.0))
- return;
-
- d->lineHeight = lineHeight;
- d->updateLayout();
- emit lineHeightChanged(lineHeight);
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::Text::lineHeightMode
-
- This property determines how the line height is specified.
- The possible values are:
-
- \list
- \o Text.ProportionalHeight (default) - this sets the spacing proportional to the
- line (as a multiplier). For example, set to 2 for double spacing.
- \o Text.FixedHeight - this sets the line height to a fixed line height (in pixels).
- \endlist
-*/
-QQuickText::LineHeightMode QQuickText::lineHeightMode() const
-{
- Q_D(const QQuickText);
- return d->lineHeightMode;
-}
-
-void QQuickText::setLineHeightMode(LineHeightMode mode)
-{
- Q_D(QQuickText);
- if (mode == d->lineHeightMode)
- return;
-
- d->lineHeightMode = mode;
- d->updateLayout();
-
- emit lineHeightModeChanged(mode);
-}
-
-/*!
- Returns the number of resources (images) that are being loaded asynchronously.
-*/
-int QQuickText::resourcesLoading() const
-{
- Q_D(const QQuickText);
- return d->doc ? d->doc->resourcesLoading() : 0;
-}
-
-/*! \internal */
-void QQuickText::componentComplete()
-{
- Q_D(QQuickText);
- if (d->updateOnComponentComplete) {
- if (d->richText) {
- d->ensureDoc();
- d->doc->setText(d->text);
- d->rightToLeftText = d->doc->toPlainText().isRightToLeft();
- d->richTextAsImage = enableImageCache();
- } else {
- d->rightToLeftText = d->text.isRightToLeft();
- }
- d->determineHorizontalAlignment();
- }
- QQuickItem::componentComplete();
- if (d->updateOnComponentComplete)
- d->updateLayout();
-}
-
-
-QString QQuickTextPrivate::anchorAt(const QPointF &mousePos)
-{
- if (styledText) {
- for (int i = 0; i < layout.lineCount(); ++i) {
- QTextLine line = layout.lineAt(i);
- if (line.naturalTextRect().contains(mousePos)) {
- int charPos = line.xToCursor(mousePos.x());
- foreach (const QTextLayout::FormatRange &formatRange, layout.additionalFormats()) {
- if (formatRange.format.isAnchor()
- && charPos >= formatRange.start
- && charPos <= formatRange.start + formatRange.length) {
- return formatRange.format.anchorHref();
- }
- }
- break;
- }
- }
- }
- return QString();
-}
-
-bool QQuickTextPrivate::isLinkActivatedConnected()
-{
- static int idx = this->signalIndex("linkActivated(QString)");
- return this->isSignalConnected(idx);
-}
-
-/*! \internal */
-void QQuickText::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QQuickText);
-
- if (d->isLinkActivatedConnected()) {
- if (d->styledText)
- d->activeLink = d->anchorAt(event->localPos());
- else if (d->richText && d->doc)
- d->activeLink = d->doc->documentLayout()->anchorAt(event->localPos());
- }
-
- if (d->activeLink.isEmpty())
- event->setAccepted(false);
-
- // ### may malfunction if two of the same links are clicked & dragged onto each other)
-
- if (!event->isAccepted())
- QQuickItem::mousePressEvent(event);
-
-}
-
-/*! \internal */
-void QQuickText::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QQuickText);
-
- // ### confirm the link, and send a signal out
-
- QString link;
- if (d->isLinkActivatedConnected()) {
- if (d->styledText)
- link = d->anchorAt(event->localPos());
- else if (d->richText && d->doc)
- link = d->doc->documentLayout()->anchorAt(event->localPos());
- }
-
- if (!link.isEmpty() && d->activeLink == link)
- emit linkActivated(d->activeLink);
- else
- event->setAccepted(false);
-
- if (!event->isAccepted())
- QQuickItem::mouseReleaseEvent(event);
-}
-
-QT_END_NAMESPACE
-
-#include "qquicktext.moc"
diff --git a/src/declarative/items/qquicktext_p.h b/src/declarative/items/qquicktext_p.h
deleted file mode 100644
index be77f2eb45..0000000000
--- a/src/declarative/items/qquicktext_p.h
+++ /dev/null
@@ -1,252 +0,0 @@
-// Commit: 27e4302b7f45f22180693d26747f419177c81e27
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKTEXT_P_H
-#define QQUICKTEXT_P_H
-
-#include "qquickimplicitsizeitem_p.h"
-
-#include <private/qdeclarativeglobal_p.h>
-
-#include <QtGui/qtextoption.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-class QQuickTextPrivate;
-class QQuickTextLine;
-class Q_DECLARATIVE_PRIVATE_EXPORT QQuickText : public QQuickImplicitSizeItem
-{
- Q_OBJECT
- Q_ENUMS(HAlignment)
- Q_ENUMS(VAlignment)
- Q_ENUMS(TextStyle)
- Q_ENUMS(TextFormat)
- Q_ENUMS(TextElideMode)
- Q_ENUMS(WrapMode)
- Q_ENUMS(LineHeightMode)
-
- Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
- Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged)
- Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
- Q_PROPERTY(TextStyle style READ style WRITE setStyle NOTIFY styleChanged)
- Q_PROPERTY(QColor styleColor READ styleColor WRITE setStyleColor NOTIFY styleColorChanged)
- Q_PROPERTY(HAlignment horizontalAlignment READ hAlign WRITE setHAlign RESET resetHAlign NOTIFY horizontalAlignmentChanged)
- Q_PROPERTY(HAlignment effectiveHorizontalAlignment READ effectiveHAlign NOTIFY effectiveHorizontalAlignmentChanged)
- Q_PROPERTY(VAlignment verticalAlignment READ vAlign WRITE setVAlign NOTIFY verticalAlignmentChanged)
- Q_PROPERTY(WrapMode wrapMode READ wrapMode WRITE setWrapMode NOTIFY wrapModeChanged)
- Q_PROPERTY(int lineCount READ lineCount NOTIFY lineCountChanged)
- Q_PROPERTY(bool truncated READ truncated NOTIFY truncatedChanged)
- Q_PROPERTY(int maximumLineCount READ maximumLineCount WRITE setMaximumLineCount NOTIFY maximumLineCountChanged RESET resetMaximumLineCount)
-
- Q_PROPERTY(TextFormat textFormat READ textFormat WRITE setTextFormat NOTIFY textFormatChanged)
- Q_PROPERTY(TextElideMode elide READ elideMode WRITE setElideMode NOTIFY elideModeChanged) //### elideMode?
- Q_PROPERTY(qreal paintedWidth READ paintedWidth NOTIFY paintedSizeChanged)
- Q_PROPERTY(qreal paintedHeight READ paintedHeight NOTIFY paintedSizeChanged)
- Q_PROPERTY(qreal lineHeight READ lineHeight WRITE setLineHeight NOTIFY lineHeightChanged)
- Q_PROPERTY(LineHeightMode lineHeightMode READ lineHeightMode WRITE setLineHeightMode NOTIFY lineHeightModeChanged)
-
-public:
- QQuickText(QQuickItem *parent=0);
- ~QQuickText();
-
- enum HAlignment { AlignLeft = Qt::AlignLeft,
- AlignRight = Qt::AlignRight,
- AlignHCenter = Qt::AlignHCenter,
- AlignJustify = Qt::AlignJustify };
- enum VAlignment { AlignTop = Qt::AlignTop,
- AlignBottom = Qt::AlignBottom,
- AlignVCenter = Qt::AlignVCenter };
- enum TextStyle { Normal,
- Outline,
- Raised,
- Sunken };
- enum TextFormat { PlainText = Qt::PlainText,
- RichText = Qt::RichText,
- AutoText = Qt::AutoText,
- StyledText = 4 };
- enum TextElideMode { ElideLeft = Qt::ElideLeft,
- ElideRight = Qt::ElideRight,
- ElideMiddle = Qt::ElideMiddle,
- ElideNone = Qt::ElideNone };
-
- enum WrapMode { NoWrap = QTextOption::NoWrap,
- WordWrap = QTextOption::WordWrap,
- WrapAnywhere = QTextOption::WrapAnywhere,
- WrapAtWordBoundaryOrAnywhere = QTextOption::WrapAtWordBoundaryOrAnywhere, // COMPAT
- Wrap = QTextOption::WrapAtWordBoundaryOrAnywhere
- };
-
- enum LineHeightMode { ProportionalHeight, FixedHeight };
-
- QString text() const;
- void setText(const QString &);
-
- QFont font() const;
- void setFont(const QFont &font);
-
- QColor color() const;
- void setColor(const QColor &c);
-
- TextStyle style() const;
- void setStyle(TextStyle style);
-
- QColor styleColor() const;
- void setStyleColor(const QColor &c);
-
- HAlignment hAlign() const;
- void setHAlign(HAlignment align);
- void resetHAlign();
- HAlignment effectiveHAlign() const;
-
- VAlignment vAlign() const;
- void setVAlign(VAlignment align);
-
- WrapMode wrapMode() const;
- void setWrapMode(WrapMode w);
-
- int lineCount() const;
- bool truncated() const;
-
- int maximumLineCount() const;
- void setMaximumLineCount(int lines);
- void resetMaximumLineCount();
-
- TextFormat textFormat() const;
- void setTextFormat(TextFormat format);
-
- TextElideMode elideMode() const;
- void setElideMode(TextElideMode);
-
- qreal lineHeight() const;
- void setLineHeight(qreal lineHeight);
-
- LineHeightMode lineHeightMode() const;
- void setLineHeightMode(LineHeightMode);
-
- virtual void componentComplete();
-
- int resourcesLoading() const; // mainly for testing
-
- qreal paintedWidth() const;
- qreal paintedHeight() const;
-
- QRectF boundingRect() const;
- Q_INVOKABLE void doLayout();
-
-Q_SIGNALS:
- void textChanged(const QString &text);
- void linkActivated(const QString &link);
- void fontChanged(const QFont &font);
- void colorChanged(const QColor &color);
- void styleChanged(TextStyle style);
- void styleColorChanged(const QColor &color);
- void horizontalAlignmentChanged(HAlignment alignment);
- void verticalAlignmentChanged(VAlignment alignment);
- void wrapModeChanged();
- void lineCountChanged();
- void truncatedChanged();
- void maximumLineCountChanged();
- void textFormatChanged(TextFormat textFormat);
- void elideModeChanged(TextElideMode mode);
- void paintedSizeChanged();
- void lineHeightChanged(qreal lineHeight);
- void lineHeightModeChanged(LineHeightMode mode);
- void effectiveHorizontalAlignmentChanged();
- void lineLaidOut(QQuickTextLine *line);
-
-protected:
- void mousePressEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- virtual void geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry);
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
- virtual bool event(QEvent *);
-
-private:
- Q_DISABLE_COPY(QQuickText)
- Q_DECLARE_PRIVATE(QQuickText)
-};
-
-class QTextLine;
-class Q_AUTOTEST_EXPORT QQuickTextLine : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(int number READ number)
- Q_PROPERTY(qreal width READ width WRITE setWidth)
- Q_PROPERTY(qreal height READ height WRITE setHeight)
- Q_PROPERTY(qreal x READ x WRITE setX)
- Q_PROPERTY(qreal y READ y WRITE setY)
-
-public:
- QQuickTextLine();
-
- void setLine(QTextLine* line);
- int number() const;
-
- qreal width() const;
- void setWidth(qreal width);
-
- qreal height() const;
- void setHeight(qreal height);
-
- qreal x() const;
- void setX(qreal x);
-
- qreal y() const;
- void setY(qreal y);
-
-private:
- QTextLine *m_line;
- qreal m_height;
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickText)
-QML_DECLARE_TYPE(QQuickTextLine)
-
-QT_END_HEADER
-
-#endif // QQUICKTEXT_P_H
diff --git a/src/declarative/items/qquicktext_p_p.h b/src/declarative/items/qquicktext_p_p.h
deleted file mode 100644
index 2035f47a9d..0000000000
--- a/src/declarative/items/qquicktext_p_p.h
+++ /dev/null
@@ -1,169 +0,0 @@
-// Commit: 6e5a642c9484536fc173714f560f739944368cf5
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKTEXT_P_P_H
-#define QQUICKTEXT_P_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 "qquickitem.h"
-#include "qquickimplicitsizeitem_p_p.h"
-
-#include <QtDeclarative/qdeclarative.h>
-#include <QtGui/qtextlayout.h>
-
-QT_BEGIN_NAMESPACE
-
-class QTextLayout;
-class QQuickTextDocumentWithImageResources;
-class QSGPlainTexture;
-
-class Q_AUTOTEST_EXPORT QQuickTextPrivate : public QQuickImplicitSizeItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickText)
-public:
- QQuickTextPrivate();
- ~QQuickTextPrivate();
- void init();
-
- void updateSize();
- void updateLayout();
- bool determineHorizontalAlignment();
- bool setHAlign(QQuickText::HAlignment, bool forceAlign = false);
- void mirrorChange();
- QTextDocument *textDocument();
- bool isLineLaidOutConnected();
-
- QString text;
- QFont font;
- QFont sourceFont;
- QColor color;
- QQuickText::TextStyle style;
- QColor styleColor;
- QString activeLink;
- QQuickText::HAlignment hAlign;
- QQuickText::VAlignment vAlign;
- QQuickText::TextElideMode elideMode;
- QQuickText::TextFormat format;
- QQuickText::WrapMode wrapMode;
- qreal lineHeight;
- QQuickText::LineHeightMode lineHeightMode;
- int lineCount;
- int maximumLineCount;
- int maximumLineCountValid;
- QPointF elidePos;
-
- static QString elideChar;
-
- void invalidateImageCache();
- void checkImageCache();
- QPixmap imageCache;
- QSGTexture *texture;
-
- bool imageCacheDirty:1;
- bool updateOnComponentComplete:1;
- bool richText:1;
- bool styledText:1;
- bool singleline:1;
- bool cacheAllTextAsImage:1;
- bool internalWidthUpdate:1;
- bool requireImplicitWidth:1;
- bool truncated:1;
- bool hAlignImplicit:1;
- bool rightToLeftText:1;
- bool layoutTextElided:1;
- bool richTextAsImage:1;
- bool textureImageCacheDirty:1;
- bool textHasChanged:1;
-
- QRect layedOutTextRect;
- QSize paintedSize;
- qreal naturalWidth;
- virtual qreal getImplicitWidth() const;
-
- void ensureDoc();
- QPixmap textDocumentImage(bool drawStyle);
- QQuickTextDocumentWithImageResources *doc;
-
- QRect setupTextLayout();
- void setupCustomLineGeometry(QTextLine &line, qreal &height, qreal elideWidth);
- QPixmap textLayoutImage(bool drawStyle);
- void drawTextLayout(QPainter *p, const QPointF &pos, bool drawStyle);
- bool isLinkActivatedConnected();
- QString anchorAt(const QPointF &pos);
- QTextLayout layout;
- QTextLayout *elipsisLayout;
- QList<QRectF> linesRects;
- QQuickTextLine *textLine;
-
- static QPixmap drawOutline(const QPixmap &source, const QPixmap &styleSource);
- static QPixmap drawOutline(const QPixmap &source, const QPixmap &styleSource, int yOffset);
-
- static inline QQuickTextPrivate *get(QQuickText *t) {
- return t->d_func();
- }
-
- enum NodeType {
- NodeIsNull,
- NodeIsTexture,
- NodeIsText
- };
- NodeType nodeType;
-
-#if defined(Q_OS_MAC)
- QThread *layoutThread;
- QThread *paintingThread;
-#endif
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKTEXT_P_P_H
diff --git a/src/declarative/items/qquicktextedit.cpp b/src/declarative/items/qquicktextedit.cpp
deleted file mode 100644
index b40b5c09a1..0000000000
--- a/src/declarative/items/qquicktextedit.cpp
+++ /dev/null
@@ -1,2091 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquicktextedit_p.h"
-#include "qquicktextedit_p_p.h"
-#include "qquickevents_p_p.h"
-#include "qquickcanvas.h"
-#include "qquicktextnode_p.h"
-#include "qsgsimplerectnode.h"
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtGui/qguiapplication.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qpainter.h>
-#include <QtGui/qtextobject.h>
-#include <QtCore/qmath.h>
-
-#include <private/qdeclarativeglobal_p.h>
-#include <private/qtextcontrol_p.h>
-#include <private/qtextengine_p.h>
-#include <private/qsgtexture_p.h>
-#include <private/qsgadaptationlayer_p.h>
-
-QT_BEGIN_NAMESPACE
-
-DEFINE_BOOL_CONFIG_OPTION(qmlDisableDistanceField, QML_DISABLE_DISTANCEFIELD)
-DEFINE_BOOL_CONFIG_OPTION(qmlEnableImageCache, QML_ENABLE_TEXT_IMAGE_CACHE)
-
-/*!
- \qmlclass TextEdit QQuickTextEdit
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
- \brief The TextEdit item displays multiple lines of editable formatted text.
- \inherits Item
-
- The TextEdit item displays a block of editable, formatted text.
-
- It can display both plain and rich text. For example:
-
- \qml
-TextEdit {
- width: 240
- text: "<b>Hello</b> <i>World!</i>"
- font.family: "Helvetica"
- font.pointSize: 20
- color: "blue"
- focus: true
-}
- \endqml
-
- \image declarative-textedit.gif
-
- Setting \l {Item::focus}{focus} to \c true enables the TextEdit item to receive keyboard focus.
-
- Note that the TextEdit does not implement scrolling, following the cursor, or other behaviors specific
- to a look-and-feel. For example, to add flickable scrolling that follows the cursor:
-
- \snippet snippets/declarative/texteditor.qml 0
-
- A particular look-and-feel might use smooth scrolling (eg. using SmoothedFollow), might have a visible
- scrollbar, or a scrollbar that fades in to show location, etc.
-
- Clipboard support is provided by the cut(), copy(), and paste() functions, and the selection can
- be handled in a traditional "mouse" mechanism by setting selectByMouse, or handled completely
- from QML by manipulating selectionStart and selectionEnd, or using selectAll() or selectWord().
-
- You can translate between cursor positions (characters from the start of the document) and pixel
- points using positionAt() and positionToRectangle().
-
- \sa Text, TextInput, {declarative/text/textselection}{Text Selection example}
-*/
-
-/*!
- \qmlsignal QtQuick2::TextEdit::onLinkActivated(string link)
-
- This handler is called when the user clicks on a link embedded in the text.
- The link must be in rich text or HTML format and the
- \a link string provides access to the particular link.
-*/
-QQuickTextEdit::QQuickTextEdit(QQuickItem *parent)
-: QQuickImplicitSizeItem(*(new QQuickTextEditPrivate), parent)
-{
- Q_D(QQuickTextEdit);
- d->init();
-}
-
-QString QQuickTextEdit::text() const
-{
- Q_D(const QQuickTextEdit);
-
-#ifndef QT_NO_TEXTHTMLPARSER
- if (d->richText)
- return d->document->toHtml();
- else
-#endif
- return d->document->toPlainText();
-}
-
-/*!
- \qmlproperty string QtQuick2::TextEdit::font.family
-
- Sets the family name of the font.
-
- The family name is case insensitive and may optionally include a foundry name, e.g. "Helvetica [Cronyx]".
- If the family is available from more than one foundry and the foundry isn't specified, an arbitrary foundry is chosen.
- If the family isn't available a family will be set using the font matching algorithm.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::font.bold
-
- Sets whether the font weight is bold.
-*/
-
-/*!
- \qmlproperty enumeration QtQuick2::TextEdit::font.weight
-
- Sets the font's weight.
-
- The weight can be one of:
- \list
- \o Font.Light
- \o Font.Normal - the default
- \o Font.DemiBold
- \o Font.Bold
- \o Font.Black
- \endlist
-
- \qml
- TextEdit { text: "Hello"; font.weight: Font.DemiBold }
- \endqml
-*/
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::font.italic
-
- Sets whether the font has an italic style.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::font.underline
-
- Sets whether the text is underlined.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::font.strikeout
-
- Sets whether the font has a strikeout style.
-*/
-
-/*!
- \qmlproperty real QtQuick2::TextEdit::font.pointSize
-
- Sets the font size in points. The point size must be greater than zero.
-*/
-
-/*!
- \qmlproperty int QtQuick2::TextEdit::font.pixelSize
-
- Sets the font size in pixels.
-
- Using this function makes the font device dependent. Use
- \l{TextEdit::font.pointSize} to set the size of the font in a
- device independent manner.
-*/
-
-/*!
- \qmlproperty real QtQuick2::TextEdit::font.letterSpacing
-
- Sets the letter spacing for the font.
-
- Letter spacing changes the default spacing between individual letters in the font.
- A positive value increases the letter spacing by the corresponding pixels; a negative value decreases the spacing.
-*/
-
-/*!
- \qmlproperty real QtQuick2::TextEdit::font.wordSpacing
-
- Sets the word spacing for the font.
-
- Word spacing changes the default spacing between individual words.
- A positive value increases the word spacing by a corresponding amount of pixels,
- while a negative value decreases the inter-word spacing accordingly.
-*/
-
-/*!
- \qmlproperty enumeration QtQuick2::TextEdit::font.capitalization
-
- Sets the capitalization for the text.
-
- \list
- \o Font.MixedCase - This is the normal text rendering option where no capitalization change is applied.
- \o Font.AllUppercase - This alters the text to be rendered in all uppercase type.
- \o Font.AllLowercase - This alters the text to be rendered in all lowercase type.
- \o Font.SmallCaps - This alters the text to be rendered in small-caps type.
- \o Font.Capitalize - This alters the text to be rendered with the first character of each word as an uppercase character.
- \endlist
-
- \qml
- TextEdit { text: "Hello"; font.capitalization: Font.AllLowercase }
- \endqml
-*/
-
-/*!
- \qmlproperty string QtQuick2::TextEdit::text
-
- The text to display. If the text format is AutoText the text edit will
- automatically determine whether the text should be treated as
- rich text. This determination is made using Qt::mightBeRichText().
-*/
-void QQuickTextEdit::setText(const QString &text)
-{
- Q_D(QQuickTextEdit);
- if (QQuickTextEdit::text() == text)
- return;
-
- d->richText = d->format == RichText || (d->format == AutoText && Qt::mightBeRichText(text));
- if (d->richText) {
-#ifndef QT_NO_TEXTHTMLPARSER
- d->control->setHtml(text);
-#else
- d->control->setPlainText(text);
-#endif
- d->useImageFallback = qmlEnableImageCache();
- } else {
- d->control->setPlainText(text);
- }
- q_textChanged();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::TextEdit::textFormat
-
- The way the text property should be displayed.
-
- \list
- \o TextEdit.AutoText
- \o TextEdit.PlainText
- \o TextEdit.RichText
- \endlist
-
- The default is TextEdit.AutoText. If the text format is TextEdit.AutoText the text edit
- will automatically determine whether the text should be treated as
- rich text. This determination is made using Qt::mightBeRichText().
-
- \table
- \row
- \o
- \qml
-Column {
- TextEdit {
- font.pointSize: 24
- text: "<b>Hello</b> <i>World!</i>"
- }
- TextEdit {
- font.pointSize: 24
- textFormat: TextEdit.RichText
- text: "<b>Hello</b> <i>World!</i>"
- }
- TextEdit {
- font.pointSize: 24
- textFormat: TextEdit.PlainText
- text: "<b>Hello</b> <i>World!</i>"
- }
-}
- \endqml
- \o \image declarative-textformat.png
- \endtable
-*/
-QQuickTextEdit::TextFormat QQuickTextEdit::textFormat() const
-{
- Q_D(const QQuickTextEdit);
- return d->format;
-}
-
-void QQuickTextEdit::setTextFormat(TextFormat format)
-{
- Q_D(QQuickTextEdit);
- if (format == d->format)
- return;
- bool wasRich = d->richText;
- d->richText = format == RichText || (format == AutoText && Qt::mightBeRichText(d->text));
-
- if (wasRich && !d->richText) {
- d->control->setPlainText(d->text);
- updateSize();
- } else if (!wasRich && d->richText) {
-#ifndef QT_NO_TEXTHTMLPARSER
- d->control->setHtml(d->text);
-#else
- d->control->setPlainText(d->text);
-#endif
- updateSize();
- d->useImageFallback = qmlEnableImageCache();
- }
- d->format = format;
- d->control->setAcceptRichText(d->format != PlainText);
- emit textFormatChanged(d->format);
-}
-
-QFont QQuickTextEdit::font() const
-{
- Q_D(const QQuickTextEdit);
- return d->sourceFont;
-}
-
-void QQuickTextEdit::setFont(const QFont &font)
-{
- Q_D(QQuickTextEdit);
- if (d->sourceFont == font)
- return;
-
- d->sourceFont = font;
- QFont oldFont = d->font;
- d->font = font;
- if (d->font.pointSizeF() != -1) {
- // 0.5pt resolution
- qreal size = qRound(d->font.pointSizeF()*2.0);
- d->font.setPointSizeF(size/2.0);
- }
-
- if (oldFont != d->font) {
- d->document->setDefaultFont(d->font);
- if (d->cursor) {
- d->cursor->setHeight(QFontMetrics(d->font).height());
- moveCursorDelegate();
- }
- updateSize();
- updateDocument();
- }
- emit fontChanged(d->sourceFont);
-}
-
-/*!
- \qmlproperty color QtQuick2::TextEdit::color
-
- The text color.
-
- \qml
- // green text using hexadecimal notation
- TextEdit { color: "#00FF00" }
- \endqml
-
- \qml
- // steelblue text using SVG color name
- TextEdit { color: "steelblue" }
- \endqml
-*/
-QColor QQuickTextEdit::color() const
-{
- Q_D(const QQuickTextEdit);
- return d->color;
-}
-
-void QQuickTextEdit::setColor(const QColor &color)
-{
- Q_D(QQuickTextEdit);
- if (d->color == color)
- return;
-
- d->color = color;
- QPalette pal = d->control->palette();
- pal.setColor(QPalette::Text, color);
- d->control->setPalette(pal);
- updateDocument();
- emit colorChanged(d->color);
-}
-
-/*!
- \qmlproperty color QtQuick2::TextEdit::selectionColor
-
- The text highlight color, used behind selections.
-*/
-QColor QQuickTextEdit::selectionColor() const
-{
- Q_D(const QQuickTextEdit);
- return d->selectionColor;
-}
-
-void QQuickTextEdit::setSelectionColor(const QColor &color)
-{
- Q_D(QQuickTextEdit);
- if (d->selectionColor == color)
- return;
-
- d->selectionColor = color;
- QPalette pal = d->control->palette();
- pal.setColor(QPalette::Highlight, color);
- d->control->setPalette(pal);
- updateDocument();
- emit selectionColorChanged(d->selectionColor);
-}
-
-/*!
- \qmlproperty color QtQuick2::TextEdit::selectedTextColor
-
- The selected text color, used in selections.
-*/
-QColor QQuickTextEdit::selectedTextColor() const
-{
- Q_D(const QQuickTextEdit);
- return d->selectedTextColor;
-}
-
-void QQuickTextEdit::setSelectedTextColor(const QColor &color)
-{
- Q_D(QQuickTextEdit);
- if (d->selectedTextColor == color)
- return;
-
- d->selectedTextColor = color;
- QPalette pal = d->control->palette();
- pal.setColor(QPalette::HighlightedText, color);
- d->control->setPalette(pal);
- updateDocument();
- emit selectedTextColorChanged(d->selectedTextColor);
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::TextEdit::horizontalAlignment
- \qmlproperty enumeration QtQuick2::TextEdit::verticalAlignment
- \qmlproperty enumeration QtQuick2::TextEdit::effectiveHorizontalAlignment
-
- Sets the horizontal and vertical alignment of the text within the TextEdit item's
- width and height. By default, the text alignment follows the natural alignment
- of the text, for example text that is read from left to right will be aligned to
- the left.
-
- Valid values for \c horizontalAlignment are:
- \list
- \o TextEdit.AlignLeft (default)
- \o TextEdit.AlignRight
- \o TextEdit.AlignHCenter
- \o TextEdit.AlignJustify
- \endlist
-
- Valid values for \c verticalAlignment are:
- \list
- \o TextEdit.AlignTop (default)
- \o TextEdit.AlignBottom
- \o TextEdit.AlignVCenter
- \endlist
-
- When using the attached property LayoutMirroring::enabled to mirror application
- layouts, the horizontal alignment of text will also be mirrored. However, the property
- \c horizontalAlignment will remain unchanged. To query the effective horizontal alignment
- of TextEdit, use the read-only property \c effectiveHorizontalAlignment.
-*/
-QQuickTextEdit::HAlignment QQuickTextEdit::hAlign() const
-{
- Q_D(const QQuickTextEdit);
- return d->hAlign;
-}
-
-void QQuickTextEdit::setHAlign(HAlignment align)
-{
- Q_D(QQuickTextEdit);
- bool forceAlign = d->hAlignImplicit && d->effectiveLayoutMirror;
- d->hAlignImplicit = false;
- if (d->setHAlign(align, forceAlign) && isComponentComplete()) {
- d->updateDefaultTextOption();
- updateSize();
- }
-}
-
-void QQuickTextEdit::resetHAlign()
-{
- Q_D(QQuickTextEdit);
- d->hAlignImplicit = true;
- if (d->determineHorizontalAlignment() && isComponentComplete()) {
- d->updateDefaultTextOption();
- updateSize();
- }
-}
-
-QQuickTextEdit::HAlignment QQuickTextEdit::effectiveHAlign() const
-{
- Q_D(const QQuickTextEdit);
- QQuickTextEdit::HAlignment effectiveAlignment = d->hAlign;
- if (!d->hAlignImplicit && d->effectiveLayoutMirror) {
- switch (d->hAlign) {
- case QQuickTextEdit::AlignLeft:
- effectiveAlignment = QQuickTextEdit::AlignRight;
- break;
- case QQuickTextEdit::AlignRight:
- effectiveAlignment = QQuickTextEdit::AlignLeft;
- break;
- default:
- break;
- }
- }
- return effectiveAlignment;
-}
-
-bool QQuickTextEditPrivate::setHAlign(QQuickTextEdit::HAlignment alignment, bool forceAlign)
-{
- Q_Q(QQuickTextEdit);
- if (hAlign != alignment || forceAlign) {
- QQuickTextEdit::HAlignment oldEffectiveHAlign = q->effectiveHAlign();
- hAlign = alignment;
- emit q->horizontalAlignmentChanged(alignment);
- if (oldEffectiveHAlign != q->effectiveHAlign())
- emit q->effectiveHorizontalAlignmentChanged();
- return true;
- }
- return false;
-}
-
-bool QQuickTextEditPrivate::determineHorizontalAlignment()
-{
- Q_Q(QQuickTextEdit);
- if (hAlignImplicit && q->isComponentComplete()) {
- bool alignToRight;
- if (text.isEmpty()) {
- const QString preeditText = control->textCursor().block().layout()->preeditAreaText();
- alignToRight = preeditText.isEmpty()
- ? QGuiApplication::keyboardInputDirection() == Qt::RightToLeft
- : preeditText.isRightToLeft();
- } else {
- alignToRight = rightToLeftText;
- }
- return setHAlign(alignToRight ? QQuickTextEdit::AlignRight : QQuickTextEdit::AlignLeft);
- }
- return false;
-}
-
-void QQuickTextEditPrivate::mirrorChange()
-{
- Q_Q(QQuickTextEdit);
- if (q->isComponentComplete()) {
- if (!hAlignImplicit && (hAlign == QQuickTextEdit::AlignRight || hAlign == QQuickTextEdit::AlignLeft)) {
- updateDefaultTextOption();
- q->updateSize();
- emit q->effectiveHorizontalAlignmentChanged();
- }
- }
-}
-
-QQuickTextEdit::VAlignment QQuickTextEdit::vAlign() const
-{
- Q_D(const QQuickTextEdit);
- return d->vAlign;
-}
-
-void QQuickTextEdit::setVAlign(QQuickTextEdit::VAlignment alignment)
-{
- Q_D(QQuickTextEdit);
- if (alignment == d->vAlign)
- return;
- d->vAlign = alignment;
- d->updateDefaultTextOption();
- updateSize();
- moveCursorDelegate();
- emit verticalAlignmentChanged(d->vAlign);
-}
-/*!
- \qmlproperty enumeration QtQuick2::TextEdit::wrapMode
-
- Set this property to wrap the text to the TextEdit item's width.
- The text will only wrap if an explicit width has been set.
-
- \list
- \o TextEdit.NoWrap - no wrapping will be performed. If the text contains insufficient newlines, then implicitWidth will exceed a set width.
- \o TextEdit.WordWrap - wrapping is done on word boundaries only. If a word is too long, implicitWidth will exceed a set width.
- \o TextEdit.WrapAnywhere - wrapping is done at any point on a line, even if it occurs in the middle of a word.
- \o TextEdit.Wrap - if possible, wrapping occurs at a word boundary; otherwise it will occur at the appropriate point on the line, even in the middle of a word.
- \endlist
-
- The default is TextEdit.NoWrap. If you set a width, consider using TextEdit.Wrap.
-*/
-QQuickTextEdit::WrapMode QQuickTextEdit::wrapMode() const
-{
- Q_D(const QQuickTextEdit);
- return d->wrapMode;
-}
-
-void QQuickTextEdit::setWrapMode(WrapMode mode)
-{
- Q_D(QQuickTextEdit);
- if (mode == d->wrapMode)
- return;
- d->wrapMode = mode;
- d->updateDefaultTextOption();
- updateSize();
- emit wrapModeChanged();
-}
-
-/*!
- \qmlproperty int QtQuick2::TextEdit::lineCount
-
- Returns the total number of lines in the textEdit item.
-*/
-int QQuickTextEdit::lineCount() const
-{
- Q_D(const QQuickTextEdit);
- return d->lineCount;
-}
-
-/*!
- \qmlproperty int QtQuick2::TextEdit::length
-
- Returns the total number of plain text characters in the TextEdit item.
-
- As this number doesn't include any formatting markup it may not be the same as the
- length of the string returned by the \l text property.
-
- This property can be faster than querying the length the \l text property as it doesn't
- require any copying or conversion of the TextEdit's internal string data.
-*/
-
-int QQuickTextEdit::length() const
-{
- Q_D(const QQuickTextEdit);
- // QTextDocument::characterCount() includes the terminating null character.
- return qMax(0, d->document->characterCount() - 1);
-}
-
-/*!
- \qmlproperty real QtQuick2::TextEdit::paintedWidth
-
- Returns the width of the text, including the width past the width
- which is covered due to insufficient wrapping if \l wrapMode is set.
-*/
-qreal QQuickTextEdit::paintedWidth() const
-{
- Q_D(const QQuickTextEdit);
- return d->paintedSize.width();
-}
-
-/*!
- \qmlproperty real QtQuick2::TextEdit::paintedHeight
-
- Returns the height of the text, including the height past the height
- that is covered if the text does not fit within the set height.
-*/
-qreal QQuickTextEdit::paintedHeight() const
-{
- Q_D(const QQuickTextEdit);
- return d->paintedSize.height();
-}
-
-/*!
- \qmlmethod rectangle QtQuick2::TextEdit::positionToRectangle(position)
-
- Returns the rectangle at the given \a position in the text. The x, y,
- and height properties correspond to the cursor that would describe
- that position.
-*/
-QRectF QQuickTextEdit::positionToRectangle(int pos) const
-{
- Q_D(const QQuickTextEdit);
- QTextCursor c(d->document);
- c.setPosition(pos);
- return d->control->cursorRect(c);
-
-}
-
-/*!
- \qmlmethod int QtQuick2::TextEdit::positionAt(int x, int y)
-
- Returns the text position closest to pixel position (\a x, \a y).
-
- Position 0 is before the first character, position 1 is after the first character
- but before the second, and so on until position \l {text}.length, which is after all characters.
-*/
-int QQuickTextEdit::positionAt(int x, int y) const
-{
- Q_D(const QQuickTextEdit);
- int r = d->document->documentLayout()->hitTest(QPoint(x,y-d->yoff), Qt::FuzzyHit);
- QTextCursor cursor = d->control->textCursor();
- if (r > cursor.position()) {
- // The cursor position includes positions within the preedit text, but only positions in the
- // same text block are offset so it is possible to get a position that is either part of the
- // preedit or the next text block.
- QTextLayout *layout = cursor.block().layout();
- const int preeditLength = layout
- ? layout->preeditAreaText().length()
- : 0;
- if (preeditLength > 0
- && d->document->documentLayout()->blockBoundingRect(cursor.block()).contains(x,y-d->yoff)) {
- r = r > cursor.position() + preeditLength
- ? r - preeditLength
- : cursor.position();
- }
- }
- return r;
-}
-
-/*!
- \qmlmethod void QtQuick2::TextEdit::moveCursorSelection(int position, SelectionMode mode = TextEdit.SelectCharacters)
-
- Moves the cursor to \a position and updates the selection according to the optional \a mode
- parameter. (To only move the cursor, set the \l cursorPosition property.)
-
- When this method is called it additionally sets either the
- selectionStart or the selectionEnd (whichever was at the previous cursor position)
- to the specified position. This allows you to easily extend and contract the selected
- text range.
-
- The selection mode specifies whether the selection is updated on a per character or a per word
- basis. If not specified the selection mode will default to TextEdit.SelectCharacters.
-
- \list
- \o TextEdit.SelectCharacters - Sets either the selectionStart or selectionEnd (whichever was at
- the previous cursor position) to the specified position.
- \o TextEdit.SelectWords - Sets the selectionStart and selectionEnd to include all
- words between the specified position and the previous cursor position. Words partially in the
- range are included.
- \endlist
-
- For example, take this sequence of calls:
-
- \code
- cursorPosition = 5
- moveCursorSelection(9, TextEdit.SelectCharacters)
- moveCursorSelection(7, TextEdit.SelectCharacters)
- \endcode
-
- This moves the cursor to position 5, extend the selection end from 5 to 9
- and then retract the selection end from 9 to 7, leaving the text from position 5 to 7
- selected (the 6th and 7th characters).
-
- The same sequence with TextEdit.SelectWords will extend the selection start to a word boundary
- before or on position 5 and extend the selection end to a word boundary on or past position 9.
-*/
-void QQuickTextEdit::moveCursorSelection(int pos)
-{
- //Note that this is the same as setCursorPosition but with the KeepAnchor flag set
- Q_D(QQuickTextEdit);
- QTextCursor cursor = d->control->textCursor();
- if (cursor.position() == pos)
- return;
- cursor.setPosition(pos, QTextCursor::KeepAnchor);
- d->control->setTextCursor(cursor);
-}
-
-void QQuickTextEdit::moveCursorSelection(int pos, SelectionMode mode)
-{
- Q_D(QQuickTextEdit);
- QTextCursor cursor = d->control->textCursor();
- if (cursor.position() == pos)
- return;
- if (mode == SelectCharacters) {
- cursor.setPosition(pos, QTextCursor::KeepAnchor);
- } else if (cursor.anchor() < pos || (cursor.anchor() == pos && cursor.position() < pos)) {
- if (cursor.anchor() > cursor.position()) {
- cursor.setPosition(cursor.anchor(), QTextCursor::MoveAnchor);
- cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor);
- if (cursor.position() == cursor.anchor())
- cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::MoveAnchor);
- else
- cursor.setPosition(cursor.position(), QTextCursor::MoveAnchor);
- } else {
- cursor.setPosition(cursor.anchor(), QTextCursor::MoveAnchor);
- cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
- }
-
- cursor.setPosition(pos, QTextCursor::KeepAnchor);
- cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor);
- if (cursor.position() != pos)
- cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
- } else if (cursor.anchor() > pos || (cursor.anchor() == pos && cursor.position() > pos)) {
- if (cursor.anchor() < cursor.position()) {
- cursor.setPosition(cursor.anchor(), QTextCursor::MoveAnchor);
- cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::MoveAnchor);
- } else {
- cursor.setPosition(cursor.anchor(), QTextCursor::MoveAnchor);
- cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
- cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
- if (cursor.position() != cursor.anchor()) {
- cursor.setPosition(cursor.anchor(), QTextCursor::MoveAnchor);
- cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::MoveAnchor);
- }
- }
-
- cursor.setPosition(pos, QTextCursor::KeepAnchor);
- cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
- if (cursor.position() != pos) {
- cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
- cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor);
- }
- }
- d->control->setTextCursor(cursor);
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::cursorVisible
- If true the text edit shows a cursor.
-
- This property is set and unset when the text edit gets active focus, but it can also
- be set directly (useful, for example, if a KeyProxy might forward keys to it).
-*/
-bool QQuickTextEdit::isCursorVisible() const
-{
- Q_D(const QQuickTextEdit);
- return d->cursorVisible;
-}
-
-void QQuickTextEdit::setCursorVisible(bool on)
-{
- Q_D(QQuickTextEdit);
- if (d->cursorVisible == on)
- return;
- d->cursorVisible = on;
- QFocusEvent focusEvent(on ? QEvent::FocusIn : QEvent::FocusOut);
- if (!on && !d->persistentSelection)
- d->control->setCursorIsFocusIndicator(true);
- d->control->processEvent(&focusEvent, QPointF(0, -d->yoff));
- emit cursorVisibleChanged(d->cursorVisible);
-}
-
-/*!
- \qmlproperty int QtQuick2::TextEdit::cursorPosition
- The position of the cursor in the TextEdit.
-*/
-int QQuickTextEdit::cursorPosition() const
-{
- Q_D(const QQuickTextEdit);
- return d->control->textCursor().position();
-}
-
-void QQuickTextEdit::setCursorPosition(int pos)
-{
- Q_D(QQuickTextEdit);
- if (pos < 0 || pos > d->text.length())
- return;
- QTextCursor cursor = d->control->textCursor();
- if (cursor.position() == pos && cursor.anchor() == pos)
- return;
- cursor.setPosition(pos);
- d->control->setTextCursor(cursor);
-}
-
-/*!
- \qmlproperty Component QtQuick2::TextEdit::cursorDelegate
- The delegate for the cursor in the TextEdit.
-
- If you set a cursorDelegate for a TextEdit, this delegate will be used for
- drawing the cursor instead of the standard cursor. An instance of the
- delegate will be created and managed by the text edit when a cursor is
- needed, and the x and y properties of delegate instance will be set so as
- to be one pixel before the top left of the current character.
-
- Note that the root item of the delegate component must be a QDeclarativeItem or
- QDeclarativeItem derived item.
-*/
-QDeclarativeComponent* QQuickTextEdit::cursorDelegate() const
-{
- Q_D(const QQuickTextEdit);
- return d->cursorComponent;
-}
-
-void QQuickTextEdit::setCursorDelegate(QDeclarativeComponent* c)
-{
- Q_D(QQuickTextEdit);
- if (d->cursorComponent) {
- if (d->cursor) {
- d->control->setCursorWidth(-1);
- updateCursor();
- delete d->cursor;
- d->cursor = 0;
- }
- }
- d->cursorComponent = c;
- if (c && c->isReady()) {
- loadCursorDelegate();
- } else {
- if (c)
- connect(c, SIGNAL(statusChanged()),
- this, SLOT(loadCursorDelegate()));
- }
-
- emit cursorDelegateChanged();
-}
-
-void QQuickTextEdit::loadCursorDelegate()
-{
- Q_D(QQuickTextEdit);
- if (d->cursorComponent->isLoading())
- return;
- QDeclarativeContext *creationContext = d->cursorComponent->creationContext();
- QObject *object = d->cursorComponent->create(creationContext ? creationContext : qmlContext(this));
- d->cursor = qobject_cast<QQuickItem*>(object);
- if (d->cursor) {
- d->control->setCursorWidth(0);
- updateCursor();
- QDeclarative_setParent_noEvent(d->cursor, this);
- d->cursor->setParentItem(this);
- d->cursor->setHeight(QFontMetrics(d->font).height());
- moveCursorDelegate();
- }else{
- delete object;
- qmlInfo(this) << "Error loading cursor delegate.";
- }
-}
-
-/*!
- \qmlproperty int QtQuick2::TextEdit::selectionStart
-
- The cursor position before the first character in the current selection.
-
- This property is read-only. To change the selection, use select(start,end),
- selectAll(), or selectWord().
-
- \sa selectionEnd, cursorPosition, selectedText
-*/
-int QQuickTextEdit::selectionStart() const
-{
- Q_D(const QQuickTextEdit);
- return d->control->textCursor().selectionStart();
-}
-
-/*!
- \qmlproperty int QtQuick2::TextEdit::selectionEnd
-
- The cursor position after the last character in the current selection.
-
- This property is read-only. To change the selection, use select(start,end),
- selectAll(), or selectWord().
-
- \sa selectionStart, cursorPosition, selectedText
-*/
-int QQuickTextEdit::selectionEnd() const
-{
- Q_D(const QQuickTextEdit);
- return d->control->textCursor().selectionEnd();
-}
-
-/*!
- \qmlproperty string QtQuick2::TextEdit::selectedText
-
- This read-only property provides the text currently selected in the
- text edit.
-
- It is equivalent to the following snippet, but is faster and easier
- to use.
- \code
- //myTextEdit is the id of the TextEdit
- myTextEdit.text.toString().substring(myTextEdit.selectionStart,
- myTextEdit.selectionEnd);
- \endcode
-*/
-QString QQuickTextEdit::selectedText() const
-{
- Q_D(const QQuickTextEdit);
- return d->control->textCursor().selectedText();
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::activeFocusOnPress
-
- Whether the TextEdit should gain active focus on a mouse press. By default this is
- set to true.
-*/
-bool QQuickTextEdit::focusOnPress() const
-{
- Q_D(const QQuickTextEdit);
- return d->focusOnPress;
-}
-
-void QQuickTextEdit::setFocusOnPress(bool on)
-{
- Q_D(QQuickTextEdit);
- if (d->focusOnPress == on)
- return;
- d->focusOnPress = on;
- emit activeFocusOnPressChanged(d->focusOnPress);
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::persistentSelection
-
- Whether the TextEdit should keep the selection visible when it loses active focus to another
- item in the scene. By default this is set to true;
-*/
-bool QQuickTextEdit::persistentSelection() const
-{
- Q_D(const QQuickTextEdit);
- return d->persistentSelection;
-}
-
-void QQuickTextEdit::setPersistentSelection(bool on)
-{
- Q_D(QQuickTextEdit);
- if (d->persistentSelection == on)
- return;
- d->persistentSelection = on;
- emit persistentSelectionChanged(d->persistentSelection);
-}
-
-/*
- \qmlproperty real QtQuick2::TextEdit::textMargin
-
- The margin, in pixels, around the text in the TextEdit.
-*/
-qreal QQuickTextEdit::textMargin() const
-{
- Q_D(const QQuickTextEdit);
- return d->textMargin;
-}
-
-void QQuickTextEdit::setTextMargin(qreal margin)
-{
- Q_D(QQuickTextEdit);
- if (d->textMargin == margin)
- return;
- d->textMargin = margin;
- d->document->setDocumentMargin(d->textMargin);
- emit textMarginChanged(d->textMargin);
-}
-
-void QQuickTextEdit::geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry)
-{
- if (newGeometry.width() != oldGeometry.width())
- updateSize();
- QQuickImplicitSizeItem::geometryChanged(newGeometry, oldGeometry);
-}
-
-/*!
- Ensures any delayed caching or data loading the class
- needs to performed is complete.
-*/
-void QQuickTextEdit::componentComplete()
-{
- Q_D(QQuickTextEdit);
- QQuickImplicitSizeItem::componentComplete();
-
- if (d->richText)
- d->useImageFallback = qmlEnableImageCache();
-
- if (d->dirty) {
- d->determineHorizontalAlignment();
- d->updateDefaultTextOption();
- updateSize();
- d->dirty = false;
- }
-
-}
-/*!
- \qmlproperty bool QtQuick2::TextEdit::selectByMouse
-
- Defaults to false.
-
- If true, the user can use the mouse to select text in some
- platform-specific way. Note that for some platforms this may
- not be an appropriate interaction (eg. may conflict with how
- the text needs to behave inside a Flickable.
-*/
-bool QQuickTextEdit::selectByMouse() const
-{
- Q_D(const QQuickTextEdit);
- return d->selectByMouse;
-}
-
-void QQuickTextEdit::setSelectByMouse(bool on)
-{
- Q_D(QQuickTextEdit);
- if (d->selectByMouse != on) {
- d->selectByMouse = on;
- setKeepMouseGrab(on);
- if (on)
- setTextInteractionFlags(d->control->textInteractionFlags() | Qt::TextSelectableByMouse);
- else
- setTextInteractionFlags(d->control->textInteractionFlags() & ~Qt::TextSelectableByMouse);
- emit selectByMouseChanged(on);
- }
-}
-
-/*!
- \qmlproperty enum QtQuick2::TextEdit::mouseSelectionMode
-
- Specifies how text should be selected using a mouse.
-
- \list
- \o TextEdit.SelectCharacters - The selection is updated with individual characters. (Default)
- \o TextEdit.SelectWords - The selection is updated with whole words.
- \endlist
-
- This property only applies when \l selectByMouse is true.
-*/
-QQuickTextEdit::SelectionMode QQuickTextEdit::mouseSelectionMode() const
-{
- Q_D(const QQuickTextEdit);
- return d->mouseSelectionMode;
-}
-
-void QQuickTextEdit::setMouseSelectionMode(SelectionMode mode)
-{
- Q_D(QQuickTextEdit);
- if (d->mouseSelectionMode != mode) {
- d->mouseSelectionMode = mode;
- d->control->setWordSelectionEnabled(mode == SelectWords);
- emit mouseSelectionModeChanged(mode);
- }
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::readOnly
-
- Whether the user can interact with the TextEdit item. If this
- property is set to true the text cannot be edited by user interaction.
-
- By default this property is false.
-*/
-void QQuickTextEdit::setReadOnly(bool r)
-{
- Q_D(QQuickTextEdit);
- if (r == isReadOnly())
- return;
-
- setFlag(QQuickItem::ItemAcceptsInputMethod, !r);
- Qt::TextInteractionFlags flags = Qt::LinksAccessibleByMouse;
- if (d->selectByMouse)
- flags = flags | Qt::TextSelectableByMouse;
- if (!r)
- flags = flags | Qt::TextSelectableByKeyboard | Qt::TextEditable;
- d->control->setTextInteractionFlags(flags);
- if (!r)
- d->control->moveCursor(QTextCursor::End);
-
- emit readOnlyChanged(r);
-}
-
-bool QQuickTextEdit::isReadOnly() const
-{
- Q_D(const QQuickTextEdit);
- return !(d->control->textInteractionFlags() & Qt::TextEditable);
-}
-
-/*!
- Sets how the text edit should interact with user input to the given
- \a flags.
-*/
-void QQuickTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags)
-{
- Q_D(QQuickTextEdit);
- d->control->setTextInteractionFlags(flags);
-}
-
-/*!
- Returns the flags specifying how the text edit should interact
- with user input.
-*/
-Qt::TextInteractionFlags QQuickTextEdit::textInteractionFlags() const
-{
- Q_D(const QQuickTextEdit);
- return d->control->textInteractionFlags();
-}
-
-/*!
- \qmlproperty rectangle QtQuick2::TextEdit::cursorRectangle
-
- The rectangle where the text cursor is rendered
- within the text edit. Read-only.
-*/
-QRect QQuickTextEdit::cursorRectangle() const
-{
- Q_D(const QQuickTextEdit);
- return d->control->cursorRect().toRect().translated(0,d->yoff);
-}
-
-bool QQuickTextEdit::event(QEvent *event)
-{
- Q_D(QQuickTextEdit);
- if (event->type() == QEvent::ShortcutOverride) {
- d->control->processEvent(event, QPointF(0, -d->yoff));
- return event->isAccepted();
- }
- return QQuickImplicitSizeItem::event(event);
-}
-
-/*!
-\overload
-Handles the given key \a event.
-*/
-void QQuickTextEdit::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QQuickTextEdit);
- d->control->processEvent(event, QPointF(0, -d->yoff));
- if (!event->isAccepted())
- QQuickImplicitSizeItem::keyPressEvent(event);
-}
-
-/*!
-\overload
-Handles the given key \a event.
-*/
-void QQuickTextEdit::keyReleaseEvent(QKeyEvent *event)
-{
- Q_D(QQuickTextEdit);
- d->control->processEvent(event, QPointF(0, -d->yoff));
- if (!event->isAccepted())
- QQuickImplicitSizeItem::keyReleaseEvent(event);
-}
-
-/*!
- \qmlmethod void QtQuick2::TextEdit::deselect()
-
- Removes active text selection.
-*/
-void QQuickTextEdit::deselect()
-{
- Q_D(QQuickTextEdit);
- QTextCursor c = d->control->textCursor();
- c.clearSelection();
- d->control->setTextCursor(c);
-}
-
-/*!
- \qmlmethod void QtQuick2::TextEdit::selectAll()
-
- Causes all text to be selected.
-*/
-void QQuickTextEdit::selectAll()
-{
- Q_D(QQuickTextEdit);
- d->control->selectAll();
-}
-
-/*!
- \qmlmethod void QtQuick2::TextEdit::selectWord()
-
- Causes the word closest to the current cursor position to be selected.
-*/
-void QQuickTextEdit::selectWord()
-{
- Q_D(QQuickTextEdit);
- QTextCursor c = d->control->textCursor();
- c.select(QTextCursor::WordUnderCursor);
- d->control->setTextCursor(c);
-}
-
-/*!
- \qmlmethod void QtQuick2::TextEdit::select(int start, int end)
-
- Causes the text from \a start to \a end to be selected.
-
- If either start or end is out of range, the selection is not changed.
-
- After calling this, selectionStart will become the lesser
- and selectionEnd will become the greater (regardless of the order passed
- to this method).
-
- \sa selectionStart, selectionEnd
-*/
-void QQuickTextEdit::select(int start, int end)
-{
- Q_D(QQuickTextEdit);
- if (start < 0 || end < 0 || start > d->text.length() || end > d->text.length())
- return;
- QTextCursor cursor = d->control->textCursor();
- cursor.beginEditBlock();
- cursor.setPosition(start, QTextCursor::MoveAnchor);
- cursor.setPosition(end, QTextCursor::KeepAnchor);
- cursor.endEditBlock();
- d->control->setTextCursor(cursor);
-
- // QTBUG-11100
- updateSelectionMarkers();
-}
-
-/*!
- \qmlmethod void QtQuick2::TextEdit::isRightToLeft(int start, int end)
-
- Returns true if the natural reading direction of the editor text
- found between positions \a start and \a end is right to left.
-*/
-bool QQuickTextEdit::isRightToLeft(int start, int end)
-{
- Q_D(QQuickTextEdit);
- if (start > end) {
- qmlInfo(this) << "isRightToLeft(start, end) called with the end property being smaller than the start.";
- return false;
- } else {
- return d->text.mid(start, end - start).isRightToLeft();
- }
-}
-
-#ifndef QT_NO_CLIPBOARD
-/*!
- \qmlmethod QtQuick2::TextEdit::cut()
-
- Moves the currently selected text to the system clipboard.
-*/
-void QQuickTextEdit::cut()
-{
- Q_D(QQuickTextEdit);
- d->control->cut();
-}
-
-/*!
- \qmlmethod QtQuick2::TextEdit::copy()
-
- Copies the currently selected text to the system clipboard.
-*/
-void QQuickTextEdit::copy()
-{
- Q_D(QQuickTextEdit);
- d->control->copy();
-}
-
-/*!
- \qmlmethod QtQuick2::TextEdit::paste()
-
- Replaces the currently selected text by the contents of the system clipboard.
-*/
-void QQuickTextEdit::paste()
-{
- Q_D(QQuickTextEdit);
- d->control->paste();
-}
-#endif // QT_NO_CLIPBOARD
-
-/*!
-\overload
-Handles the given mouse \a event.
-*/
-void QQuickTextEdit::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QQuickTextEdit);
- if (d->focusOnPress){
- bool hadActiveFocus = hasActiveFocus();
- forceActiveFocus();
- // re-open input panel on press if already focused
- if (hasActiveFocus() && hadActiveFocus && !isReadOnly())
- openSoftwareInputPanel();
- }
- d->control->processEvent(event, QPointF(0, -d->yoff));
- if (!event->isAccepted())
- QQuickImplicitSizeItem::mousePressEvent(event);
-}
-
-/*!
-\overload
-Handles the given mouse \a event.
-*/
-void QQuickTextEdit::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QQuickTextEdit);
- d->control->processEvent(event, QPointF(0, -d->yoff));
-
- if (!event->isAccepted())
- QQuickImplicitSizeItem::mouseReleaseEvent(event);
-}
-
-/*!
-\overload
-Handles the given mouse \a event.
-*/
-void QQuickTextEdit::mouseDoubleClickEvent(QMouseEvent *event)
-{
- Q_D(QQuickTextEdit);
- d->control->processEvent(event, QPointF(0, -d->yoff));
- if (!event->isAccepted())
- QQuickImplicitSizeItem::mouseDoubleClickEvent(event);
-}
-
-/*!
-\overload
-Handles the given mouse \a event.
-*/
-void QQuickTextEdit::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QQuickTextEdit);
- d->control->processEvent(event, QPointF(0, -d->yoff));
- if (!event->isAccepted())
- QQuickImplicitSizeItem::mouseMoveEvent(event);
-}
-
-/*!
-\overload
-Handles the given input method \a event.
-*/
-void QQuickTextEdit::inputMethodEvent(QInputMethodEvent *event)
-{
- Q_D(QQuickTextEdit);
- const bool wasComposing = isInputMethodComposing();
- d->control->processEvent(event, QPointF(0, -d->yoff));
- if (wasComposing != isInputMethodComposing())
- emit inputMethodComposingChanged();
-}
-
-void QQuickTextEdit::itemChange(ItemChange change, const ItemChangeData &value)
-{
- if (change == ItemActiveFocusHasChanged) {
- setCursorVisible(value.boolValue); // ### refactor: focus handling && d->canvas && d->canvas->hasFocus());
- }
- QQuickItem::itemChange(change, value);
-}
-
-/*!
-\overload
-Returns the value of the given \a property.
-*/
-QVariant QQuickTextEdit::inputMethodQuery(Qt::InputMethodQuery property) const
-{
- Q_D(const QQuickTextEdit);
-
- QVariant v;
- switch (property) {
- case Qt::ImEnabled:
- v = (bool)(flags() & ItemAcceptsInputMethod);
- break;
- case Qt::ImHints:
- v = (int)inputMethodHints();
- break;
- default:
- v = d->control->inputMethodQuery(property);
- break;
- }
- return v;
-
-}
-
-void QQuickTextEdit::updateImageCache(const QRectF &)
-{
- Q_D(QQuickTextEdit);
-
- // Do we really need the image cache?
- if (!d->richText || !d->useImageFallback) {
- if (!d->pixmapCache.isNull())
- d->pixmapCache = QPixmap();
- return;
- }
-
- if (width() != d->pixmapCache.width() || height() != d->pixmapCache.height())
- d->pixmapCache = QPixmap(width(), height());
-
- if (d->pixmapCache.isNull())
- return;
-
- // ### Use supplied rect, clear area and update only this part (for cursor updates)
- QRectF bounds = QRectF(0, 0, width(), height());
- d->pixmapCache.fill(Qt::transparent);
- {
- QPainter painter(&d->pixmapCache);
-
- painter.setRenderHint(QPainter::TextAntialiasing);
- painter.translate(0, d->yoff);
-
- d->control->drawContents(&painter, bounds);
- }
-
-}
-
-QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData)
-{
- Q_UNUSED(updatePaintNodeData);
- Q_D(QQuickTextEdit);
-
- QSGNode *currentNode = oldNode;
- if (d->richText && d->useImageFallback) {
- QSGImageNode *node = 0;
- if (oldNode == 0 || d->nodeType != QQuickTextEditPrivate::NodeIsTexture) {
- delete oldNode;
- node = QQuickItemPrivate::get(this)->sceneGraphContext()->createImageNode();
- d->texture = new QSGPlainTexture();
- d->nodeType = QQuickTextEditPrivate::NodeIsTexture;
- currentNode = node;
- } else {
- node = static_cast<QSGImageNode *>(oldNode);
- }
-
- qobject_cast<QSGPlainTexture *>(d->texture)->setImage(d->pixmapCache.toImage());
- node->setTexture(0);
- node->setTexture(d->texture);
-
- node->setTargetRect(QRectF(0, 0, d->pixmapCache.width(), d->pixmapCache.height()));
- node->setSourceRect(QRectF(0, 0, 1, 1));
- node->setHorizontalWrapMode(QSGTexture::ClampToEdge);
- node->setVerticalWrapMode(QSGTexture::ClampToEdge);
- node->setFiltering(QSGTexture::Linear); // Nonsmooth text just ugly, so don't do that..
- node->update();
-
- } else if (oldNode == 0 || d->documentDirty) {
- d->documentDirty = false;
-
-#if defined(Q_OS_MAC)
- // Make sure document is relayouted in the paint node on Mac
- // to avoid crashes due to the font engines created in the
- // shaping process
- d->document->markContentsDirty(0, d->document->characterCount());
-#endif
-
- QQuickTextNode *node = 0;
- if (oldNode == 0 || d->nodeType != QQuickTextEditPrivate::NodeIsText) {
- delete oldNode;
- node = new QQuickTextNode(QQuickItemPrivate::get(this)->sceneGraphContext());
- d->nodeType = QQuickTextEditPrivate::NodeIsText;
- currentNode = node;
- } else {
- node = static_cast<QQuickTextNode *>(oldNode);
- }
-
- node->deleteContent();
- node->setMatrix(QMatrix4x4());
-
- QRectF bounds = boundingRect();
-
- QColor selectionColor = d->control->palette().color(QPalette::Highlight);
- QColor selectedTextColor = d->control->palette().color(QPalette::HighlightedText);
- node->addTextDocument(bounds.topLeft(), d->document, d->color, QQuickText::Normal, QColor(),
- selectionColor, selectedTextColor, selectionStart(),
- selectionEnd() - 1); // selectionEnd() returns first char after
- // selection
-
-#if defined(Q_OS_MAC)
- // We also need to make sure the document layout is redone when
- // control is returned to the main thread, as all the font engines
- // are now owned by the rendering thread
- d->document->markContentsDirty(0, d->document->characterCount());
-#endif
- }
-
- if (d->nodeType == QQuickTextEditPrivate::NodeIsText && d->cursorComponent == 0 && !isReadOnly()) {
- QQuickTextNode *node = static_cast<QQuickTextNode *>(currentNode);
-
- QColor color = (!d->cursorVisible || !d->control->cursorOn())
- ? QColor(0, 0, 0, 0)
- : d->color;
-
- if (node->cursorNode() == 0) {
- node->setCursor(cursorRectangle(), color);
- } else {
- node->cursorNode()->setRect(cursorRectangle());
- node->cursorNode()->setColor(color);
- }
-
- }
-
- return currentNode;
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::smooth
-
- This property holds whether the text is smoothly scaled or transformed.
-
- Smooth filtering gives better visual quality, but is slower. If
- the item is displayed at its natural size, this property has no visual or
- performance effect.
-
- \note Generally scaling artifacts are only visible if the item is stationary on
- the screen. A common pattern when animating an item is to disable smooth
- filtering at the beginning of the animation and reenable it at the conclusion.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::canPaste
-
- Returns true if the TextEdit is writable and the content of the clipboard is
- suitable for pasting into the TextEdit.
-*/
-bool QQuickTextEdit::canPaste() const
-{
- Q_D(const QQuickTextEdit);
- return d->canPaste;
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextEdit::inputMethodComposing
-
-
- This property holds whether the TextEdit has partial text input from an
- input method.
-
- While it is composing an input method may rely on mouse or key events from
- the TextEdit to edit or commit the partial text. This property can be used
- to determine when to disable events handlers that may interfere with the
- correct operation of an input method.
-*/
-bool QQuickTextEdit::isInputMethodComposing() const
-{
- Q_D(const QQuickTextEdit);
- if (QTextLayout *layout = d->control->textCursor().block().layout())
- return layout->preeditAreaText().length() > 0;
- return false;
-}
-
-void QQuickTextEditPrivate::init()
-{
- Q_Q(QQuickTextEdit);
-
- q->setSmooth(smooth);
- q->setAcceptedMouseButtons(Qt::LeftButton);
- q->setFlag(QQuickItem::ItemAcceptsInputMethod);
- q->setFlag(QQuickItem::ItemHasContents);
-
- control = new QTextControl(q);
- control->setIgnoreUnusedNavigationEvents(true);
- control->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::TextSelectableByKeyboard | Qt::TextEditable);
- control->setDragEnabled(false);
-
- // By default, QTextControl will issue both a updateCursorRequest() and an updateRequest()
- // when the cursor needs to be repainted. We need the signals to be separate to be able to
- // distinguish the cursor updates so that we can avoid updating the whole subtree when the
- // cursor blinks.
- if (!QObject::disconnect(control, SIGNAL(updateCursorRequest(QRectF)),
- control, SIGNAL(updateRequest(QRectF)))) {
- qWarning("QQuickTextEditPrivate::init: Failed to disconnect updateCursorRequest and updateRequest");
- }
-
- // QTextControl follows the default text color
- // defined by the platform, declarative text
- // should be black by default
- QPalette pal = control->palette();
- if (pal.color(QPalette::Text) != color) {
- pal.setColor(QPalette::Text, color);
- control->setPalette(pal);
- }
-
- QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(updateDocument()));
- QObject::connect(control, SIGNAL(updateCursorRequest()), q, SLOT(updateCursor()));
- QObject::connect(control, SIGNAL(textChanged()), q, SLOT(q_textChanged()));
- QObject::connect(control, SIGNAL(selectionChanged()), q, SIGNAL(selectionChanged()));
- QObject::connect(control, SIGNAL(selectionChanged()), q, SLOT(updateSelectionMarkers()));
- QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SLOT(updateSelectionMarkers()));
- QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SIGNAL(cursorPositionChanged()));
- QObject::connect(control, SIGNAL(microFocusChanged()), q, SLOT(moveCursorDelegate()));
- QObject::connect(control, SIGNAL(linkActivated(QString)), q, SIGNAL(linkActivated(QString)));
-#ifndef QT_NO_CLIPBOARD
- QObject::connect(q, SIGNAL(readOnlyChanged(bool)), q, SLOT(q_canPasteChanged()));
- QObject::connect(QGuiApplication::clipboard(), SIGNAL(dataChanged()), q, SLOT(q_canPasteChanged()));
- canPaste = control->canPaste();
-#endif
-
- document = control->document();
- document->setDefaultFont(font);
- document->setDocumentMargin(textMargin);
- document->setUndoRedoEnabled(false); // flush undo buffer.
- document->setUndoRedoEnabled(true);
- updateDefaultTextOption();
-}
-
-void QQuickTextEdit::q_textChanged()
-{
- Q_D(QQuickTextEdit);
- d->text = text();
- d->rightToLeftText = d->document->begin().layout()->engine()->isRightToLeft();
- d->determineHorizontalAlignment();
- d->updateDefaultTextOption();
- updateSize();
- updateTotalLines();
- emit textChanged(d->text);
-}
-
-void QQuickTextEdit::moveCursorDelegate()
-{
- Q_D(QQuickTextEdit);
- d->determineHorizontalAlignment();
- updateMicroFocus();
- emit cursorRectangleChanged();
- if (!d->cursor)
- return;
- QRectF cursorRect = cursorRectangle();
- d->cursor->setX(cursorRect.x());
- d->cursor->setY(cursorRect.y());
-}
-
-void QQuickTextEditPrivate::updateSelection()
-{
- Q_Q(QQuickTextEdit);
- QTextCursor cursor = control->textCursor();
- bool startChange = (lastSelectionStart != cursor.selectionStart());
- bool endChange = (lastSelectionEnd != cursor.selectionEnd());
- cursor.beginEditBlock();
- cursor.setPosition(lastSelectionStart, QTextCursor::MoveAnchor);
- cursor.setPosition(lastSelectionEnd, QTextCursor::KeepAnchor);
- cursor.endEditBlock();
- control->setTextCursor(cursor);
- if (startChange)
- q->selectionStartChanged();
- if (endChange)
- q->selectionEndChanged();
-}
-
-void QQuickTextEdit::updateSelectionMarkers()
-{
- Q_D(QQuickTextEdit);
- if (d->lastSelectionStart != d->control->textCursor().selectionStart()) {
- d->lastSelectionStart = d->control->textCursor().selectionStart();
- emit selectionStartChanged();
- }
- if (d->lastSelectionEnd != d->control->textCursor().selectionEnd()) {
- d->lastSelectionEnd = d->control->textCursor().selectionEnd();
- emit selectionEndChanged();
- }
-}
-
-QRectF QQuickTextEdit::boundingRect() const
-{
- Q_D(const QQuickTextEdit);
- QRectF r = QQuickImplicitSizeItem::boundingRect();
- int cursorWidth = 1;
- if (d->cursor)
- cursorWidth = d->cursor->width();
- if (!d->document->isEmpty())
- cursorWidth += 3;// ### Need a better way of accounting for space between char and cursor
-
- // Could include font max left/right bearings to either side of rectangle.
-
- r.setRight(r.right() + cursorWidth);
- return r.translated(0,d->yoff);
-}
-
-qreal QQuickTextEditPrivate::getImplicitWidth() const
-{
- Q_Q(const QQuickTextEdit);
- if (!requireImplicitWidth) {
- // We don't calculate implicitWidth unless it is required.
- // We need to force a size update now to ensure implicitWidth is calculated
- const_cast<QQuickTextEditPrivate*>(this)->requireImplicitWidth = true;
- const_cast<QQuickTextEdit*>(q)->updateSize();
- }
- return implicitWidth;
-}
-
-//### 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 QQuickTextEdit::updateSize()
-{
- Q_D(QQuickTextEdit);
- if (isComponentComplete()) {
- qreal naturalWidth = d->implicitWidth;
- // ### assumes that if the width is set, the text will fill to edges
- // ### (unless wrap is false, then clipping will occur)
- if (widthValid()) {
- if (!d->requireImplicitWidth) {
- emit implicitWidthChanged();
- // if the implicitWidth is used, then updateSize() has already been called (recursively)
- if (d->requireImplicitWidth)
- return;
- }
- if (d->requireImplicitWidth) {
- d->document->setTextWidth(-1);
- naturalWidth = d->document->idealWidth();
- }
- if (d->document->textWidth() != width())
- d->document->setTextWidth(width());
- } else {
- d->document->setTextWidth(-1);
- }
- QFontMetrics fm = QFontMetrics(d->font);
- int dy = height();
- dy -= (int)d->document->size().height();
-
- int nyoff;
- if (heightValid()) {
- if (d->vAlign == AlignBottom)
- nyoff = dy;
- else if (d->vAlign == AlignVCenter)
- nyoff = dy/2;
- else
- nyoff = 0;
- } else {
- nyoff = 0;
- }
- if (nyoff != d->yoff)
- d->yoff = nyoff;
- setBaselineOffset(fm.ascent() + d->yoff + d->textMargin);
-
- //### need to comfirm cost of always setting these
- int newWidth = qCeil(d->document->idealWidth());
- if (!widthValid() && d->document->textWidth() != newWidth)
- d->document->setTextWidth(newWidth); // ### Text does not align if width is not set (QTextDoc bug)
- // ### Setting the implicitWidth triggers another updateSize(), and unless there are bindings nothing has changed.
- qreal iWidth = -1;
- if (!widthValid())
- iWidth = newWidth;
- else if (d->requireImplicitWidth)
- iWidth = naturalWidth;
- qreal newHeight = d->document->isEmpty() ? fm.height() : (int)d->document->size().height();
- if (iWidth > -1)
- setImplicitSize(iWidth, newHeight);
- else
- setImplicitHeight(newHeight);
-
- d->paintedSize = QSize(newWidth, newHeight);
- emit paintedSizeChanged();
- } else {
- d->dirty = true;
- }
- updateDocument();
-}
-
-void QQuickTextEdit::updateDocument()
-{
- Q_D(QQuickTextEdit);
- d->documentDirty = true;
-
- if (isComponentComplete()) {
- updateImageCache();
- update();
- }
-}
-
-void QQuickTextEdit::updateCursor()
-{
- Q_D(QQuickTextEdit);
- if (isComponentComplete()) {
- updateImageCache(d->control->cursorRect());
- update();
- }
-}
-
-void QQuickTextEdit::updateTotalLines()
-{
- Q_D(QQuickTextEdit);
-
- int subLines = 0;
-
- for (QTextBlock it = d->document->begin(); it != d->document->end(); it = it.next()) {
- QTextLayout *layout = it.layout();
- if (!layout)
- continue;
- subLines += layout->lineCount()-1;
- }
-
- int newTotalLines = d->document->lineCount() + subLines;
- if (d->lineCount != newTotalLines) {
- d->lineCount = newTotalLines;
- emit lineCountChanged();
- }
-}
-
-void QQuickTextEditPrivate::updateDefaultTextOption()
-{
- Q_Q(QQuickTextEdit);
- QTextOption opt = document->defaultTextOption();
- int oldAlignment = opt.alignment();
-
- QQuickTextEdit::HAlignment horizontalAlignment = q->effectiveHAlign();
- if (rightToLeftText) {
- if (horizontalAlignment == QQuickTextEdit::AlignLeft)
- horizontalAlignment = QQuickTextEdit::AlignRight;
- else if (horizontalAlignment == QQuickTextEdit::AlignRight)
- horizontalAlignment = QQuickTextEdit::AlignLeft;
- }
- opt.setAlignment((Qt::Alignment)(int)(horizontalAlignment | vAlign));
-
- QTextOption::WrapMode oldWrapMode = opt.wrapMode();
- opt.setWrapMode(QTextOption::WrapMode(wrapMode));
-
- bool oldUseDesignMetrics = opt.useDesignMetrics();
- bool useDesignMetrics = !qmlDisableDistanceField();
- opt.setUseDesignMetrics(useDesignMetrics);
-
- if (oldWrapMode == opt.wrapMode()
- && oldAlignment == opt.alignment()
- && oldUseDesignMetrics == useDesignMetrics) {
- return;
- }
- document->setDefaultTextOption(opt);
-}
-
-
-
-/*!
- \qmlmethod void QtQuick2::TextEdit::openSoftwareInputPanel()
-
- Opens software input panels like virtual keyboards for typing, useful for
- customizing when you want the input keyboard to be shown and hidden in
- your application.
-
- By default the opening of input panels follows the platform style. Input panels are
- always closed if no editor has active focus.
-
- You can disable the automatic behavior by setting the property \c activeFocusOnPress to false
- and use functions openSoftwareInputPanel() and closeSoftwareInputPanel() to implement
- the behavior you want.
-
- Only relevant on platforms, which provide virtual keyboards.
-
- \code
- import QtQuick 1.0
- TextEdit {
- id: textEdit
- text: "Hello world!"
- activeFocusOnPress: false
- MouseArea {
- anchors.fill: parent
- onClicked: {
- if (!textEdit.activeFocus) {
- textEdit.forceActiveFocus();
- textEdit.openSoftwareInputPanel();
- } else {
- textEdit.focus = false;
- }
- }
- onPressAndHold: textEdit.closeSoftwareInputPanel();
- }
- }
- \endcode
-*/
-void QQuickTextEdit::openSoftwareInputPanel()
-{
- if (qGuiApp)
- qGuiApp->inputPanel()->show();
-}
-
-/*!
- \qmlmethod void QtQuick2::TextEdit::closeSoftwareInputPanel()
-
- Closes a software input panel like a virtual keyboard shown on the screen, useful
- for customizing when you want the input keyboard to be shown and hidden in
- your application.
-
- By default the opening of input panels follows the platform style. Input panels are
- always closed if no editor has active focus.
-
- You can disable the automatic behavior by setting the property \c activeFocusOnPress to false
- and use functions openSoftwareInputPanel() and closeSoftwareInputPanel() to implement
- the behavior you want.
-
- Only relevant on platforms, which provide virtual keyboards.
-
- \code
- import QtQuick 1.0
- TextEdit {
- id: textEdit
- text: "Hello world!"
- activeFocusOnPress: false
- MouseArea {
- anchors.fill: parent
- onClicked: {
- if (!textEdit.activeFocus) {
- textEdit.forceActiveFocus();
- textEdit.openSoftwareInputPanel();
- } else {
- textEdit.focus = false;
- }
- }
- onPressAndHold: textEdit.closeSoftwareInputPanel();
- }
- }
- \endcode
-*/
-void QQuickTextEdit::closeSoftwareInputPanel()
-{
- if (qGuiApp)
- qGuiApp->inputPanel()->hide();
-}
-
-void QQuickTextEdit::focusInEvent(QFocusEvent *event)
-{
- Q_D(const QQuickTextEdit);
- if (d->focusOnPress && !isReadOnly())
- openSoftwareInputPanel();
- QQuickImplicitSizeItem::focusInEvent(event);
-}
-
-void QQuickTextEdit::q_canPasteChanged()
-{
- Q_D(QQuickTextEdit);
- bool old = d->canPaste;
- d->canPaste = d->control->canPaste();
- if (old!=d->canPaste)
- emit canPasteChanged();
-}
-
-/*!
- \qmlmethod string QtQuick2::TextEdit::getText(int start, int end)
-
- Returns the section of text that is between the \a start and \a end positions.
-
- The returned text does not include any rich text formatting.
-*/
-
-QString QQuickTextEdit::getText(int start, int end) const
-{
- Q_D(const QQuickTextEdit);
- start = qBound(0, start, d->document->characterCount() - 1);
- end = qBound(0, end, d->document->characterCount() - 1);
- QTextCursor cursor(d->document);
- cursor.setPosition(start, QTextCursor::MoveAnchor);
- cursor.setPosition(end, QTextCursor::KeepAnchor);
- return cursor.selectedText();
-}
-
-/*!
- \qmlmethod string QtQuick2::TextEdit::getFormattedText(int start, int end)
-
- Returns the section of text that is between the \a start and \a end positions.
-
- The returned text will be formatted according the \l textFormat property.
-*/
-
-QString QQuickTextEdit::getFormattedText(int start, int end) const
-{
- Q_D(const QQuickTextEdit);
-
- start = qBound(0, start, d->document->characterCount() - 1);
- end = qBound(0, end, d->document->characterCount() - 1);
-
- QTextCursor cursor(d->document);
- cursor.setPosition(start, QTextCursor::MoveAnchor);
- cursor.setPosition(end, QTextCursor::KeepAnchor);
-
- if (d->richText) {
-#ifndef QT_NO_TEXTHTMLPARSER
- return cursor.selection().toHtml();
-#else
- return cursor.selection().toPlainText();
-#endif
- } else {
- return cursor.selection().toPlainText();
- }
-}
-
-/*!
- \qmlmethod void QtQuick2::TextEdit::insert(int position, string text)
-
- Inserts \a text into the TextEdit at position.
-*/
-void QQuickTextEdit::insert(int position, const QString &text)
-{
- Q_D(QQuickTextEdit);
- if (position < 0 || position >= d->document->characterCount())
- return;
- QTextCursor cursor(d->document);
- cursor.setPosition(position);
- d->richText = d->richText || (d->format == AutoText && Qt::mightBeRichText(text));
- if (d->richText) {
-#ifndef QT_NO_TEXTHTMLPARSER
- cursor.insertHtml(text);
-#else
- cursor.insertText(text);
-#endif
- } else {
- cursor.insertText(text);
- }
-}
-
-/*!
- \qmlmethod string QtQuick2::TextEdit::getText(int start, int end)
-
- Removes the section of text that is between the \a start and \a end positions from the TextEdit.
-*/
-
-void QQuickTextEdit::remove(int start, int end)
-{
- Q_D(QQuickTextEdit);
- start = qBound(0, start, d->document->characterCount() - 1);
- end = qBound(0, end, d->document->characterCount() - 1);
- QTextCursor cursor(d->document);
- cursor.setPosition(start, QTextCursor::MoveAnchor);
- cursor.setPosition(end, QTextCursor::KeepAnchor);
- cursor.removeSelectedText();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquicktextedit_p.h b/src/declarative/items/qquicktextedit_p.h
deleted file mode 100644
index 25988959f6..0000000000
--- a/src/declarative/items/qquicktextedit_p.h
+++ /dev/null
@@ -1,314 +0,0 @@
-// Commit: 27e4302b7f45f22180693d26747f419177c81e27
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKTEXTEDIT_P_H
-#define QQUICKTEXTEDIT_P_H
-
-#include "qquickimplicitsizeitem_p.h"
-
-#include <QtGui/qtextoption.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickTextEditPrivate;
-class Q_AUTOTEST_EXPORT QQuickTextEdit : public QQuickImplicitSizeItem
-{
- Q_OBJECT
- Q_ENUMS(VAlignment)
- Q_ENUMS(HAlignment)
- Q_ENUMS(TextFormat)
- Q_ENUMS(WrapMode)
- Q_ENUMS(SelectionMode)
-
- Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
- Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
- Q_PROPERTY(QColor selectionColor READ selectionColor WRITE setSelectionColor NOTIFY selectionColorChanged)
- Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor NOTIFY selectedTextColorChanged)
- Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged)
- Q_PROPERTY(HAlignment horizontalAlignment READ hAlign WRITE setHAlign RESET resetHAlign NOTIFY horizontalAlignmentChanged)
- Q_PROPERTY(HAlignment effectiveHorizontalAlignment READ effectiveHAlign NOTIFY effectiveHorizontalAlignmentChanged)
- Q_PROPERTY(VAlignment verticalAlignment READ vAlign WRITE setVAlign NOTIFY verticalAlignmentChanged)
- Q_PROPERTY(WrapMode wrapMode READ wrapMode WRITE setWrapMode NOTIFY wrapModeChanged)
- Q_PROPERTY(int lineCount READ lineCount NOTIFY lineCountChanged)
- Q_PROPERTY(int length READ length NOTIFY textChanged)
- Q_PROPERTY(qreal paintedWidth READ paintedWidth NOTIFY paintedSizeChanged)
- Q_PROPERTY(qreal paintedHeight READ paintedHeight NOTIFY paintedSizeChanged)
- Q_PROPERTY(TextFormat textFormat READ textFormat WRITE setTextFormat NOTIFY textFormatChanged)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly NOTIFY readOnlyChanged)
- Q_PROPERTY(bool cursorVisible READ isCursorVisible WRITE setCursorVisible NOTIFY cursorVisibleChanged)
- Q_PROPERTY(int cursorPosition READ cursorPosition WRITE setCursorPosition NOTIFY cursorPositionChanged)
- Q_PROPERTY(QRect cursorRectangle READ cursorRectangle NOTIFY cursorRectangleChanged)
- Q_PROPERTY(QDeclarativeComponent* cursorDelegate READ cursorDelegate WRITE setCursorDelegate NOTIFY cursorDelegateChanged)
- Q_PROPERTY(int selectionStart READ selectionStart NOTIFY selectionStartChanged)
- Q_PROPERTY(int selectionEnd READ selectionEnd NOTIFY selectionEndChanged)
- Q_PROPERTY(QString selectedText READ selectedText NOTIFY selectionChanged)
- Q_PROPERTY(bool activeFocusOnPress READ focusOnPress WRITE setFocusOnPress NOTIFY activeFocusOnPressChanged)
- Q_PROPERTY(bool persistentSelection READ persistentSelection WRITE setPersistentSelection NOTIFY persistentSelectionChanged)
- Q_PROPERTY(qreal textMargin READ textMargin WRITE setTextMargin NOTIFY textMarginChanged)
- Q_PROPERTY(Qt::InputMethodHints inputMethodHints READ inputMethodHints WRITE setInputMethodHints)
- Q_PROPERTY(bool selectByMouse READ selectByMouse WRITE setSelectByMouse NOTIFY selectByMouseChanged)
- Q_PROPERTY(SelectionMode mouseSelectionMode READ mouseSelectionMode WRITE setMouseSelectionMode NOTIFY mouseSelectionModeChanged)
- Q_PROPERTY(bool canPaste READ canPaste NOTIFY canPasteChanged)
- Q_PROPERTY(bool inputMethodComposing READ isInputMethodComposing NOTIFY inputMethodComposingChanged)
-
-public:
- QQuickTextEdit(QQuickItem *parent=0);
-
- enum HAlignment {
- AlignLeft = Qt::AlignLeft,
- AlignRight = Qt::AlignRight,
- AlignHCenter = Qt::AlignHCenter,
- AlignJustify = Qt::AlignJustify
- };
-
- enum VAlignment {
- AlignTop = Qt::AlignTop,
- AlignBottom = Qt::AlignBottom,
- AlignVCenter = Qt::AlignVCenter
- };
-
- enum TextFormat {
- PlainText = Qt::PlainText,
- RichText = Qt::RichText,
- AutoText = Qt::AutoText
- };
-
- enum WrapMode { NoWrap = QTextOption::NoWrap,
- WordWrap = QTextOption::WordWrap,
- WrapAnywhere = QTextOption::WrapAnywhere,
- WrapAtWordBoundaryOrAnywhere = QTextOption::WrapAtWordBoundaryOrAnywhere, // COMPAT
- Wrap = QTextOption::WrapAtWordBoundaryOrAnywhere
- };
-
- enum SelectionMode {
- SelectCharacters,
- SelectWords
- };
-
- Q_INVOKABLE void openSoftwareInputPanel();
- Q_INVOKABLE void closeSoftwareInputPanel();
-
- QString text() const;
- void setText(const QString &);
-
- TextFormat textFormat() const;
- void setTextFormat(TextFormat format);
-
- QFont font() const;
- void setFont(const QFont &font);
-
- QColor color() const;
- void setColor(const QColor &c);
-
- QColor selectionColor() const;
- void setSelectionColor(const QColor &c);
-
- QColor selectedTextColor() const;
- void setSelectedTextColor(const QColor &c);
-
- HAlignment hAlign() const;
- void setHAlign(HAlignment align);
- void resetHAlign();
- HAlignment effectiveHAlign() const;
-
- VAlignment vAlign() const;
- void setVAlign(VAlignment align);
-
- WrapMode wrapMode() const;
- void setWrapMode(WrapMode w);
-
- int lineCount() const;
-
- int length() const;
-
- bool isCursorVisible() const;
- void setCursorVisible(bool on);
-
- int cursorPosition() const;
- void setCursorPosition(int pos);
-
- QDeclarativeComponent* cursorDelegate() const;
- void setCursorDelegate(QDeclarativeComponent*);
-
- int selectionStart() const;
- int selectionEnd() const;
-
- QString selectedText() const;
-
- bool focusOnPress() const;
- void setFocusOnPress(bool on);
-
- bool persistentSelection() const;
- void setPersistentSelection(bool on);
-
- qreal textMargin() const;
- void setTextMargin(qreal margin);
-
- bool selectByMouse() const;
- void setSelectByMouse(bool);
-
- SelectionMode mouseSelectionMode() const;
- void setMouseSelectionMode(SelectionMode mode);
-
- bool canPaste() const;
-
- virtual void componentComplete();
-
- /* FROM EDIT */
- void setReadOnly(bool);
- bool isReadOnly() const;
-
- void setTextInteractionFlags(Qt::TextInteractionFlags flags);
- Qt::TextInteractionFlags textInteractionFlags() const;
-
- QRect cursorRectangle() const;
-
- QVariant inputMethodQuery(Qt::InputMethodQuery property) const;
-
- qreal paintedWidth() const;
- qreal paintedHeight() const;
-
- Q_INVOKABLE QRectF positionToRectangle(int) const;
- Q_INVOKABLE int positionAt(int x, int y) const;
- Q_INVOKABLE void moveCursorSelection(int pos);
- Q_INVOKABLE void moveCursorSelection(int pos, SelectionMode mode);
-
- QRectF boundingRect() const;
-
- bool isInputMethodComposing() const;
-
- Q_INVOKABLE QString getText(int start, int end) const;
- Q_INVOKABLE QString getFormattedText(int start, int end) const;
-
-Q_SIGNALS:
- void textChanged(const QString &);
- void paintedSizeChanged();
- void cursorPositionChanged();
- void cursorRectangleChanged();
- void selectionStartChanged();
- void selectionEndChanged();
- void selectionChanged();
- void colorChanged(const QColor &color);
- void selectionColorChanged(const QColor &color);
- void selectedTextColorChanged(const QColor &color);
- void fontChanged(const QFont &font);
- void horizontalAlignmentChanged(HAlignment alignment);
- void verticalAlignmentChanged(VAlignment alignment);
- void wrapModeChanged();
- void lineCountChanged();
- void textFormatChanged(TextFormat textFormat);
- void readOnlyChanged(bool isReadOnly);
- void cursorVisibleChanged(bool isCursorVisible);
- void cursorDelegateChanged();
- void activeFocusOnPressChanged(bool activeFocusOnPressed);
- void persistentSelectionChanged(bool isPersistentSelection);
- void textMarginChanged(qreal textMargin);
- void selectByMouseChanged(bool selectByMouse);
- void mouseSelectionModeChanged(SelectionMode mode);
- void linkActivated(const QString &link);
- void canPasteChanged();
- void inputMethodComposingChanged();
- void effectiveHorizontalAlignmentChanged();
-
-public Q_SLOTS:
- void selectAll();
- void selectWord();
- void select(int start, int end);
- void deselect();
- bool isRightToLeft(int start, int end);
-#ifndef QT_NO_CLIPBOARD
- void cut();
- void copy();
- void paste();
-#endif
- void insert(int position, const QString &text);
- void remove(int start, int end);
-
-private Q_SLOTS:
- void q_textChanged();
- void updateSelectionMarkers();
- void moveCursorDelegate();
- void loadCursorDelegate();
- void q_canPasteChanged();
- void updateDocument();
- void updateCursor();
-
-private:
- void updateSize();
- void updateTotalLines();
- void updateImageCache(const QRectF &rect = QRectF());
-
-protected:
- virtual void geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry);
-
- bool event(QEvent *);
- void keyPressEvent(QKeyEvent *);
- void keyReleaseEvent(QKeyEvent *);
- void focusInEvent(QFocusEvent *event);
-
- // mouse filter?
- void mousePressEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void mouseDoubleClickEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void inputMethodEvent(QInputMethodEvent *e);
- virtual void itemChange(ItemChange, const ItemChangeData &);
-
- QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData);
-
-private:
- Q_DISABLE_COPY(QQuickTextEdit)
- Q_DECLARE_PRIVATE(QQuickTextEdit)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickTextEdit)
-
-QT_END_HEADER
-
-#endif // QQUICKTEXTEDIT_P_H
diff --git a/src/declarative/items/qquicktextedit_p_p.h b/src/declarative/items/qquicktextedit_p_p.h
deleted file mode 100644
index 7bcbe2a189..0000000000
--- a/src/declarative/items/qquicktextedit_p_p.h
+++ /dev/null
@@ -1,144 +0,0 @@
-// Commit: 27e4302b7f45f22180693d26747f419177c81e27
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKTEXTEDIT_P_P_H
-#define QQUICKTEXTEDIT_P_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 "qquicktextedit_p.h"
-#include "qquickimplicitsizeitem_p_p.h"
-
-#include <QtDeclarative/qdeclarative.h>
-#include <QtGui/qpixmap.h>
-
-QT_BEGIN_NAMESPACE
-class QTextLayout;
-class QTextDocument;
-class QTextControl;
-class QQuickTextEditPrivate : public QQuickImplicitSizeItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickTextEdit)
-
-public:
- QQuickTextEditPrivate()
- : color("black"), hAlign(QQuickTextEdit::AlignLeft), vAlign(QQuickTextEdit::AlignTop),
- documentDirty(true), dirty(false), richText(false), cursorVisible(false), focusOnPress(true),
- persistentSelection(true), requireImplicitWidth(false), selectByMouse(false), canPaste(false),
- hAlignImplicit(true), rightToLeftText(false), useImageFallback(false),
- textMargin(0.0), lastSelectionStart(0), lastSelectionEnd(0), cursorComponent(0), cursor(0),
- format(QQuickTextEdit::AutoText), document(0), wrapMode(QQuickTextEdit::NoWrap),
- mouseSelectionMode(QQuickTextEdit::SelectCharacters),
- lineCount(0), yoff(0), nodeType(NodeIsNull), texture(0)
- {
- }
-
- void init();
-
- void updateDefaultTextOption();
- void relayoutDocument();
- void updateSelection();
- bool determineHorizontalAlignment();
- bool setHAlign(QQuickTextEdit::HAlignment, bool forceAlign = false);
- void mirrorChange();
- qreal getImplicitWidth() const;
-
- QString text;
- QFont font;
- QFont sourceFont;
- QColor color;
- QColor selectionColor;
- QColor selectedTextColor;
- QString style;
- QColor styleColor;
- QQuickTextEdit::HAlignment hAlign;
- QQuickTextEdit::VAlignment vAlign;
-
- bool documentDirty : 1;
- bool dirty : 1;
- bool richText : 1;
- bool cursorVisible : 1;
- bool focusOnPress : 1;
- bool persistentSelection : 1;
- bool requireImplicitWidth:1;
- bool selectByMouse:1;
- bool canPaste:1;
- bool hAlignImplicit:1;
- bool rightToLeftText:1;
- bool useImageFallback:1;
-
- qreal textMargin;
- int lastSelectionStart;
- int lastSelectionEnd;
- QDeclarativeComponent* cursorComponent;
- QQuickItem* cursor;
- QQuickTextEdit::TextFormat format;
- QTextDocument *document;
- QTextControl *control;
- QQuickTextEdit::WrapMode wrapMode;
- QQuickTextEdit::SelectionMode mouseSelectionMode;
- int lineCount;
- int yoff;
- QSize paintedSize;
-
- enum NodeType {
- NodeIsNull,
- NodeIsTexture,
- NodeIsText
- };
- NodeType nodeType;
- QSGTexture *texture;
- QPixmap pixmapCache;
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKTEXTEDIT_P_P_H
diff --git a/src/declarative/items/qquicktextinput.cpp b/src/declarative/items/qquicktextinput.cpp
deleted file mode 100644
index f3cdc8835a..0000000000
--- a/src/declarative/items/qquicktextinput.cpp
+++ /dev/null
@@ -1,2007 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquicktextinput_p.h"
-#include "qquicktextinput_p_p.h"
-#include "qquickcanvas.h"
-
-#include <private/qdeclarativeglobal_p.h>
-
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtGui/qevent.h>
-#include <QTextBoundaryFinder>
-#include "qquicktextnode_p.h"
-#include <qsgsimplerectnode.h>
-
-#include <QtGui/qstylehints.h>
-#include <QtGui/qinputpanel.h>
-
-QT_BEGIN_NAMESPACE
-
-DEFINE_BOOL_CONFIG_OPTION(qmlDisableDistanceField, QML_DISABLE_DISTANCEFIELD)
-
-/*!
- \qmlclass TextInput QQuickTextInput
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
- \brief The TextInput item displays an editable line of text.
- \inherits Item
-
- The TextInput element displays a single line of editable plain text.
-
- TextInput is used to accept a line of text input. Input constraints
- can be placed on a TextInput item (for example, through a \l validator or \l inputMask),
- and setting \l echoMode to an appropriate value enables TextInput to be used for
- a password input field.
-
- On Mac OS X, the Up/Down key bindings for Home/End are explicitly disabled.
- If you want such bindings (on any platform), you will need to construct them in QML.
-
- \sa TextEdit, Text, {declarative/text/textselection}{Text Selection example}
-*/
-QQuickTextInput::QQuickTextInput(QQuickItem* parent)
-: QQuickImplicitSizeItem(*(new QQuickTextInputPrivate), parent)
-{
- Q_D(QQuickTextInput);
- d->init();
-}
-
-QQuickTextInput::~QQuickTextInput()
-{
-}
-
-/*!
- \qmlproperty string QtQuick2::TextInput::text
-
- The text in the TextInput.
-*/
-QString QQuickTextInput::text() const
-{
- Q_D(const QQuickTextInput);
- return d->control->text();
-}
-
-void QQuickTextInput::setText(const QString &s)
-{
- Q_D(QQuickTextInput);
- if (s == text())
- return;
- d->control->setText(s);
-}
-
-/*!
- \qmlproperty string QtQuick2::TextInput::font.family
-
- Sets the family name of the font.
-
- The family name is case insensitive and may optionally include a foundry name, e.g. "Helvetica [Cronyx]".
- If the family is available from more than one foundry and the foundry isn't specified, an arbitrary foundry is chosen.
- If the family isn't available a family will be set using the font matching algorithm.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::font.bold
-
- Sets whether the font weight is bold.
-*/
-
-/*!
- \qmlproperty enumeration QtQuick2::TextInput::font.weight
-
- Sets the font's weight.
-
- The weight can be one of:
- \list
- \o Font.Light
- \o Font.Normal - the default
- \o Font.DemiBold
- \o Font.Bold
- \o Font.Black
- \endlist
-
- \qml
- TextInput { text: "Hello"; font.weight: Font.DemiBold }
- \endqml
-*/
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::font.italic
-
- Sets whether the font has an italic style.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::font.underline
-
- Sets whether the text is underlined.
-*/
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::font.strikeout
-
- Sets whether the font has a strikeout style.
-*/
-
-/*!
- \qmlproperty real QtQuick2::TextInput::font.pointSize
-
- Sets the font size in points. The point size must be greater than zero.
-*/
-
-/*!
- \qmlproperty int QtQuick2::TextInput::font.pixelSize
-
- Sets the font size in pixels.
-
- Using this function makes the font device dependent.
- Use \c pointSize to set the size of the font in a device independent manner.
-*/
-
-/*!
- \qmlproperty real QtQuick2::TextInput::font.letterSpacing
-
- Sets the letter spacing for the font.
-
- Letter spacing changes the default spacing between individual letters in the font.
- A positive value increases the letter spacing by the corresponding pixels; a negative value decreases the spacing.
-*/
-
-/*!
- \qmlproperty real QtQuick2::TextInput::font.wordSpacing
-
- Sets the word spacing for the font.
-
- Word spacing changes the default spacing between individual words.
- A positive value increases the word spacing by a corresponding amount of pixels,
- while a negative value decreases the inter-word spacing accordingly.
-*/
-
-/*!
- \qmlproperty enumeration QtQuick2::TextInput::font.capitalization
-
- Sets the capitalization for the text.
-
- \list
- \o Font.MixedCase - This is the normal text rendering option where no capitalization change is applied.
- \o Font.AllUppercase - This alters the text to be rendered in all uppercase type.
- \o Font.AllLowercase - This alters the text to be rendered in all lowercase type.
- \o Font.SmallCaps - This alters the text to be rendered in small-caps type.
- \o Font.Capitalize - This alters the text to be rendered with the first character of each word as an uppercase character.
- \endlist
-
- \qml
- TextInput { text: "Hello"; font.capitalization: Font.AllLowercase }
- \endqml
-*/
-
-QFont QQuickTextInput::font() const
-{
- Q_D(const QQuickTextInput);
- return d->sourceFont;
-}
-
-void QQuickTextInput::setFont(const QFont &font)
-{
- Q_D(QQuickTextInput);
- if (d->sourceFont == font)
- return;
-
- d->sourceFont = font;
- QFont oldFont = d->font;
- d->font = font;
- if (d->font.pointSizeF() != -1) {
- // 0.5pt resolution
- qreal size = qRound(d->font.pointSizeF()*2.0);
- d->font.setPointSizeF(size/2.0);
- }
- if (oldFont != d->font) {
- d->control->setFont(d->font);
- updateSize();
- updateCursorRectangle();
- if (d->cursorItem) {
- d->cursorItem->setHeight(QFontMetrics(d->font).height());
- }
- }
- emit fontChanged(d->sourceFont);
-}
-
-/*!
- \qmlproperty color QtQuick2::TextInput::color
-
- The text color.
-*/
-QColor QQuickTextInput::color() const
-{
- Q_D(const QQuickTextInput);
- return d->color;
-}
-
-void QQuickTextInput::setColor(const QColor &c)
-{
- Q_D(QQuickTextInput);
- if (c != d->color) {
- d->color = c;
- update();
- emit colorChanged(c);
- }
-}
-
-
-/*!
- \qmlproperty color QtQuick2::TextInput::selectionColor
-
- The text highlight color, used behind selections.
-*/
-QColor QQuickTextInput::selectionColor() const
-{
- Q_D(const QQuickTextInput);
- return d->selectionColor;
-}
-
-void QQuickTextInput::setSelectionColor(const QColor &color)
-{
- Q_D(QQuickTextInput);
- if (d->selectionColor == color)
- return;
-
- d->selectionColor = color;
- QPalette p = d->control->palette();
- p.setColor(QPalette::Highlight, d->selectionColor);
- d->control->setPalette(p);
- if (d->control->hasSelectedText())
- update();
- emit selectionColorChanged(color);
-}
-/*!
- \qmlproperty color QtQuick2::TextInput::selectedTextColor
-
- The highlighted text color, used in selections.
-*/
-QColor QQuickTextInput::selectedTextColor() const
-{
- Q_D(const QQuickTextInput);
- return d->selectedTextColor;
-}
-
-void QQuickTextInput::setSelectedTextColor(const QColor &color)
-{
- Q_D(QQuickTextInput);
- if (d->selectedTextColor == color)
- return;
-
- d->selectedTextColor = color;
- QPalette p = d->control->palette();
- p.setColor(QPalette::HighlightedText, d->selectedTextColor);
- d->control->setPalette(p);
- if (d->control->hasSelectedText())
- update();
- emit selectedTextColorChanged(color);
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::TextInput::horizontalAlignment
- \qmlproperty enumeration QtQuick2::TextInput::effectiveHorizontalAlignment
-
- Sets the horizontal alignment of the text within the TextInput item's
- width and height. By default, the text alignment follows the natural alignment
- of the text, for example text that is read from left to right will be aligned to
- the left.
-
- TextInput does not have vertical alignment, as the natural height is
- exactly the height of the single line of text. If you set the height
- manually to something larger, TextInput will always be top aligned
- vertically. You can use anchors to align it however you want within
- another item.
-
- The valid values for \c horizontalAlignment are \c TextInput.AlignLeft, \c TextInput.AlignRight and
- \c TextInput.AlignHCenter.
-
- When using the attached property LayoutMirroring::enabled to mirror application
- layouts, the horizontal alignment of text will also be mirrored. However, the property
- \c horizontalAlignment will remain unchanged. To query the effective horizontal alignment
- of TextInput, use the read-only property \c effectiveHorizontalAlignment.
-*/
-QQuickTextInput::HAlignment QQuickTextInput::hAlign() const
-{
- Q_D(const QQuickTextInput);
- return d->hAlign;
-}
-
-void QQuickTextInput::setHAlign(HAlignment align)
-{
- Q_D(QQuickTextInput);
- bool forceAlign = d->hAlignImplicit && d->effectiveLayoutMirror;
- d->hAlignImplicit = false;
- if (d->setHAlign(align, forceAlign) && isComponentComplete()) {
- updateCursorRectangle();
- }
-}
-
-void QQuickTextInput::resetHAlign()
-{
- Q_D(QQuickTextInput);
- d->hAlignImplicit = true;
- if (d->determineHorizontalAlignment() && isComponentComplete()) {
- updateCursorRectangle();
- }
-}
-
-QQuickTextInput::HAlignment QQuickTextInput::effectiveHAlign() const
-{
- Q_D(const QQuickTextInput);
- QQuickTextInput::HAlignment effectiveAlignment = d->hAlign;
- if (!d->hAlignImplicit && d->effectiveLayoutMirror) {
- switch (d->hAlign) {
- case QQuickTextInput::AlignLeft:
- effectiveAlignment = QQuickTextInput::AlignRight;
- break;
- case QQuickTextInput::AlignRight:
- effectiveAlignment = QQuickTextInput::AlignLeft;
- break;
- default:
- break;
- }
- }
- return effectiveAlignment;
-}
-
-bool QQuickTextInputPrivate::setHAlign(QQuickTextInput::HAlignment alignment, bool forceAlign)
-{
- Q_Q(QQuickTextInput);
- if ((hAlign != alignment || forceAlign) && alignment <= QQuickTextInput::AlignHCenter) { // justify not supported
- QQuickTextInput::HAlignment oldEffectiveHAlign = q->effectiveHAlign();
- hAlign = alignment;
- emit q->horizontalAlignmentChanged(alignment);
- if (oldEffectiveHAlign != q->effectiveHAlign())
- emit q->effectiveHorizontalAlignmentChanged();
- return true;
- }
- return false;
-}
-
-bool QQuickTextInputPrivate::determineHorizontalAlignment()
-{
- if (hAlignImplicit) {
- // if no explicit alignment has been set, follow the natural layout direction of the text
- QString text = control->text();
- if (text.isEmpty())
- text = control->preeditAreaText();
- bool isRightToLeft = text.isEmpty() ? QGuiApplication::keyboardInputDirection() == Qt::RightToLeft : text.isRightToLeft();
- return setHAlign(isRightToLeft ? QQuickTextInput::AlignRight : QQuickTextInput::AlignLeft);
- }
- return false;
-}
-
-void QQuickTextInputPrivate::mirrorChange()
-{
- Q_Q(QQuickTextInput);
- if (q->isComponentComplete()) {
- if (!hAlignImplicit && (hAlign == QQuickTextInput::AlignRight || hAlign == QQuickTextInput::AlignLeft)) {
- q->updateCursorRectangle();
- emit q->effectiveHorizontalAlignmentChanged();
- }
- }
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::readOnly
-
- Sets whether user input can modify the contents of the TextInput.
-
- If readOnly is set to true, then user input will not affect the text
- property. Any bindings or attempts to set the text property will still
- work.
-*/
-bool QQuickTextInput::isReadOnly() const
-{
- Q_D(const QQuickTextInput);
- return d->control->isReadOnly();
-}
-
-void QQuickTextInput::setReadOnly(bool ro)
-{
- Q_D(QQuickTextInput);
- if (d->control->isReadOnly() == ro)
- return;
-
- setFlag(QQuickItem::ItemAcceptsInputMethod, !ro);
- d->control->setReadOnly(ro);
- if (!ro)
- d->control->setCursorPosition(d->control->end());
-
- emit readOnlyChanged(ro);
-}
-
-/*!
- \qmlproperty int QtQuick2::TextInput::maximumLength
- The maximum permitted length of the text in the TextInput.
-
- If the text is too long, it is truncated at the limit.
-
- By default, this property contains a value of 32767.
-*/
-int QQuickTextInput::maxLength() const
-{
- Q_D(const QQuickTextInput);
- return d->control->maxLength();
-}
-
-void QQuickTextInput::setMaxLength(int ml)
-{
- Q_D(QQuickTextInput);
- if (d->control->maxLength() == ml)
- return;
-
- d->control->setMaxLength(ml);
-
- emit maximumLengthChanged(ml);
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::cursorVisible
- Set to true when the TextInput shows a cursor.
-
- This property is set and unset when the TextInput gets active focus, so that other
- properties can be bound to whether the cursor is currently showing. As it
- gets set and unset automatically, when you set the value yourself you must
- keep in mind that your value may be overwritten.
-
- It can be set directly in script, for example if a KeyProxy might
- forward keys to it and you desire it to look active when this happens
- (but without actually giving it active focus).
-
- It should not be set directly on the element, like in the below QML,
- as the specified value will be overridden an lost on focus changes.
-
- \code
- TextInput {
- text: "Text"
- cursorVisible: false
- }
- \endcode
-
- In the above snippet the cursor will still become visible when the
- TextInput gains active focus.
-*/
-bool QQuickTextInput::isCursorVisible() const
-{
- Q_D(const QQuickTextInput);
- return d->cursorVisible;
-}
-
-void QQuickTextInput::setCursorVisible(bool on)
-{
- Q_D(QQuickTextInput);
- if (d->cursorVisible == on)
- return;
- d->cursorVisible = on;
- d->control->setCursorBlinkPeriod(on ? qApp->styleHints()->cursorFlashTime() : 0);
- QRect r = d->control->cursorRect();
- if (d->control->inputMask().isEmpty())
- updateRect(r);
- else
- updateRect();
- emit cursorVisibleChanged(d->cursorVisible);
-}
-
-/*!
- \qmlproperty int QtQuick2::TextInput::cursorPosition
- The position of the cursor in the TextInput.
-*/
-int QQuickTextInput::cursorPosition() const
-{
- Q_D(const QQuickTextInput);
- return d->control->cursor();
-}
-void QQuickTextInput::setCursorPosition(int cp)
-{
- Q_D(QQuickTextInput);
- if (cp < 0 || cp > d->control->text().length())
- return;
- d->control->moveCursor(cp);
-}
-
-/*!
- Returns a Rect which encompasses the cursor, but which may be larger than is
- required. Ignores custom cursor delegates.
-*/
-QRect QQuickTextInput::cursorRectangle() const
-{
- Q_D(const QQuickTextInput);
- QRect r = d->control->cursorRect();
- // Scroll and make consistent with TextEdit
- // QLineControl inexplicably adds 1 to the height and horizontal padding
- // for unicode direction markers.
- r.adjust(5 - d->hscroll, 0, -4 - d->hscroll, -1);
- return r;
-}
-/*!
- \qmlproperty int QtQuick2::TextInput::selectionStart
-
- The cursor position before the first character in the current selection.
-
- This property is read-only. To change the selection, use select(start,end),
- selectAll(), or selectWord().
-
- \sa selectionEnd, cursorPosition, selectedText
-*/
-int QQuickTextInput::selectionStart() const
-{
- Q_D(const QQuickTextInput);
- return d->lastSelectionStart;
-}
-/*!
- \qmlproperty int QtQuick2::TextInput::selectionEnd
-
- The cursor position after the last character in the current selection.
-
- This property is read-only. To change the selection, use select(start,end),
- selectAll(), or selectWord().
-
- \sa selectionStart, cursorPosition, selectedText
-*/
-int QQuickTextInput::selectionEnd() const
-{
- Q_D(const QQuickTextInput);
- return d->lastSelectionEnd;
-}
-/*!
- \qmlmethod void QtQuick2::TextInput::select(int start, int end)
-
- Causes the text from \a start to \a end to be selected.
-
- If either start or end is out of range, the selection is not changed.
-
- After calling this, selectionStart will become the lesser
- and selectionEnd will become the greater (regardless of the order passed
- to this method).
-
- \sa selectionStart, selectionEnd
-*/
-void QQuickTextInput::select(int start, int end)
-{
- Q_D(QQuickTextInput);
- if (start < 0 || end < 0 || start > d->control->text().length() || end > d->control->text().length())
- return;
- d->control->setSelection(start, end-start);
-}
-
-/*!
- \qmlproperty string QtQuick2::TextInput::selectedText
-
- This read-only property provides the text currently selected in the
- text input.
-
- It is equivalent to the following snippet, but is faster and easier
- to use.
-
- \js
- myTextInput.text.toString().substring(myTextInput.selectionStart,
- myTextInput.selectionEnd);
- \endjs
-*/
-QString QQuickTextInput::selectedText() const
-{
- Q_D(const QQuickTextInput);
- return d->control->selectedText();
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::activeFocusOnPress
-
- Whether the TextInput should gain active focus on a mouse press. By default this is
- set to true.
-*/
-bool QQuickTextInput::focusOnPress() const
-{
- Q_D(const QQuickTextInput);
- return d->focusOnPress;
-}
-
-void QQuickTextInput::setFocusOnPress(bool b)
-{
- Q_D(QQuickTextInput);
- if (d->focusOnPress == b)
- return;
-
- d->focusOnPress = b;
-
- emit activeFocusOnPressChanged(d->focusOnPress);
-}
-/*!
- \qmlproperty bool QtQuick2::TextInput::autoScroll
-
- Whether the TextInput should scroll when the text is longer than the width. By default this is
- set to true.
-*/
-bool QQuickTextInput::autoScroll() const
-{
- Q_D(const QQuickTextInput);
- return d->autoScroll;
-}
-
-void QQuickTextInput::setAutoScroll(bool b)
-{
- Q_D(QQuickTextInput);
- if (d->autoScroll == b)
- return;
-
- d->autoScroll = b;
- //We need to repaint so that the scrolling is taking into account.
- updateSize(true);
- updateCursorRectangle();
- emit autoScrollChanged(d->autoScroll);
-}
-
-#ifndef QT_NO_VALIDATOR
-
-/*!
- \qmlclass IntValidator QIntValidator
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
-
- This element provides a validator for integer values.
-
- IntValidator uses the \l {QLocale::setDefault()}{default locale} to interpret the number and
- will accept locale specific digits, group separators, and positive and negative signs. In
- addition, IntValidator is always guaranteed to accept a number formatted according to the "C"
- locale.
-*/
-/*!
- \qmlproperty int QtQuick2::IntValidator::top
-
- This property holds the validator's highest acceptable value.
- By default, this property's value is derived from the highest signed integer available (typically 2147483647).
-*/
-/*!
- \qmlproperty int QtQuick2::IntValidator::bottom
-
- This property holds the validator's lowest acceptable value.
- By default, this property's value is derived from the lowest signed integer available (typically -2147483647).
-*/
-
-/*!
- \qmlclass DoubleValidator QDoubleValidator
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
-
- This element provides a validator for non-integer numbers.
-*/
-
-/*!
- \qmlproperty real QtQuick2::DoubleValidator::top
-
- This property holds the validator's maximum acceptable value.
- By default, this property contains a value of infinity.
-*/
-/*!
- \qmlproperty real QtQuick2::DoubleValidator::bottom
-
- This property holds the validator's minimum acceptable value.
- By default, this property contains a value of -infinity.
-*/
-/*!
- \qmlproperty int QtQuick2::DoubleValidator::decimals
-
- This property holds the validator's maximum number of digits after the decimal point.
- By default, this property contains a value of 1000.
-*/
-/*!
- \qmlproperty enumeration QtQuick2::DoubleValidator::notation
- This property holds the notation of how a string can describe a number.
-
- The possible values for this property are:
-
- \list
- \o DoubleValidator.StandardNotation
- \o DoubleValidator.ScientificNotation (default)
- \endlist
-
- If this property is set to DoubleValidator.ScientificNotation, the written number may have an exponent part (e.g. 1.5E-2).
-*/
-
-/*!
- \qmlclass RegExpValidator QRegExpValidator
- \inqmlmodule QtQuick 2
- \ingroup qml-basic-visual-elements
-
- This element provides a validator, which counts as valid any string which
- matches a specified regular expression.
-*/
-/*!
- \qmlproperty regExp QtQuick2::RegExpValidator::regExp
-
- This property holds the regular expression used for validation.
-
- Note that this property should be a regular expression in JS syntax, e.g /a/ for the regular expression
- matching "a".
-
- By default, this property contains a regular expression with the pattern .* that matches any string.
-*/
-
-/*!
- \qmlproperty Validator QtQuick2::TextInput::validator
-
- Allows you to set a validator on the TextInput. When a validator is set
- the TextInput will only accept input which leaves the text property in
- an acceptable or intermediate state. The accepted signal will only be sent
- if the text is in an acceptable state when enter is pressed.
-
- Currently supported validators are IntValidator, DoubleValidator and
- RegExpValidator. An example of using validators is shown below, which allows
- input of integers between 11 and 31 into the text input:
-
- \code
- import QtQuick 1.0
- TextInput{
- validator: IntValidator{bottom: 11; top: 31;}
- focus: true
- }
- \endcode
-
- \sa acceptableInput, inputMask
-*/
-
-QValidator* QQuickTextInput::validator() const
-{
- Q_D(const QQuickTextInput);
- //###const cast isn't good, but needed for property system?
- return const_cast<QValidator*>(d->control->validator());
-}
-
-void QQuickTextInput::setValidator(QValidator* v)
-{
- Q_D(QQuickTextInput);
- if (d->control->validator() == v)
- return;
-
- d->control->setValidator(v);
- if (!d->control->hasAcceptableInput()) {
- d->oldValidity = false;
- emit acceptableInputChanged();
- }
-
- emit validatorChanged();
-}
-#endif // QT_NO_VALIDATOR
-
-/*!
- \qmlproperty string QtQuick2::TextInput::inputMask
-
- Allows you to set an input mask on the TextInput, restricting the allowable
- text inputs. See QLineEdit::inputMask for further details, as the exact
- same mask strings are used by TextInput.
-
- \sa acceptableInput, validator
-*/
-QString QQuickTextInput::inputMask() const
-{
- Q_D(const QQuickTextInput);
- return d->control->inputMask();
-}
-
-void QQuickTextInput::setInputMask(const QString &im)
-{
- Q_D(QQuickTextInput);
- if (d->control->inputMask() == im)
- return;
-
- d->control->setInputMask(im);
- emit inputMaskChanged(d->control->inputMask());
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::acceptableInput
-
- This property is always true unless a validator or input mask has been set.
- If a validator or input mask has been set, this property will only be true
- if the current text is acceptable to the validator or input mask as a final
- string (not as an intermediate string).
-*/
-bool QQuickTextInput::hasAcceptableInput() const
-{
- Q_D(const QQuickTextInput);
- return d->control->hasAcceptableInput();
-}
-
-/*!
- \qmlsignal QtQuick2::TextInput::onAccepted()
-
- This handler is called when the Return or Enter key is pressed.
- Note that if there is a \l validator or \l inputMask set on the text
- input, the handler will only be emitted if the input is in an acceptable
- state.
-*/
-
-void QQuickTextInputPrivate::updateInputMethodHints()
-{
- Q_Q(QQuickTextInput);
- Qt::InputMethodHints hints = inputMethodHints;
- uint echo = control->echoMode();
- if (echo == QQuickTextInput::Password || echo == QQuickTextInput::NoEcho)
- hints |= Qt::ImhHiddenText;
- else if (echo == QQuickTextInput::PasswordEchoOnEdit)
- hints &= ~Qt::ImhHiddenText;
- if (echo != QQuickTextInput::Normal)
- hints |= (Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText);
- q->setInputMethodHints(hints);
-}
-/*!
- \qmlproperty enumeration QtQuick2::TextInput::echoMode
-
- Specifies how the text should be displayed in the TextInput.
- \list
- \o TextInput.Normal - Displays the text as it is. (Default)
- \o TextInput.Password - Displays asterisks instead of characters.
- \o TextInput.NoEcho - Displays nothing.
- \o TextInput.PasswordEchoOnEdit - Displays characters as they are entered
- while editing, otherwise displays asterisks.
- \endlist
-*/
-QQuickTextInput::EchoMode QQuickTextInput::echoMode() const
-{
- Q_D(const QQuickTextInput);
- return (QQuickTextInput::EchoMode)d->control->echoMode();
-}
-
-void QQuickTextInput::setEchoMode(QQuickTextInput::EchoMode echo)
-{
- Q_D(QQuickTextInput);
- if (echoMode() == echo)
- return;
- d->control->setEchoMode((QLineControl::EchoMode)echo);
- d->updateInputMethodHints();
- q_textChanged();
- emit echoModeChanged(echoMode());
-}
-
-Qt::InputMethodHints QQuickTextInput::imHints() const
-{
- Q_D(const QQuickTextInput);
- return d->inputMethodHints;
-}
-
-void QQuickTextInput::setIMHints(Qt::InputMethodHints hints)
-{
- Q_D(QQuickTextInput);
- if (d->inputMethodHints == hints)
- return;
- d->inputMethodHints = hints;
- d->updateInputMethodHints();
-}
-
-/*!
- \qmlproperty Component QtQuick2::TextInput::cursorDelegate
- The delegate for the cursor in the TextInput.
-
- If you set a cursorDelegate for a TextInput, this delegate will be used for
- drawing the cursor instead of the standard cursor. An instance of the
- delegate will be created and managed by the TextInput when a cursor is
- needed, and the x property of delegate instance will be set so as
- to be one pixel before the top left of the current character.
-
- Note that the root item of the delegate component must be a QDeclarativeItem or
- QDeclarativeItem derived item.
-*/
-QDeclarativeComponent* QQuickTextInput::cursorDelegate() const
-{
- Q_D(const QQuickTextInput);
- return d->cursorComponent;
-}
-
-void QQuickTextInput::setCursorDelegate(QDeclarativeComponent* c)
-{
- Q_D(QQuickTextInput);
- if (d->cursorComponent == c)
- return;
-
- d->cursorComponent = c;
- if (!c) {
- //note that the components are owned by something else
- delete d->cursorItem;
- } else {
- d->startCreatingCursor();
- }
-
- emit cursorDelegateChanged();
-}
-
-void QQuickTextInputPrivate::startCreatingCursor()
-{
- Q_Q(QQuickTextInput);
- if (cursorComponent->isReady()) {
- q->createCursor();
- } else if (cursorComponent->isLoading()) {
- q->connect(cursorComponent, SIGNAL(statusChanged(int)),
- q, SLOT(createCursor()));
- } else { // isError
- qmlInfo(q, cursorComponent->errors()) << QQuickTextInput::tr("Could not load cursor delegate");
- }
-}
-
-void QQuickTextInput::createCursor()
-{
- Q_D(QQuickTextInput);
- if (d->cursorComponent->isError()) {
- qmlInfo(this, d->cursorComponent->errors()) << tr("Could not load cursor delegate");
- return;
- }
-
- if (!d->cursorComponent->isReady())
- return;
-
- if (d->cursorItem)
- delete d->cursorItem;
- QDeclarativeContext *creationContext = d->cursorComponent->creationContext();
- QObject *object = d->cursorComponent->create(creationContext ? creationContext : qmlContext(this));
- d->cursorItem = qobject_cast<QQuickItem*>(object);
- if (!d->cursorItem) {
- delete object;
- qmlInfo(this, d->cursorComponent->errors()) << tr("Could not instantiate cursor delegate");
- return;
- }
-
- QDeclarative_setParent_noEvent(d->cursorItem, this);
- d->cursorItem->setParentItem(this);
- d->cursorItem->setX(d->control->cursorToX());
- d->cursorItem->setHeight(d->control->height()-1); // -1 to counter QLineControl's +1 which is not consistent with Text.
-}
-
-/*!
- \qmlmethod rect QtQuick2::TextInput::positionToRectangle(int pos)
-
- This function takes a character position and returns the rectangle that the
- cursor would occupy, if it was placed at that character position.
-
- This is similar to setting the cursorPosition, and then querying the cursor
- rectangle, but the cursorPosition is not changed.
-*/
-QRectF QQuickTextInput::positionToRectangle(int pos) const
-{
- Q_D(const QQuickTextInput);
- if (pos > d->control->cursorPosition())
- pos += d->control->preeditAreaText().length();
- return QRectF(d->control->cursorToX(pos)-d->hscroll,
- 0.0,
- d->control->cursorWidth(),
- cursorRectangle().height());
-}
-
-/*!
- \qmlmethod int QtQuick2::TextInput::positionAt(int x, CursorPosition position = CursorBetweenCharacters)
-
- This function returns the character position at
- x pixels from the left of the textInput. Position 0 is before the
- first character, position 1 is after the first character but before the second,
- and so on until position text.length, which is after all characters.
-
- This means that for all x values before the first character this function returns 0,
- and for all x values after the last character this function returns text.length.
-
- The cursor position type specifies how the cursor position should be resolved.
-
- \list
- \o TextInput.CursorBetweenCharacters - Returns the position between characters that is nearest x.
- \o TextInput.CursorOnCharacter - Returns the position before the character that is nearest x.
- \endlist
-*/
-int QQuickTextInput::positionAt(int x) const
-{
- return positionAt(x, CursorBetweenCharacters);
-}
-
-int QQuickTextInput::positionAt(int x, CursorPosition position) const
-{
- Q_D(const QQuickTextInput);
- int pos = d->control->xToPos(x + d->hscroll, QTextLine::CursorPosition(position));
- const int cursor = d->control->cursor();
- if (pos > cursor) {
- const int preeditLength = d->control->preeditAreaText().length();
- pos = pos > cursor + preeditLength
- ? pos - preeditLength
- : cursor;
- }
- return pos;
-}
-
-void QQuickTextInput::keyPressEvent(QKeyEvent* ev)
-{
- Q_D(QQuickTextInput);
- // Don't allow MacOSX up/down support, and we don't allow a completer.
- bool ignore = (ev->key() == Qt::Key_Up || ev->key() == Qt::Key_Down) && ev->modifiers() == Qt::NoModifier;
- if (!ignore && (d->lastSelectionStart == d->lastSelectionEnd) && (ev->key() == Qt::Key_Right || ev->key() == Qt::Key_Left)) {
- // Ignore when moving off the end unless there is a selection,
- // because then moving will do something (deselect).
- int cursorPosition = d->control->cursor();
- if (cursorPosition == 0)
- ignore = ev->key() == (d->control->layoutDirection() == Qt::LeftToRight ? Qt::Key_Left : Qt::Key_Right);
- if (cursorPosition == d->control->text().length())
- ignore = ev->key() == (d->control->layoutDirection() == Qt::LeftToRight ? Qt::Key_Right : Qt::Key_Left);
- }
- if (ignore) {
- ev->ignore();
- } else {
- d->control->processKeyEvent(ev);
- }
- if (!ev->isAccepted())
- QQuickImplicitSizeItem::keyPressEvent(ev);
-}
-
-void QQuickTextInput::inputMethodEvent(QInputMethodEvent *ev)
-{
- Q_D(QQuickTextInput);
- const bool wasComposing = d->control->preeditAreaText().length() > 0;
- if (d->control->isReadOnly()) {
- ev->ignore();
- } else {
- d->control->processInputMethodEvent(ev);
- }
- if (!ev->isAccepted())
- QQuickImplicitSizeItem::inputMethodEvent(ev);
-
- if (wasComposing != (d->control->preeditAreaText().length() > 0))
- emit inputMethodComposingChanged();
-}
-
-void QQuickTextInput::mouseDoubleClickEvent(QMouseEvent *event)
-{
- Q_D(QQuickTextInput);
-
- if (d->selectByMouse && event->button() == Qt::LeftButton) {
- d->control->commitPreedit();
- int cursor = d->xToPos(event->localPos().x());
- d->control->selectWordAtPos(cursor);
- event->setAccepted(true);
- if (!d->hasPendingTripleClick()) {
- d->tripleClickStartPoint = event->localPos().toPoint();
- d->tripleClickTimer.start();
- }
- } else {
- if (d->sendMouseEventToInputContext(event))
- return;
- QQuickImplicitSizeItem::mouseDoubleClickEvent(event);
- }
-}
-
-void QQuickTextInput::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QQuickTextInput);
-
- d->pressPos = event->localPos();
-
- if (d->focusOnPress) {
- bool hadActiveFocus = hasActiveFocus();
- forceActiveFocus();
- // re-open input panel on press if already focused
- if (hasActiveFocus() && hadActiveFocus && !isReadOnly())
- openSoftwareInputPanel();
- }
- if (d->selectByMouse) {
- setKeepMouseGrab(false);
- d->selectPressed = true;
- QPoint distanceVector = d->pressPos.toPoint() - d->tripleClickStartPoint;
- if (d->hasPendingTripleClick()
- && distanceVector.manhattanLength() < qApp->styleHints()->startDragDistance()) {
- event->setAccepted(true);
- selectAll();
- return;
- }
- }
-
- if (d->sendMouseEventToInputContext(event))
- return;
-
- bool mark = (event->modifiers() & Qt::ShiftModifier) && d->selectByMouse;
- int cursor = d->xToPos(event->localPos().x());
- d->control->moveCursor(cursor, mark);
- event->setAccepted(true);
-}
-
-void QQuickTextInput::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QQuickTextInput);
-
- if (d->selectPressed) {
- if (qAbs(int(event->localPos().x() - d->pressPos.x())) > qApp->styleHints()->startDragDistance())
- setKeepMouseGrab(true);
-
- if (d->control->composeMode()) {
- // start selection
- int startPos = d->xToPos(d->pressPos.x());
- int currentPos = d->xToPos(event->localPos().x());
- if (startPos != currentPos)
- d->control->setSelection(startPos, currentPos - startPos);
- } else {
- moveCursorSelection(d->xToPos(event->localPos().x()), d->mouseSelectionMode);
- }
- event->setAccepted(true);
- } else {
- QQuickImplicitSizeItem::mouseMoveEvent(event);
- }
-}
-
-void QQuickTextInput::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QQuickTextInput);
- if (d->sendMouseEventToInputContext(event))
- return;
- if (d->selectPressed) {
- d->selectPressed = false;
- setKeepMouseGrab(false);
- }
- d->control->processEvent(event);
- if (!event->isAccepted())
- QQuickImplicitSizeItem::mouseReleaseEvent(event);
-}
-
-bool QQuickTextInputPrivate::sendMouseEventToInputContext(QMouseEvent *event)
-{
-#if !defined QT_NO_IM
- if (control->composeMode()) {
- int tmp_cursor = xToPos(event->localPos().x());
- int mousePos = tmp_cursor - control->cursor();
- if (mousePos >= 0 && mousePos <= control->preeditAreaText().length()) {
- if (event->type() == QEvent::MouseButtonRelease) {
- qApp->inputPanel()->invokeAction(QInputPanel::Click, mousePos);
- }
- return true;
- }
- }
-#else
- Q_UNUSED(event);
- Q_UNUSED(eventType)
-#endif
-
- return false;
-}
-
-void QQuickTextInput::mouseUngrabEvent()
-{
- Q_D(QQuickTextInput);
- d->selectPressed = false;
- setKeepMouseGrab(false);
-}
-
-bool QQuickTextInput::event(QEvent* ev)
-{
- Q_D(QQuickTextInput);
- //Anything we don't deal with ourselves, pass to the control
- bool handled = false;
- switch (ev->type()) {
- case QEvent::KeyPress:
- case QEvent::KeyRelease://###Should the control be doing anything with release?
- case QEvent::InputMethod:
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- break;
- default:
- handled = d->control->processEvent(ev);
- }
- if (!handled)
- handled = QQuickImplicitSizeItem::event(ev);
- return handled;
-}
-
-void QQuickTextInput::geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry)
-{
- if (newGeometry.width() != oldGeometry.width()) {
- updateSize();
- updateCursorRectangle();
- }
- QQuickImplicitSizeItem::geometryChanged(newGeometry, oldGeometry);
-}
-
-int QQuickTextInputPrivate::calculateTextWidth()
-{
- return qRound(control->naturalTextWidth());
-}
-
-void QQuickTextInputPrivate::updateHorizontalScroll()
-{
- Q_Q(QQuickTextInput);
- const int preeditLength = control->preeditAreaText().length();
- const int width = q->width();
- int widthUsed = calculateTextWidth();
-
- if (!autoScroll || widthUsed <= width) {
- QQuickTextInput::HAlignment effectiveHAlign = q->effectiveHAlign();
- // text fits in br; use hscroll for alignment
- switch (effectiveHAlign & ~(Qt::AlignAbsolute|Qt::AlignVertical_Mask)) {
- case Qt::AlignRight:
- hscroll = widthUsed - width;
- break;
- case Qt::AlignHCenter:
- hscroll = (widthUsed - width) / 2;
- break;
- default:
- // Left
- hscroll = 0;
- break;
- }
- } else {
- int cix = qRound(control->cursorToX(control->cursor() + preeditLength));
- if (cix - hscroll >= width) {
- // text doesn't fit, cursor is to the right of br (scroll right)
- hscroll = cix - width;
- } else if (cix - hscroll < 0 && hscroll < widthUsed) {
- // text doesn't fit, cursor is to the left of br (scroll left)
- hscroll = cix;
- } else if (widthUsed - hscroll < width) {
- // text doesn't fit, text document is to the left of br; align
- // right
- hscroll = widthUsed - width;
- }
- if (preeditLength > 0) {
- // check to ensure long pre-edit text doesn't push the cursor
- // off to the left
- cix = qRound(control->cursorToX(
- control->cursor() + qMax(0, control->preeditCursor() - 1)));
- if (cix < hscroll)
- hscroll = cix;
- }
- }
-}
-
-QSGNode *QQuickTextInput::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
-{
- Q_UNUSED(data);
- Q_D(QQuickTextInput);
-
- QQuickTextNode *node = static_cast<QQuickTextNode *>(oldNode);
- if (node == 0)
- node = new QQuickTextNode(QQuickItemPrivate::get(this)->sceneGraphContext());
- d->textNode = node;
-
- if (!d->textLayoutDirty) {
- QSGSimpleRectNode *cursorNode = node->cursorNode();
- if (cursorNode != 0 && !isReadOnly()) {
- QFontMetrics fm = QFontMetrics(d->font);
- // the y offset is there to keep the baseline constant in case we have script changes in the text.
- QPoint offset(-d->hscroll, fm.ascent() - d->control->ascent());
- offset.rx() += d->control->cursorToX();
-
- QRect br(boundingRect().toRect());
- cursorNode->setRect(QRectF(offset, QSizeF(d->control->cursorWidth(), br.height())));
-
- if (!d->cursorVisible
- || (!d->control->cursorBlinkStatus() && d->control->cursorBlinkPeriod() > 0)) {
- d->hideCursor();
- } else {
- d->showCursor();
- }
- }
- } else {
- node->deleteContent();
- node->setMatrix(QMatrix4x4());
-
- QPoint offset = QPoint(0,0);
- QFontMetrics fm = QFontMetrics(d->font);
- QRect br(boundingRect().toRect());
- if (d->autoScroll) {
- // the y offset is there to keep the baseline constant in case we have script changes in the text.
- offset = br.topLeft() - QPoint(d->hscroll, d->control->ascent() - fm.ascent());
- } else {
- offset = QPoint(d->hscroll, 0);
- }
-
- QTextLayout *textLayout = d->control->textLayout();
- if (!textLayout->text().isEmpty()) {
- node->addTextLayout(offset, textLayout, d->color,
- QQuickText::Normal, QColor(),
- d->selectionColor, d->selectedTextColor,
- d->control->selectionStart(),
- d->control->selectionEnd() - 1); // selectionEnd() returns first char after
- // selection
- }
-
- if (!isReadOnly() && d->cursorItem == 0) {
- offset.rx() += d->control->cursorToX();
- node->setCursor(QRectF(offset, QSizeF(d->control->cursorWidth(), br.height())), d->color);
- if (!d->cursorVisible
- || (!d->control->cursorBlinkStatus() && d->control->cursorBlinkPeriod() > 0)) {
- d->hideCursor();
- } else {
- d->showCursor();
- }
- }
-
- d->textLayoutDirty = false;
- }
-
- return node;
-}
-
-QVariant QQuickTextInput::inputMethodQuery(Qt::InputMethodQuery property) const
-{
- Q_D(const QQuickTextInput);
- switch (property) {
- case Qt::ImEnabled:
- return QVariant((bool)(flags() & ItemAcceptsInputMethod));
- case Qt::ImHints:
- return QVariant((int)inputMethodHints());
- case Qt::ImCursorRectangle:
- return cursorRectangle();
- case Qt::ImFont:
- return font();
- case Qt::ImCursorPosition:
- return QVariant(d->control->cursor());
- case Qt::ImSurroundingText:
- if (d->control->echoMode() == QLineControl::PasswordEchoOnEdit
- && !d->control->passwordEchoEditing()) {
- return QVariant(displayText());
- } else {
- return QVariant(d->control->realText());
- }
- case Qt::ImCurrentSelection:
- return QVariant(selectedText());
- case Qt::ImMaximumTextLength:
- return QVariant(maxLength());
- case Qt::ImAnchorPosition:
- if (d->control->selectionStart() == d->control->selectionEnd())
- return QVariant(d->control->cursor());
- else if (d->control->selectionStart() == d->control->cursor())
- return QVariant(d->control->selectionEnd());
- else
- return QVariant(d->control->selectionStart());
- default:
- return QVariant();
- }
-}
-
-/*!
- \qmlmethod void QtQuick2::TextInput::deselect()
-
- Removes active text selection.
-*/
-void QQuickTextInput::deselect()
-{
- Q_D(QQuickTextInput);
- d->control->deselect();
-}
-
-/*!
- \qmlmethod void QtQuick2::TextInput::selectAll()
-
- Causes all text to be selected.
-*/
-void QQuickTextInput::selectAll()
-{
- Q_D(QQuickTextInput);
- d->control->setSelection(0, d->control->text().length());
-}
-
-/*!
- \qmlmethod void QtQuick2::TextInput::isRightToLeft(int start, int end)
-
- Returns true if the natural reading direction of the editor text
- found between positions \a start and \a end is right to left.
-*/
-bool QQuickTextInput::isRightToLeft(int start, int end)
-{
- Q_D(QQuickTextInput);
- if (start > end) {
- qmlInfo(this) << "isRightToLeft(start, end) called with the end property being smaller than the start.";
- return false;
- } else {
- return d->control->text().mid(start, end - start).isRightToLeft();
- }
-}
-
-#ifndef QT_NO_CLIPBOARD
-/*!
- \qmlmethod QtQuick2::TextInput::cut()
-
- Moves the currently selected text to the system clipboard.
-*/
-void QQuickTextInput::cut()
-{
- Q_D(QQuickTextInput);
- d->control->copy();
- d->control->del();
-}
-
-/*!
- \qmlmethod QtQuick2::TextInput::copy()
-
- Copies the currently selected text to the system clipboard.
-*/
-void QQuickTextInput::copy()
-{
- Q_D(QQuickTextInput);
- d->control->copy();
-}
-
-/*!
- \qmlmethod QtQuick2::TextInput::paste()
-
- Replaces the currently selected text by the contents of the system clipboard.
-*/
-void QQuickTextInput::paste()
-{
- Q_D(QQuickTextInput);
- if (!d->control->isReadOnly())
- d->control->paste();
-}
-#endif // QT_NO_CLIPBOARD
-
-/*!
- \qmlmethod void QtQuick2::TextInput::selectWord()
-
- Causes the word closest to the current cursor position to be selected.
-*/
-void QQuickTextInput::selectWord()
-{
- Q_D(QQuickTextInput);
- d->control->selectWordAtPos(d->control->cursor());
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::smooth
-
- This property holds whether the text is smoothly scaled or transformed.
-
- Smooth filtering gives better visual quality, but is slower. If
- the item is displayed at its natural size, this property has no visual or
- performance effect.
-
- \note Generally scaling artifacts are only visible if the item is stationary on
- the screen. A common pattern when animating an item is to disable smooth
- filtering at the beginning of the animation and reenable it at the conclusion.
-*/
-
-/*!
- \qmlproperty string QtQuick2::TextInput::passwordCharacter
-
- This is the character displayed when echoMode is set to Password or
- PasswordEchoOnEdit. By default it is an asterisk.
-
- If this property is set to a string with more than one character,
- the first character is used. If the string is empty, the value
- is ignored and the property is not set.
-*/
-QString QQuickTextInput::passwordCharacter() const
-{
- Q_D(const QQuickTextInput);
- return QString(d->control->passwordCharacter());
-}
-
-void QQuickTextInput::setPasswordCharacter(const QString &str)
-{
- Q_D(QQuickTextInput);
- if (str.length() < 1)
- return;
- d->control->setPasswordCharacter(str.constData()[0]);
- EchoMode echoMode_ = echoMode();
- if (echoMode_ == Password || echoMode_ == PasswordEchoOnEdit) {
- updateSize();
- }
- emit passwordCharacterChanged();
-}
-
-/*!
- \qmlproperty string QtQuick2::TextInput::displayText
-
- This is the text displayed in the TextInput.
-
- If \l echoMode is set to TextInput::Normal, this holds the
- same value as the TextInput::text property. Otherwise,
- this property holds the text visible to the user, while
- the \l text property holds the actual entered text.
-*/
-QString QQuickTextInput::displayText() const
-{
- Q_D(const QQuickTextInput);
- return d->control->displayText();
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::selectByMouse
-
- Defaults to false.
-
- If true, the user can use the mouse to select text in some
- platform-specific way. Note that for some platforms this may
- not be an appropriate interaction (eg. may conflict with how
- the text needs to behave inside a Flickable.
-*/
-bool QQuickTextInput::selectByMouse() const
-{
- Q_D(const QQuickTextInput);
- return d->selectByMouse;
-}
-
-void QQuickTextInput::setSelectByMouse(bool on)
-{
- Q_D(QQuickTextInput);
- if (d->selectByMouse != on) {
- d->selectByMouse = on;
- emit selectByMouseChanged(on);
- }
-}
-
-/*!
- \qmlproperty enum QtQuick2::TextInput::mouseSelectionMode
-
- Specifies how text should be selected using a mouse.
-
- \list
- \o TextInput.SelectCharacters - The selection is updated with individual characters. (Default)
- \o TextInput.SelectWords - The selection is updated with whole words.
- \endlist
-
- This property only applies when \l selectByMouse is true.
-*/
-
-QQuickTextInput::SelectionMode QQuickTextInput::mouseSelectionMode() const
-{
- Q_D(const QQuickTextInput);
- return d->mouseSelectionMode;
-}
-
-void QQuickTextInput::setMouseSelectionMode(SelectionMode mode)
-{
- Q_D(QQuickTextInput);
- if (d->mouseSelectionMode != mode) {
- d->mouseSelectionMode = mode;
- emit mouseSelectionModeChanged(mode);
- }
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::canPaste
-
- Returns true if the TextInput is writable and the content of the clipboard is
- suitable for pasting into the TextEdit.
-*/
-bool QQuickTextInput::canPaste() const
-{
- Q_D(const QQuickTextInput);
- return d->canPaste;
-}
-
-void QQuickTextInput::moveCursorSelection(int position)
-{
- Q_D(QQuickTextInput);
- d->control->moveCursor(position, true);
-}
-
-/*!
- \qmlmethod void QtQuick2::TextInput::moveCursorSelection(int position, SelectionMode mode = TextInput.SelectCharacters)
-
- Moves the cursor to \a position and updates the selection according to the optional \a mode
- parameter. (To only move the cursor, set the \l cursorPosition property.)
-
- When this method is called it additionally sets either the
- selectionStart or the selectionEnd (whichever was at the previous cursor position)
- to the specified position. This allows you to easily extend and contract the selected
- text range.
-
- The selection mode specifies whether the selection is updated on a per character or a per word
- basis. If not specified the selection mode will default to TextInput.SelectCharacters.
-
- \list
- \o TextEdit.SelectCharacters - Sets either the selectionStart or selectionEnd (whichever was at
- the previous cursor position) to the specified position.
- \o TextEdit.SelectWords - Sets the selectionStart and selectionEnd to include all
- words between the specified position and the previous cursor position. Words partially in the
- range are included.
- \endlist
-
- For example, take this sequence of calls:
-
- \code
- cursorPosition = 5
- moveCursorSelection(9, TextInput.SelectCharacters)
- moveCursorSelection(7, TextInput.SelectCharacters)
- \endcode
-
- This moves the cursor to position 5, extend the selection end from 5 to 9
- and then retract the selection end from 9 to 7, leaving the text from position 5 to 7
- selected (the 6th and 7th characters).
-
- The same sequence with TextInput.SelectWords will extend the selection start to a word boundary
- before or on position 5 and extend the selection end to a word boundary on or past position 9.
-*/
-void QQuickTextInput::moveCursorSelection(int pos, SelectionMode mode)
-{
- Q_D(QQuickTextInput);
-
- if (mode == SelectCharacters) {
- d->control->moveCursor(pos, true);
- } else if (pos != d->control->cursor()){
- const int cursor = d->control->cursor();
- int anchor;
- if (!d->control->hasSelectedText())
- anchor = d->control->cursor();
- else if (d->control->selectionStart() == d->control->cursor())
- anchor = d->control->selectionEnd();
- else
- anchor = d->control->selectionStart();
-
- if (anchor < pos || (anchor == pos && cursor < pos)) {
- const QString text = d->control->text();
- QTextBoundaryFinder finder(QTextBoundaryFinder::Word, text);
- finder.setPosition(anchor);
-
- const QTextBoundaryFinder::BoundaryReasons reasons = finder.boundaryReasons();
- if (anchor < text.length() && (!(reasons & QTextBoundaryFinder::StartWord)
- || ((reasons & QTextBoundaryFinder::EndWord) && anchor > cursor))) {
- finder.toPreviousBoundary();
- }
- anchor = finder.position() != -1 ? finder.position() : 0;
-
- finder.setPosition(pos);
- if (pos > 0 && !finder.boundaryReasons())
- finder.toNextBoundary();
- const int cursor = finder.position() != -1 ? finder.position() : text.length();
-
- d->control->setSelection(anchor, cursor - anchor);
- } else if (anchor > pos || (anchor == pos && cursor > pos)) {
- const QString text = d->control->text();
- QTextBoundaryFinder finder(QTextBoundaryFinder::Word, text);
- finder.setPosition(anchor);
-
- const QTextBoundaryFinder::BoundaryReasons reasons = finder.boundaryReasons();
- if (anchor > 0 && (!(reasons & QTextBoundaryFinder::EndWord)
- || ((reasons & QTextBoundaryFinder::StartWord) && anchor < cursor))) {
- finder.toNextBoundary();
- }
-
- anchor = finder.position() != -1 ? finder.position() : text.length();
-
- finder.setPosition(pos);
- if (pos < text.length() && !finder.boundaryReasons())
- finder.toPreviousBoundary();
- const int cursor = finder.position() != -1 ? finder.position() : 0;
-
- d->control->setSelection(anchor, cursor - anchor);
- }
- }
-}
-
-/*!
- \qmlmethod void QtQuick2::TextInput::openSoftwareInputPanel()
-
- Opens software input panels like virtual keyboards for typing, useful for
- customizing when you want the input keyboard to be shown and hidden in
- your application.
-
- By default the opening of input panels follows the platform style. Input panels are
- always closed if no editor has active focus.
-
- You can disable the automatic behavior by setting the property \c activeFocusOnPress to false
- and use functions openSoftwareInputPanel() and closeSoftwareInputPanel() to implement
- the behavior you want.
-
- Only relevant on platforms, which provide virtual keyboards.
-
- \qml
- import QtQuick 1.0
- TextInput {
- id: textInput
- text: "Hello world!"
- activeFocusOnPress: false
- MouseArea {
- anchors.fill: parent
- onClicked: {
- if (!textInput.activeFocus) {
- textInput.forceActiveFocus()
- textInput.openSoftwareInputPanel();
- } else {
- textInput.focus = false;
- }
- }
- onPressAndHold: textInput.closeSoftwareInputPanel();
- }
- }
- \endqml
-*/
-void QQuickTextInput::openSoftwareInputPanel()
-{
- if (qGuiApp)
- qGuiApp->inputPanel()->show();
-}
-
-/*!
- \qmlmethod void QtQuick2::TextInput::closeSoftwareInputPanel()
-
- Closes a software input panel like a virtual keyboard shown on the screen, useful
- for customizing when you want the input keyboard to be shown and hidden in
- your application.
-
- By default the opening of input panels follows the platform style. Input panels are
- always closed if no editor has active focus.
-
- You can disable the automatic behavior by setting the property \c activeFocusOnPress to false
- and use functions openSoftwareInputPanel() and closeSoftwareInputPanel() to implement
- the behavior you want.
-
- Only relevant on platforms, which provide virtual keyboards.
-
- \qml
- import QtQuick 1.0
- TextInput {
- id: textInput
- text: "Hello world!"
- activeFocusOnPress: false
- MouseArea {
- anchors.fill: parent
- onClicked: {
- if (!textInput.activeFocus) {
- textInput.forceActiveFocus();
- textInput.openSoftwareInputPanel();
- } else {
- textInput.focus = false;
- }
- }
- onPressAndHold: textInput.closeSoftwareInputPanel();
- }
- }
- \endqml
-*/
-void QQuickTextInput::closeSoftwareInputPanel()
-{
- if (qGuiApp)
- qGuiApp->inputPanel()->hide();
-}
-
-void QQuickTextInput::focusInEvent(QFocusEvent *event)
-{
- Q_D(const QQuickTextInput);
- if (d->focusOnPress && !isReadOnly())
- openSoftwareInputPanel();
- QQuickImplicitSizeItem::focusInEvent(event);
-}
-
-void QQuickTextInput::itemChange(ItemChange change, const ItemChangeData &value)
-{
- Q_D(QQuickTextInput);
- if (change == ItemActiveFocusHasChanged) {
- bool hasFocus = value.boolValue;
- d->focused = hasFocus;
- setCursorVisible(hasFocus); // ### refactor: && d->canvas && d->canvas->hasFocus()
- if (echoMode() == QQuickTextInput::PasswordEchoOnEdit && !hasFocus)
- d->control->updatePasswordEchoEditing(false);//QLineControl sets it on key events, but doesn't deal with focus events
- if (!hasFocus)
- d->control->deselect();
- }
- QQuickItem::itemChange(change, value);
-}
-
-/*!
- \qmlproperty bool QtQuick2::TextInput::inputMethodComposing
-
-
- This property holds whether the TextInput has partial text input from an
- input method.
-
- While it is composing an input method may rely on mouse or key events from
- the TextInput to edit or commit the partial text. This property can be
- used to determine when to disable events handlers that may interfere with
- the correct operation of an input method.
-*/
-bool QQuickTextInput::isInputMethodComposing() const
-{
- Q_D(const QQuickTextInput);
- return d->control->preeditAreaText().length() > 0;
-}
-
-void QQuickTextInputPrivate::init()
-{
- Q_Q(QQuickTextInput);
- control->setParent(q);//Now mandatory due to accessibility changes
- control->setCursorWidth(1);
- control->setPasswordCharacter(QLatin1Char('*'));
- q->setSmooth(smooth);
- q->setAcceptedMouseButtons(Qt::LeftButton);
- q->setFlag(QQuickItem::ItemAcceptsInputMethod);
- q->setFlag(QQuickItem::ItemHasContents);
- q->connect(control, SIGNAL(cursorPositionChanged(int,int)),
- q, SLOT(cursorPosChanged()));
- q->connect(control, SIGNAL(selectionChanged()),
- q, SLOT(selectionChanged()));
- q->connect(control, SIGNAL(textChanged(QString)),
- q, SLOT(q_textChanged()));
- q->connect(control, SIGNAL(accepted()),
- q, SIGNAL(accepted()));
- q->connect(control, SIGNAL(updateNeeded(QRect)),
- q, SLOT(updateRect(QRect)));
-#ifndef QT_NO_CLIPBOARD
- q->connect(q, SIGNAL(readOnlyChanged(bool)),
- q, SLOT(q_canPasteChanged()));
- q->connect(QGuiApplication::clipboard(), SIGNAL(dataChanged()),
- q, SLOT(q_canPasteChanged()));
- canPaste = !control->isReadOnly() && QGuiApplication::clipboard()->text().length() != 0;
-#endif // QT_NO_CLIPBOARD
- q->connect(control, SIGNAL(updateMicroFocus()),
- q, SLOT(updateCursorRectangle()));
- q->connect(control, SIGNAL(displayTextChanged(QString)),
- q, SLOT(updateRect()));
- q->updateSize();
- imHints &= ~Qt::ImhMultiLine;
- oldValidity = control->hasAcceptableInput();
- lastSelectionStart = 0;
- lastSelectionEnd = 0;
- QPalette p = control->palette();
- selectedTextColor = p.color(QPalette::HighlightedText);
- selectionColor = p.color(QPalette::Highlight);
- determineHorizontalAlignment();
-
- if (!qmlDisableDistanceField()) {
- QTextOption option = control->textLayout()->textOption();
- option.setUseDesignMetrics(true);
- control->textLayout()->setTextOption(option);
- }
-}
-
-void QQuickTextInput::cursorPosChanged()
-{
- Q_D(QQuickTextInput);
- updateCursorRectangle();
- emit cursorPositionChanged();
- // XXX todo - not in 4.8?
-#if 0
- d->control->resetCursorBlinkTimer();
-#endif
-
- if (!d->control->hasSelectedText()) {
- if (d->lastSelectionStart != d->control->cursor()) {
- d->lastSelectionStart = d->control->cursor();
- emit selectionStartChanged();
- }
- if (d->lastSelectionEnd != d->control->cursor()) {
- d->lastSelectionEnd = d->control->cursor();
- emit selectionEndChanged();
- }
- }
-}
-
-void QQuickTextInput::updateCursorRectangle()
-{
- Q_D(QQuickTextInput);
- d->determineHorizontalAlignment();
- d->updateHorizontalScroll();
- updateRect();//TODO: Only update rect between pos's
- updateMicroFocus();
- emit cursorRectangleChanged();
- if (d->cursorItem)
- d->cursorItem->setX(d->control->cursorToX() - d->hscroll);
-}
-
-void QQuickTextInput::selectionChanged()
-{
- Q_D(QQuickTextInput);
- updateRect();//TODO: Only update rect in selection
- emit selectedTextChanged();
-
- if (d->lastSelectionStart != d->control->selectionStart()) {
- d->lastSelectionStart = d->control->selectionStart();
- if (d->lastSelectionStart == -1)
- d->lastSelectionStart = d->control->cursor();
- emit selectionStartChanged();
- }
- if (d->lastSelectionEnd != d->control->selectionEnd()) {
- d->lastSelectionEnd = d->control->selectionEnd();
- if (d->lastSelectionEnd == -1)
- d->lastSelectionEnd = d->control->cursor();
- emit selectionEndChanged();
- }
-}
-
-void QQuickTextInput::q_textChanged()
-{
- Q_D(QQuickTextInput);
- emit textChanged();
- emit displayTextChanged();
- updateSize();
- d->determineHorizontalAlignment();
- d->updateHorizontalScroll();
- updateMicroFocus();
- if (hasAcceptableInput() != d->oldValidity) {
- d->oldValidity = hasAcceptableInput();
- emit acceptableInputChanged();
- }
-}
-
-void QQuickTextInputPrivate::showCursor()
-{
- if (textNode != 0 && textNode->cursorNode() != 0)
- textNode->cursorNode()->setColor(color);
-}
-
-void QQuickTextInputPrivate::hideCursor()
-{
- if (textNode != 0 && textNode->cursorNode() != 0)
- textNode->cursorNode()->setColor(QColor(0, 0, 0, 0));
-}
-
-void QQuickTextInput::updateRect(const QRect &r)
-{
- Q_D(QQuickTextInput);
- if (!isComponentComplete())
- return;
-
- if (r.isEmpty()) {
- d->textLayoutDirty = true;
- }
-
- update();
-}
-
-QRectF QQuickTextInput::boundingRect() const
-{
- Q_D(const QQuickTextInput);
- QRectF r = QQuickImplicitSizeItem::boundingRect();
-
- int cursorWidth = d->cursorItem ? d->cursorItem->width() : d->control->cursorWidth();
-
- // Could include font max left/right bearings to either side of rectangle.
-
- r.setRight(r.right() + cursorWidth);
- return r;
-}
-
-void QQuickTextInput::updateSize(bool needsRedraw)
-{
- Q_D(QQuickTextInput);
- int w = width();
- int h = height();
- setImplicitSize(d->calculateTextWidth(), d->control->height()-1); // -1 to counter QLineControl's +1 which is not consistent with Text.
- if (w==width() && h==height() && needsRedraw)
- update();
-}
-
-void QQuickTextInput::q_canPasteChanged()
-{
- Q_D(QQuickTextInput);
- bool old = d->canPaste;
-#ifndef QT_NO_CLIPBOARD
- d->canPaste = !d->control->isReadOnly() && QGuiApplication::clipboard()->text().length() != 0;
-#endif
- if (d->canPaste != old)
- emit canPasteChanged();
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/items/qquicktextinput_p.h b/src/declarative/items/qquicktextinput_p.h
deleted file mode 100644
index 493788ec84..0000000000
--- a/src/declarative/items/qquicktextinput_p.h
+++ /dev/null
@@ -1,302 +0,0 @@
-// Commit: 2f173e4945dd8414636c1061acfaf9c2d8b718d8
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKTEXTINPUT_P_H
-#define QQUICKTEXTINPUT_P_H
-
-#include "qquickimplicitsizeitem_p.h"
-#include <QtGui/qvalidator.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickTextInputPrivate;
-class QValidator;
-class Q_AUTOTEST_EXPORT QQuickTextInput : public QQuickImplicitSizeItem
-{
- Q_OBJECT
- Q_ENUMS(HAlignment)
- Q_ENUMS(EchoMode)
- Q_ENUMS(SelectionMode)
-
- Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
- Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
- Q_PROPERTY(QColor selectionColor READ selectionColor WRITE setSelectionColor NOTIFY selectionColorChanged)
- Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor NOTIFY selectedTextColorChanged)
- Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged)
- Q_PROPERTY(HAlignment horizontalAlignment READ hAlign WRITE setHAlign RESET resetHAlign NOTIFY horizontalAlignmentChanged)
- Q_PROPERTY(HAlignment effectiveHorizontalAlignment READ effectiveHAlign NOTIFY effectiveHorizontalAlignmentChanged)
-
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly NOTIFY readOnlyChanged)
- Q_PROPERTY(bool cursorVisible READ isCursorVisible WRITE setCursorVisible NOTIFY cursorVisibleChanged)
- Q_PROPERTY(int cursorPosition READ cursorPosition WRITE setCursorPosition NOTIFY cursorPositionChanged)
- Q_PROPERTY(QRect cursorRectangle READ cursorRectangle NOTIFY cursorRectangleChanged)
- Q_PROPERTY(QDeclarativeComponent *cursorDelegate READ cursorDelegate WRITE setCursorDelegate NOTIFY cursorDelegateChanged)
- Q_PROPERTY(int selectionStart READ selectionStart NOTIFY selectionStartChanged)
- Q_PROPERTY(int selectionEnd READ selectionEnd NOTIFY selectionEndChanged)
- Q_PROPERTY(QString selectedText READ selectedText NOTIFY selectedTextChanged)
-
- Q_PROPERTY(int maximumLength READ maxLength WRITE setMaxLength NOTIFY maximumLengthChanged)
-#ifndef QT_NO_VALIDATOR
- Q_PROPERTY(QValidator* validator READ validator WRITE setValidator NOTIFY validatorChanged)
-#endif
- Q_PROPERTY(QString inputMask READ inputMask WRITE setInputMask NOTIFY inputMaskChanged)
- Q_PROPERTY(Qt::InputMethodHints inputMethodHints READ imHints WRITE setIMHints)
-
- Q_PROPERTY(bool acceptableInput READ hasAcceptableInput NOTIFY acceptableInputChanged)
- Q_PROPERTY(EchoMode echoMode READ echoMode WRITE setEchoMode NOTIFY echoModeChanged)
- Q_PROPERTY(bool activeFocusOnPress READ focusOnPress WRITE setFocusOnPress NOTIFY activeFocusOnPressChanged)
- Q_PROPERTY(QString passwordCharacter READ passwordCharacter WRITE setPasswordCharacter NOTIFY passwordCharacterChanged)
- Q_PROPERTY(QString displayText READ displayText NOTIFY displayTextChanged)
- Q_PROPERTY(bool autoScroll READ autoScroll WRITE setAutoScroll NOTIFY autoScrollChanged)
- Q_PROPERTY(bool selectByMouse READ selectByMouse WRITE setSelectByMouse NOTIFY selectByMouseChanged)
- Q_PROPERTY(SelectionMode mouseSelectionMode READ mouseSelectionMode WRITE setMouseSelectionMode NOTIFY mouseSelectionModeChanged)
- Q_PROPERTY(bool canPaste READ canPaste NOTIFY canPasteChanged)
- Q_PROPERTY(bool inputMethodComposing READ isInputMethodComposing NOTIFY inputMethodComposingChanged)
-
-public:
- QQuickTextInput(QQuickItem * parent=0);
- ~QQuickTextInput();
-
- enum EchoMode {//To match QLineEdit::EchoMode
- Normal,
- NoEcho,
- Password,
- PasswordEchoOnEdit
- };
-
- enum HAlignment {
- AlignLeft = Qt::AlignLeft,
- AlignRight = Qt::AlignRight,
- AlignHCenter = Qt::AlignHCenter
- };
-
- enum SelectionMode {
- SelectCharacters,
- SelectWords
- };
-
- enum CursorPosition {
- CursorBetweenCharacters,
- CursorOnCharacter
- };
-
- //Auxilliary functions needed to control the TextInput from QML
- Q_INVOKABLE int positionAt(int x) const;
- Q_INVOKABLE int positionAt(int x, CursorPosition position) const;
- Q_INVOKABLE QRectF positionToRectangle(int pos) const;
- Q_INVOKABLE void moveCursorSelection(int pos);
- Q_INVOKABLE void moveCursorSelection(int pos, SelectionMode mode);
-
- Q_INVOKABLE void openSoftwareInputPanel();
- Q_INVOKABLE void closeSoftwareInputPanel();
-
- QString text() const;
- void setText(const QString &);
-
- QFont font() const;
- void setFont(const QFont &font);
-
- QColor color() const;
- void setColor(const QColor &c);
-
- QColor selectionColor() const;
- void setSelectionColor(const QColor &c);
-
- QColor selectedTextColor() const;
- void setSelectedTextColor(const QColor &c);
-
- HAlignment hAlign() const;
- void setHAlign(HAlignment align);
- void resetHAlign();
- HAlignment effectiveHAlign() const;
-
- bool isReadOnly() const;
- void setReadOnly(bool);
-
- bool isCursorVisible() const;
- void setCursorVisible(bool on);
-
- int cursorPosition() const;
- void setCursorPosition(int cp);
-
- QRect cursorRectangle() const;
-
- int selectionStart() const;
- int selectionEnd() const;
-
- QString selectedText() const;
-
- int maxLength() const;
- void setMaxLength(int ml);
-
-#ifndef QT_NO_VALIDATOR
- QValidator * validator() const;
- void setValidator(QValidator* v);
-#endif
- QString inputMask() const;
- void setInputMask(const QString &im);
-
- EchoMode echoMode() const;
- void setEchoMode(EchoMode echo);
-
- QString passwordCharacter() const;
- void setPasswordCharacter(const QString &str);
-
- QString displayText() const;
-
- QDeclarativeComponent* cursorDelegate() const;
- void setCursorDelegate(QDeclarativeComponent*);
-
- bool focusOnPress() const;
- void setFocusOnPress(bool);
-
- bool autoScroll() const;
- void setAutoScroll(bool);
-
- bool selectByMouse() const;
- void setSelectByMouse(bool);
-
- SelectionMode mouseSelectionMode() const;
- void setMouseSelectionMode(SelectionMode mode);
-
- bool hasAcceptableInput() const;
-
- QVariant inputMethodQuery(Qt::InputMethodQuery property) const;
-
- QRectF boundingRect() const;
- bool canPaste() const;
-
- bool isInputMethodComposing() const;
-
- Qt::InputMethodHints imHints() const;
- void setIMHints(Qt::InputMethodHints hints);
-
-Q_SIGNALS:
- void textChanged();
- void cursorPositionChanged();
- void cursorRectangleChanged();
- void selectionStartChanged();
- void selectionEndChanged();
- void selectedTextChanged();
- void accepted();
- void acceptableInputChanged();
- void colorChanged(const QColor &color);
- void selectionColorChanged(const QColor &color);
- void selectedTextColorChanged(const QColor &color);
- void fontChanged(const QFont &font);
- void horizontalAlignmentChanged(HAlignment alignment);
- void readOnlyChanged(bool isReadOnly);
- void cursorVisibleChanged(bool isCursorVisible);
- void cursorDelegateChanged();
- void maximumLengthChanged(int maximumLength);
- void validatorChanged();
- void inputMaskChanged(const QString &inputMask);
- void echoModeChanged(EchoMode echoMode);
- void passwordCharacterChanged();
- void displayTextChanged();
- void activeFocusOnPressChanged(bool activeFocusOnPress);
- void autoScrollChanged(bool autoScroll);
- void selectByMouseChanged(bool selectByMouse);
- void mouseSelectionModeChanged(SelectionMode mode);
- void canPasteChanged();
- void inputMethodComposingChanged();
- void effectiveHorizontalAlignmentChanged();
-
-protected:
- virtual void geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry);
-
- void mousePressEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void mouseDoubleClickEvent(QMouseEvent *event);
- void keyPressEvent(QKeyEvent* ev);
- void inputMethodEvent(QInputMethodEvent *);
- void mouseUngrabEvent();
- bool event(QEvent *e);
- void focusInEvent(QFocusEvent *event);
- virtual void itemChange(ItemChange, const ItemChangeData &);
- QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data);
-
-public Q_SLOTS:
- void selectAll();
- void selectWord();
- void select(int start, int end);
- void deselect();
- bool isRightToLeft(int start, int end);
-#ifndef QT_NO_CLIPBOARD
- void cut();
- void copy();
- void paste();
-#endif
-
-private Q_SLOTS:
- void updateSize(bool needsRedraw = true);
- void q_textChanged();
- void selectionChanged();
- void createCursor();
- void cursorPosChanged();
- void updateCursorRectangle();
- void updateRect(const QRect &r = QRect());
- void q_canPasteChanged();
-
-private:
- Q_DECLARE_PRIVATE(QQuickTextInput)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickTextInput)
-#ifndef QT_NO_VALIDATOR
-QML_DECLARE_TYPE(QValidator)
-QML_DECLARE_TYPE(QIntValidator)
-QML_DECLARE_TYPE(QDoubleValidator)
-QML_DECLARE_TYPE(QRegExpValidator)
-#endif
-
-QT_END_HEADER
-
-#endif // QQUICKTEXTINPUT_P_H
diff --git a/src/declarative/items/qquicktextinput_p_p.h b/src/declarative/items/qquicktextinput_p_p.h
deleted file mode 100644
index 900b0804bb..0000000000
--- a/src/declarative/items/qquicktextinput_p_p.h
+++ /dev/null
@@ -1,172 +0,0 @@
-// Commit: 47712d1f330e4b22ce6dd30e7557288ef7f7fca0
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKTEXTINPUT_P_P_H
-#define QQUICKTEXTINPUT_P_P_H
-
-#include "qquicktextinput_p.h"
-#include "qquicktext_p.h"
-#include "qquickimplicitsizeitem_p_p.h"
-
-#include <private/qlinecontrol_p.h>
-
-#include <QtDeclarative/qdeclarative.h>
-#include <QtCore/qelapsedtimer.h>
-#include <QtCore/qpointer.h>
-#include <QtGui/qguiapplication.h>
-#include <QtGui/qstylehints.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.
-
-QT_BEGIN_NAMESPACE
-
-class QQuickTextNode;
-
-class Q_AUTOTEST_EXPORT QQuickTextInputPrivate : public QQuickImplicitSizeItemPrivate
-{
- Q_DECLARE_PUBLIC(QQuickTextInput)
-public:
- QQuickTextInputPrivate()
- : control(new QLineControl(QString()))
- , color((QRgb)0)
- , style(QQuickText::Normal)
- , styleColor((QRgb)0)
- , hAlign(QQuickTextInput::AlignLeft)
- , mouseSelectionMode(QQuickTextInput::SelectCharacters)
- , inputMethodHints(Qt::ImhNone)
- , textNode(0)
- , hscroll(0)
- , oldScroll(0)
- , oldValidity(false)
- , focused(false)
- , focusOnPress(true)
- , cursorVisible(false)
- , autoScroll(true)
- , selectByMouse(false)
- , canPaste(false)
- , hAlignImplicit(true)
- , selectPressed(false)
- , textLayoutDirty(true)
- {
- }
-
- ~QQuickTextInputPrivate()
- {
- }
-
- int xToPos(int x, QTextLine::CursorPosition betweenOrOn = QTextLine::CursorBetweenCharacters) const
- {
- Q_Q(const QQuickTextInput);
- QRect cr = q->boundingRect().toRect();
- x-= cr.x() - hscroll;
- return control->xToPos(x, betweenOrOn);
- }
-
- void init();
- void startCreatingCursor();
- void updateHorizontalScroll();
- bool determineHorizontalAlignment();
- bool setHAlign(QQuickTextInput::HAlignment, bool forceAlign = false);
- void mirrorChange();
- int calculateTextWidth();
- bool sendMouseEventToInputContext(QMouseEvent *event);
- void updateInputMethodHints();
- void hideCursor();
- void showCursor();
-
- QLineControl* control;
-
- QFont font;
- QFont sourceFont;
- QColor color;
- QColor selectionColor;
- QColor selectedTextColor;
- QQuickText::TextStyle style;
- QColor styleColor;
- QQuickTextInput::HAlignment hAlign;
- QQuickTextInput::SelectionMode mouseSelectionMode;
- Qt::InputMethodHints inputMethodHints;
- QPointer<QDeclarativeComponent> cursorComponent;
- QPointer<QQuickItem> cursorItem;
- QPointF pressPos;
- QQuickTextNode *textNode;
- QElapsedTimer tripleClickTimer;
- QPoint tripleClickStartPoint;
-
- int lastSelectionStart;
- int lastSelectionEnd;
- int oldHeight;
- int oldWidth;
- int hscroll;
- int oldScroll;
-
- bool oldValidity:1;
- bool focused:1;
- bool focusOnPress:1;
- bool cursorVisible:1;
- bool autoScroll:1;
- bool selectByMouse:1;
- bool canPaste:1;
- bool hAlignImplicit:1;
- bool selectPressed:1;
- bool textLayoutDirty:1;
-
- static inline QQuickTextInputPrivate *get(QQuickTextInput *t) {
- return t->d_func();
- }
- bool hasPendingTripleClick() const {
- return !tripleClickTimer.hasExpired(qApp->styleHints()->mouseDoubleClickInterval());
- }
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKTEXTINPUT_P_P_H
diff --git a/src/declarative/items/qquicktextnode.cpp b/src/declarative/items/qquicktextnode.cpp
deleted file mode 100644
index 56c3b54cd7..0000000000
--- a/src/declarative/items/qquicktextnode.cpp
+++ /dev/null
@@ -1,1344 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquicktextnode_p.h"
-#include "qsgsimplerectnode.h"
-#include <private/qsgadaptationlayer_p.h>
-#include <private/qsgdistancefieldglyphnode_p.h>
-
-#include <private/qsgcontext_p.h>
-
-#include <QtCore/qpoint.h>
-#include <qmath.h>
-#include <qtextdocument.h>
-#include <qtextlayout.h>
-#include <qabstracttextdocumentlayout.h>
-#include <qxmlstream.h>
-#include <qrawfont.h>
-#include <qtexttable.h>
-#include <qtextlist.h>
-#include <private/qdeclarativestyledtext_p.h>
-#include <private/qfont_p.h>
-#include <private/qfontengine_p.h>
-#include <private/qrawfont_p.h>
-#include <private/qtextimagehandler_p.h>
-#include <private/qtextdocumentlayout_p.h>
-#include <qhash.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- Creates an empty QQuickTextNode
-*/
-QQuickTextNode::QQuickTextNode(QSGContext *context)
- : m_context(context), m_cursorNode(0)
-{
-#if defined(QML_RUNTIME_TESTING)
- description = QLatin1String("text");
-#endif
-}
-
-QQuickTextNode::~QQuickTextNode()
-{
- qDeleteAll(m_textures);
-}
-
-#if 0
-void QQuickTextNode::setColor(const QColor &color)
-{
- if (m_usePixmapCache) {
- setUpdateFlag(UpdateNodes);
- } else {
- for (QSGNode *childNode = firstChild(); childNode; childNode = childNode->nextSibling()) {
- if (childNode->subType() == GlyphNodeSubType) {
- QSGGlyphNode *glyphNode = static_cast<QSGGlyphNode *>(childNode);
- if (glyphNode->color() == m_color)
- glyphNode->setColor(color);
- } else if (childNode->subType() == SolidRectNodeSubType) {
- QSGSimpleRectNode *solidRectNode = static_cast<QSGSimpleRectNode *>(childNode);
- if (solidRectNode->color() == m_color)
- solidRectNode->setColor(color);
- }
- }
- }
- m_color = color;
-}
-
-void QQuickTextNode::setStyleColor(const QColor &styleColor)
-{
- if (m_textStyle != QQuickTextNode::NormalTextStyle) {
- if (m_usePixmapCache) {
- setUpdateFlag(UpdateNodes);
- } else {
- for (QSGNode *childNode = firstChild(); childNode; childNode = childNode->nextSibling()) {
- if (childNode->subType() == GlyphNodeSubType) {
- QSGGlyphNode *glyphNode = static_cast<QSGGlyphNode *>(childNode);
- if (glyphNode->color() == m_styleColor)
- glyphNode->setColor(styleColor);
- } else if (childNode->subType() == SolidRectNodeSubType) {
- QSGSimpleRectNode *solidRectNode = static_cast<QSGSimpleRectNode *>(childNode);
- if (solidRectNode->color() == m_styleColor)
- solidRectNode->setColor(styleColor);
- }
- }
- }
- }
- m_styleColor = styleColor;
-}
-#endif
-
-QSGGlyphNode *QQuickTextNode::addGlyphs(const QPointF &position, const QGlyphRun &glyphs, const QColor &color,
- QQuickText::TextStyle style, const QColor &styleColor,
- QSGNode *parentNode)
-{
- QSGGlyphNode *node = m_context->createGlyphNode();
- node->setGlyphs(position + QPointF(0, glyphs.rawFont().ascent()), glyphs);
- node->setStyle(style);
- node->setStyleColor(styleColor);
- node->setColor(color);
- node->update();
-
- /* We flag the geometry as static, but we never call markVertexDataDirty
- or markIndexDataDirty on them. This is because all text nodes are
- discarded when a change occurs. If we start appending/removing from
- existing geometry, then we also need to start marking the geometry as
- dirty.
- */
- node->geometry()->setIndexDataPattern(QSGGeometry::StaticPattern);
- node->geometry()->setVertexDataPattern(QSGGeometry::StaticPattern);
-
- if (parentNode == 0)
- parentNode = this;
- parentNode->appendChildNode(node);
-
- return node;
-}
-
-void QQuickTextNode::setCursor(const QRectF &rect, const QColor &color)
-{
- if (m_cursorNode != 0)
- delete m_cursorNode;
-
- m_cursorNode = new QSGSimpleRectNode(rect, color);
- appendChildNode(m_cursorNode);
-}
-
-namespace {
-
- struct BinaryTreeNode {
- enum SelectionState {
- Unselected,
- Selected
- };
-
- BinaryTreeNode()
- : selectionState(Unselected)
- , clipNode(0)
- , decorations(QQuickTextNode::NoDecoration)
- , ascent(0.0)
- , leftChildIndex(-1)
- , rightChildIndex(-1)
- {
-
- }
-
- BinaryTreeNode(const QRectF &brect, const QImage &i, SelectionState selState, qreal a)
- : boundingRect(brect)
- , selectionState(selState)
- , clipNode(0)
- , decorations(QQuickTextNode::NoDecoration)
- , image(i)
- , ascent(a)
- , leftChildIndex(-1)
- , rightChildIndex(-1)
- {
- }
-
- BinaryTreeNode(const QGlyphRun &g, SelectionState selState, const QRectF &brect,
- const QQuickTextNode::Decorations &decs, const QColor &c, const QColor &bc,
- const QPointF &pos, qreal a)
- : glyphRun(g)
- , boundingRect(brect)
- , selectionState(selState)
- , clipNode(0)
- , decorations(decs)
- , color(c)
- , backgroundColor(bc)
- , position(pos)
- , ascent(a)
- , leftChildIndex(-1)
- , rightChildIndex(-1)
- {
- }
-
- QGlyphRun glyphRun;
- QRectF boundingRect;
- SelectionState selectionState;
- QSGClipNode *clipNode;
- QQuickTextNode::Decorations decorations;
- QColor color;
- QColor backgroundColor;
- QPointF position;
- QImage image;
- qreal ascent;
-
- int leftChildIndex;
- int rightChildIndex;
-
- static void insert(QVarLengthArray<BinaryTreeNode> *binaryTree,
- const QRectF &rect,
- const QImage &image,
- qreal ascent,
- SelectionState selectionState)
- {
- insert(binaryTree, BinaryTreeNode(rect, image, selectionState, ascent));
- }
-
- static void insert(QVarLengthArray<BinaryTreeNode> *binaryTree,
- const QGlyphRun &glyphRun,
- SelectionState selectionState,
- const QColor &textColor,
- const QColor &backgroundColor,
- const QPointF &position)
- {
- QRectF searchRect = glyphRun.boundingRect();
- searchRect.translate(position);
-
- if (qFuzzyIsNull(searchRect.width()) || qFuzzyIsNull(searchRect.height()))
- return;
-
- QQuickTextNode::Decorations decorations = QQuickTextNode::NoDecoration;
- decorations |= (glyphRun.underline() ? QQuickTextNode::Underline : QQuickTextNode::NoDecoration);
- decorations |= (glyphRun.overline() ? QQuickTextNode::Overline : QQuickTextNode::NoDecoration);
- decorations |= (glyphRun.strikeOut() ? QQuickTextNode::StrikeOut : QQuickTextNode::NoDecoration);
- decorations |= (backgroundColor.isValid() ? QQuickTextNode::Background : QQuickTextNode::NoDecoration);
-
- qreal ascent = glyphRun.rawFont().ascent();
- insert(binaryTree, BinaryTreeNode(glyphRun, selectionState, searchRect, decorations,
- textColor, backgroundColor, position, ascent));
- }
-
- static void insert(QVarLengthArray<BinaryTreeNode> *binaryTree,
- const BinaryTreeNode &binaryTreeNode)
- {
- int newIndex = binaryTree->size();
- binaryTree->append(binaryTreeNode);
- if (newIndex == 0)
- return;
-
- int searchIndex = 0;
- forever {
- BinaryTreeNode *node = binaryTree->data() + searchIndex;
- if (binaryTreeNode.boundingRect.left() < node->boundingRect.left()) {
- if (node->leftChildIndex < 0) {
- node->leftChildIndex = newIndex;
- break;
- } else {
- searchIndex = node->leftChildIndex;
- }
- } else {
- if (node->rightChildIndex < 0) {
- node->rightChildIndex = newIndex;
- break;
- } else {
- searchIndex = node->rightChildIndex;
- }
- }
- }
- }
-
- static void inOrder(const QVarLengthArray<BinaryTreeNode> &binaryTree,
- QVarLengthArray<int> *sortedIndexes,
- int currentIndex = 0)
- {
- Q_ASSERT(currentIndex < binaryTree.size());
-
- const BinaryTreeNode *node = binaryTree.data() + currentIndex;
- if (node->leftChildIndex >= 0)
- inOrder(binaryTree, sortedIndexes, node->leftChildIndex);
-
- sortedIndexes->append(currentIndex);
-
- if (node->rightChildIndex >= 0)
- inOrder(binaryTree, sortedIndexes, node->rightChildIndex);
- }
- };
-
- // Engine that takes glyph runs as input, and produces a set of glyph nodes, clip nodes,
- // and rectangle nodes to represent the text, decorations and selection. Will try to minimize
- // number of nodes, and join decorations in neighbouring items
- class SelectionEngine
- {
- public:
- SelectionEngine() : m_hasSelection(false) {}
-
- QTextLine currentLine() const { return m_currentLine; }
-
- void setCurrentLine(const QTextLine &currentLine)
- {
- if (m_currentLine.isValid())
- processCurrentLine();
-
- m_currentLine = currentLine;
- }
-
- void addBorder(const QRectF &rect, qreal border, QTextFrameFormat::BorderStyle borderStyle,
- const QBrush &borderBrush);
- void addFrameDecorations(QTextDocument *document, QTextFrame *frame);
- void addImage(const QRectF &rect, const QImage &image, qreal ascent,
- BinaryTreeNode::SelectionState selectionState,
- QTextFrameFormat::Position layoutPosition);
- void addTextObject(const QPointF &position, const QTextCharFormat &format,
- BinaryTreeNode::SelectionState selectionState,
- QTextDocument *textDocument, int pos,
- QTextFrameFormat::Position layoutPosition = QTextFrameFormat::InFlow);
- void addSelectedGlyphs(const QGlyphRun &glyphRun);
- void addUnselectedGlyphs(const QGlyphRun &glyphRun);
- void addGlyphsInRange(int rangeStart, int rangeEnd,
- const QColor &color, const QColor &backgroundColor,
- int selectionStart, int selectionEnd);
- void addGlyphsForRanges(const QVarLengthArray<QTextLayout::FormatRange> &ranges,
- int start, int end,
- int selectionStart, int selectionEnd);
-
- void addToSceneGraph(QQuickTextNode *parent,
- QQuickText::TextStyle style = QQuickText::Normal,
- const QColor &styleColor = QColor());
-
- void setSelectionColor(const QColor &selectionColor)
- {
- m_selectionColor = selectionColor;
- }
-
- void setSelectedTextColor(const QColor &selectedTextColor)
- {
- m_selectedTextColor = selectedTextColor;
- }
-
- void setTextColor(const QColor &textColor)
- {
- m_textColor = textColor;
- }
-
- void setPosition(const QPointF &position)
- {
- m_position = position;
- }
-
- private:
- struct TextDecoration
- {
- TextDecoration() : selectionState(BinaryTreeNode::Unselected) {}
- TextDecoration(const BinaryTreeNode::SelectionState &s,
- const QRectF &r,
- const QColor &c)
- : selectionState(s)
- , rect(r)
- , color(c)
- {
- }
-
- BinaryTreeNode::SelectionState selectionState;
- QRectF rect;
- QColor color;
- };
-
- void processCurrentLine();
- void addTextDecorations(const QVarLengthArray<TextDecoration> &textDecorations,
- qreal offset, qreal thickness);
-
- QColor m_selectionColor;
- QColor m_textColor;
- QColor m_backgroundColor;
- QColor m_selectedTextColor;
- QPointF m_position;
-
- QTextLine m_currentLine;
- bool m_hasSelection;
-
- QList<QPair<QRectF, QColor> > m_backgrounds;
- QList<QRectF> m_selectionRects;
- QVarLengthArray<BinaryTreeNode> m_currentLineTree;
-
- QList<TextDecoration> m_lines;
- QVector<BinaryTreeNode> m_processedNodes;
-
- QList<QPair<QRectF, QImage> > m_images;
- };
-
- void SelectionEngine::addTextDecorations(const QVarLengthArray<TextDecoration> &textDecorations,
- qreal offset, qreal thickness)
- {
- for (int i=0; i<textDecorations.size(); ++i) {
- TextDecoration textDecoration = textDecorations.at(i);
-
- {
- QRectF &rect = textDecoration.rect;
- rect.setY(qRound(rect.y() + m_currentLine.ascent() + offset));
- rect.setHeight(thickness);
- }
-
- m_lines.append(textDecoration);
- }
- }
-
- void SelectionEngine::processCurrentLine()
- {
- // No glyphs, do nothing
- if (m_currentLineTree.isEmpty())
- return;
-
- // 1. Go through current line and get correct decoration position for each node based on
- // neighbouring decorations. Add decoration to global list
- // 2. Create clip nodes for all selected text. Try to merge as many as possible within
- // the line.
- // 3. Add QRects to a list of selection rects.
- // 4. Add all nodes to a global processed list
- QVarLengthArray<int> sortedIndexes; // Indexes in tree sorted by x position
- BinaryTreeNode::inOrder(m_currentLineTree, &sortedIndexes);
-
- Q_ASSERT(sortedIndexes.size() == m_currentLineTree.size());
-
- BinaryTreeNode::SelectionState currentSelectionState = BinaryTreeNode::Unselected;
- QRectF currentRect;
-
- QQuickTextNode::Decorations currentDecorations = QQuickTextNode::NoDecoration;
- qreal underlineOffset = 0.0;
- qreal underlineThickness = 0.0;
-
- qreal overlineOffset = 0.0;
- qreal overlineThickness = 0.0;
-
- qreal strikeOutOffset = 0.0;
- qreal strikeOutThickness = 0.0;
-
- QRectF decorationRect = currentRect;
-
- QColor lastColor;
- QColor lastBackgroundColor;
-
- QVarLengthArray<TextDecoration> pendingUnderlines;
- QVarLengthArray<TextDecoration> pendingOverlines;
- QVarLengthArray<TextDecoration> pendingStrikeOuts;
- if (!sortedIndexes.isEmpty()) {
- QSGClipNode *currentClipNode = m_hasSelection ? new QSGClipNode : 0;
- bool currentClipNodeUsed = false;
- for (int i=0; i<=sortedIndexes.size(); ++i) {
- BinaryTreeNode *node = 0;
- if (i < sortedIndexes.size()) {
- int sortedIndex = sortedIndexes.at(i);
- Q_ASSERT(sortedIndex < m_currentLineTree.size());
-
- node = m_currentLineTree.data() + sortedIndex;
- }
-
- if (i == 0)
- currentSelectionState = node->selectionState;
-
- // Update decorations
- if (currentDecorations != QQuickTextNode::NoDecoration) {
- decorationRect.setY(m_position.y() + m_currentLine.y());
- decorationRect.setHeight(m_currentLine.height());
-
- if (node != 0)
- decorationRect.setRight(node->boundingRect.left());
-
- TextDecoration textDecoration(currentSelectionState, decorationRect, lastColor);
- if (currentDecorations & QQuickTextNode::Underline)
- pendingUnderlines.append(textDecoration);
-
- if (currentDecorations & QQuickTextNode::Overline)
- pendingOverlines.append(textDecoration);
-
- if (currentDecorations & QQuickTextNode::StrikeOut)
- pendingStrikeOuts.append(textDecoration);
-
- if (currentDecorations & QQuickTextNode::Background)
- m_backgrounds.append(qMakePair(decorationRect, lastBackgroundColor));
- }
-
- // If we've reached an unselected node from a selected node, we add the
- // selection rect to the graph, and we add decoration every time the
- // selection state changes, because that means the text color changes
- if (node == 0 || node->selectionState != currentSelectionState) {
- if (node != 0)
- currentRect.setRight(node->boundingRect.left());
- currentRect.setY(m_position.y() + m_currentLine.y());
- currentRect.setHeight(m_currentLine.height());
-
- // Draw selection all the way up to the left edge of the unselected item
- if (currentSelectionState == BinaryTreeNode::Selected)
- m_selectionRects.append(currentRect);
-
- if (currentClipNode != 0) {
- if (!currentClipNodeUsed) {
- delete currentClipNode;
- } else {
- currentClipNode->setIsRectangular(true);
- currentClipNode->setClipRect(currentRect);
- }
- }
-
- if (node != 0 && m_hasSelection)
- currentClipNode = new QSGClipNode;
- else
- currentClipNode = 0;
- currentClipNodeUsed = false;
-
- if (node != 0) {
- currentSelectionState = node->selectionState;
- currentRect = node->boundingRect;
-
- // Make sure currentRect is valid, otherwise the unite won't work
- if (currentRect.isNull())
- currentRect.setSize(QSizeF(1, 1));
- }
- } else {
- if (currentRect.isNull())
- currentRect = node->boundingRect;
- else
- currentRect = currentRect.united(node->boundingRect);
- }
-
- if (node != 0) {
- node->clipNode = currentClipNode;
- currentClipNodeUsed = true;
-
- decorationRect = node->boundingRect;
-
- // If previous item(s) had underline and current does not, then we add the
- // pending lines to the lists and likewise for overlines and strikeouts
- if (!pendingUnderlines.isEmpty()
- && !(node->decorations & QQuickTextNode::Underline)) {
- addTextDecorations(pendingUnderlines, underlineOffset, underlineThickness);
-
- pendingUnderlines.clear();
-
- underlineOffset = 0.0;
- underlineThickness = 0.0;
- }
-
- // ### Add pending when overlineOffset/thickness changes to minimize number of
- // nodes
- if (!pendingOverlines.isEmpty()) {
- addTextDecorations(pendingOverlines, overlineOffset, overlineThickness);
-
- pendingOverlines.clear();
-
- overlineOffset = 0.0;
- overlineThickness = 0.0;
- }
-
- // ### Add pending when overlineOffset/thickness changes to minimize number of
- // nodes
- if (!pendingStrikeOuts.isEmpty()) {
- addTextDecorations(pendingStrikeOuts, strikeOutOffset, strikeOutThickness);
-
- pendingStrikeOuts.clear();
-
- strikeOutOffset = 0.0;
- strikeOutThickness = 0.0;
- }
-
- // Merge current values with previous. Prefer greatest thickness
- QRawFont rawFont = node->glyphRun.rawFont();
- if (node->decorations & QQuickTextNode::Underline) {
- if (rawFont.lineThickness() > underlineThickness) {
- underlineThickness = rawFont.lineThickness();
- underlineOffset = rawFont.underlinePosition();
- }
- }
-
- if (node->decorations & QQuickTextNode::Overline) {
- overlineOffset = -rawFont.ascent();
- overlineThickness = rawFont.lineThickness();
- }
-
- if (node->decorations & QQuickTextNode::StrikeOut) {
- strikeOutThickness = rawFont.lineThickness();
- strikeOutOffset = rawFont.ascent() / -3.0;
- }
-
- currentDecorations = node->decorations;
- lastColor = node->color;
- lastBackgroundColor = node->backgroundColor;
- m_processedNodes.append(*node);
- }
- }
-
- if (!pendingUnderlines.isEmpty())
- addTextDecorations(pendingUnderlines, underlineOffset, underlineThickness);
-
- if (!pendingOverlines.isEmpty())
- addTextDecorations(pendingOverlines, overlineOffset, overlineThickness);
-
- if (!pendingStrikeOuts.isEmpty())
- addTextDecorations(pendingStrikeOuts, strikeOutOffset, strikeOutThickness);
- }
-
- m_currentLineTree.clear();
- m_currentLine = QTextLine();
- m_hasSelection = false;
- }
-
- void SelectionEngine::addImage(const QRectF &rect, const QImage &image, qreal ascent,
- BinaryTreeNode::SelectionState selectionState,
- QTextFrameFormat::Position layoutPosition)
- {
- QRectF searchRect = rect;
- if (layoutPosition == QTextFrameFormat::InFlow) {
- if (m_currentLineTree.isEmpty()) {
- searchRect.moveTopLeft(m_position);
- } else {
- const BinaryTreeNode *lastNode = m_currentLineTree.data() + m_currentLineTree.size() - 1;
- if (lastNode->glyphRun.isRightToLeft()) {
- QPointF lastPos = lastNode->boundingRect.topLeft();
- searchRect.moveTopRight(lastPos - QPointF(0, ascent));
- } else {
- QPointF lastPos = lastNode->boundingRect.topRight();
- searchRect.moveTopLeft(lastPos - QPointF(0, ascent));
- }
- }
- }
-
- BinaryTreeNode::insert(&m_currentLineTree, searchRect, image, ascent, selectionState);
- }
-
- void SelectionEngine::addTextObject(const QPointF &position, const QTextCharFormat &format,
- BinaryTreeNode::SelectionState selectionState,
- QTextDocument *textDocument, int pos,
- QTextFrameFormat::Position layoutPosition)
- {
- QTextObjectInterface *handler = textDocument->documentLayout()->handlerForObject(format.objectType());
- if (handler != 0) {
- QImage image;
- QSizeF size = handler->intrinsicSize(textDocument, pos, format);
-
- if (format.objectType() == QTextFormat::ImageObject) {
- QTextImageFormat imageFormat = format.toImageFormat();
- QTextImageHandler *imageHandler = static_cast<QTextImageHandler *>(handler);
- image = imageHandler->image(textDocument, imageFormat);
- }
-
- if (image.isNull()) {
- image = QImage(size.toSize(), QImage::Format_ARGB32_Premultiplied);
- image.fill(Qt::transparent);
- {
- QPainter painter(&image);
- handler->drawObject(&painter, image.rect(), textDocument, pos, format);
- }
- }
-
- qreal ascent;
- QFontMetrics m(format.font());
- switch (format.verticalAlignment())
- {
- case QTextCharFormat::AlignMiddle:
- ascent = size.height() / 2 - 1;
- break;
- case QTextCharFormat::AlignBaseline:
- ascent = size.height() - m.descent() - 1;
- break;
- default:
- ascent = size.height() - 1;
- }
-
- addImage(QRectF(position, size), image, ascent, selectionState, layoutPosition);
- }
- }
-
- void SelectionEngine::addUnselectedGlyphs(const QGlyphRun &glyphRun)
- {
- BinaryTreeNode::insert(&m_currentLineTree, glyphRun, BinaryTreeNode::Unselected,
- m_textColor, m_backgroundColor, m_position);
- }
-
- void SelectionEngine::addSelectedGlyphs(const QGlyphRun &glyphRun)
- {
- int currentSize = m_currentLineTree.size();
- BinaryTreeNode::insert(&m_currentLineTree, glyphRun, BinaryTreeNode::Selected,
- m_textColor, m_backgroundColor, m_position);
- m_hasSelection = m_hasSelection || m_currentLineTree.size() > currentSize;
- }
-
- void SelectionEngine::addGlyphsForRanges(const QVarLengthArray<QTextLayout::FormatRange> &ranges,
- int start, int end,
- int selectionStart, int selectionEnd)
- {
- int currentPosition = start;
- int remainingLength = end - start;
- for (int j=0; j<ranges.size(); ++j) {
- const QTextLayout::FormatRange &range = ranges.at(j);
- if (range.start + range.length >= currentPosition
- && range.start < currentPosition + remainingLength) {
-
- if (range.start > currentPosition) {
- addGlyphsInRange(currentPosition, range.start - currentPosition,
- QColor(), QColor(), selectionStart, selectionEnd);
- }
-
- int rangeEnd = qMin(range.start + range.length, currentPosition + remainingLength);
- QColor rangeColor = range.format.hasProperty(QTextFormat::ForegroundBrush)
- ? range.format.foreground().color()
- : QColor();
- QColor rangeBackgroundColor = range.format.hasProperty(QTextFormat::BackgroundBrush)
- ? range.format.background().color()
- : QColor();
-
- addGlyphsInRange(range.start, rangeEnd - range.start,
- rangeColor, rangeBackgroundColor,
- selectionStart, selectionEnd);
-
- currentPosition = range.start + range.length;
- remainingLength = end - currentPosition;
-
- } else if (range.start > currentPosition + remainingLength || remainingLength <= 0) {
- break;
- }
- }
-
- if (remainingLength > 0) {
- addGlyphsInRange(currentPosition, remainingLength, QColor(), QColor(),
- selectionStart, selectionEnd);
- }
-
- }
-
- void SelectionEngine::addGlyphsInRange(int rangeStart, int rangeLength,
- const QColor &color, const QColor &backgroundColor,
- int selectionStart, int selectionEnd)
- {
- QColor oldColor;
- if (color.isValid()) {
- oldColor = m_textColor;
- m_textColor = color;
- }
-
- QColor oldBackgroundColor = m_backgroundColor;
- if (backgroundColor.isValid()) {
- oldBackgroundColor = m_backgroundColor;
- m_backgroundColor = backgroundColor;
- }
-
- bool hasSelection = selectionEnd >= 0
- && selectionStart <= selectionEnd;
-
- QTextLine &line = m_currentLine;
- int rangeEnd = rangeStart + rangeLength;
- if (!hasSelection || (selectionStart > rangeEnd || selectionEnd < rangeStart)) {
- QList<QGlyphRun> glyphRuns = line.glyphRuns(rangeStart, rangeLength);
- for (int j=0; j<glyphRuns.size(); ++j) {
- const QGlyphRun &glyphRun = glyphRuns.at(j);
- addUnselectedGlyphs(glyphRun);
- }
- } else {
- if (rangeStart < selectionStart) {
- QList<QGlyphRun> glyphRuns = line.glyphRuns(rangeStart,
- qMin(selectionStart - rangeStart,
- rangeLength));
-
- for (int j=0; j<glyphRuns.size(); ++j) {
- const QGlyphRun &glyphRun = glyphRuns.at(j);
- addUnselectedGlyphs(glyphRun);
- }
- }
-
- if (rangeEnd > selectionStart) {
- int start = qMax(selectionStart, rangeStart);
- int length = qMin(selectionEnd - start + 1, rangeEnd - start);
- QList<QGlyphRun> glyphRuns = line.glyphRuns(start, length);
-
- for (int j=0; j<glyphRuns.size(); ++j) {
- const QGlyphRun &glyphRun = glyphRuns.at(j);
- addSelectedGlyphs(glyphRun);
- }
- }
-
- if (selectionEnd >= rangeStart && selectionEnd < rangeEnd) {
- QList<QGlyphRun> glyphRuns = line.glyphRuns(selectionEnd + 1, rangeEnd - selectionEnd - 1);
- for (int j=0; j<glyphRuns.size(); ++j) {
- const QGlyphRun &glyphRun = glyphRuns.at(j);
- addUnselectedGlyphs(glyphRun);
- }
- }
- }
-
- if (backgroundColor.isValid())
- m_backgroundColor = oldBackgroundColor;
-
- if (oldColor.isValid())
- m_textColor = oldColor;
- }
-
- void SelectionEngine::addBorder(const QRectF &rect, qreal border,
- QTextFrameFormat::BorderStyle borderStyle,
- const QBrush &borderBrush)
- {
- QColor color = borderBrush.color();
-
- // Currently we don't support other styles than solid
- Q_UNUSED(borderStyle);
-
- m_backgrounds.append(qMakePair(QRectF(rect.left(), rect.top(), border, rect.height() + border), color));
- m_backgrounds.append(qMakePair(QRectF(rect.left() + border, rect.top(), rect.width(), border), color));
- m_backgrounds.append(qMakePair(QRectF(rect.right(), rect.top() + border, border, rect.height() - border), color));
- m_backgrounds.append(qMakePair(QRectF(rect.left() + border, rect.bottom(), rect.width(), border), color));
- }
-
- void SelectionEngine::addFrameDecorations(QTextDocument *document, QTextFrame *frame)
- {
- QTextDocumentLayout *documentLayout = qobject_cast<QTextDocumentLayout *>(document->documentLayout());
- QTextFrameFormat frameFormat = frame->format().toFrameFormat();
-
- QTextTable *table = qobject_cast<QTextTable *>(frame);
- QRectF boundingRect = table == 0
- ? documentLayout->frameBoundingRect(frame)
- : documentLayout->tableBoundingRect(table);
-
- QBrush bg = frame->frameFormat().background();
- if (bg.style() != Qt::NoBrush)
- m_backgrounds.append(qMakePair(boundingRect, bg.color()));
-
- if (!frameFormat.hasProperty(QTextFormat::FrameBorder))
- return;
-
- qreal borderWidth = frameFormat.border();
- if (qFuzzyIsNull(borderWidth))
- return;
-
- QBrush borderBrush = frameFormat.borderBrush();
- QTextFrameFormat::BorderStyle borderStyle = frameFormat.borderStyle();
- if (borderStyle == QTextFrameFormat::BorderStyle_None)
- return;
-
- addBorder(boundingRect.adjusted(frameFormat.leftMargin(), frameFormat.topMargin(),
- -frameFormat.rightMargin(), -frameFormat.bottomMargin()),
- borderWidth, borderStyle, borderBrush);
- if (table != 0) {
- int rows = table->rows();
- int columns = table->columns();
-
- for (int row=0; row<rows; ++row) {
- for (int column=0; column<columns; ++column) {
- QTextTableCell cell = table->cellAt(row, column);
-
- QRectF cellRect = documentLayout->tableCellBoundingRect(table, cell);
- addBorder(cellRect.adjusted(-borderWidth, -borderWidth, 0, 0), borderWidth,
- borderStyle, borderBrush);
- }
- }
- }
- }
-
- void SelectionEngine::addToSceneGraph(QQuickTextNode *parentNode,
- QQuickText::TextStyle style,
- const QColor &styleColor)
- {
- if (m_currentLine.isValid())
- processCurrentLine();
-
-
- for (int i=0; i<m_backgrounds.size(); ++i) {
- const QRectF &rect = m_backgrounds.at(i).first;
- const QColor &color = m_backgrounds.at(i).second;
-
- parentNode->appendChildNode(new QSGSimpleRectNode(rect, color));
- }
-
- // First, prepend all selection rectangles to the tree
- for (int i=0; i<m_selectionRects.size(); ++i) {
- const QRectF &rect = m_selectionRects.at(i);
-
- parentNode->appendChildNode(new QSGSimpleRectNode(rect, m_selectionColor));
- }
-
- // Finally, add decorations for each node to the tree.
- for (int i=0; i<m_lines.size(); ++i) {
- const TextDecoration &textDecoration = m_lines.at(i);
-
- QColor color = textDecoration.selectionState == BinaryTreeNode::Selected
- ? m_selectedTextColor
- : textDecoration.color;
-
- parentNode->appendChildNode(new QSGSimpleRectNode(textDecoration.rect, color));
- }
-
- // Then, go through all the nodes for all lines and combine all QGlyphRuns with a common
- // font, selection state and clip node.
- typedef QPair<QFontEngine *, QPair<QSGClipNode *, QPair<QRgb, int> > > KeyType;
- QHash<KeyType, BinaryTreeNode *> map;
- for (int i=0; i<m_processedNodes.size(); ++i) {
- BinaryTreeNode *node = m_processedNodes.data() + i;
-
- if (node->image.isNull()) {
- QGlyphRun glyphRun = node->glyphRun;
- QRawFont rawFont = glyphRun.rawFont();
- QRawFontPrivate *rawFontD = QRawFontPrivate::get(rawFont);
-
- QFontEngine *fontEngine = rawFontD->fontEngine;
-
- KeyType key(qMakePair(fontEngine,
- qMakePair(node->clipNode,
- qMakePair(node->color.rgba(), int(node->selectionState)))));
-
- BinaryTreeNode *otherNode = map.value(key, 0);
- if (otherNode != 0) {
- QGlyphRun &otherGlyphRun = otherNode->glyphRun;
-
- QVector<quint32> otherGlyphIndexes = otherGlyphRun.glyphIndexes();
- QVector<QPointF> otherGlyphPositions = otherGlyphRun.positions();
-
- otherGlyphIndexes += glyphRun.glyphIndexes();
-
- QVector<QPointF> glyphPositions = glyphRun.positions();
- for (int j=0; j<glyphPositions.size(); ++j) {
- otherGlyphPositions += glyphPositions.at(j) + (node->position - otherNode->position);
- }
-
- otherGlyphRun.setGlyphIndexes(otherGlyphIndexes);
- otherGlyphRun.setPositions(otherGlyphPositions);
-
- } else {
- map.insert(key, node);
- }
- } else {
- parentNode->addImage(node->boundingRect, node->image);
- if (node->selectionState == BinaryTreeNode::Selected) {
- QColor color = m_selectionColor;
- color.setAlpha(128);
- parentNode->appendChildNode(new QSGSimpleRectNode(node->boundingRect, color));
- }
- }
- }
-
- // ...and add clip nodes and glyphs to tree.
- QHash<KeyType, BinaryTreeNode *>::const_iterator it = map.constBegin();
- while (it != map.constEnd()) {
-
- BinaryTreeNode *node = it.value();
-
- QSGClipNode *clipNode = node->clipNode;
- if (clipNode != 0 && clipNode->parent() == 0 )
- parentNode->appendChildNode(clipNode);
-
- QColor color = node->selectionState == BinaryTreeNode::Selected
- ? m_selectedTextColor
- : node->color;
-
- parentNode->addGlyphs(node->position, node->glyphRun, color, style, styleColor, clipNode);
-
- ++it;
- }
- }
-}
-
-void QQuickTextNode::mergeFormats(QTextLayout *textLayout,
- QVarLengthArray<QTextLayout::FormatRange> *mergedFormats)
-{
- Q_ASSERT(mergedFormats != 0);
- if (textLayout == 0)
- return;
-
- QList<QTextLayout::FormatRange> additionalFormats = textLayout->additionalFormats();
- for (int i=0; i<additionalFormats.size(); ++i) {
- QTextLayout::FormatRange additionalFormat = additionalFormats.at(i);
- if (additionalFormat.format.hasProperty(QTextFormat::ForegroundBrush)
- || additionalFormat.format.hasProperty(QTextFormat::BackgroundBrush)) {
- // Merge overlapping formats
- if (!mergedFormats->isEmpty()) {
- QTextLayout::FormatRange *lastFormat = mergedFormats->data() + mergedFormats->size() - 1;
-
- if (additionalFormat.start < lastFormat->start + lastFormat->length) {
- QTextLayout::FormatRange *mergedRange = 0;
-
- int length = additionalFormat.length;
- if (additionalFormat.start > lastFormat->start) {
- lastFormat->length = additionalFormat.start - lastFormat->start;
- length -= lastFormat->length;
-
- mergedFormats->append(QTextLayout::FormatRange());
- mergedRange = mergedFormats->data() + mergedFormats->size() - 1;
- lastFormat = mergedFormats->data() + mergedFormats->size() - 2;
- } else {
- mergedRange = lastFormat;
- }
-
- mergedRange->format = lastFormat->format;
- mergedRange->format.merge(additionalFormat.format);
- mergedRange->start = additionalFormat.start;
-
- int end = qMin(additionalFormat.start + additionalFormat.length,
- lastFormat->start + lastFormat->length);
-
- mergedRange->length = end - mergedRange->start;
- length -= mergedRange->length;
-
- additionalFormat.start = end;
- additionalFormat.length = length;
- }
- }
-
- if (additionalFormat.length > 0)
- mergedFormats->append(additionalFormat);
- }
- }
-
-}
-
-namespace {
-
- class ProtectedLayoutAccessor: public QAbstractTextDocumentLayout
- {
- public:
- inline QTextCharFormat formatAccessor(int pos)
- {
- return format(pos);
- }
- };
-
-}
-
-void QQuickTextNode::addImage(const QRectF &rect, const QImage &image)
-{
- QSGImageNode *node = m_context->createImageNode();
- QSGTexture *texture = m_context->createTexture(image);
- m_textures.append(texture);
- node->setTargetRect(rect);
- node->setTexture(texture);
- appendChildNode(node);
- node->update();
-}
-
-void QQuickTextNode::addTextDocument(const QPointF &, QTextDocument *textDocument,
- const QColor &textColor,
- QQuickText::TextStyle style, const QColor &styleColor,
- const QColor &selectionColor, const QColor &selectedTextColor,
- int selectionStart, int selectionEnd)
-{
- SelectionEngine engine;
- engine.setTextColor(textColor);
- engine.setSelectedTextColor(selectedTextColor);
- engine.setSelectionColor(selectionColor);
-
- QList<QTextFrame *> frames;
- frames.append(textDocument->rootFrame());
- while (!frames.isEmpty()) {
- QTextFrame *textFrame = frames.takeFirst();
- frames.append(textFrame->childFrames());
-
- engine.addFrameDecorations(textDocument, textFrame);
-
- if (textFrame->firstPosition() > textFrame->lastPosition()
- && textFrame->frameFormat().position() != QTextFrameFormat::InFlow) {
- const int pos = textFrame->firstPosition() - 1;
- ProtectedLayoutAccessor *a = static_cast<ProtectedLayoutAccessor *>(textDocument->documentLayout());
- QTextCharFormat format = a->formatAccessor(pos);
- QRectF rect = a->frameBoundingRect(textFrame);
-
- QTextBlock block = textFrame->firstCursorPosition().block();
- engine.setCurrentLine(block.layout()->lineForTextPosition(pos - block.position()));
- engine.addTextObject(rect.topLeft(), format, BinaryTreeNode::Unselected, textDocument,
- pos, textFrame->frameFormat().position());
- } else {
- QTextFrame::iterator it = textFrame->begin();
-
- while (!it.atEnd()) {
- Q_ASSERT(!engine.currentLine().isValid());
-
- QTextBlock block = it.currentBlock();
- int preeditLength = block.isValid() ? block.layout()->preeditAreaText().length() : 0;
- int preeditPosition = block.isValid() ? block.layout()->preeditAreaPosition() : -1;
-
- QVarLengthArray<QTextLayout::FormatRange> colorChanges;
- mergeFormats(block.layout(), &colorChanges);
-
- QPointF blockPosition = textDocument->documentLayout()->blockBoundingRect(block).topLeft();
- if (QTextList *textList = block.textList()) {
- QPointF pos = blockPosition;
- QTextLayout *layout = block.layout();
- if (layout->lineCount() > 0) {
- QTextLine firstLine = layout->lineAt(0);
- Q_ASSERT(firstLine.isValid());
-
- engine.setCurrentLine(firstLine);
-
- QRectF textRect = firstLine.naturalTextRect();
- pos += textRect.topLeft();
- if (block.textDirection() == Qt::RightToLeft)
- pos.rx() += textRect.width();
-
- const QTextCharFormat charFormat = block.charFormat();
- QFont font(charFormat.font());
- QFontMetricsF fontMetrics(font);
- QTextListFormat listFormat = textList->format();
-
- QString listItemBullet;
- switch (listFormat.style()) {
- case QTextListFormat::ListCircle:
- listItemBullet = QChar(0x25E6); // White bullet
- break;
- case QTextListFormat::ListSquare:
- listItemBullet = QChar(0x25AA); // Black small square
- break;
- case QTextListFormat::ListDecimal:
- case QTextListFormat::ListLowerAlpha:
- case QTextListFormat::ListUpperAlpha:
- case QTextListFormat::ListLowerRoman:
- case QTextListFormat::ListUpperRoman:
- listItemBullet = textList->itemText(block);
- break;
- default:
- listItemBullet = QChar(0x2022); // Black bullet
- break;
- };
-
- QSizeF size(fontMetrics.width(listItemBullet), fontMetrics.height());
- qreal xoff = fontMetrics.width(QLatin1Char(' '));
- if (block.textDirection() == Qt::LeftToRight)
- xoff = -xoff - size.width();
- engine.setPosition(pos + QPointF(xoff, 0));
-
- QTextLayout layout;
- layout.setFont(font);
- layout.setText(listItemBullet); // Bullet
- layout.beginLayout();
- QTextLine line = layout.createLine();
- line.setPosition(QPointF(0, 0));
- layout.endLayout();
-
- QList<QGlyphRun> glyphRuns = layout.glyphRuns();
- for (int i=0; i<glyphRuns.size(); ++i)
- engine.addUnselectedGlyphs(glyphRuns.at(i));
- }
- }
-
- int textPos = block.position();
- QTextBlock::iterator blockIterator = block.begin();
- while (!blockIterator.atEnd()) {
- QTextFragment fragment = blockIterator.fragment();
- QString text = fragment.text();
- if (text.isEmpty())
- continue;
-
- QTextCharFormat charFormat = fragment.charFormat();
- engine.setPosition(blockPosition);
- if (text.contains(QChar::ObjectReplacementCharacter)) {
- QTextFrame *frame = qobject_cast<QTextFrame *>(textDocument->objectForFormat(charFormat));
- if (frame && frame->frameFormat().position() == QTextFrameFormat::InFlow) {
- BinaryTreeNode::SelectionState selectionState =
- (selectionStart < textPos + text.length()
- && selectionEnd >= textPos)
- ? BinaryTreeNode::Selected
- : BinaryTreeNode::Unselected;
-
- engine.addTextObject(QPointF(), charFormat, selectionState, textDocument, textPos);
- }
- textPos += text.length();
- } else {
- if (charFormat.foreground().style() != Qt::NoBrush)
- engine.setTextColor(charFormat.foreground().color());
- else
- engine.setTextColor(textColor);
-
- int fragmentEnd = textPos + fragment.length();
- if (preeditPosition >= 0
- && preeditPosition >= textPos
- && preeditPosition < fragmentEnd) {
- fragmentEnd += preeditLength;
- }
-
- while (textPos < fragmentEnd) {
- int blockRelativePosition = textPos - block.position();
- QTextLine line = block.layout()->lineForTextPosition(blockRelativePosition);
- if (!engine.currentLine().isValid()
- || line.lineNumber() != engine.currentLine().lineNumber()) {
- engine.setCurrentLine(line);
- }
-
- Q_ASSERT(line.textLength() > 0);
- int lineEnd = line.textStart() + block.position() + line.textLength();
-
- int len = qMin(lineEnd - textPos, fragmentEnd - textPos);
- Q_ASSERT(len > 0);
-
- int currentStepEnd = textPos + len;
-
- engine.addGlyphsForRanges(colorChanges,
- textPos - block.position(),
- currentStepEnd - block.position(),
- selectionStart - block.position(),
- selectionEnd - block.position());
-
- textPos = currentStepEnd;
- }
- }
-
- ++blockIterator;
- }
-
- engine.setCurrentLine(QTextLine()); // Reset current line because the text layout changed
- ++it;
- }
- }
- }
-
- engine.addToSceneGraph(this, style, styleColor);
-}
-
-void QQuickTextNode::addTextLayout(const QPointF &position, QTextLayout *textLayout, const QColor &color,
- QQuickText::TextStyle style, const QColor &styleColor,
- const QColor &selectionColor, const QColor &selectedTextColor,
- int selectionStart, int selectionEnd)
-{
- SelectionEngine engine;
- engine.setTextColor(color);
- engine.setSelectedTextColor(selectedTextColor);
- engine.setSelectionColor(selectionColor);
- engine.setPosition(position);
-
- int preeditLength = textLayout->preeditAreaText().length();
- int preeditPosition = textLayout->preeditAreaPosition();
-
- QVarLengthArray<QTextLayout::FormatRange> colorChanges;
- mergeFormats(textLayout, &colorChanges);
-
- for (int i=0; i<textLayout->lineCount(); ++i) {
- QTextLine line = textLayout->lineAt(i);
-
- int start = line.textStart();
- int length = line.textLength();
- int end = start + length;
-
- if (preeditPosition >= 0
- && preeditPosition >= start
- && preeditPosition < end) {
- end += preeditLength;
- }
-
- engine.setCurrentLine(line);
- engine.addGlyphsForRanges(colorChanges, start, end, selectionStart, selectionEnd);
- }
-
- engine.addToSceneGraph(this, style, styleColor);
-}
-
-void QQuickTextNode::deleteContent()
-{
- while (firstChild() != 0)
- delete firstChild();
- m_cursorNode = 0;
-}
-
-#if 0
-void QQuickTextNode::updateNodes()
-{
- return;
- deleteContent();
- if (m_text.isEmpty())
- return;
-
- if (m_usePixmapCache) {
- // ### gunnar: port properly
-// QPixmap pixmap = generatedPixmap();
-// if (pixmap.isNull())
-// return;
-
-// QSGImageNode *pixmapNode = m_context->createImageNode();
-// pixmapNode->setRect(pixmap.rect());
-// pixmapNode->setSourceRect(pixmap.rect());
-// pixmapNode->setOpacity(m_opacity);
-// pixmapNode->setClampToEdge(true);
-// pixmapNode->setLinearFiltering(m_linearFiltering);
-
-// appendChildNode(pixmapNode);
- } else {
- if (m_text.isEmpty())
- return;
-
- // Implement styling by drawing text several times at slight shifts. shiftForStyle
- // contains the sequence of shifted positions at which to draw the text. All except
- // the last will be drawn with styleColor.
- QList<QPointF> shiftForStyle;
- switch (m_textStyle) {
- case OutlineTextStyle:
- // ### Should be made faster by implementing outline material
- shiftForStyle << QPointF(-1, 0);
- shiftForStyle << QPointF(0, -1);
- shiftForStyle << QPointF(1, 0);
- shiftForStyle << QPointF(0, 1);
- break;
- case SunkenTextStyle:
- shiftForStyle << QPointF(0, -1);
- break;
- case RaisedTextStyle:
- shiftForStyle << QPointF(0, 1);
- break;
- default:
- break;
- }
-
- shiftForStyle << QPointF(0, 0); // Regular position
- while (!shiftForStyle.isEmpty()) {
- QPointF shift = shiftForStyle.takeFirst();
-
- // Use styleColor for all but last shift
- if (m_richText) {
- QColor overrideColor = shiftForStyle.isEmpty() ? QColor() : m_styleColor;
-
- QTextFrame *textFrame = m_textDocument->rootFrame();
- QPointF p = m_textDocument->documentLayout()->frameBoundingRect(textFrame).topLeft();
-
- QTextFrame::iterator it = textFrame->begin();
- while (!it.atEnd()) {
- addTextBlock(shift + p, it.currentBlock(), overrideColor);
- ++it;
- }
- } else {
- addTextLayout(shift, m_textLayout, shiftForStyle.isEmpty()
- ? m_color
- : m_styleColor);
- }
- }
- }
-}
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquicktextnode_p.h b/src/declarative/items/qquicktextnode_p.h
deleted file mode 100644
index 16e92e34f3..0000000000
--- a/src/declarative/items/qquicktextnode_p.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKTEXTNODE_P_H
-#define QQUICKTEXTNODE_P_H
-
-#include <qsgnode.h>
-#include "qquicktext_p.h"
-#include <qglyphrun.h>
-
-#include <QtGui/qcolor.h>
-#include <QtGui/qtextlayout.h>
-#include <QtCore/qvarlengtharray.h>
-
-QT_BEGIN_NAMESPACE
-
-class QSGGlyphNode;
-class QTextBlock;
-class QColor;
-class QTextDocument;
-class QSGContext;
-class QRawFont;
-class QSGSimpleRectNode;
-class QSGClipNode;
-class QSGTexture;
-
-class QQuickTextNode : public QSGTransformNode
-{
-public:
- enum Decoration {
- NoDecoration = 0x0,
- Underline = 0x1,
- Overline = 0x2,
- StrikeOut = 0x4,
- Background = 0x8
- };
- Q_DECLARE_FLAGS(Decorations, Decoration)
-
- QQuickTextNode(QSGContext *);
- ~QQuickTextNode();
-
- static bool isComplexRichText(QTextDocument *);
-
- void deleteContent();
- void addTextLayout(const QPointF &position, QTextLayout *textLayout, const QColor &color = QColor(),
- QQuickText::TextStyle style = QQuickText::Normal, const QColor &styleColor = QColor(),
- const QColor &selectionColor = QColor(), const QColor &selectedTextColor = QColor(),
- int selectionStart = -1, int selectionEnd = -1);
- void addTextDocument(const QPointF &position, QTextDocument *textDocument, const QColor &color = QColor(),
- QQuickText::TextStyle style = QQuickText::Normal, const QColor &styleColor = QColor(),
- const QColor &selectionColor = QColor(), const QColor &selectedTextColor = QColor(),
- int selectionStart = -1, int selectionEnd = -1);
-
- void setCursor(const QRectF &rect, const QColor &color);
- QSGSimpleRectNode *cursorNode() const { return m_cursorNode; }
-
- QSGGlyphNode *addGlyphs(const QPointF &position, const QGlyphRun &glyphs, const QColor &color,
- QQuickText::TextStyle style = QQuickText::Normal, const QColor &styleColor = QColor(),
- QSGNode *parentNode = 0);
- void addImage(const QRectF &rect, const QImage &image);
-
-private:
- void mergeFormats(QTextLayout *textLayout, QVarLengthArray<QTextLayout::FormatRange> *mergedFormats);
-
- QSGContext *m_context;
- QSGSimpleRectNode *m_cursorNode;
- QList<QSGTexture *> m_textures;
-};
-
-QT_END_NAMESPACE
-
-#endif // QQUICKTEXTNODE_P_H
diff --git a/src/declarative/items/qquicktranslate.cpp b/src/declarative/items/qquicktranslate.cpp
deleted file mode 100644
index 7347cb0624..0000000000
--- a/src/declarative/items/qquicktranslate.cpp
+++ /dev/null
@@ -1,319 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquicktranslate_p.h"
-#include "qquickitem_p.h"
-
-#include <QtCore/qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-class QQuickTranslatePrivate : public QQuickTransformPrivate
-{
-public:
- QQuickTranslatePrivate()
- : x(0), y(0) {}
-
- qreal x;
- qreal y;
-};
-
-/*!
- Constructs an empty QQuickTranslate object with the given \a parent.
-*/
-QQuickTranslate::QQuickTranslate(QObject *parent)
-: QQuickTransform(*new QQuickTranslatePrivate, parent)
-{
-}
-
-/*!
- Destroys the graphics scale.
-*/
-QQuickTranslate::~QQuickTranslate()
-{
-}
-
-/*!
- \property QQuickTranslate::x
- \brief the horizontal translation.
-
- The translation can be any real number; the default value is 0.0.
-
- \sa y
-*/
-qreal QQuickTranslate::x() const
-{
- Q_D(const QQuickTranslate);
- return d->x;
-}
-
-void QQuickTranslate::setX(qreal x)
-{
- Q_D(QQuickTranslate);
- if (d->x == x)
- return;
- d->x = x;
- update();
- emit xChanged();
-}
-
-/*!
- \property QQuickTranslate::y
- \brief the vertical translation.
-
- The translation can be any real number; the default value is 0.0.
-
- \sa x
-*/
-qreal QQuickTranslate::y() const
-{
- Q_D(const QQuickTranslate);
- return d->y;
-}
-void QQuickTranslate::setY(qreal y)
-{
- Q_D(QQuickTranslate);
- if (d->y == y)
- return;
- d->y = y;
- update();
- emit yChanged();
-}
-
-void QQuickTranslate::applyTo(QMatrix4x4 *matrix) const
-{
- Q_D(const QQuickTranslate);
- matrix->translate(d->x, d->y, 0);
-}
-
-class QQuickScalePrivate : public QQuickTransformPrivate
-{
-public:
- QQuickScalePrivate()
- : xScale(1), yScale(1), zScale(1) {}
- QVector3D origin;
- qreal xScale;
- qreal yScale;
- qreal zScale;
-};
-
-QQuickScale::QQuickScale(QObject *parent)
- : QQuickTransform(*new QQuickScalePrivate, parent)
-{
-}
-
-QQuickScale::~QQuickScale()
-{
-}
-
-QVector3D QQuickScale::origin() const
-{
- Q_D(const QQuickScale);
- return d->origin;
-}
-void QQuickScale::setOrigin(const QVector3D &point)
-{
- Q_D(QQuickScale);
- if (d->origin == point)
- return;
- d->origin = point;
- update();
- emit originChanged();
-}
-
-qreal QQuickScale::xScale() const
-{
- Q_D(const QQuickScale);
- return d->xScale;
-}
-void QQuickScale::setXScale(qreal scale)
-{
- Q_D(QQuickScale);
- if (d->xScale == scale)
- return;
- d->xScale = scale;
- update();
- emit xScaleChanged();
- emit scaleChanged();
-}
-
-qreal QQuickScale::yScale() const
-{
- Q_D(const QQuickScale);
- return d->yScale;
-}
-void QQuickScale::setYScale(qreal scale)
-{
- Q_D(QQuickScale);
- if (d->yScale == scale)
- return;
- d->yScale = scale;
- update();
- emit yScaleChanged();
- emit scaleChanged();
-}
-
-qreal QQuickScale::zScale() const
-{
- Q_D(const QQuickScale);
- return d->zScale;
-}
-void QQuickScale::setZScale(qreal scale)
-{
- Q_D(QQuickScale);
- if (d->zScale == scale)
- return;
- d->zScale = scale;
- update();
- emit zScaleChanged();
- emit scaleChanged();
-}
-
-void QQuickScale::applyTo(QMatrix4x4 *matrix) const
-{
- Q_D(const QQuickScale);
- matrix->translate(d->origin);
- matrix->scale(d->xScale, d->yScale, d->zScale);
- matrix->translate(-d->origin);
-}
-
-class QQuickRotationPrivate : public QQuickTransformPrivate
-{
-public:
- QQuickRotationPrivate()
- : angle(0), axis(0, 0, 1) {}
- QVector3D origin;
- qreal angle;
- QVector3D axis;
-};
-
-QQuickRotation::QQuickRotation(QObject *parent)
- : QQuickTransform(*new QQuickRotationPrivate, parent)
-{
-}
-
-QQuickRotation::~QQuickRotation()
-{
-}
-
-QVector3D QQuickRotation::origin() const
-{
- Q_D(const QQuickRotation);
- return d->origin;
-}
-
-void QQuickRotation::setOrigin(const QVector3D &point)
-{
- Q_D(QQuickRotation);
- if (d->origin == point)
- return;
- d->origin = point;
- update();
- emit originChanged();
-}
-
-qreal QQuickRotation::angle() const
-{
- Q_D(const QQuickRotation);
- return d->angle;
-}
-void QQuickRotation::setAngle(qreal angle)
-{
- Q_D(QQuickRotation);
- if (d->angle == angle)
- return;
- d->angle = angle;
- update();
- emit angleChanged();
-}
-
-QVector3D QQuickRotation::axis() const
-{
- Q_D(const QQuickRotation);
- return d->axis;
-}
-void QQuickRotation::setAxis(const QVector3D &axis)
-{
- Q_D(QQuickRotation);
- if (d->axis == axis)
- return;
- d->axis = axis;
- update();
- emit axisChanged();
-}
-
-void QQuickRotation::setAxis(Qt::Axis axis)
-{
- switch (axis)
- {
- case Qt::XAxis:
- setAxis(QVector3D(1, 0, 0));
- break;
- case Qt::YAxis:
- setAxis(QVector3D(0, 1, 0));
- break;
- case Qt::ZAxis:
- setAxis(QVector3D(0, 0, 1));
- break;
- }
-}
-
-class QGraphicsRotation {
-public:
- static inline void projectedRotate(QMatrix4x4 *matrix, qreal angle, qreal x, qreal y, qreal z)
- {
- matrix->projectedRotate(angle, x, y, z);
- }
-};
-
-void QQuickRotation::applyTo(QMatrix4x4 *matrix) const
-{
- Q_D(const QQuickRotation);
-
- if (d->angle == 0. || d->axis.isNull())
- return;
-
- matrix->translate(d->origin);
- QGraphicsRotation::projectedRotate(matrix, d->angle, d->axis.x(), d->axis.y(), d->axis.z());
- matrix->translate(-d->origin);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquicktranslate_p.h b/src/declarative/items/qquicktranslate_p.h
deleted file mode 100644
index 6c2333df34..0000000000
--- a/src/declarative/items/qquicktranslate_p.h
+++ /dev/null
@@ -1,162 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKTRANSLATE_P_H
-#define QQUICKTRANSLATE_P_H
-
-#include "qquickitem.h"
-
-#include <QtGui/qmatrix4x4.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickTranslatePrivate;
-class Q_AUTOTEST_EXPORT QQuickTranslate : public QQuickTransform
-{
- Q_OBJECT
-
- Q_PROPERTY(qreal x READ x WRITE setX NOTIFY xChanged)
- Q_PROPERTY(qreal y READ y WRITE setY NOTIFY yChanged)
-
-public:
- QQuickTranslate(QObject *parent = 0);
- ~QQuickTranslate();
-
- qreal x() const;
- void setX(qreal);
-
- qreal y() const;
- void setY(qreal);
-
- void applyTo(QMatrix4x4 *matrix) const;
-
-Q_SIGNALS:
- void xChanged();
- void yChanged();
-
-private:
- Q_DECLARE_PRIVATE(QQuickTranslate)
- Q_DISABLE_COPY(QQuickTranslate)
-};
-
-class QQuickScalePrivate;
-class Q_AUTOTEST_EXPORT QQuickScale : public QQuickTransform
-{
- Q_OBJECT
-
- Q_PROPERTY(QVector3D origin READ origin WRITE setOrigin NOTIFY originChanged)
- Q_PROPERTY(qreal xScale READ xScale WRITE setXScale NOTIFY xScaleChanged)
- Q_PROPERTY(qreal yScale READ yScale WRITE setYScale NOTIFY yScaleChanged)
- Q_PROPERTY(qreal zScale READ zScale WRITE setZScale NOTIFY zScaleChanged)
-public:
- QQuickScale(QObject *parent = 0);
- ~QQuickScale();
-
- QVector3D origin() const;
- void setOrigin(const QVector3D &point);
-
- qreal xScale() const;
- void setXScale(qreal);
-
- qreal yScale() const;
- void setYScale(qreal);
-
- qreal zScale() const;
- void setZScale(qreal);
-
- void applyTo(QMatrix4x4 *matrix) const;
-
-Q_SIGNALS:
- void originChanged();
- void xScaleChanged();
- void yScaleChanged();
- void zScaleChanged();
- void scaleChanged();
-
-private:
- Q_DECLARE_PRIVATE(QQuickScale)
-};
-
-class QQuickRotationPrivate;
-class Q_AUTOTEST_EXPORT QQuickRotation : public QQuickTransform
-{
- Q_OBJECT
-
- Q_PROPERTY(QVector3D origin READ origin WRITE setOrigin NOTIFY originChanged)
- Q_PROPERTY(qreal angle READ angle WRITE setAngle NOTIFY angleChanged)
- Q_PROPERTY(QVector3D axis READ axis WRITE setAxis NOTIFY axisChanged)
-public:
- QQuickRotation(QObject *parent = 0);
- ~QQuickRotation();
-
- QVector3D origin() const;
- void setOrigin(const QVector3D &point);
-
- qreal angle() const;
- void setAngle(qreal);
-
- QVector3D axis() const;
- void setAxis(const QVector3D &axis);
- void setAxis(Qt::Axis axis);
-
- void applyTo(QMatrix4x4 *matrix) const;
-
-Q_SIGNALS:
- void originChanged();
- void angleChanged();
- void axisChanged();
-
-private:
- Q_DECLARE_PRIVATE(QQuickRotation)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickTranslate)
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/items/qquickview.cpp b/src/declarative/items/qquickview.cpp
deleted file mode 100644
index 9d431c865a..0000000000
--- a/src/declarative/items/qquickview.cpp
+++ /dev/null
@@ -1,539 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickview.h"
-#include "qquickview_p.h"
-
-#include "qquickcanvas_p.h"
-#include "qquickitem_p.h"
-#include "qquickitemchangelistener_p.h"
-
-#include <private/qdeclarativedebugtrace_p.h>
-#include <private/qdeclarativeinspectorservice_p.h>
-
-#include <QtDeclarative/qdeclarativeengine.h>
-#include <private/qdeclarativeengine_p.h>
-#include <QtCore/qbasictimer.h>
-
-
-QT_BEGIN_NAMESPACE
-
-void QQuickViewPrivate::init()
-{
- Q_Q(QQuickView);
-
- engine.setIncubationController(q->incubationController());
-
- if (QDeclarativeDebugService::isDebuggingEnabled())
- QDeclarativeInspectorService::instance()->addView(q);
-}
-
-QQuickViewPrivate::QQuickViewPrivate()
- : root(0), component(0), resizeMode(QQuickView::SizeViewToRootObject), initialSize(0,0)
-{
-}
-
-QQuickViewPrivate::~QQuickViewPrivate()
-{
- if (QDeclarativeDebugService::isDebuggingEnabled())
- QDeclarativeInspectorService::instance()->removeView(q_func());
-
- delete root;
-}
-
-void QQuickViewPrivate::execute()
-{
- Q_Q(QQuickView);
- if (root) {
- delete root;
- root = 0;
- }
- if (component) {
- delete component;
- component = 0;
- }
- if (!source.isEmpty()) {
- component = new QDeclarativeComponent(&engine, source, q);
- if (!component->isLoading()) {
- q->continueExecute();
- } else {
- QObject::connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)),
- q, SLOT(continueExecute()));
- }
- }
-}
-
-void QQuickViewPrivate::itemGeometryChanged(QQuickItem *resizeItem, const QRectF &newGeometry, const QRectF &oldGeometry)
-{
- Q_Q(QQuickView);
- if (resizeItem == root && resizeMode == QQuickView::SizeViewToRootObject) {
- // wait for both width and height to be changed
- resizetimer.start(0,q);
- }
- QQuickItemChangeListener::itemGeometryChanged(resizeItem, newGeometry, oldGeometry);
-}
-
-/*!
- \class QQuickView
- \since QtQuick 2.0
- \brief The QQuickView class provides a window for displaying a Qt Quick user interface.
-
- This is a convenience subclass of QQuickCanvas which
- will automatically load and display a QML scene when given the URL of the main source file. Alternatively,
- you can instantiate your own objects using QDeclarativeComponent and place them in a manually setup QQuickCanvas.
-
- Typical usage:
-
- \code
- QQuickView *view = new QQuickView;
- view->setSource(QUrl::fromLocalFile("myqmlfile.qml"));
- view->show();
- \endcode
-
- To receive errors related to loading and executing QML with QQuickView,
- you can connect to the statusChanged() signal and monitor for QQuickView::Error.
- The errors are available via QQuickView::errors().
-
- \sa {Using QML Bindings in C++ Applications}
-*/
-
-
-/*! \fn void QQuickView::sceneResized(QSize size)
- This signal is emitted when the view is resized to \a size.
-*/
-
-/*! \fn void QQuickView::statusChanged(QQuickView::Status status)
- This signal is emitted when the component's current \a status changes.
-*/
-
-/*! \fn void QQuickView::initialSizeChanged(QSize size)
- \internal
-*/
-
-/*!
- \fn QQuickView::QQuickView(QWindow *parent)
-
- Constructs a QQuickView with the given \a parent.
-*/
-QQuickView::QQuickView(QWindow *parent, Qt::WindowFlags f)
-: QQuickCanvas(*(new QQuickViewPrivate), parent)
-{
- setWindowFlags(f);
- d_func()->init();
-}
-
-/*!
- \fn QQuickView::QQuickView(const QUrl &source, QWidget *parent)
-
- Constructs a QQuickView with the given QML \a source and \a parent.
-*/
-QQuickView::QQuickView(const QUrl &source, QWindow *parent, Qt::WindowFlags f)
-: QQuickCanvas(*(new QQuickViewPrivate), parent)
-{
- setWindowFlags(f);
- d_func()->init();
- setSource(source);
-}
-
-QQuickView::~QQuickView()
-{
-}
-
-/*! \property QQuickView::source
- \brief The URL of the source of the QML component.
-
- Changing this property causes the QML component to be reloaded.
-
- Ensure that the URL provided is full and correct, in particular, use
- \l QUrl::fromLocalFile() when loading a file from the local filesystem.
- */
-
-/*!
- Sets the source to the \a url, loads the QML component and instantiates it.
-
- Ensure that the URL provided is full and correct, in particular, use
- \l QUrl::fromLocalFile() when loading a file from the local filesystem.
-
- Calling this methods multiple times with the same url will result
- in the QML being reloaded.
- */
-void QQuickView::setSource(const QUrl& url)
-{
- Q_D(QQuickView);
- d->source = url;
- d->execute();
-}
-
-/*!
- Returns the source URL, if set.
-
- \sa setSource()
- */
-QUrl QQuickView::source() const
-{
- Q_D(const QQuickView);
- return d->source;
-}
-
-/*!
- Returns a pointer to the QDeclarativeEngine used for instantiating
- QML Components.
- */
-QDeclarativeEngine* QQuickView::engine() const
-{
- Q_D(const QQuickView);
- return const_cast<QDeclarativeEngine *>(&d->engine);
-}
-
-/*!
- This function returns the root of the context hierarchy. Each QML
- component is instantiated in a QDeclarativeContext. QDeclarativeContext's are
- essential for passing data to QML components. In QML, contexts are
- arranged hierarchically and this hierarchy is managed by the
- QDeclarativeEngine.
- */
-QDeclarativeContext* QQuickView::rootContext() const
-{
- Q_D(const QQuickView);
- return d->engine.rootContext();
-}
-
-/*!
- \enum QQuickView::Status
- Specifies the loading status of the QQuickView.
-
- \value Null This QQuickView has no source set.
- \value Ready This QQuickView has loaded and created the QML component.
- \value Loading This QQuickView is loading network data.
- \value Error One or more errors has occurred. Call errors() to retrieve a list
- of errors.
-*/
-
-/*! \enum QQuickView::ResizeMode
-
- This enum specifies how to resize the view.
-
- \value SizeViewToRootObject The view resizes with the root item in the QML.
- \value SizeRootObjectToView The view will automatically resize the root item to the size of the view.
-*/
-
-/*!
- \property QQuickView::status
- The component's current \l{QQuickView::Status} {status}.
-*/
-
-QQuickView::Status QQuickView::status() const
-{
- Q_D(const QQuickView);
- if (!d->component)
- return QQuickView::Null;
-
- return QQuickView::Status(d->component->status());
-}
-
-/*!
- Return the list of errors that occurred during the last compile or create
- operation. When the status is not Error, an empty list is returned.
-*/
-QList<QDeclarativeError> QQuickView::errors() const
-{
- Q_D(const QQuickView);
- if (d->component)
- return d->component->errors();
- return QList<QDeclarativeError>();
-}
-
-/*!
- \property QQuickView::resizeMode
- \brief whether the view should resize the canvas contents
-
- If this property is set to SizeViewToRootObject (the default), the view
- resizes with the root item in the QML.
-
- If this property is set to SizeRootObjectToView, the view will
- automatically resize the root item.
-
- Regardless of this property, the sizeHint of the view
- is the initial size of the root item. Note though that
- since QML may load dynamically, that size may change.
-*/
-
-void QQuickView::setResizeMode(ResizeMode mode)
-{
- Q_D(QQuickView);
- if (d->resizeMode == mode)
- return;
-
- if (d->root) {
- if (d->resizeMode == SizeViewToRootObject) {
- QQuickItemPrivate *p = QQuickItemPrivate::get(d->root);
- p->removeItemChangeListener(d, QQuickItemPrivate::Geometry);
- }
- }
-
- d->resizeMode = mode;
- if (d->root) {
- d->initResize();
- }
-}
-
-void QQuickViewPrivate::initResize()
-{
- if (root) {
- if (resizeMode == QQuickView::SizeViewToRootObject) {
- QQuickItemPrivate *p = QQuickItemPrivate::get(root);
- p->addItemChangeListener(this, QQuickItemPrivate::Geometry);
- }
- }
- updateSize();
-}
-
-void QQuickViewPrivate::updateSize()
-{
- Q_Q(QQuickView);
- if (!root)
- return;
-
- if (resizeMode == QQuickView::SizeViewToRootObject) {
- QSize newSize = QSize(root->width(), root->height());
- if (newSize.isValid() && newSize != q->size()) {
- q->resize(newSize);
- }
- } else if (resizeMode == QQuickView::SizeRootObjectToView) {
- if (!qFuzzyCompare(q->width(), root->width()))
- root->setWidth(q->width());
- if (!qFuzzyCompare(q->height(), root->height()))
- root->setHeight(q->height());
- }
-}
-
-QSize QQuickViewPrivate::rootObjectSize() const
-{
- QSize rootObjectSize(0,0);
- int widthCandidate = -1;
- int heightCandidate = -1;
- if (root) {
- widthCandidate = root->width();
- heightCandidate = root->height();
- }
- if (widthCandidate > 0) {
- rootObjectSize.setWidth(widthCandidate);
- }
- if (heightCandidate > 0) {
- rootObjectSize.setHeight(heightCandidate);
- }
- return rootObjectSize;
-}
-
-QQuickView::ResizeMode QQuickView::resizeMode() const
-{
- Q_D(const QQuickView);
- return d->resizeMode;
-}
-
-/*!
- \internal
- */
-void QQuickView::continueExecute()
-{
- Q_D(QQuickView);
- disconnect(d->component, SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(continueExecute()));
-
- if (d->component->isError()) {
- QList<QDeclarativeError> errorList = d->component->errors();
- foreach (const QDeclarativeError &error, errorList) {
- qWarning() << error;
- }
- emit statusChanged(status());
- return;
- }
-
- QObject *obj = d->component->create();
-
- if (d->component->isError()) {
- QList<QDeclarativeError> errorList = d->component->errors();
- foreach (const QDeclarativeError &error, errorList) {
- qWarning() << error;
- }
- emit statusChanged(status());
- return;
- }
-
- d->setRootObject(obj);
- emit statusChanged(status());
-}
-
-
-/*!
- \internal
-*/
-void QQuickViewPrivate::setRootObject(QObject *obj)
-{
- Q_Q(QQuickView);
- if (root == obj)
- return;
- if (QQuickItem *sgItem = qobject_cast<QQuickItem *>(obj)) {
- root = sgItem;
- sgItem->setParentItem(q->QQuickCanvas::rootItem());
- } else {
- qWarning() << "QQuickView only supports loading of root objects that derive from QQuickItem." << endl
- << endl
- << "If your example is using QML 2, (such as qmlscene) and the .qml file you" << endl
- << "loaded has 'import QtQuick 1.0' or 'import Qt 4.7', this error will occur." << endl
- << endl
- << "To load files with 'import QtQuick 1.0' with QML 2, specify:" << endl
- << " QMLSCENE_IMPORT_NAME=quick1" << endl
- << "on as an environment variable prior to launching the application." << endl
- << endl
- << "To load files with 'import Qt 4.7' with QML 2, specify:" << endl
- << " QMLSCENE_IMPORT_NAME=qt" << endl
- << "on as an environment variable prior to launching the application." << endl;
- delete obj;
- root = 0;
- }
- if (root) {
- initialSize = rootObjectSize();
- if ((resizeMode == QQuickView::SizeViewToRootObject || !q->width() || !q->height())
- && initialSize != q->size()) {
- q->resize(initialSize);
- }
- initResize();
- }
-}
-
-/*!
- \internal
- If the \l {QTimerEvent} {timer event} \a e is this
- view's resize timer, sceneResized() is emitted.
- */
-void QQuickView::timerEvent(QTimerEvent* e)
-{
- Q_D(QQuickView);
- if (!e || e->timerId() == d->resizetimer.timerId()) {
- d->updateSize();
- d->resizetimer.stop();
- }
-}
-
-/*!
- \internal
- Preferred size follows the root object geometry.
-*/
-QSize QQuickView::sizeHint() const
-{
- Q_D(const QQuickView);
- QSize rootObjectSize = d->rootObjectSize();
- if (rootObjectSize.isEmpty()) {
- return size();
- } else {
- return rootObjectSize;
- }
-}
-
-/*!
- Returns the initial size of the root object
-*/
-QSize QQuickView::initialSize() const
-{
- Q_D(const QQuickView);
- return d->initialSize;
-}
-
-/*!
- Returns the view's root \l {QQuickItem} {item}.
- */
-QQuickItem *QQuickView::rootObject() const
-{
- Q_D(const QQuickView);
- return d->root;
-}
-
-/*!
- \internal
- This function handles the \l {QResizeEvent} {resize event}
- \a e.
- */
-void QQuickView::resizeEvent(QResizeEvent *e)
-{
- Q_D(QQuickView);
- if (d->resizeMode == SizeRootObjectToView)
- d->updateSize();
-
- QQuickCanvas::resizeEvent(e);
-}
-
-void QQuickView::keyPressEvent(QKeyEvent *e)
-{
- QDeclarativeDebugTrace::addEvent(QDeclarativeDebugTrace::Key);
-
- QQuickCanvas::keyPressEvent(e);
-}
-
-void QQuickView::keyReleaseEvent(QKeyEvent *e)
-{
- QDeclarativeDebugTrace::addEvent(QDeclarativeDebugTrace::Key);
-
- QQuickCanvas::keyReleaseEvent(e);
-}
-
-void QQuickView::mouseMoveEvent(QMouseEvent *e)
-{
- QDeclarativeDebugTrace::addEvent(QDeclarativeDebugTrace::Mouse);
-
- QQuickCanvas::mouseMoveEvent(e);
-}
-
-void QQuickView::mousePressEvent(QMouseEvent *e)
-{
- QDeclarativeDebugTrace::addEvent(QDeclarativeDebugTrace::Mouse);
-
- QQuickCanvas::mousePressEvent(e);
-}
-
-void QQuickView::mouseReleaseEvent(QMouseEvent *e)
-{
- QDeclarativeDebugTrace::addEvent(QDeclarativeDebugTrace::Mouse);
-
- QQuickCanvas::mouseReleaseEvent(e);
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/items/qquickview.h b/src/declarative/items/qquickview.h
deleted file mode 100644
index 8321655d63..0000000000
--- a/src/declarative/items/qquickview.h
+++ /dev/null
@@ -1,120 +0,0 @@
-// Commit: 0b83a2161261be525f01359397ab1c8c34827749
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKVIEW_H
-#define QQUICKVIEW_H
-
-#include <qquickcanvas.h>
-#include <QtCore/qurl.h>
-#include <QtDeclarative/qdeclarativedebug.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeEngine;
-class QDeclarativeContext;
-class QDeclarativeError;
-class QQuickItem;
-
-class QQuickViewPrivate;
-class Q_DECLARATIVE_EXPORT QQuickView : public QQuickCanvas
-{
- Q_OBJECT
- Q_PROPERTY(ResizeMode resizeMode READ resizeMode WRITE setResizeMode)
- Q_PROPERTY(Status status READ status NOTIFY statusChanged)
- Q_PROPERTY(QUrl source READ source WRITE setSource DESIGNABLE true)
- Q_ENUMS(ResizeMode Status)
-public:
- explicit QQuickView(QWindow *parent = 0, Qt::WindowFlags f = 0);
- QQuickView(const QUrl &source, QWindow *parent = 0, Qt::WindowFlags f = 0);
- virtual ~QQuickView();
-
- QUrl source() const;
-
- QDeclarativeEngine* engine() const;
- QDeclarativeContext* rootContext() const;
-
- QQuickItem *rootObject() const;
-
- enum ResizeMode { SizeViewToRootObject, SizeRootObjectToView };
- ResizeMode resizeMode() const;
- void setResizeMode(ResizeMode);
-
- enum Status { Null, Ready, Loading, Error };
- Status status() const;
-
- QList<QDeclarativeError> errors() const;
-
- QSize sizeHint() const;
- QSize initialSize() const;
-
-public Q_SLOTS:
- void setSource(const QUrl&);
-
-Q_SIGNALS:
- void statusChanged(QQuickView::Status);
-
-private Q_SLOTS:
- void continueExecute();
-
-protected:
- virtual void resizeEvent(QResizeEvent *);
- virtual void timerEvent(QTimerEvent*);
-
- virtual void keyPressEvent(QKeyEvent *);
- virtual void keyReleaseEvent(QKeyEvent *);
- virtual void mousePressEvent(QMouseEvent *);
- virtual void mouseReleaseEvent(QMouseEvent *);
- virtual void mouseMoveEvent(QMouseEvent *);
-private:
- Q_DISABLE_COPY(QQuickView)
- Q_DECLARE_PRIVATE(QQuickView)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKVIEW_H
diff --git a/src/declarative/items/qquickview_p.h b/src/declarative/items/qquickview_p.h
deleted file mode 100644
index 8c835268f5..0000000000
--- a/src/declarative/items/qquickview_p.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKVIEW_P_H
-#define QQUICKVIEW_P_H
-
-#include "qquickview.h"
-
-#include <QtCore/qurl.h>
-#include <QtCore/qelapsedtimer.h>
-#include <QtCore/qtimer.h>
-#include <QtCore/qpointer.h>
-#include <QtDeclarative/qdeclarativeengine.h>
-#include "qquickcanvas_p.h"
-
-#include "qquickitemchangelistener_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeContext;
-class QDeclarativeError;
-class QQuickItem;
-class QDeclarativeComponent;
-
-class QQuickViewPrivate : public QQuickCanvasPrivate,
- public QQuickItemChangeListener
-{
- Q_DECLARE_PUBLIC(QQuickView)
-public:
- static QQuickViewPrivate* get(QQuickView *view) { return view->d_func(); }
- static const QQuickViewPrivate* get(const QQuickView *view) { return view->d_func(); }
-
- QQuickViewPrivate();
- ~QQuickViewPrivate();
-
- void execute();
- void itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry);
- void initResize();
- void updateSize();
- void setRootObject(QObject *);
-
- void init();
-
- QSize rootObjectSize() const;
-
- QPointer<QQuickItem> root;
-
- QUrl source;
-
- QDeclarativeEngine engine;
- QDeclarativeComponent *component;
- QBasicTimer resizetimer;
-
- QQuickView::ResizeMode resizeMode;
- QSize initialSize;
- QElapsedTimer frameTimer;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQUICKVIEW_P_H
diff --git a/src/declarative/items/qquickvisualadaptormodel.cpp b/src/declarative/items/qquickvisualadaptormodel.cpp
deleted file mode 100644
index 25baee6e29..0000000000
--- a/src/declarative/items/qquickvisualadaptormodel.cpp
+++ /dev/null
@@ -1,889 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickvisualadaptormodel_p.h"
-#include "qquickitem.h"
-
-#include <QtDeclarative/qdeclarativecontext.h>
-#include <QtDeclarative/qdeclarativeengine.h>
-#include <QtDeclarative/qdeclarativeexpression.h>
-#include <QtDeclarative/qdeclarativeinfo.h>
-
-#include <private/qdeclarativecontext_p.h>
-#include <private/qdeclarativepackage_p.h>
-#include <private/qdeclarativeopenmetaobject_p.h>
-#include <private/qdeclarativelistaccessor_p.h>
-#include <private/qdeclarativedata_p.h>
-#include <private/qdeclarativepropertycache_p.h>
-#include <private/qdeclarativeguard_p.h>
-#include <private/qdeclarativeglobal_p.h>
-#include <private/qlistmodelinterface_p.h>
-#include <private/qmetaobjectbuilder_p.h>
-#include <private/qdeclarativeproperty_p.h>
-#include <private/qintrusivelist_p.h>
-#include <private/qobject_p.h>
-
-#include <QtCore/qhash.h>
-#include <QtCore/qlist.h>
-
-Q_DECLARE_METATYPE(QModelIndex)
-
-QT_BEGIN_NAMESPACE
-
-class VDMDelegateDataType : public QDeclarativeRefCount
-{
-public:
- VDMDelegateDataType()
- : metaObject(0)
- , propertyCache(0)
- , propertyOffset(0)
- , signalOffset(0)
- , shared(true)
- {
- }
-
- VDMDelegateDataType(const VDMDelegateDataType &type)
- : metaObject(0)
- , propertyCache(0)
- , propertyOffset(type.propertyOffset)
- , signalOffset(type.signalOffset)
- , shared(false)
- , builder(type.metaObject, QMetaObjectBuilder::Properties
- | QMetaObjectBuilder::Signals
- | QMetaObjectBuilder::SuperClass
- | QMetaObjectBuilder::ClassName)
- {
- builder.setFlags(QMetaObjectBuilder::DynamicMetaObject);
- }
-
- ~VDMDelegateDataType()
- {
- if (propertyCache)
- propertyCache->release();
- qFree(metaObject);
- }
-
- QMetaObject *metaObject;
- QDeclarativePropertyCache *propertyCache;
- int propertyOffset;
- int signalOffset;
- bool shared : 1;
- QMetaObjectBuilder builder;
-};
-
-class QQuickVisualAdaptorModelData : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(int index READ index NOTIFY indexChanged)
-public:
- QQuickVisualAdaptorModelData(int index, QQuickVisualAdaptorModel *model);
- ~QQuickVisualAdaptorModelData();
-
- int index() const;
- void setIndex(int index);
-
-Q_SIGNALS:
- void indexChanged();
-
-public:
- int m_index;
- QDeclarativeGuard<QQuickVisualAdaptorModel> m_model;
- QIntrusiveListNode m_cacheNode;
-};
-
-typedef QIntrusiveList<QQuickVisualAdaptorModelData, &QQuickVisualAdaptorModelData::m_cacheNode> QQuickVisualAdaptorModelDataCache;
-
-class QQuickVisualAdaptorModelDataMetaObject;
-class QQuickVisualAdaptorModelPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QQuickVisualAdaptorModel)
-public:
- QQuickVisualAdaptorModelPrivate()
- : m_engine(0)
- , m_listAccessor(0)
- , m_delegateDataType(0)
- , createModelData(&initializeModelData)
- , m_ref(0)
- , m_count(0)
- , m_objectList(false)
- {
- }
-
-
- static QQuickVisualAdaptorModelPrivate *get(QQuickVisualAdaptorModel *m) {
- return static_cast<QQuickVisualAdaptorModelPrivate *>(QObjectPrivate::get(m));
- }
-
- void addProperty(int role, int propertyId, const char *propertyName, const char *propertyType, bool isModelData = false);
- template <typename T> void setModelDataType()
- {
- createModelData = &T::create;
- m_delegateDataType->builder.setFlags(QMetaObjectBuilder::DynamicMetaObject);
- m_delegateDataType->builder.setClassName(T::staticMetaObject.className());
- m_delegateDataType->builder.setSuperClass(&T::staticMetaObject);
- m_delegateDataType->propertyOffset = T::staticMetaObject.propertyCount();
- m_delegateDataType->signalOffset = T::staticMetaObject.methodCount();
- }
- QQuickVisualAdaptorModelData *createMetaObject(int index, QQuickVisualAdaptorModel *model);
-
- static QQuickVisualAdaptorModelData *initializeModelData(int index, QQuickVisualAdaptorModel *model) {
- return get(model)->createMetaObject(index, model);
- }
-
- typedef QQuickVisualAdaptorModelData *(*CreateModelData)(int index, QQuickVisualAdaptorModel *model);
-
- struct PropertyData {
- int role;
- bool isModelData : 1;
- };
-
- int modelCount() const {
- if (m_listModelInterface)
- return m_listModelInterface->count();
- if (m_abstractItemModel)
- return m_abstractItemModel->rowCount(m_root);
- if (m_listAccessor)
- return m_listAccessor->count();
- return 0;
- }
-
- QDeclarativeGuard<QDeclarativeEngine> m_engine;
- QDeclarativeGuard<QListModelInterface> m_listModelInterface;
- QDeclarativeGuard<QAbstractItemModel> m_abstractItemModel;
- QDeclarativeListAccessor *m_listAccessor;
- VDMDelegateDataType *m_delegateDataType;
- CreateModelData createModelData;
-
- int m_ref;
- int m_count;
- QQuickVisualAdaptorModel::Flags m_flags;
- bool m_objectList : 1;
-
- QVariant m_modelVariant;
- QModelIndex m_root;
-
- QList<int> m_roles;
- QList<int> watchedRoleIds;
- QList<QByteArray> watchedRoles;
- QHash<QByteArray,int> m_roleNames;
- QVector<PropertyData> m_propertyData;
- QQuickVisualAdaptorModelDataCache m_cache;
-};
-
-class QQuickVisualAdaptorModelDataMetaObject : public QAbstractDynamicMetaObject
-{
-public:
- QQuickVisualAdaptorModelDataMetaObject(QQuickVisualAdaptorModelData *data, VDMDelegateDataType *type)
- : m_data(data)
- , m_type(type)
- {
- QObjectPrivate *op = QObjectPrivate::get(m_data);
- *static_cast<QMetaObject *>(this) = *type->metaObject;
- op->metaObject = this;
- m_type->addref();
- }
-
- ~QQuickVisualAdaptorModelDataMetaObject() { m_type->release(); }
-
- QQuickVisualAdaptorModelData *m_data;
- VDMDelegateDataType *m_type;
-};
-
-class QQuickVDMAbstractItemModelDataMetaObject : public QQuickVisualAdaptorModelDataMetaObject
-{
-public:
- QQuickVDMAbstractItemModelDataMetaObject(QQuickVisualAdaptorModelData *object, VDMDelegateDataType *type)
- : QQuickVisualAdaptorModelDataMetaObject(object, type) {}
-
- int metaCall(QMetaObject::Call call, int id, void **arguments)
- {
- if (call == QMetaObject::ReadProperty && id >= m_type->propertyOffset) {
- QQuickVisualAdaptorModelPrivate *model = QQuickVisualAdaptorModelPrivate::get(m_data->m_model);
- if (m_data->m_index == -1 || !model->m_abstractItemModel)
- return -1;
- *static_cast<QVariant *>(arguments[0]) = model->m_abstractItemModel->index(
- m_data->m_index, 0, model->m_root).data(model->m_propertyData.at(id - m_type->propertyOffset).role);
- return -1;
- } else {
- return m_data->qt_metacall(call, id, arguments);
- }
- }
-};
-
-class QQuickVDMAbstractItemModelData : public QQuickVisualAdaptorModelData
-{
- Q_OBJECT
- Q_PROPERTY(bool hasModelChildren READ hasModelChildren CONSTANT)
-public:
- bool hasModelChildren() const
- {
- QQuickVisualAdaptorModelPrivate *model = QQuickVisualAdaptorModelPrivate::get(m_model);
- return model->m_abstractItemModel->hasChildren(model->m_abstractItemModel->index(m_index, 0, model->m_root));
- }
-
- static QQuickVisualAdaptorModelData *create(int index, QQuickVisualAdaptorModel *model) {
- return new QQuickVDMAbstractItemModelData(index, model); }
-private:
- QQuickVDMAbstractItemModelData(int index, QQuickVisualAdaptorModel *model)
- : QQuickVisualAdaptorModelData(index, model)
- {
- new QQuickVDMAbstractItemModelDataMetaObject(
- this, QQuickVisualAdaptorModelPrivate::get(m_model)->m_delegateDataType);
- }
-};
-
-class QQuickVDMListModelInterfaceDataMetaObject : public QQuickVisualAdaptorModelDataMetaObject
-{
-public:
- QQuickVDMListModelInterfaceDataMetaObject(QQuickVisualAdaptorModelData *object, VDMDelegateDataType *type)
- : QQuickVisualAdaptorModelDataMetaObject(object, type) {}
-
- int metaCall(QMetaObject::Call call, int id, void **arguments)
- {
- if (call == QMetaObject::ReadProperty && id >= m_type->propertyOffset) {
- QQuickVisualAdaptorModelPrivate *model = QQuickVisualAdaptorModelPrivate::get(m_data->m_model);
- if (m_data->m_index == -1 || !model->m_listModelInterface)
- return -1;
- *static_cast<QVariant *>(arguments[0]) = model->m_listModelInterface->data(
- m_data->m_index, model->m_propertyData.at(id - m_type->propertyOffset).role);
- return -1;
- } else {
- return m_data->qt_metacall(call, id, arguments);
- }
- }
-};
-
-class QQuickVDMListModelInterfaceData : public QQuickVisualAdaptorModelData
-{
-public:
- static QQuickVisualAdaptorModelData *create(int index, QQuickVisualAdaptorModel *model) {
- return new QQuickVDMListModelInterfaceData(index, model); }
-private:
- QQuickVDMListModelInterfaceData(int index, QQuickVisualAdaptorModel *model)
- : QQuickVisualAdaptorModelData(index, model)
- {
- new QQuickVDMListModelInterfaceDataMetaObject(
- this, QQuickVisualAdaptorModelPrivate::get(m_model)->m_delegateDataType);
- }
-};
-
-class QQuickVDMListAccessorData : public QQuickVisualAdaptorModelData
-{
- Q_OBJECT
- Q_PROPERTY(QVariant modelData READ modelData CONSTANT)
-public:
- QVariant modelData() const {
- return QQuickVisualAdaptorModelPrivate::get(m_model)->m_listAccessor->at(m_index); }
-
- static QQuickVisualAdaptorModelData *create(int index, QQuickVisualAdaptorModel *model) {
- return new QQuickVDMListAccessorData(index, model); }
-private:
- QQuickVDMListAccessorData(int index, QQuickVisualAdaptorModel *model)
- : QQuickVisualAdaptorModelData(index, model)
- {
- }
-};
-
-class QQuickVDMObjectDataMetaObject : public QQuickVisualAdaptorModelDataMetaObject
-{
-public:
- QQuickVDMObjectDataMetaObject(QQuickVisualAdaptorModelData *data, VDMDelegateDataType *type)
- : QQuickVisualAdaptorModelDataMetaObject(data, type)
- , m_object(QQuickVisualAdaptorModelPrivate::get(data->m_model)->m_listAccessor->at(data->m_index).value<QObject *>())
- {}
-
- int metaCall(QMetaObject::Call call, int id, void **arguments)
- {
- if (id >= m_type->propertyOffset
- && (call == QMetaObject::ReadProperty
- || call == QMetaObject::WriteProperty
- || call == QMetaObject::ResetProperty)) {
- if (m_object)
- QMetaObject::metacall(m_object, call, id - m_type->propertyOffset + 1, arguments);
- return -1;
- } else if (id >= m_type->signalOffset && call == QMetaObject::InvokeMetaMethod) {
- QMetaObject::activate(m_data, this, id, 0);
- return -1;
- } else {
- return m_data->qt_metacall(call, id, arguments);
- }
- }
-
- int createProperty(const char *name, const char *)
- {
- if (!m_object)
- return -1;
- const QMetaObject *metaObject = m_object->metaObject();
-
- const int previousPropertyCount = propertyCount() - propertyOffset();
- int propertyIndex = metaObject->indexOfProperty(name);
- if (propertyIndex == -1)
- return -1;
- if (previousPropertyCount + 1 == metaObject->propertyCount())
- return propertyIndex + m_type->propertyOffset - 1;
-
- if (m_type->shared) {
- VDMDelegateDataType *type = m_type;
- m_type = new VDMDelegateDataType(*m_type);
- type->release();
- }
-
- const int previousMethodCount = methodCount();
- int notifierId = previousMethodCount;
- for (int propertyId = previousPropertyCount; propertyId < metaObject->propertyCount() - 1; ++propertyId) {
- QMetaProperty property = metaObject->property(propertyId + 1);
- QMetaPropertyBuilder propertyBuilder;
- if (property.hasNotifySignal()) {
- m_type->builder.addSignal("__" + QByteArray::number(propertyId) + "()");
- propertyBuilder = m_type->builder.addProperty(property.name(), property.typeName(), notifierId);
- ++notifierId;
- } else {
- propertyBuilder = m_type->builder.addProperty(property.name(), property.typeName());
- }
- propertyBuilder.setWritable(property.isWritable());
- propertyBuilder.setResettable(property.isResettable());
- propertyBuilder.setConstant(property.isConstant());
- }
-
- if (m_type->metaObject)
- qFree(m_type->metaObject);
- m_type->metaObject = m_type->builder.toMetaObject();
- *static_cast<QMetaObject *>(this) = *m_type->metaObject;
-
- notifierId = previousMethodCount;
- for (int i = previousPropertyCount; i < metaObject->propertyCount(); ++i) {
- QMetaProperty property = metaObject->property(i);
- if (property.hasNotifySignal()) {
- QDeclarativePropertyPrivate::connect(
- m_object, property.notifySignalIndex(), m_data, notifierId);
- ++notifierId;
- }
- }
- return propertyIndex + m_type->propertyOffset - 1;
- }
-
- QDeclarativeGuard<QObject> m_object;
-};
-
-class QQuickVDMObjectData : public QQuickVisualAdaptorModelData, public QQuickVisualAdaptorModelProxyInterface
-{
- Q_OBJECT
- Q_PROPERTY(QObject *modelData READ modelData CONSTANT)
- Q_INTERFACES(QQuickVisualAdaptorModelProxyInterface)
-public:
- QObject *modelData() const { return m_metaObject->m_object; }
- QObject *proxiedObject() { return m_metaObject->m_object; }
-
- static QQuickVisualAdaptorModelData *create(int index, QQuickVisualAdaptorModel *model) {
- return new QQuickVDMObjectData(index, model); }
-
-private:
- QQuickVDMObjectData(int index, QQuickVisualAdaptorModel *model)
- : QQuickVisualAdaptorModelData(index, model)
- , m_metaObject(new QQuickVDMObjectDataMetaObject(this, QQuickVisualAdaptorModelPrivate::get(m_model)->m_delegateDataType))
- {
- }
-
- QQuickVDMObjectDataMetaObject *m_metaObject;
-};
-
-void QQuickVisualAdaptorModelPrivate::addProperty(
- int role, int propertyId, const char *propertyName, const char *propertyType, bool isModelData)
-{
- PropertyData propertyData;
- propertyData.role = role;
- propertyData.isModelData = isModelData;
- m_delegateDataType->builder.addSignal("__" + QByteArray::number(propertyId) + "()");
- QMetaPropertyBuilder property = m_delegateDataType->builder.addProperty(
- propertyName, propertyType, propertyId);
- property.setWritable(false);
-
- m_propertyData.append(propertyData);
-}
-
-QQuickVisualAdaptorModelData *QQuickVisualAdaptorModelPrivate::createMetaObject(int index, QQuickVisualAdaptorModel *model)
-{
- Q_ASSERT(!m_delegateDataType);
-
- m_objectList = false;
- m_propertyData.clear();
- if (m_listAccessor
- && m_listAccessor->type() != QDeclarativeListAccessor::ListProperty
- && m_listAccessor->type() != QDeclarativeListAccessor::Instance) {
- createModelData = &QQuickVDMListAccessorData::create;
- m_flags = QQuickVisualAdaptorModel::MetaObjectCacheable;
- return QQuickVDMListAccessorData::create(index, model);
- }
-
- m_delegateDataType = new VDMDelegateDataType;
- if (m_listModelInterface) {
- setModelDataType<QQuickVDMListModelInterfaceData>();
- QList<int> roles = m_listModelInterface->roles();
- for (int propertyId = 0; propertyId < roles.count(); ++propertyId) {
- const int role = roles.at(propertyId);
- const QByteArray propertyName = m_listModelInterface->toString(role).toUtf8();
- addProperty(role, propertyId, propertyName, "QVariant");
- m_roleNames.insert(propertyName, role);
- }
- if (m_propertyData.count() == 1)
- addProperty(roles.first(), 1, "modelData", "QVariant", true);
- m_flags = QQuickVisualAdaptorModel::MetaObjectCacheable;
- } else if (m_abstractItemModel) {
- setModelDataType<QQuickVDMAbstractItemModelData>();
- QHash<int, QByteArray> roleNames = m_abstractItemModel->roleNames();
- for (QHash<int, QByteArray>::const_iterator it = roleNames.begin(); it != roleNames.end(); ++it) {
- addProperty(it.key(), m_propertyData.count(), it.value(), "QVariant");
- m_roleNames.insert(it.value(), it.key());
- }
- if (m_propertyData.count() == 1)
- addProperty(roleNames.begin().key(), 1, "modelData", "QVariant", true);
- m_flags = QQuickVisualAdaptorModel::MetaObjectCacheable;
- } else if (m_listAccessor) {
- setModelDataType<QQuickVDMObjectData>();
- m_objectList = true;
- m_flags = QQuickVisualAdaptorModel::ProxiedObject;
- } else {
- Q_ASSERT(!"No model set on VisualDataModel");
- return 0;
- }
- m_delegateDataType->metaObject = m_delegateDataType->builder.toMetaObject();
- if (!m_objectList) {
- m_delegateDataType->propertyCache = new QDeclarativePropertyCache(
- m_engine, m_delegateDataType->metaObject);
- }
- return createModelData(index, model);
-}
-
-QQuickVisualAdaptorModelData::QQuickVisualAdaptorModelData(int index, QQuickVisualAdaptorModel *model)
- : m_index(index)
- , m_model(model)
-{
-}
-
-QQuickVisualAdaptorModelData::~QQuickVisualAdaptorModelData()
-{
-}
-
-int QQuickVisualAdaptorModelData::index() const
-{
- return m_index;
-}
-
-// This is internal only - it should not be set from qml
-void QQuickVisualAdaptorModelData::setIndex(int index)
-{
- m_index = index;
- emit indexChanged();
-}
-
-//---------------------------------------------------------------------------
-
-QQuickVisualAdaptorModel::QQuickVisualAdaptorModel(QObject *parent)
- : QObject(*(new QQuickVisualAdaptorModelPrivate), parent)
-{
-}
-
-QQuickVisualAdaptorModel::~QQuickVisualAdaptorModel()
-{
- Q_D(QQuickVisualAdaptorModel);
- if (d->m_listAccessor)
- delete d->m_listAccessor;
- if (d->m_delegateDataType)
- d->m_delegateDataType->release();
-}
-
-QQuickVisualAdaptorModel::Flags QQuickVisualAdaptorModel::flags() const
-{
- Q_D(const QQuickVisualAdaptorModel);
- return d->m_flags;
-}
-
-QVariant QQuickVisualAdaptorModel::model() const
-{
- Q_D(const QQuickVisualAdaptorModel);
- return d->m_modelVariant;
-}
-
-void QQuickVisualAdaptorModel::setModel(const QVariant &model, QDeclarativeEngine *engine)
-{
- Q_D(QQuickVisualAdaptorModel);
- delete d->m_listAccessor;
- d->m_engine = engine;
- d->m_listAccessor = 0;
- d->m_modelVariant = model;
- if (d->m_listModelInterface) {
- // Assume caller has released all items.
- QObject::disconnect(d->m_listModelInterface, SIGNAL(itemsChanged(int,int,QList<int>)),
- this, SLOT(_q_itemsChanged(int,int,QList<int>)));
- QObject::disconnect(d->m_listModelInterface, SIGNAL(itemsInserted(int,int)),
- this, SLOT(_q_itemsInserted(int,int)));
- QObject::disconnect(d->m_listModelInterface, SIGNAL(itemsRemoved(int,int)),
- this, SLOT(_q_itemsRemoved(int,int)));
- QObject::disconnect(d->m_listModelInterface, SIGNAL(itemsMoved(int,int,int)),
- this, SLOT(_q_itemsMoved(int,int,int)));
- d->m_listModelInterface = 0;
- } else if (d->m_abstractItemModel) {
- QObject::disconnect(d->m_abstractItemModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex,int,int)));
- QObject::disconnect(d->m_abstractItemModel, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- QObject::disconnect(d->m_abstractItemModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- QObject::disconnect(d->m_abstractItemModel, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_rowsMoved(QModelIndex,int,int,QModelIndex,int)));
- QObject::disconnect(d->m_abstractItemModel, SIGNAL(modelReset()), this, SLOT(_q_modelReset()));
- QObject::disconnect(d->m_abstractItemModel, SIGNAL(layoutChanged()), this, SLOT(_q_layoutChanged()));
- d->m_abstractItemModel = 0;
- }
-
- d->m_roles.clear();
- d->m_roleNames.clear();
- d->m_flags = QQuickVisualAdaptorModel::Flags();
- if (d->m_delegateDataType)
- d->m_delegateDataType->release();
- d->m_delegateDataType = 0;
- d->createModelData = &QQuickVisualAdaptorModelPrivate::initializeModelData;
-
- if (d->m_count)
- emit itemsRemoved(0, d->m_count);
-
- QObject *object = qvariant_cast<QObject *>(model);
- if (object && (d->m_listModelInterface = qobject_cast<QListModelInterface *>(object))) {
- QObject::connect(d->m_listModelInterface, SIGNAL(itemsChanged(int,int,QList<int>)),
- this, SLOT(_q_itemsChanged(int,int,QList<int>)));
- QObject::connect(d->m_listModelInterface, SIGNAL(itemsInserted(int,int)),
- this, SLOT(_q_itemsInserted(int,int)));
- QObject::connect(d->m_listModelInterface, SIGNAL(itemsRemoved(int,int)),
- this, SLOT(_q_itemsRemoved(int,int)));
- QObject::connect(d->m_listModelInterface, SIGNAL(itemsMoved(int,int,int)),
- this, SLOT(_q_itemsMoved(int,int,int)));
- if ((d->m_count = d->m_listModelInterface->count()))
- emit itemsInserted(0, d->m_count);
- return;
- } else if (object && (d->m_abstractItemModel = qobject_cast<QAbstractItemModel *>(object))) {
- QObject::connect(d->m_abstractItemModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex,int,int)));
- QObject::connect(d->m_abstractItemModel, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- QObject::connect(d->m_abstractItemModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- QObject::connect(d->m_abstractItemModel, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_rowsMoved(QModelIndex,int,int,QModelIndex,int)));
- QObject::connect(d->m_abstractItemModel, SIGNAL(modelReset()), this, SLOT(_q_modelReset()));
- QObject::connect(d->m_abstractItemModel, SIGNAL(layoutChanged()), this, SLOT(_q_layoutChanged()));
-
- if ((d->m_count = d->m_abstractItemModel->rowCount(d->m_root)))
- emit itemsInserted(0, d->m_count);
- return;
- }
-
- d->m_listAccessor = new QDeclarativeListAccessor;
- d->m_listAccessor->setList(model, d->m_engine);
- if ((d->m_count = d->m_listAccessor->count()))
- emit itemsInserted(0, d->m_count);
-}
-
-QVariant QQuickVisualAdaptorModel::rootIndex() const
-{
- Q_D(const QQuickVisualAdaptorModel);
- return QVariant::fromValue(d->m_root);
-}
-
-void QQuickVisualAdaptorModel::setRootIndex(const QVariant &root)
-{
- Q_D(QQuickVisualAdaptorModel);
- QModelIndex modelIndex = qvariant_cast<QModelIndex>(root);
- if (d->m_root != modelIndex) {
- int oldCount = d->modelCount();
- d->m_root = modelIndex;
- if (d->m_abstractItemModel && d->m_abstractItemModel->canFetchMore(modelIndex))
- d->m_abstractItemModel->fetchMore(modelIndex);
- int newCount = d->modelCount();
- if (oldCount)
- emit itemsRemoved(0, oldCount);
- if (newCount)
- emit itemsInserted(0, newCount);
- emit rootIndexChanged();
- }
-}
-
-QVariant QQuickVisualAdaptorModel::modelIndex(int idx) const
-{
- Q_D(const QQuickVisualAdaptorModel);
- if (d->m_abstractItemModel)
- return QVariant::fromValue(d->m_abstractItemModel->index(idx, 0, d->m_root));
- return QVariant::fromValue(QModelIndex());
-}
-
-QVariant QQuickVisualAdaptorModel::parentModelIndex() const
-{
- Q_D(const QQuickVisualAdaptorModel);
- if (d->m_abstractItemModel)
- return QVariant::fromValue(d->m_abstractItemModel->parent(d->m_root));
- return QVariant::fromValue(QModelIndex());
-}
-
-int QQuickVisualAdaptorModel::count() const
-{
- Q_D(const QQuickVisualAdaptorModel);
- return d->modelCount();
-}
-
-QObject *QQuickVisualAdaptorModel::data(int index)
-{
- Q_D(QQuickVisualAdaptorModel);
- QQuickVisualAdaptorModelData *data = d->createModelData(index, this);
- d->m_cache.insert(data);
- return data;
-}
-
-QString QQuickVisualAdaptorModel::stringValue(int index, const QString &name)
-{
- Q_D(QQuickVisualAdaptorModel);
- if ((!d->m_listModelInterface || !d->m_abstractItemModel) && d->m_listAccessor) {
- if (QObject *object = d->m_listAccessor->at(index).value<QObject*>())
- return object->property(name.toUtf8()).toString();
- }
-
- QString val;
- QQuickVisualAdaptorModelData *data = d->createModelData(index, this);
-
- QDeclarativeData *ddata = QDeclarativeData::get(data);
- if (ddata && ddata->propertyCache) {
- QDeclarativePropertyData *prop = ddata->propertyCache->property(name);
- if (prop) {
- if (prop->propType == QVariant::String) {
- void *args[] = { &val, 0 };
- QMetaObject::metacall(data, QMetaObject::ReadProperty, prop->coreIndex, args);
- } else if (prop->propType == qMetaTypeId<QVariant>()) {
- QVariant v;
- void *args[] = { &v, 0 };
- QMetaObject::metacall(data, QMetaObject::ReadProperty, prop->coreIndex, args);
- val = v.toString();
- }
- } else {
- val = data->property(name.toUtf8()).toString();
- }
- } else {
- val = data->property(name.toUtf8()).toString();
- }
-
- delete data;
-
- return val;
-}
-
-int QQuickVisualAdaptorModel::indexOf(QObject *object) const
-{
- if (QQuickVisualAdaptorModelData *data = qobject_cast<QQuickVisualAdaptorModelData *>(object))
- return data->index();
- return -1;
-}
-
-bool QQuickVisualAdaptorModel::canFetchMore() const
-{
- Q_D(const QQuickVisualAdaptorModel);
- return d->m_abstractItemModel && d->m_abstractItemModel->canFetchMore(d->m_root);
-}
-
-void QQuickVisualAdaptorModel::fetchMore()
-{
- Q_D(QQuickVisualAdaptorModel);
- if (d->m_abstractItemModel)
- d->m_abstractItemModel->fetchMore(d->m_root);
-}
-
-void QQuickVisualAdaptorModel::replaceWatchedRoles(const QList<QByteArray> &oldRoles, const QList<QByteArray> &newRoles)
-{
- Q_D(QQuickVisualAdaptorModel);
- d->watchedRoleIds.clear();
- foreach (const QByteArray &oldRole, oldRoles)
- d->watchedRoles.removeOne(oldRole);
- d->watchedRoles += newRoles;
-}
-
-void QQuickVisualAdaptorModel::_q_itemsChanged(int index, int count, const QList<int> &roles)
-{
- Q_D(QQuickVisualAdaptorModel);
- bool changed = roles.isEmpty();
- if (!d->watchedRoles.isEmpty() && d->watchedRoleIds.isEmpty()) {
- foreach (QByteArray r, d->watchedRoles) {
- if (d->m_roleNames.contains(r))
- d->watchedRoleIds << d->m_roleNames.value(r);
- }
- }
-
- QVector<int> signalIndexes;
- for (int i = 0; i < roles.count(); ++i) {
- const int role = roles.at(i);
- if (!changed && d->watchedRoleIds.contains(role))
- changed = true;
- for (int propertyId = 0; propertyId < d->m_propertyData.count(); ++propertyId) {
- if (d->m_propertyData.at(propertyId).role == role)
- signalIndexes.append(propertyId + d->m_delegateDataType->signalOffset);
- }
- }
- if (roles.isEmpty()) {
- for (int propertyId = 0; propertyId < d->m_propertyData.count(); ++propertyId)
- signalIndexes.append(propertyId + d->m_delegateDataType->signalOffset);
- }
-
- typedef QQuickVisualAdaptorModelDataCache::iterator iterator;
- for (iterator it = d->m_cache.begin(); it != d->m_cache.end(); ++it) {
- const int idx = it->index();
- if (idx >= index && idx < index + count) {
- QQuickVisualAdaptorModelData *data = *it;
- for (int i = 0; i < signalIndexes.count(); ++i)
- QMetaObject::activate(data, signalIndexes.at(i), 0);
- }
- }
- if (changed)
- emit itemsChanged(index, count);
-}
-
-void QQuickVisualAdaptorModel::_q_itemsInserted(int index, int count)
-{
- Q_D(QQuickVisualAdaptorModel);
- if (count <= 0)
- return;
- d->m_count += count;
-
- typedef QQuickVisualAdaptorModelDataCache::iterator iterator;
- for (iterator it = d->m_cache.begin(); it != d->m_cache.end(); ++it) {
- if (it->index() >= index)
- it->setIndex(it->index() + count);
- }
-
- emit itemsInserted(index, count);
-}
-
-void QQuickVisualAdaptorModel::_q_itemsRemoved(int index, int count)
-{
- Q_D(QQuickVisualAdaptorModel);
- if (count <= 0)
- return;
- d->m_count -= count;
-
- typedef QQuickVisualAdaptorModelDataCache::iterator iterator;
- for (iterator it = d->m_cache.begin(); it != d->m_cache.end(); ++it) {
- if (it->index() >= index + count)
- it->setIndex(it->index() - count);
- else if (it->index() >= index)
- it->setIndex(-1);
- }
-
- emit itemsRemoved(index, count);
-}
-
-void QQuickVisualAdaptorModel::_q_itemsMoved(int from, int to, int count)
-{
- Q_D(QQuickVisualAdaptorModel);
- const int minimum = qMin(from, to);
- const int maximum = qMax(from, to) + count;
- const int difference = from > to ? count : -count;
-
- typedef QQuickVisualAdaptorModelDataCache::iterator iterator;
- for (iterator it = d->m_cache.begin(); it != d->m_cache.end(); ++it) {
- if (it->index() >= from && it->index() < from + count)
- it->setIndex(it->index() - from + to);
- else if (it->index() >= minimum && it->index() < maximum)
- it->setIndex(it->index() + difference);
- }
- emit itemsMoved(from, to, count);
-}
-
-void QQuickVisualAdaptorModel::_q_rowsInserted(const QModelIndex &parent, int begin, int end)
-{
- Q_D(QQuickVisualAdaptorModel);
- if (parent == d->m_root)
- _q_itemsInserted(begin, end - begin + 1);
-}
-
-void QQuickVisualAdaptorModel::_q_rowsRemoved(const QModelIndex &parent, int begin, int end)
-{
- Q_D(QQuickVisualAdaptorModel);
- if (parent == d->m_root)
- _q_itemsRemoved(begin, end - begin + 1);
-}
-
-void QQuickVisualAdaptorModel::_q_rowsMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)
-{
- Q_D(QQuickVisualAdaptorModel);
- const int count = sourceEnd - sourceStart + 1;
- if (destinationParent == d->m_root && sourceParent == d->m_root) {
- _q_itemsMoved(sourceStart, sourceStart > destinationRow ? destinationRow : destinationRow-count, count);
- } else if (sourceParent == d->m_root) {
- _q_itemsRemoved(sourceStart, count);
- } else if (destinationParent == d->m_root) {
- _q_itemsInserted(destinationRow, count);
- }
-}
-
-void QQuickVisualAdaptorModel::_q_dataChanged(const QModelIndex &begin, const QModelIndex &end)
-{
- Q_D(QQuickVisualAdaptorModel);
- if (begin.parent() == d->m_root)
- _q_itemsChanged(begin.row(), end.row() - begin.row() + 1, d->m_roles);
-}
-
-void QQuickVisualAdaptorModel::_q_layoutChanged()
-{
- Q_D(QQuickVisualAdaptorModel);
- _q_itemsChanged(0, count(), d->m_roles);
-}
-
-void QQuickVisualAdaptorModel::_q_modelReset()
-{
- Q_D(QQuickVisualAdaptorModel);
- int oldCount = d->m_count;
- d->m_root = QModelIndex();
- d->m_count = d->modelCount();
- emit modelReset(oldCount, d->m_count);
- emit rootIndexChanged();
- if (d->m_abstractItemModel && d->m_abstractItemModel->canFetchMore(d->m_root))
- d->m_abstractItemModel->fetchMore(d->m_root);
-}
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QListModelInterface)
-
-#include <qquickvisualadaptormodel.moc>
diff --git a/src/declarative/items/qquickvisualadaptormodel_p.h b/src/declarative/items/qquickvisualadaptormodel_p.h
deleted file mode 100644
index 31eba503ea..0000000000
--- a/src/declarative/items/qquickvisualadaptormodel_p.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKVISUALADAPTORMODEL_P_H
-#define QQUICKVISUALADAPTORMODEL_P_H
-
-#include <QtCore/qobject.h>
-#include <QtCore/qabstractitemmodel.h>
-
-#include <private/qdeclarativerefcount_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeEngine;
-
-class QQuickVisualAdaptorModelPrivate;
-class QQuickVisualAdaptorModel : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickVisualAdaptorModel)
-public:
- enum Flag
- {
- MetaObjectCacheable = 0x01,
- ProxiedObject = 0x02
- };
- Q_DECLARE_FLAGS(Flags, Flag)
-
- QQuickVisualAdaptorModel(QObject *parent = 0);
- virtual ~QQuickVisualAdaptorModel();
-
- Flags flags() const;
-
- QVariant model() const;
- void setModel(const QVariant &, QDeclarativeEngine *);
-
- QVariant rootIndex() const;
- void setRootIndex(const QVariant &root);
-
- QVariant modelIndex(int idx) const;
- QVariant parentModelIndex() const;
-
- int count() const;
- QObject *data(int index);
- QString stringValue(int index, const QString &role);
- void replaceWatchedRoles(const QList<QByteArray> &oldRoles, const QList<QByteArray> &newRoles);
- int indexOf(QObject *object) const;
-
- bool canFetchMore() const;
- void fetchMore();
-
-Q_SIGNALS:
- void rootIndexChanged();
- void modelReset(int oldCount, int newCount);
-
- void itemsInserted(int index, int count);
- void itemsRemoved(int index, int count);
- void itemsMoved(int from, int to, int count);
- void itemsChanged(int index, int count);
-
-private Q_SLOTS:
- void _q_itemsChanged(int, int, const QList<int> &);
- void _q_itemsInserted(int index, int count);
- void _q_itemsRemoved(int index, int count);
- void _q_itemsMoved(int from, int to, int count);
- void _q_rowsInserted(const QModelIndex &,int,int);
- void _q_rowsRemoved(const QModelIndex &,int,int);
- void _q_rowsMoved(const QModelIndex &, int, int, const QModelIndex &, int);
- void _q_dataChanged(const QModelIndex&,const QModelIndex&);
- void _q_layoutChanged();
- void _q_modelReset();
-
-private:
- Q_DISABLE_COPY(QQuickVisualAdaptorModel)
-};
-
-class QQuickVisualAdaptorModelProxyInterface
-{
-public:
- virtual ~QQuickVisualAdaptorModelProxyInterface() {}
-
- virtual QObject *proxiedObject() = 0;
-};
-
-Q_DECLARE_INTERFACE(QQuickVisualAdaptorModelProxyInterface, "com.trolltech.qml.QQuickVisualAdaptorModelProxyInterface")
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/declarative/items/qquickvisualdatamodel.cpp b/src/declarative/items/qquickvisualdatamodel.cpp
deleted file mode 100644
index 649ca6f96b..0000000000
--- a/src/declarative/items/qquickvisualdatamodel.cpp
+++ /dev/null
@@ -1,2668 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickvisualdatamodel_p.h"
-#include "qquickitem.h"
-
-#include <QtCore/qcoreapplication.h>
-#include <QtDeclarative/qdeclarativecontext.h>
-#include <QtDeclarative/qdeclarativeengine.h>
-#include <QtDeclarative/qdeclarativeexpression.h>
-#include <QtDeclarative/qdeclarativeinfo.h>
-#include <QtDeclarative/qdeclarativeincubator.h>
-
-#include <private/qdeclarativecontext_p.h>
-#include <private/qdeclarativepackage_p.h>
-#include <private/qdeclarativeopenmetaobject_p.h>
-#include <private/qdeclarativelistaccessor_p.h>
-#include <private/qdeclarativedata_p.h>
-#include <private/qdeclarativepropertycache_p.h>
-#include <private/qdeclarativeguard_p.h>
-#include <private/qdeclarativeglobal_p.h>
-#include <private/qmetaobjectbuilder_p.h>
-#include <private/qdeclarativeproperty_p.h>
-#include <private/qquickvisualadaptormodel_p.h>
-#include <private/qdeclarativechangeset_p.h>
-#include <private/qdeclarativelistcompositor_p.h>
-#include <private/qdeclarativeengine_p.h>
-#include <private/qquickitem_p.h>
-#include <private/qobject_p.h>
-
-#include <QtCore/qhash.h>
-#include <QtCore/qlist.h>
-
-QT_BEGIN_NAMESPACE
-
-typedef QDeclarativeListCompositor Compositor;
-
-class QQuickVisualDataModelPrivate;
-class QVDMIncubationTask : public QDeclarativeIncubator
-{
-public:
- QVDMIncubationTask(QQuickVisualDataModelPrivate *l, IncubationMode mode)
- : QDeclarativeIncubator(mode)
- , incubating(0)
- , incubatingContext(0)
- , vdm(l) {}
-
- virtual void statusChanged(Status);
- virtual void setInitialState(QObject *);
-
- QQuickVisualDataModelCacheItem *incubating;
- QDeclarativeContext *incubatingContext;
-
-private:
- QQuickVisualDataModelPrivate *vdm;
-};
-
-
-class QQuickVisualDataGroupEmitter
-{
-public:
- virtual void emitModelUpdated(const QDeclarativeChangeSet &changeSet, bool reset) = 0;
- virtual void createdPackage(int, QDeclarativePackage *) {}
- virtual void initPackage(int, QDeclarativePackage *) {}
- virtual void destroyingPackage(QDeclarativePackage *) {}
-
- QIntrusiveListNode emitterNode;
-};
-
-typedef QIntrusiveList<QQuickVisualDataGroupEmitter, &QQuickVisualDataGroupEmitter::emitterNode> QQuickVisualDataGroupEmitterList;
-
-//---------------------------------------------------------------------------
-
-class QQuickVisualDataGroupPrivate : public QObjectPrivate
-{
-public:
- Q_DECLARE_PUBLIC(QQuickVisualDataGroup)
-
- QQuickVisualDataGroupPrivate() : group(Compositor::Cache), defaultInclude(false) {}
-
- static QQuickVisualDataGroupPrivate *get(QQuickVisualDataGroup *group) {
- return static_cast<QQuickVisualDataGroupPrivate *>(QObjectPrivate::get(group)); }
-
- void setModel(QQuickVisualDataModel *model, Compositor::Group group);
- void emitChanges(QV8Engine *engine);
- void emitModelUpdated(bool reset);
-
- void createdPackage(int index, QDeclarativePackage *package);
- void initPackage(int index, QDeclarativePackage *package);
- void destroyingPackage(QDeclarativePackage *package);
-
- bool parseGroupArgs(QDeclarativeV8Function *args, int *index, int *count, int *groups) const;
-
- Compositor::Group group;
- QDeclarativeGuard<QQuickVisualDataModel> model;
- QQuickVisualDataGroupEmitterList emitters;
- QDeclarativeChangeSet changeSet;
- QString name;
- bool defaultInclude;
-};
-
-//---------------------------------------------------------------------------
-
-class QQuickVisualDataModelCacheItem;
-class QQuickVisualDataModelCacheMetaType;
-class QQuickVisualDataModelParts;
-
-class QQuickVisualDataModelCacheMetaType : public QDeclarativeRefCount
-{
-public:
- QQuickVisualDataModelCacheMetaType(QV8Engine *engine, QQuickVisualDataModel *model, const QStringList &groupNames);
- ~QQuickVisualDataModelCacheMetaType();
-
- int parseGroups(const QStringList &groupNames) const;
- int parseGroups(QV8Engine *engine, const v8::Local<v8::Value> &groupNames) const;
-
- static v8::Handle<v8::Value> get_model(v8::Local<v8::String>, const v8::AccessorInfo &info);
- static v8::Handle<v8::Value> get_groups(v8::Local<v8::String>, const v8::AccessorInfo &info);
- static void set_groups(
- v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info);
- static v8::Handle<v8::Value> get_member(v8::Local<v8::String>, const v8::AccessorInfo &info);
- static void set_member(
- v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info);
- static v8::Handle<v8::Value> get_index(v8::Local<v8::String>, const v8::AccessorInfo &info);
-
- QDeclarativeGuard<QQuickVisualDataModel> model;
- const int groupCount;
- const int memberPropertyOffset;
- const int indexPropertyOffset;
- QV8Engine * const v8Engine;
- QMetaObject *metaObject;
- const QStringList groupNames;
- v8::Persistent<v8::Function> constructor;
-};
-
-class QQuickVisualDataModelCacheItem : public QV8ObjectResource
-{
- V8_RESOURCE_TYPE(VisualDataItemType)
-public:
- QQuickVisualDataModelCacheItem(QQuickVisualDataModelCacheMetaType *metaType)
- : QV8ObjectResource(metaType->v8Engine)
- , metaType(metaType)
- , object(0)
- , attached(0)
- , objectRef(0)
- , scriptRef(0)
- , groups(0)
- , incubationTask(0)
- {
- metaType->addref();
- }
-
- ~QQuickVisualDataModelCacheItem();
-
- void referenceObject() { ++objectRef; }
- bool releaseObject() { return --objectRef == 0 && !(groups & Compositor::PersistedFlag); }
- bool isObjectReferenced() const { return objectRef == 0 && !(groups & Compositor::PersistedFlag); }
-
- bool isReferenced() const { return objectRef || scriptRef || (groups & Compositor::PersistedFlag) || incubationTask; }
-
- void Dispose();
-
- QQuickVisualDataModelCacheMetaType * const metaType;
- QDeclarativeGuard<QObject> object;
- QQuickVisualDataModelAttached *attached;
- int objectRef;
- int scriptRef;
- int groups;
- int index[Compositor::MaximumGroupCount];
- QVDMIncubationTask *incubationTask;
-};
-
-
-class QQuickVisualDataModelPrivate : public QObjectPrivate, public QQuickVisualDataGroupEmitter
-{
- Q_DECLARE_PUBLIC(QQuickVisualDataModel)
-public:
- QQuickVisualDataModelPrivate(QDeclarativeContext *);
- ~QQuickVisualDataModelPrivate();
-
- static QQuickVisualDataModelPrivate *get(QQuickVisualDataModel *m) {
- return static_cast<QQuickVisualDataModelPrivate *>(QObjectPrivate::get(m));
- }
-
- void init();
- void connectModel(QQuickVisualAdaptorModel *model);
-
- QObject *object(Compositor::Group group, int index, bool asynchronous, bool reference);
- void destroy(QObject *object);
- QQuickVisualDataModel::ReleaseFlags release(QObject *object);
- QString stringValue(Compositor::Group group, int index, const QString &name);
- int cacheIndexOf(QObject *object) const;
- void emitCreatedPackage(QQuickVisualDataModelCacheItem *cacheItem, QDeclarativePackage *package);
- void emitInitPackage(QQuickVisualDataModelCacheItem *cacheItem, QDeclarativePackage *package);
- void emitCreatedItem(QQuickVisualDataModelCacheItem *cacheItem, QQuickItem *item) {
- emit q_func()->createdItem(cacheItem->index[m_compositorGroup], item); }
- void emitInitItem(QQuickVisualDataModelCacheItem *cacheItem, QQuickItem *item) {
- emit q_func()->initItem(cacheItem->index[m_compositorGroup], item); }
- void emitDestroyingPackage(QDeclarativePackage *package);
- void emitDestroyingItem(QQuickItem *item) { emit q_func()->destroyingItem(item); }
-
- void updateFilterGroup();
-
- void addGroups(Compositor::Group group, int index, int count, int groupFlags);
- void removeGroups(Compositor::Group group, int index, int count, int groupFlags);
- void setGroups(Compositor::Group group, int index, int count, int groupFlags);
-
- void itemsInserted(
- const QVector<Compositor::Insert> &inserts,
- QVarLengthArray<QVector<QDeclarativeChangeSet::Insert>, Compositor::MaximumGroupCount> *translatedInserts,
- QHash<int, QList<QQuickVisualDataModelCacheItem *> > *movedItems = 0);
- void itemsInserted(const QVector<Compositor::Insert> &inserts);
- void itemsRemoved(
- const QVector<Compositor::Remove> &removes,
- QVarLengthArray<QVector<QDeclarativeChangeSet::Remove>, Compositor::MaximumGroupCount> *translatedRemoves,
- QHash<int, QList<QQuickVisualDataModelCacheItem *> > *movedItems = 0);
- void itemsRemoved(const QVector<Compositor::Remove> &removes);
- void itemsMoved(
- const QVector<Compositor::Remove> &removes, const QVector<Compositor::Insert> &inserts);
- void itemsChanged(const QVector<Compositor::Change> &changes);
- template <typename T> static v8::Local<v8::Array> buildChangeList(const QVector<T> &changes);
- void emitChanges();
- void emitModelUpdated(const QDeclarativeChangeSet &changeSet, bool reset);
-
-
- static void group_append(QDeclarativeListProperty<QQuickVisualDataGroup> *property, QQuickVisualDataGroup *group);
- static int group_count(QDeclarativeListProperty<QQuickVisualDataGroup> *property);
- static QQuickVisualDataGroup *group_at(QDeclarativeListProperty<QQuickVisualDataGroup> *property, int index);
-
- void releaseIncubator(QVDMIncubationTask *incubationTask);
- void incubatorStatusChanged(QVDMIncubationTask *incubationTask, QDeclarativeIncubator::Status status);
- void setInitialState(QVDMIncubationTask *incubationTask, QObject *o);
-
- QQuickVisualAdaptorModel *m_adaptorModel;
- QDeclarativeComponent *m_delegate;
- QQuickVisualDataModelCacheMetaType *m_cacheMetaType;
- QDeclarativeGuard<QDeclarativeContext> m_context;
-
- QList<QQuickVisualDataModelCacheItem *> m_cache;
- QQuickVisualDataModelParts *m_parts;
- QQuickVisualDataGroupEmitterList m_pendingParts;
-
- QDeclarativeListCompositor m_compositor;
- QDeclarativeListCompositor::Group m_compositorGroup;
- bool m_complete : 1;
- bool m_delegateValidated : 1;
- bool m_reset : 1;
- bool m_transaction : 1;
- bool m_incubatorCleanupScheduled : 1;
-
- QString m_filterGroup;
- QList<QByteArray> watchedRoles;
-
- union {
- struct {
- QQuickVisualDataGroup *m_cacheItems;
- QQuickVisualDataGroup *m_items;
- QQuickVisualDataGroup *m_persistedItems;
- };
- QQuickVisualDataGroup *m_groups[Compositor::MaximumGroupCount];
- };
- int m_groupCount;
-
- QList<QVDMIncubationTask *> m_finishedIncubating;
-};
-
-//---------------------------------------------------------------------------
-
-class QQuickVisualPartsModel : public QQuickVisualModel, public QQuickVisualDataGroupEmitter
-{
- Q_OBJECT
- Q_PROPERTY(QString filterOnGroup READ filterGroup WRITE setFilterGroup NOTIFY filterGroupChanged RESET resetFilterGroup)
-public:
- QQuickVisualPartsModel(QQuickVisualDataModel *model, const QString &part, QObject *parent = 0);
- ~QQuickVisualPartsModel();
-
- QString filterGroup() const;
- void setFilterGroup(const QString &group);
- void resetFilterGroup();
- void updateFilterGroup();
- void updateFilterGroup(Compositor::Group group, const QDeclarativeChangeSet &changeSet);
-
- int count() const;
- bool isValid() const;
- QQuickItem *item(int index, bool asynchronous=false);
- ReleaseFlags release(QQuickItem *item);
- QString stringValue(int index, const QString &role);
- void setWatchedRoles(QList<QByteArray> roles);
-
- int indexOf(QQuickItem *item, QObject *objectContext) const;
-
- void emitModelUpdated(const QDeclarativeChangeSet &changeSet, bool reset);
-
- void createdPackage(int index, QDeclarativePackage *package);
- void initPackage(int index, QDeclarativePackage *package);
- void destroyingPackage(QDeclarativePackage *package);
-
-Q_SIGNALS:
- void filterGroupChanged();
-
-private:
- QQuickVisualDataModel *m_model;
- QHash<QObject *, QDeclarativePackage *> m_packaged;
- QString m_part;
- QString m_filterGroup;
- QList<QByteArray> m_watchedRoles;
- Compositor::Group m_compositorGroup;
- bool m_inheritGroup;
-};
-
-class QQuickVisualDataModelPartsMetaObject : public QDeclarativeOpenMetaObject
-{
-public:
- QQuickVisualDataModelPartsMetaObject(QObject *parent)
- : QDeclarativeOpenMetaObject(parent) {}
-
- virtual void propertyCreated(int, QMetaPropertyBuilder &);
- virtual QVariant initialValue(int);
-};
-
-class QQuickVisualDataModelParts : public QObject
-{
-Q_OBJECT
-public:
- QQuickVisualDataModelParts(QQuickVisualDataModel *parent);
-
- QQuickVisualDataModel *model;
- QList<QQuickVisualPartsModel *> models;
-};
-
-void QQuickVisualDataModelPartsMetaObject::propertyCreated(int, QMetaPropertyBuilder &prop)
-{
- prop.setWritable(false);
-}
-
-QVariant QQuickVisualDataModelPartsMetaObject::initialValue(int id)
-{
- QQuickVisualDataModelParts *parts = static_cast<QQuickVisualDataModelParts *>(object());
- QQuickVisualPartsModel *m = new QQuickVisualPartsModel(
- parts->model, QString::fromUtf8(name(id)), parts);
- parts->models.append(m);
- return QVariant::fromValue(static_cast<QObject *>(m));
-}
-
-QQuickVisualDataModelParts::QQuickVisualDataModelParts(QQuickVisualDataModel *parent)
-: QObject(parent), model(parent)
-{
- new QQuickVisualDataModelPartsMetaObject(this);
-}
-
-class QQuickVisualDataModelAttachedMetaObject : public QAbstractDynamicMetaObject
-{
-public:
- QQuickVisualDataModelAttachedMetaObject(
- QQuickVisualDataModelAttached *attached, QQuickVisualDataModelCacheMetaType *metaType);
- ~QQuickVisualDataModelAttachedMetaObject();
-
- int metaCall(QMetaObject::Call, int _id, void **);
-
-private:
- QQuickVisualDataModelAttached *attached;
- QQuickVisualDataModelCacheMetaType *metaType;
-};
-
-//---------------------------------------------------------------------------
-
-QHash<QObject*, QQuickVisualDataModelAttached*> QQuickVisualDataModelAttached::attachedProperties;
-
-/*!
- \qmlclass VisualDataModel QQuickVisualDataModel
- \inqmlmodule QtQuick 2
- \ingroup qml-working-with-data
- \brief The VisualDataModel encapsulates a model and delegate
-
- A VisualDataModel encapsulates a model and the delegate that will
- be instantiated for items in the model.
-
- It is usually not necessary to create VisualDataModel elements.
- However, it can be useful for manipulating and accessing the \l modelIndex
- when a QAbstractItemModel subclass is used as the
- model. Also, VisualDataModel is used together with \l Package to
- provide delegates to multiple views.
-
- The example below illustrates using a VisualDataModel with a ListView.
-
- \snippet doc/src/snippets/declarative/visualdatamodel.qml 0
-*/
-
-QQuickVisualDataModelPrivate::QQuickVisualDataModelPrivate(QDeclarativeContext *ctxt)
- : m_adaptorModel(0)
- , m_delegate(0)
- , m_cacheMetaType(0)
- , m_context(ctxt)
- , m_parts(0)
- , m_compositorGroup(Compositor::Cache)
- , m_complete(false)
- , m_delegateValidated(false)
- , m_reset(false)
- , m_transaction(false)
- , m_incubatorCleanupScheduled(false)
- , m_filterGroup(QStringLiteral("items"))
- , m_cacheItems(0)
- , m_items(0)
- , m_groupCount(3)
-{
-}
-
-QQuickVisualDataModelPrivate::~QQuickVisualDataModelPrivate()
-{
- qDeleteAll(m_finishedIncubating);
-}
-
-void QQuickVisualDataModelPrivate::connectModel(QQuickVisualAdaptorModel *model)
-{
- Q_Q(QQuickVisualDataModel);
-
- QObject::connect(model, SIGNAL(itemsInserted(int,int)), q, SLOT(_q_itemsInserted(int,int)));
- QObject::connect(model, SIGNAL(itemsRemoved(int,int)), q, SLOT(_q_itemsRemoved(int,int)));
- QObject::connect(model, SIGNAL(itemsMoved(int,int,int)), q, SLOT(_q_itemsMoved(int,int,int)));
- QObject::connect(model, SIGNAL(itemsChanged(int,int)), q, SLOT(_q_itemsChanged(int,int)));
- QObject::connect(model, SIGNAL(modelReset(int,int)), q, SLOT(_q_modelReset(int,int)));
-}
-
-void QQuickVisualDataModelPrivate::init()
-{
- Q_Q(QQuickVisualDataModel);
- m_compositor.setRemoveGroups(Compositor::GroupMask & ~Compositor::PersistedFlag);
-
- m_adaptorModel = new QQuickVisualAdaptorModel;
- QObject::connect(m_adaptorModel, SIGNAL(rootIndexChanged()), q, SIGNAL(rootIndexChanged()));
-
- m_items = new QQuickVisualDataGroup(QStringLiteral("items"), q, Compositor::Default, q);
- m_items->setDefaultInclude(true);
- m_persistedItems = new QQuickVisualDataGroup(QStringLiteral("persistedItems"), q, Compositor::Persisted, q);
- QQuickVisualDataGroupPrivate::get(m_items)->emitters.insert(this);
-}
-
-QQuickVisualDataModel::QQuickVisualDataModel()
-: QQuickVisualModel(*(new QQuickVisualDataModelPrivate(0)))
-{
- Q_D(QQuickVisualDataModel);
- d->init();
-}
-
-QQuickVisualDataModel::QQuickVisualDataModel(QDeclarativeContext *ctxt, QObject *parent)
-: QQuickVisualModel(*(new QQuickVisualDataModelPrivate(ctxt)), parent)
-{
- Q_D(QQuickVisualDataModel);
- d->init();
-}
-
-QQuickVisualDataModel::~QQuickVisualDataModel()
-{
- Q_D(QQuickVisualDataModel);
-
- foreach (QQuickVisualDataModelCacheItem *cacheItem, d->m_cache) {
- delete cacheItem->object;
- cacheItem->object = 0;
- cacheItem->objectRef = 0;
- if (!cacheItem->isReferenced())
- delete cacheItem;
- }
-
- delete d->m_adaptorModel;
- if (d->m_cacheMetaType)
- d->m_cacheMetaType->release();
-}
-
-
-void QQuickVisualDataModel::classBegin()
-{
-}
-
-void QQuickVisualDataModel::componentComplete()
-{
- Q_D(QQuickVisualDataModel);
- d->m_complete = true;
-
- int defaultGroups = 0;
- QStringList groupNames;
- groupNames.append(QStringLiteral("items"));
- groupNames.append(QStringLiteral("persistedItems"));
- if (QQuickVisualDataGroupPrivate::get(d->m_items)->defaultInclude)
- defaultGroups |= Compositor::DefaultFlag;
- if (QQuickVisualDataGroupPrivate::get(d->m_persistedItems)->defaultInclude)
- defaultGroups |= Compositor::PersistedFlag;
- for (int i = 3; i < d->m_groupCount; ++i) {
- QString name = d->m_groups[i]->name();
- if (name.isEmpty()) {
- d->m_groups[i] = d->m_groups[d->m_groupCount - 1];
- --d->m_groupCount;
- --i;
- } else if (name.at(0).isUpper()) {
- qmlInfo(d->m_groups[i]) << QQuickVisualDataGroup::tr("Group names must start with a lower case letter");
- d->m_groups[i] = d->m_groups[d->m_groupCount - 1];
- --d->m_groupCount;
- --i;
- } else {
- groupNames.append(name);
-
- QQuickVisualDataGroupPrivate *group = QQuickVisualDataGroupPrivate::get(d->m_groups[i]);
- group->setModel(this, Compositor::Group(i));
- if (group->defaultInclude)
- defaultGroups |= (1 << i);
- }
- }
- if (!d->m_context)
- d->m_context = qmlContext(this);
-
- d->m_cacheMetaType = new QQuickVisualDataModelCacheMetaType(
- QDeclarativeEnginePrivate::getV8Engine(d->m_context->engine()), this, groupNames);
-
- d->m_compositor.setGroupCount(d->m_groupCount);
- d->m_compositor.setDefaultGroups(defaultGroups);
- d->updateFilterGroup();
-
- while (!d->m_pendingParts.isEmpty())
- static_cast<QQuickVisualPartsModel *>(d->m_pendingParts.first())->updateFilterGroup();
-
- d->connectModel(d->m_adaptorModel);
- QVector<Compositor::Insert> inserts;
- d->m_reset = true;
- d->m_compositor.append(
- d->m_adaptorModel,
- 0,
- qMax(0, d->m_adaptorModel->count()),
- defaultGroups | Compositor::AppendFlag | Compositor::PrependFlag,
- &inserts);
- d->itemsInserted(inserts);
- d->emitChanges();
-
- if (d->m_adaptorModel->canFetchMore())
- QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
-}
-
-/*!
- \qmlproperty model QtQuick2::VisualDataModel::model
- This property holds the model providing data for the VisualDataModel.
-
- The model provides a set of data that is used to create the items
- for a view. For large or dynamic datasets the model is usually
- provided by a C++ model object. The C++ model object must be a \l
- {QAbstractItemModel} subclass or a simple list.
-
- Models can also be created directly in QML, using a \l{ListModel} or
- \l{XmlListModel}.
-
- \sa {qmlmodels}{Data Models}
-*/
-QVariant QQuickVisualDataModel::model() const
-{
- Q_D(const QQuickVisualDataModel);
- return d->m_adaptorModel->model();
-}
-
-void QQuickVisualDataModel::setModel(const QVariant &model)
-{
- Q_D(QQuickVisualDataModel);
- d->m_adaptorModel->setModel(model, d->m_context ? d->m_context->engine() : qmlEngine(this));
- if (d->m_complete && d->m_adaptorModel->canFetchMore())
- QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
-}
-
-/*!
- \qmlproperty Component QtQuick2::VisualDataModel::delegate
-
- The delegate provides a template defining each item instantiated by a view.
- The index is exposed as an accessible \c index property. Properties of the
- model are also available depending upon the type of \l {qmlmodels}{Data Model}.
-*/
-QDeclarativeComponent *QQuickVisualDataModel::delegate() const
-{
- Q_D(const QQuickVisualDataModel);
- return d->m_delegate;
-}
-
-void QQuickVisualDataModel::setDelegate(QDeclarativeComponent *delegate)
-{
- Q_D(QQuickVisualDataModel);
- if (d->m_transaction) {
- qmlInfo(this) << tr("The delegate of a VisualDataModel cannot be changed within onUpdated.");
- return;
- }
- bool wasValid = d->m_delegate != 0;
- d->m_delegate = delegate;
- d->m_delegateValidated = false;
- if (wasValid && d->m_complete) {
- for (int i = 1; i < d->m_groupCount; ++i) {
- QQuickVisualDataGroupPrivate::get(d->m_groups[i])->changeSet.remove(
- 0, d->m_compositor.count(Compositor::Group(i)));
- }
- }
- if (d->m_complete && d->m_delegate) {
- for (int i = 1; i < d->m_groupCount; ++i) {
- QQuickVisualDataGroupPrivate::get(d->m_groups[i])->changeSet.insert(
- 0, d->m_compositor.count(Compositor::Group(i)));
- }
- }
- d->emitChanges();
-}
-
-/*!
- \qmlproperty QModelIndex QtQuick2::VisualDataModel::rootIndex
-
- QAbstractItemModel provides a hierarchical tree of data, whereas
- QML only operates on list data. \c rootIndex allows the children of
- any node in a QAbstractItemModel to be provided by this model.
-
- This property only affects models of type QAbstractItemModel that
- are hierarchical (e.g, a tree model).
-
- For example, here is a simple interactive file system browser.
- When a directory name is clicked, the view's \c rootIndex is set to the
- QModelIndex node of the clicked directory, thus updating the view to show
- the new directory's contents.
-
- \c main.cpp:
- \snippet doc/src/snippets/declarative/visualdatamodel_rootindex/main.cpp 0
-
- \c view.qml:
- \snippet doc/src/snippets/declarative/visualdatamodel_rootindex/view.qml 0
-
- If the \l model is a QAbstractItemModel subclass, the delegate can also
- reference a \c hasModelChildren property (optionally qualified by a
- \e model. prefix) that indicates whether the delegate's model item has
- any child nodes.
-
-
- \sa modelIndex(), parentModelIndex()
-*/
-QVariant QQuickVisualDataModel::rootIndex() const
-{
- Q_D(const QQuickVisualDataModel);
- return d->m_adaptorModel->rootIndex();
-}
-
-void QQuickVisualDataModel::setRootIndex(const QVariant &root)
-{
- Q_D(QQuickVisualDataModel);
- d->m_adaptorModel->setRootIndex(root);
-}
-
-/*!
- \qmlmethod QModelIndex QtQuick2::VisualDataModel::modelIndex(int index)
-
- QAbstractItemModel provides a hierarchical tree of data, whereas
- QML only operates on list data. This function assists in using
- tree models in QML.
-
- Returns a QModelIndex for the specified index.
- This value can be assigned to rootIndex.
-
- \sa rootIndex
-*/
-QVariant QQuickVisualDataModel::modelIndex(int idx) const
-{
- Q_D(const QQuickVisualDataModel);
- return d->m_adaptorModel->modelIndex(idx);
-}
-
-/*!
- \qmlmethod QModelIndex QtQuick2::VisualDataModel::parentModelIndex()
-
- QAbstractItemModel provides a hierarchical tree of data, whereas
- QML only operates on list data. This function assists in using
- tree models in QML.
-
- Returns a QModelIndex for the parent of the current rootIndex.
- This value can be assigned to rootIndex.
-
- \sa rootIndex
-*/
-QVariant QQuickVisualDataModel::parentModelIndex() const
-{
- Q_D(const QQuickVisualDataModel);
- return d->m_adaptorModel->parentModelIndex();
-}
-
-/*!
- \qmlproperty int QtQuick2::VisualDataModel::count
-*/
-
-int QQuickVisualDataModel::count() const
-{
- Q_D(const QQuickVisualDataModel);
- if (!d->m_delegate)
- return 0;
- return d->m_compositor.count(d->m_compositorGroup);
-}
-
-void QQuickVisualDataModelPrivate::destroy(QObject *object)
-{
- QObjectPrivate *p = QObjectPrivate::get(object);
- Q_ASSERT(p->declarativeData);
- QDeclarativeData *data = static_cast<QDeclarativeData*>(p->declarativeData);
- if (data->ownContext && data->context)
- data->context->clearContext();
- object->deleteLater();
-}
-
-QQuickVisualDataModel::ReleaseFlags QQuickVisualDataModelPrivate::release(QObject *object)
-{
- QQuickVisualDataModel::ReleaseFlags stat = 0;
- if (!object)
- return stat;
-
- int cacheIndex = cacheIndexOf(object);
- if (cacheIndex != -1) {
- QQuickVisualDataModelCacheItem *cacheItem = m_cache.at(cacheIndex);
- if (cacheItem->releaseObject()) {
- destroy(object);
- if (QQuickItem *item = qobject_cast<QQuickItem *>(object))
- emitDestroyingItem(item);
- cacheItem->object = 0;
- stat |= QQuickVisualModel::Destroyed;
- if (!cacheItem->isReferenced()) {
- m_compositor.clearFlags(Compositor::Cache, cacheIndex, 1, Compositor::CacheFlag);
- m_cache.removeAt(cacheIndex);
- delete cacheItem;
- Q_ASSERT(m_cache.count() == m_compositor.count(Compositor::Cache));
- }
- } else {
- stat |= QQuickVisualDataModel::Referenced;
- }
- }
- return stat;
-}
-
-/*
- Returns ReleaseStatus flags.
-*/
-
-QQuickVisualDataModel::ReleaseFlags QQuickVisualDataModel::release(QQuickItem *item)
-{
- Q_D(QQuickVisualDataModel);
- QQuickVisualModel::ReleaseFlags stat = d->release(item);
- if (stat & Destroyed)
- item->setParentItem(0);
- return stat;
-}
-
-void QQuickVisualDataModelPrivate::group_append(
- QDeclarativeListProperty<QQuickVisualDataGroup> *property, QQuickVisualDataGroup *group)
-{
- QQuickVisualDataModelPrivate *d = static_cast<QQuickVisualDataModelPrivate *>(property->data);
- if (d->m_complete)
- return;
- if (d->m_groupCount == 11) {
- qmlInfo(d->q_func()) << QQuickVisualDataModel::tr("The maximum number of supported VisualDataGroups is 8");
- return;
- }
- d->m_groups[d->m_groupCount] = group;
- d->m_groupCount += 1;
-}
-
-int QQuickVisualDataModelPrivate::group_count(
- QDeclarativeListProperty<QQuickVisualDataGroup> *property)
-{
- QQuickVisualDataModelPrivate *d = static_cast<QQuickVisualDataModelPrivate *>(property->data);
- return d->m_groupCount - 1;
-}
-
-QQuickVisualDataGroup *QQuickVisualDataModelPrivate::group_at(
- QDeclarativeListProperty<QQuickVisualDataGroup> *property, int index)
-{
- QQuickVisualDataModelPrivate *d = static_cast<QQuickVisualDataModelPrivate *>(property->data);
- return index >= 0 && index < d->m_groupCount - 1
- ? d->m_groups[index + 1]
- : 0;
-}
-
-/*!
- \qmlproperty list<VisualDataGroup> QtQuick2::VisualDataModel::groups
-
- This property holds a visual data model's group definitions.
-
- Groups define a sub-set of the items in a visual data model and can be used to filter
- a model.
-
- For every group defined in a VisualDataModel two attached properties are added to each
- delegate item. The first of the form VisualDataModel.in\e{GroupName} holds whether the
- item belongs to the group and the second VisualDataModel.\e{groupName}Index holds the
- index of the item in that group.
-
- The following example illustrates using groups to select items in a model.
-
- \snippet doc/src/snippets/declarative/visualdatagroup.qml 0
-*/
-
-QDeclarativeListProperty<QQuickVisualDataGroup> QQuickVisualDataModel::groups()
-{
- Q_D(QQuickVisualDataModel);
- return QDeclarativeListProperty<QQuickVisualDataGroup>(
- this,
- d,
- QQuickVisualDataModelPrivate::group_append,
- QQuickVisualDataModelPrivate::group_count,
- QQuickVisualDataModelPrivate::group_at);
-}
-
-/*!
- \qmlproperty VisualDataGroup QtQuick2::VisualDataModel::items
-
- This property holds visual data model's default group to which all new items are added.
-*/
-
-QQuickVisualDataGroup *QQuickVisualDataModel::items()
-{
- Q_D(QQuickVisualDataModel);
- return d->m_items;
-}
-
-/*!
- \qmlproperty VisualDataGroup QtQuick2::VisualDataModel::persistedItems
-
- This property holds visual data model's persisted items group.
-
- Items in this group are not destroyed when released by a view, instead they are persisted
- until removed from the group.
-
- An item can be removed from the persistedItems group by setting the
- VisualDataModel.inPersistedItems property to false. If the item is not referenced by a view
- at that time it will be destroyed. Adding an item to this group will not create a new
- instance.
-
- Items returned by the \l QtQuick2::VisualDataGroup::create() function are automatically added
- to this group.
-*/
-
-QQuickVisualDataGroup *QQuickVisualDataModel::persistedItems()
-{
- Q_D(QQuickVisualDataModel);
- return d->m_persistedItems;
-}
-
-/*!
- \qmlproperty string QtQuick2::VisualDataModel::filterOnGroup
-
- This property holds the name of the group used to filter the visual data model.
-
- Only items which belong to this group are visible to a view.
-
- By default this is the \l items group.
-*/
-
-QString QQuickVisualDataModel::filterGroup() const
-{
- Q_D(const QQuickVisualDataModel);
- return d->m_filterGroup;
-}
-
-void QQuickVisualDataModel::setFilterGroup(const QString &group)
-{
- Q_D(QQuickVisualDataModel);
-
- if (d->m_transaction) {
- qmlInfo(this) << tr("The group of a VisualDataModel cannot be changed within onChanged");
- return;
- }
-
- if (d->m_filterGroup != group) {
- d->m_filterGroup = group;
- d->updateFilterGroup();
- emit filterGroupChanged();
- }
-}
-
-void QQuickVisualDataModel::resetFilterGroup()
-{
- setFilterGroup(QStringLiteral("items"));
-}
-
-void QQuickVisualDataModelPrivate::updateFilterGroup()
-{
- Q_Q(QQuickVisualDataModel);
- if (!m_cacheMetaType)
- return;
-
- QDeclarativeListCompositor::Group previousGroup = m_compositorGroup;
- m_compositorGroup = Compositor::Default;
- for (int i = 1; i < m_groupCount; ++i) {
- if (m_filterGroup == m_cacheMetaType->groupNames.at(i - 1)) {
- m_compositorGroup = Compositor::Group(i);
- break;
- }
- }
-
- QQuickVisualDataGroupPrivate::get(m_groups[m_compositorGroup])->emitters.insert(this);
- if (m_compositorGroup != previousGroup) {
- QVector<QDeclarativeChangeSet::Remove> removes;
- QVector<QDeclarativeChangeSet::Insert> inserts;
- m_compositor.transition(previousGroup, m_compositorGroup, &removes, &inserts);
-
- QDeclarativeChangeSet changeSet;
- changeSet.apply(removes, inserts);
- emit q->modelUpdated(changeSet, false);
-
- if (changeSet.difference() != 0)
- emit q->countChanged();
-
- if (m_parts) {
- foreach (QQuickVisualPartsModel *model, m_parts->models)
- model->updateFilterGroup(m_compositorGroup, changeSet);
- }
- }
-}
-
-/*!
- \qmlproperty object QtQuick2::VisualDataModel::parts
-
- The \a parts property selects a VisualDataModel which creates
- delegates from the part named. This is used in conjunction with
- the \l Package element.
-
- For example, the code below selects a model which creates
- delegates named \e list from a \l Package:
-
- \code
- VisualDataModel {
- id: visualModel
- delegate: Package {
- Item { Package.name: "list" }
- }
- model: myModel
- }
-
- ListView {
- width: 200; height:200
- model: visualModel.parts.list
- }
- \endcode
-
- \sa Package
-*/
-
-QObject *QQuickVisualDataModel::parts()
-{
- Q_D(QQuickVisualDataModel);
- if (!d->m_parts)
- d->m_parts = new QQuickVisualDataModelParts(this);
- return d->m_parts;
-}
-
-void QQuickVisualDataModelPrivate::emitCreatedPackage(QQuickVisualDataModelCacheItem *cacheItem, QDeclarativePackage *package)
-{
- for (int i = 1; i < m_groupCount; ++i)
- QQuickVisualDataGroupPrivate::get(m_groups[i])->createdPackage(cacheItem->index[i], package);
-}
-
-void QQuickVisualDataModelPrivate::emitInitPackage(QQuickVisualDataModelCacheItem *cacheItem, QDeclarativePackage *package)
-{
- for (int i = 1; i < m_groupCount; ++i)
- QQuickVisualDataGroupPrivate::get(m_groups[i])->initPackage(cacheItem->index[i], package);
-}
-
-void QQuickVisualDataModelPrivate::emitDestroyingPackage(QDeclarativePackage *package)
-{
- for (int i = 1; i < m_groupCount; ++i)
- QQuickVisualDataGroupPrivate::get(m_groups[i])->destroyingPackage(package);
-}
-
-void QVDMIncubationTask::statusChanged(Status status)
-{
- vdm->incubatorStatusChanged(this, status);
-}
-
-void QQuickVisualDataModelPrivate::releaseIncubator(QVDMIncubationTask *incubationTask)
-{
- Q_Q(QQuickVisualDataModel);
- if (!incubationTask->isError())
- incubationTask->clear();
- m_finishedIncubating.append(incubationTask);
- if (!m_incubatorCleanupScheduled) {
- m_incubatorCleanupScheduled = true;
- QCoreApplication::postEvent(q, new QEvent(QEvent::User));
- }
-}
-
-void QQuickVisualDataModelPrivate::incubatorStatusChanged(QVDMIncubationTask *incubationTask, QDeclarativeIncubator::Status status)
-{
- Q_Q(QQuickVisualDataModel);
- if (status != QDeclarativeIncubator::Ready && status != QDeclarativeIncubator::Error)
- return;
-
- QQuickVisualDataModelCacheItem *cacheItem = incubationTask->incubating;
- cacheItem->incubationTask = 0;
-
- if (status == QDeclarativeIncubator::Ready) {
- incubationTask->incubating = 0;
- releaseIncubator(incubationTask);
- if (QDeclarativePackage *package = qobject_cast<QDeclarativePackage *>(cacheItem->object))
- emitCreatedPackage(cacheItem, package);
- else if (QQuickItem *item = qobject_cast<QQuickItem *>(cacheItem->object))
- emitCreatedItem(cacheItem, item);
- } else if (status == QDeclarativeIncubator::Error) {
- delete incubationTask->incubatingContext;
- incubationTask->incubatingContext = 0;
- if (!cacheItem->isReferenced()) {
- int cidx = m_cache.indexOf(cacheItem);
- m_compositor.clearFlags(Compositor::Cache, cidx, 1, Compositor::CacheFlag);
- m_cache.removeAt(cidx);
- delete cacheItem;
- Q_ASSERT(m_cache.count() == m_compositor.count(Compositor::Cache));
- }
- releaseIncubator(incubationTask);
- qmlInfo(q, m_delegate->errors()) << "Error creating delegate";
- }
-}
-
-void QVDMIncubationTask::setInitialState(QObject *o)
-{
- vdm->setInitialState(this, o);
-}
-
-void QQuickVisualDataModelPrivate::setInitialState(QVDMIncubationTask *incubationTask, QObject *o)
-{
- QQuickVisualDataModelCacheItem *cacheItem = incubationTask->incubating;
- cacheItem->object = o;
- QDeclarative_setParent_noEvent(incubationTask->incubatingContext, cacheItem->object);
- incubationTask->incubatingContext = 0;
-
- cacheItem->attached = QQuickVisualDataModelAttached::properties(cacheItem->object);
- cacheItem->attached->m_cacheItem = cacheItem;
- new QQuickVisualDataModelAttachedMetaObject(cacheItem->attached, m_cacheMetaType);
- cacheItem->attached->emitChanges();
-
- if (QDeclarativePackage *package = qobject_cast<QDeclarativePackage *>(cacheItem->object))
- emitInitPackage(cacheItem, package);
- else if (QQuickItem *item = qobject_cast<QQuickItem *>(cacheItem->object))
- emitInitItem(cacheItem, item);
-}
-
-QObject *QQuickVisualDataModelPrivate::object(Compositor::Group group, int index, bool asynchronous, bool reference)
-{
- Q_Q(QQuickVisualDataModel);
- if (!m_delegate || index < 0 || index >= m_compositor.count(group)) {
- qWarning() << "VisualDataModel::item: index out range" << index << m_compositor.count(group);
- return 0;
- }
-
- Compositor::iterator it = m_compositor.find(group, index);
- QQuickVisualDataModelCacheItem *cacheItem = it->inCache() ? m_cache.at(it.cacheIndex) : 0;
- if (!cacheItem) {
- cacheItem = new QQuickVisualDataModelCacheItem(m_cacheMetaType);
- for (int i = 0; i < m_groupCount; ++i)
- cacheItem->index[i] = it.index[i];
- cacheItem->groups = it->flags & Compositor::GroupMask;
- }
-
- int modelIndex = it.modelIndex();
-
- if (!it->inCache()) {
- m_cache.insert(it.cacheIndex, cacheItem);
- m_compositor.setFlags(it, 1, Compositor::CacheFlag);
- Q_ASSERT(m_cache.count() == m_compositor.count(Compositor::Cache));
- }
-
- if (cacheItem->incubationTask) {
- if (!asynchronous) {
- // previously requested async - now needed immediately
- cacheItem->incubationTask->forceCompletion();
- }
- } else if (!cacheItem->object) {
- QVDMIncubationTask *incubator = new QVDMIncubationTask(this, asynchronous ? QDeclarativeIncubator::Asynchronous : QDeclarativeIncubator::AsynchronousIfNested);
- cacheItem->incubationTask = incubator;
-
- QObject *data = m_adaptorModel->data(modelIndex);
-
- QDeclarativeContext *creationContext = m_delegate->creationContext();
- QDeclarativeContext *rootContext = new QDeclarativeContext(
- creationContext ? creationContext : m_context.data());
- QDeclarativeContext *ctxt = rootContext;
- if (m_adaptorModel->flags() & QQuickVisualAdaptorModel::ProxiedObject) {
- if (QQuickVisualAdaptorModelProxyInterface *proxy = qobject_cast<QQuickVisualAdaptorModelProxyInterface *>(data)) {
- ctxt->setContextObject(proxy->proxiedObject());
- ctxt = new QDeclarativeContext(ctxt, ctxt);
- }
- }
-
- QDeclarative_setParent_noEvent(data, ctxt);
- ctxt->setContextProperty(QLatin1String("model"), data);
- ctxt->setContextObject(data);
-
- incubator->incubating = cacheItem;
- incubator->incubatingContext = rootContext;
- m_delegate->create(*incubator, ctxt, m_context);
- }
-
- if (index == m_compositor.count(group) - 1 && m_adaptorModel->canFetchMore())
- QCoreApplication::postEvent(q, new QEvent(QEvent::UpdateRequest));
- if (cacheItem->object && reference)
- cacheItem->referenceObject();
- return cacheItem->object;
-}
-
-/*
- If asynchronous is true or the component is being loaded asynchronously due
- to an ancestor being loaded asynchronously, item() may return 0. In this
- case itemCreated() will be emitted when the item is available. The item
- at this stage does not have any references, so item() must be called again
- to ensure a reference is held. Any call to item() which returns a valid item
- must be matched by a call to release() in order to destroy the item.
-*/
-QQuickItem *QQuickVisualDataModel::item(int index, bool asynchronous)
-{
- Q_D(QQuickVisualDataModel);
- if (!d->m_delegate || index < 0 || index >= d->m_compositor.count(d->m_compositorGroup)) {
- qWarning() << "VisualDataModel::item: index out range" << index << d->m_compositor.count(d->m_compositorGroup);
- return 0;
- }
-
- QObject *object = d->object(d->m_compositorGroup, index, asynchronous, true);
- if (!object)
- return 0;
-
- if (QQuickItem *item = qobject_cast<QQuickItem *>(object))
- return item;
-
- d->release(object);
- if (!d->m_delegateValidated) {
- if (object)
- qmlInfo(d->m_delegate) << QQuickVisualDataModel::tr("Delegate component must be Item type.");
- d->m_delegateValidated = true;
- }
- return 0;
-}
-
-QString QQuickVisualDataModelPrivate::stringValue(Compositor::Group group, int index, const QString &name)
-{
- Compositor::iterator it = m_compositor.find(group, index);
- if (QQuickVisualAdaptorModel *model = it.list<QQuickVisualAdaptorModel>()) {
- return model->stringValue(it.modelIndex(), name);
- }
- return QString();
-}
-
-QString QQuickVisualDataModel::stringValue(int index, const QString &name)
-{
- Q_D(QQuickVisualDataModel);
- return d->stringValue(d->m_compositorGroup, index, name);
-}
-
-int QQuickVisualDataModelPrivate::cacheIndexOf(QObject *object) const
-{
- for (int cacheIndex = 0; cacheIndex < m_cache.count(); ++cacheIndex) {
- if (m_cache.at(cacheIndex)->object == object)
- return cacheIndex;
- }
- return -1;
-}
-
-int QQuickVisualDataModel::indexOf(QQuickItem *item, QObject *) const
-{
- Q_D(const QQuickVisualDataModel);
- const int cacheIndex = d->cacheIndexOf(item);
- return cacheIndex != -1
- ? d->m_cache.at(cacheIndex)->index[d->m_compositorGroup]
- : -1;
-}
-
-void QQuickVisualDataModel::setWatchedRoles(QList<QByteArray> roles)
-{
- Q_D(QQuickVisualDataModel);
- d->m_adaptorModel->replaceWatchedRoles(d->watchedRoles, roles);
- d->watchedRoles = roles;
-}
-
-void QQuickVisualDataModelPrivate::addGroups(Compositor::Group group, int index, int count, int groupFlags)
-{
- QVector<Compositor::Insert> inserts;
- m_compositor.setFlags(group, index, count, groupFlags, &inserts);
- itemsInserted(inserts);
- emitChanges();
-}
-
-void QQuickVisualDataModelPrivate::removeGroups(Compositor::Group group, int index, int count, int groupFlags)
-{
- QVector<Compositor::Remove> removes;
- m_compositor.clearFlags(group, index, count, groupFlags, &removes);
- itemsRemoved(removes);
- emitChanges();
-}
-
-void QQuickVisualDataModelPrivate::setGroups(Compositor::Group group, int index, int count, int groupFlags)
-{
- QVector<Compositor::Insert> inserts;
- m_compositor.setFlags(group, index, count, groupFlags, &inserts);
- itemsInserted(inserts);
-
- const int removeFlags = ~groupFlags & Compositor::GroupMask;
- QVector<Compositor::Remove> removes;
- m_compositor.clearFlags(group, index, count, removeFlags, &removes);
- itemsRemoved(removes);
-
- emitChanges();
-}
-
-bool QQuickVisualDataModel::event(QEvent *e)
-{
- Q_D(QQuickVisualDataModel);
- if (e->type() == QEvent::UpdateRequest) {
- d->m_adaptorModel->fetchMore();
- } else if (e->type() == QEvent::User) {
- d->m_incubatorCleanupScheduled = false;
- qDeleteAll(d->m_finishedIncubating);
- d->m_finishedIncubating.clear();
- }
- return QQuickVisualModel::event(e);
-}
-
-void QQuickVisualDataModelPrivate::itemsChanged(const QVector<Compositor::Change> &changes)
-{
- if (!m_delegate)
- return;
-
- QVarLengthArray<QVector<QDeclarativeChangeSet::Change>, Compositor::MaximumGroupCount> translatedChanges(m_groupCount);
-
- foreach (const Compositor::Change &change, changes) {
- for (int i = 1; i < m_groupCount; ++i) {
- if (change.inGroup(i)) {
- translatedChanges[i].append(
- QDeclarativeChangeSet::Change(change.index[i], change.count));
- }
- }
- }
-
- for (int i = 1; i < m_groupCount; ++i)
- QQuickVisualDataGroupPrivate::get(m_groups[i])->changeSet.apply(translatedChanges.at(i));
-}
-
-void QQuickVisualDataModel::_q_itemsChanged(int index, int count)
-{
- Q_D(QQuickVisualDataModel);
- if (count <= 0)
- return;
- QVector<Compositor::Change> changes;
- d->m_compositor.listItemsChanged(d->m_adaptorModel, index, count, &changes);
- d->itemsChanged(changes);
- d->emitChanges();
-}
-
-void QQuickVisualDataModelPrivate::itemsInserted(
- const QVector<Compositor::Insert> &inserts,
- QVarLengthArray<QVector<QDeclarativeChangeSet::Insert>, Compositor::MaximumGroupCount> *translatedInserts,
- QHash<int, QList<QQuickVisualDataModelCacheItem *> > *movedItems)
-{
- int cacheIndex = 0;
-
- int inserted[Compositor::MaximumGroupCount];
- for (int i = 1; i < m_groupCount; ++i)
- inserted[i] = 0;
-
- foreach (const Compositor::Insert &insert, inserts) {
- for (; cacheIndex < insert.cacheIndex; ++cacheIndex) {
- QQuickVisualDataModelCacheItem *cacheItem = m_cache.at(cacheIndex);
- if (!cacheItem->groups)
- continue;
- for (int i = 1; i < m_groupCount; ++i)
- cacheItem->index[i] += inserted[i];
- }
- for (int i = 1; i < m_groupCount; ++i) {
- if (insert.inGroup(i)) {
- (*translatedInserts)[i].append(
- QDeclarativeChangeSet::Insert(insert.index[i], insert.count, insert.moveId));
- inserted[i] += insert.count;
- }
- }
-
- if (!insert.inCache())
- continue;
-
- if (movedItems && insert.isMove()) {
- QList<QQuickVisualDataModelCacheItem *> items = movedItems->take(insert.moveId);
- Q_ASSERT(items.count() == insert.count);
- m_cache = m_cache.mid(0, insert.cacheIndex) + items + m_cache.mid(insert.cacheIndex);
- }
- if (insert.inGroup()) {
- for (int offset = 0; cacheIndex < insert.cacheIndex + insert.count; ++cacheIndex, ++offset) {
- QQuickVisualDataModelCacheItem *cacheItem = m_cache.at(cacheIndex);
- cacheItem->groups |= insert.flags & Compositor::GroupMask;
- for (int i = 1; i < m_groupCount; ++i) {
- cacheItem->index[i] = cacheItem->groups & (1 << i)
- ? insert.index[i] + offset
- : insert.index[i];
- }
- }
- } else {
- cacheIndex = insert.cacheIndex + insert.count;
- }
- }
- for (; cacheIndex < m_cache.count(); ++cacheIndex) {
- QQuickVisualDataModelCacheItem *cacheItem = m_cache.at(cacheIndex);
- if (!cacheItem->groups)
- continue;
- for (int i = 1; i < m_groupCount; ++i)
- cacheItem->index[i] += inserted[i];
- }
-}
-
-void QQuickVisualDataModelPrivate::itemsInserted(const QVector<Compositor::Insert> &inserts)
-{
- QVarLengthArray<QVector<QDeclarativeChangeSet::Insert>, Compositor::MaximumGroupCount> translatedInserts(m_groupCount);
- itemsInserted(inserts, &translatedInserts);
- Q_ASSERT(m_cache.count() == m_compositor.count(Compositor::Cache));
- if (!m_delegate)
- return;
-
- for (int i = 1; i < m_groupCount; ++i)
- QQuickVisualDataGroupPrivate::get(m_groups[i])->changeSet.apply(translatedInserts.at(i));
-}
-
-void QQuickVisualDataModel::_q_itemsInserted(int index, int count)
-{
-
- Q_D(QQuickVisualDataModel);
- if (count <= 0)
- return;
- QVector<Compositor::Insert> inserts;
- d->m_compositor.listItemsInserted(d->m_adaptorModel, index, count, &inserts);
- d->itemsInserted(inserts);
- d->emitChanges();
-}
-
-void QQuickVisualDataModelPrivate::itemsRemoved(
- const QVector<Compositor::Remove> &removes,
- QVarLengthArray<QVector<QDeclarativeChangeSet::Remove>, Compositor::MaximumGroupCount> *translatedRemoves,
- QHash<int, QList<QQuickVisualDataModelCacheItem *> > *movedItems)
-{
- int cacheIndex = 0;
- int removedCache = 0;
-
- int removed[Compositor::MaximumGroupCount];
- for (int i = 1; i < m_groupCount; ++i)
- removed[i] = 0;
-
- foreach (const Compositor::Remove &remove, removes) {
- for (; cacheIndex < remove.cacheIndex; ++cacheIndex) {
- QQuickVisualDataModelCacheItem *cacheItem = m_cache.at(cacheIndex);
- if (!cacheItem->groups)
- continue;
- for (int i = 1; i < m_groupCount; ++i)
- cacheItem->index[i] -= removed[i];
- }
- for (int i = 1; i < m_groupCount; ++i) {
- if (remove.inGroup(i)) {
- (*translatedRemoves)[i].append(
- QDeclarativeChangeSet::Remove(remove.index[i], remove.count, remove.moveId));
- removed[i] += remove.count;
- }
- }
-
- if (!remove.inCache())
- continue;
-
- if (movedItems && remove.isMove()) {
- movedItems->insert(remove.moveId, m_cache.mid(remove.cacheIndex, remove.count));
- QList<QQuickVisualDataModelCacheItem *>::iterator begin = m_cache.begin() + remove.cacheIndex;
- QList<QQuickVisualDataModelCacheItem *>::iterator end = begin + remove.count;
- m_cache.erase(begin, end);
- } else {
- for (; cacheIndex < remove.cacheIndex + remove.count - removedCache; ++cacheIndex) {
- QQuickVisualDataModelCacheItem *cacheItem = m_cache.at(cacheIndex);
- if (remove.inGroup(Compositor::Persisted) && cacheItem->objectRef == 0) {
- destroy(cacheItem->object);
- if (QDeclarativePackage *package = qobject_cast<QDeclarativePackage *>(cacheItem->object))
- emitDestroyingPackage(package);
- else if (QQuickItem *item = qobject_cast<QQuickItem *>(cacheItem->object))
- emitDestroyingItem(item);
- cacheItem->object = 0;
- }
- if (remove.groups() == cacheItem->groups && !cacheItem->isReferenced()) {
- m_compositor.clearFlags(Compositor::Cache, cacheIndex, 1, Compositor::CacheFlag);
- m_cache.removeAt(cacheIndex);
- delete cacheItem;
- --cacheIndex;
- ++removedCache;
- Q_ASSERT(m_cache.count() == m_compositor.count(Compositor::Cache));
- } else if (remove.groups() == cacheItem->groups) {
- cacheItem->groups = 0;
- for (int i = 1; i < m_groupCount; ++i)
- cacheItem->index[i] = -1;
- } else {
- for (int i = 1; i < m_groupCount; ++i) {
- if (remove.inGroup(i))
- cacheItem->index[i] = remove.index[i];
- }
- cacheItem->groups &= ~remove.flags & Compositor::GroupMask;
- }
- }
- }
- }
-
- for (; cacheIndex < m_cache.count(); ++cacheIndex) {
- QQuickVisualDataModelCacheItem *cacheItem = m_cache.at(cacheIndex);
- if (!cacheItem->groups)
- continue;
- for (int i = 1; i < m_groupCount; ++i)
- cacheItem->index[i] -= removed[i];
- }
-}
-
-void QQuickVisualDataModelPrivate::itemsRemoved(const QVector<Compositor::Remove> &removes)
-{
- QVarLengthArray<QVector<QDeclarativeChangeSet::Remove>, Compositor::MaximumGroupCount> translatedRemoves(m_groupCount);
- itemsRemoved(removes, &translatedRemoves);
- Q_ASSERT(m_cache.count() == m_compositor.count(Compositor::Cache));
- if (!m_delegate)
- return;
-
- for (int i = 1; i < m_groupCount; ++i)
- QQuickVisualDataGroupPrivate::get(m_groups[i])->changeSet.apply(translatedRemoves.at(i));
-}
-
-void QQuickVisualDataModel::_q_itemsRemoved(int index, int count)
-{
- Q_D(QQuickVisualDataModel);
- if (count <= 0)
- return;
-
- QVector<Compositor::Remove> removes;
- d->m_compositor.listItemsRemoved(d->m_adaptorModel, index, count, &removes);
- d->itemsRemoved(removes);
- d->emitChanges();
-}
-
-void QQuickVisualDataModelPrivate::itemsMoved(
- const QVector<Compositor::Remove> &removes, const QVector<Compositor::Insert> &inserts)
-{
- QHash<int, QList<QQuickVisualDataModelCacheItem *> > movedItems;
-
- QVarLengthArray<QVector<QDeclarativeChangeSet::Remove>, Compositor::MaximumGroupCount> translatedRemoves(m_groupCount);
- itemsRemoved(removes, &translatedRemoves, &movedItems);
-
- QVarLengthArray<QVector<QDeclarativeChangeSet::Insert>, Compositor::MaximumGroupCount> translatedInserts(m_groupCount);
- itemsInserted(inserts, &translatedInserts, &movedItems);
- Q_ASSERT(m_cache.count() == m_compositor.count(Compositor::Cache));
- Q_ASSERT(movedItems.isEmpty());
- if (!m_delegate)
- return;
-
- for (int i = 1; i < m_groupCount; ++i) {
- QQuickVisualDataGroupPrivate::get(m_groups[i])->changeSet.apply(
- translatedRemoves.at(i),
- translatedInserts.at(i));
- }
-}
-
-void QQuickVisualDataModel::_q_itemsMoved(int from, int to, int count)
-{
- Q_D(QQuickVisualDataModel);
- if (count <= 0)
- return;
-
- QVector<Compositor::Remove> removes;
- QVector<Compositor::Insert> inserts;
- d->m_compositor.listItemsMoved(d->m_adaptorModel, from, to, count, &removes, &inserts);
- d->itemsMoved(removes, inserts);
- d->emitChanges();
-}
-
-template <typename T> v8::Local<v8::Array>
-QQuickVisualDataModelPrivate::buildChangeList(const QVector<T> &changes)
-{
- v8::Local<v8::Array> indexes = v8::Array::New(changes.count());
- v8::Local<v8::String> indexKey = v8::String::New("index");
- v8::Local<v8::String> countKey = v8::String::New("count");
- v8::Local<v8::String> moveIdKey = v8::String::New("moveId");
-
- for (int i = 0; i < changes.count(); ++i) {
- v8::Local<v8::Object> object = v8::Object::New();
- object->Set(indexKey, v8::Integer::New(changes.at(i).index));
- object->Set(countKey, v8::Integer::New(changes.at(i).count));
- object->Set(moveIdKey, changes.at(i).moveId != -1 ? v8::Integer::New(changes.at(i).count) : v8::Undefined());
- indexes->Set(i, object);
- }
- return indexes;
-}
-
-void QQuickVisualDataModelPrivate::emitModelUpdated(const QDeclarativeChangeSet &changeSet, bool reset)
-{
- Q_Q(QQuickVisualDataModel);
- emit q->modelUpdated(changeSet, reset);
- if (changeSet.difference() != 0)
- emit q->countChanged();
-}
-
-void QQuickVisualDataModelPrivate::emitChanges()
-{
- if (m_transaction || !m_complete)
- return;
-
- m_transaction = true;
- QV8Engine *engine = QDeclarativeEnginePrivate::getV8Engine(m_context->engine());
- for (int i = 1; i < m_groupCount; ++i)
- QQuickVisualDataGroupPrivate::get(m_groups[i])->emitChanges(engine);
- m_transaction = false;
-
- const bool reset = m_reset;
- m_reset = false;
- for (int i = 1; i < m_groupCount; ++i)
- QQuickVisualDataGroupPrivate::get(m_groups[i])->emitModelUpdated(reset);
-
- foreach (QQuickVisualDataModelCacheItem *cacheItem, m_cache) {
- if (cacheItem->object && cacheItem->attached)
- cacheItem->attached->emitChanges();
- }
-}
-
-void QQuickVisualDataModel::_q_modelReset(int oldCount, int newCount)
-{
- Q_D(QQuickVisualDataModel);
- if (!d->m_delegate)
- return;
-
- QVector<Compositor::Remove> removes;
- QVector<Compositor::Insert> inserts;
- if (oldCount)
- d->m_compositor.listItemsRemoved(d->m_adaptorModel, 0, oldCount, &removes);
- if (newCount)
- d->m_compositor.listItemsInserted(d->m_adaptorModel, 0, newCount, &inserts);
- d->itemsMoved(removes, inserts);
- d->m_reset = true;
- d->emitChanges();
-}
-
-QQuickVisualDataModelAttached *QQuickVisualDataModel::qmlAttachedProperties(QObject *obj)
-{
- return QQuickVisualDataModelAttached::properties(obj);
-}
-
-//============================================================================
-
-QQuickVisualDataModelCacheMetaType::QQuickVisualDataModelCacheMetaType(
- QV8Engine *engine, QQuickVisualDataModel *model, const QStringList &groupNames)
- : model(model)
- , groupCount(groupNames.count() + 1)
- , memberPropertyOffset(QQuickVisualDataModelAttached::staticMetaObject.propertyCount())
- , indexPropertyOffset(QQuickVisualDataModelAttached::staticMetaObject.propertyCount() + groupNames.count())
- , v8Engine(engine)
- , metaObject(0)
- , groupNames(groupNames)
-{
- QMetaObjectBuilder builder;
- builder.setFlags(QMetaObjectBuilder::DynamicMetaObject);
- builder.setClassName(QQuickVisualDataModelAttached::staticMetaObject.className());
- builder.setSuperClass(&QQuickVisualDataModelAttached::staticMetaObject);
-
- v8::HandleScope handleScope;
- v8::Context::Scope contextScope(engine->context());
- v8::Local<v8::FunctionTemplate> ft = v8::FunctionTemplate::New();
- ft->InstanceTemplate()->SetHasExternalResource(true);
- ft->PrototypeTemplate()->SetAccessor(v8::String::New("model"), get_model);
- ft->PrototypeTemplate()->SetAccessor(v8::String::New("groups"), get_groups, set_groups);
-
- int notifierId = 0;
- for (int i = 0; i < groupNames.count(); ++i, ++notifierId) {
- QString propertyName = QStringLiteral("in") + groupNames.at(i);
- propertyName.replace(2, 1, propertyName.at(2).toUpper());
- builder.addSignal("__" + propertyName.toUtf8() + "Changed()");
- QMetaPropertyBuilder propertyBuilder = builder.addProperty(
- propertyName.toUtf8(), "bool", notifierId);
- propertyBuilder.setWritable(true);
-
- ft->PrototypeTemplate()->SetAccessor(
- engine->toString(propertyName), get_member, set_member, v8::Int32::New(i + 1));
- }
- for (int i = 0; i < groupNames.count(); ++i, ++notifierId) {
- const QString propertyName = groupNames.at(i) + QStringLiteral("Index");
- builder.addSignal("__" + propertyName.toUtf8() + "Changed()");
- QMetaPropertyBuilder propertyBuilder = builder.addProperty(
- propertyName.toUtf8(), "int", notifierId);
- propertyBuilder.setWritable(true);
-
- ft->PrototypeTemplate()->SetAccessor(
- engine->toString(propertyName), get_index, 0, v8::Int32::New(i + 1));
- }
-
- metaObject = builder.toMetaObject();
-
- constructor = qPersistentNew<v8::Function>(ft->GetFunction());
-}
-
-QQuickVisualDataModelCacheMetaType::~QQuickVisualDataModelCacheMetaType()
-{
- qFree(metaObject);
- qPersistentDispose(constructor);
-}
-
-int QQuickVisualDataModelCacheMetaType::parseGroups(const QStringList &groups) const
-{
- int groupFlags = 0;
- foreach (const QString &groupName, groups) {
- int index = groupNames.indexOf(groupName);
- if (index != -1)
- groupFlags |= 2 << index;
- }
- return groupFlags;
-}
-
-int QQuickVisualDataModelCacheMetaType::parseGroups(QV8Engine *engine, const v8::Local<v8::Value> &groups) const
-{
- int groupFlags = 0;
- if (groups->IsString()) {
- const QString groupName = engine->toString(groups);
- int index = groupNames.indexOf(groupName);
- if (index != -1)
- groupFlags |= 2 << index;
- } else if (groups->IsArray()) {
- v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(groups);
- for (uint i = 0; i < array->Length(); ++i) {
- const QString groupName = engine->toString(array->Get(i));
- int index = groupNames.indexOf(groupName);
- if (index != -1)
- groupFlags |= 2 << index;
- }
- }
- return groupFlags;
-}
-
-v8::Handle<v8::Value> QQuickVisualDataModelCacheMetaType::get_model(
- v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QQuickVisualDataModelCacheItem *cacheItem = v8_resource_cast<QQuickVisualDataModelCacheItem>(info.This());
- if (!cacheItem)
- V8THROW_ERROR("Not a valid VisualData object");
- if (!cacheItem->metaType->model)
- return v8::Undefined();
- QObject *data = 0;
-
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(cacheItem->metaType->model);
- for (int i = 1; i < cacheItem->metaType->groupCount; ++i) {
- if (cacheItem->groups & (1 << i)) {
- Compositor::iterator it = model->m_compositor.find(
- Compositor::Group(i), cacheItem->index[i]);
- if (QQuickVisualAdaptorModel *list = it.list<QQuickVisualAdaptorModel>())
- data = list->data(it.modelIndex());
- break;
- }
- }
- if (!data)
- return v8::Undefined();
- return cacheItem->engine->newQObject(data);
-}
-
-v8::Handle<v8::Value> QQuickVisualDataModelCacheMetaType::get_groups(
- v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QQuickVisualDataModelCacheItem *cacheItem = v8_resource_cast<QQuickVisualDataModelCacheItem>(info.This());
- if (!cacheItem)
- V8THROW_ERROR("Not a valid VisualData object");
-
- QStringList groups;
- for (int i = 1; i < cacheItem->metaType->groupCount; ++i) {
- if (cacheItem->groups & (1 << i))
- groups.append(cacheItem->metaType->groupNames.at(i - 1));
- }
-
- return cacheItem->engine->fromVariant(groups);
-}
-
-void QQuickVisualDataModelCacheMetaType::set_groups(
- v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QQuickVisualDataModelCacheItem *cacheItem = v8_resource_cast<QQuickVisualDataModelCacheItem>(info.This());
- if (!cacheItem)
- V8THROW_ERROR_SETTER("Not a valid VisualData object");
-
- if (!cacheItem->metaType->model)
- return;
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(cacheItem->metaType->model);
-
- const int groupFlags = model->m_cacheMetaType->parseGroups(cacheItem->engine, value);
- for (int i = 1; i < cacheItem->metaType->groupCount; ++i) {
- if (cacheItem->groups & (1 << i)) {
- model->setGroups(Compositor::Group(i), cacheItem->index[i], 1, groupFlags);
- break;
- }
- }
-}
-
-v8::Handle<v8::Value> QQuickVisualDataModelCacheMetaType::get_member(
- v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QQuickVisualDataModelCacheItem *cacheItem = v8_resource_cast<QQuickVisualDataModelCacheItem>(info.This());
- if (!cacheItem)
- V8THROW_ERROR("Not a valid VisualData object");
-
- return v8::Boolean::New(cacheItem->groups & (1 << info.Data()->Int32Value()));
-}
-
-void QQuickVisualDataModelCacheMetaType::set_member(
- v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)
-{
- QQuickVisualDataModelCacheItem *cacheItem = v8_resource_cast<QQuickVisualDataModelCacheItem>(info.This());
- if (!cacheItem)
- V8THROW_ERROR_SETTER("Not a valid VisualData object");
-
- if (!cacheItem->metaType->model)
- return;
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(cacheItem->metaType->model);
-
- Compositor::Group group = Compositor::Group(info.Data()->Int32Value());
- const bool member = value->BooleanValue();
- const int groupFlag = (1 << group);
- if (member == ((cacheItem->groups & groupFlag) != 0))
- return;
-
- for (int i = 1; i < cacheItem->metaType->groupCount; ++i) {
- if (cacheItem->groups & (1 << i)) {
- if (member)
- model->addGroups(Compositor::Group(i), cacheItem->index[i], 1, groupFlag);
- else
- model->removeGroups(Compositor::Group(i), cacheItem->index[i], 1, groupFlag);
- break;
- }
- }
-}
-
-v8::Handle<v8::Value> QQuickVisualDataModelCacheMetaType::get_index(
- v8::Local<v8::String>, const v8::AccessorInfo &info)
-{
- QQuickVisualDataModelCacheItem *cacheItem = v8_resource_cast<QQuickVisualDataModelCacheItem>(info.This());
- if (!cacheItem)
- V8THROW_ERROR("Not a valid VisualData object");
-
- return v8::Integer::New(cacheItem->index[info.Data()->Int32Value()]);
-}
-
-
-//---------------------------------------------------------------------------
-
-QQuickVisualDataModelCacheItem::~QQuickVisualDataModelCacheItem()
-{
- Q_ASSERT(scriptRef == 0);
- Q_ASSERT(objectRef == 0);
- Q_ASSERT(!object);
- if (incubationTask && metaType->model)
- QQuickVisualDataModelPrivate::get(metaType->model)->releaseIncubator(incubationTask);
-
- metaType->release();
-}
-
-void QQuickVisualDataModelCacheItem::Dispose()
-{
- --scriptRef;
- if (isReferenced())
- return;
-
- if (metaType->model) {
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(metaType->model);
- const int cacheIndex = model->m_cache.indexOf(this);
- if (cacheIndex != -1) {
- model->m_compositor.clearFlags(Compositor::Cache, cacheIndex, 1, Compositor::CacheFlag);
- model->m_cache.removeAt(cacheIndex);
- }
- }
- delete this;
-}
-
-//---------------------------------------------------------------------------
-
-QQuickVisualDataModelAttachedMetaObject::QQuickVisualDataModelAttachedMetaObject(
- QQuickVisualDataModelAttached *attached, QQuickVisualDataModelCacheMetaType *metaType)
- : attached(attached)
- , metaType(metaType)
-{
- metaType->addref();
- *static_cast<QMetaObject *>(this) = *metaType->metaObject;
- QObjectPrivate::get(attached)->metaObject = this;
-}
-
-QQuickVisualDataModelAttachedMetaObject::~QQuickVisualDataModelAttachedMetaObject()
-{
- metaType->release();
-}
-
-int QQuickVisualDataModelAttachedMetaObject::metaCall(QMetaObject::Call call, int _id, void **arguments)
-{
- if (call == QMetaObject::ReadProperty) {
- if (_id >= metaType->indexPropertyOffset) {
- Compositor::Group group = Compositor::Group(_id - metaType->indexPropertyOffset + 1);
- *static_cast<int *>(arguments[0]) = attached->m_cacheItem->index[group];
- return -1;
- } else if (_id >= metaType->memberPropertyOffset) {
- Compositor::Group group = Compositor::Group(_id - metaType->memberPropertyOffset + 1);
- *static_cast<bool *>(arguments[0]) = attached->m_cacheItem->groups & (1 << group);
- return -1;
- }
- } else if (call == QMetaObject::WriteProperty) {
- if (_id >= metaType->memberPropertyOffset) {
- if (!metaType->model)
- return -1;
- Compositor::Group group = Compositor::Group(_id - metaType->memberPropertyOffset + 1);
- const bool member = attached->m_cacheItem->groups & (1 << group);
- if (member != *static_cast<bool *>(arguments[0])) {
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(metaType->model);
- const int cacheIndex = model->m_cache.indexOf(attached->m_cacheItem);
- if (member)
- model->removeGroups(Compositor::Cache, cacheIndex, 1, (1 << group));
- else
- model->addGroups(Compositor::Cache, cacheIndex, 1, (1 << group));
- }
- return -1;
- }
- }
- return attached->qt_metacall(call, _id, arguments);
-}
-
-void QQuickVisualDataModelAttached::setCacheItem(QQuickVisualDataModelCacheItem *item)
-{
- m_cacheItem = item;
- for (int i = 1; i < m_cacheItem->metaType->groupCount; ++i)
- m_previousIndex[i] = m_cacheItem->index[i];
-}
-
-/*!
- \qmlattachedproperty int QtQuick2::VisualDataModel::model
-
- This attached property holds the visual data model this delegate instance belongs to.
-
- It is attached to each instance of the delegate.
-*/
-
-QQuickVisualDataModel *QQuickVisualDataModelAttached::model() const
-{
- return m_cacheItem ? m_cacheItem->metaType->model : 0;
-}
-
-/*!
- \qmlattachedproperty stringlist QtQuick2::VisualDataModel::groups
-
- This attached property holds the name of VisualDataGroups the item belongs to.
-
- It is attached to each instance of the delegate.
-*/
-
-QStringList QQuickVisualDataModelAttached::groups() const
-{
- QStringList groups;
-
- if (!m_cacheItem)
- return groups;
- for (int i = 1; i < m_cacheItem->metaType->groupCount; ++i) {
- if (m_cacheItem->groups & (1 << i))
- groups.append(m_cacheItem->metaType->groupNames.at(i - 1));
- }
- return groups;
-}
-
-void QQuickVisualDataModelAttached::setGroups(const QStringList &groups)
-{
- if (!m_cacheItem)
- return;
-
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(m_cacheItem->metaType->model);
-
- const int cacheIndex = model->m_cache.indexOf(m_cacheItem);
- const int groupFlags = model->m_cacheMetaType->parseGroups(groups);
- model->setGroups(Compositor::Cache, cacheIndex, 1, groupFlags);
-}
-
-/*!
- \qmlattachedproperty int QtQuick2::VisualDataModel::inItems
-
- This attached property holds whether the item belongs to the default \l items VisualDataGroup.
-
- Changing this property will add or remove the item from the items group.
-
- It is attached to each instance of the delegate.
-*/
-
-/*!
- \qmlattachedproperty int QtQuick2::VisualDataModel::itemsIndex
-
- This attached property holds the index of the item in the default \l items VisualDataGroup.
-
- It is attached to each instance of the delegate.
-*/
-
-/*!
- \qmlattachedproperty int QtQuick2::VisualDataModel::inPersistedItems
-
- This attached property holds whether the item belongs to the \l persistedItems VisualDataGroup.
-
- Changing this property will add or remove the item from the items group. Change with caution
- as removing an item from the persistedItems group will destroy the current instance if it is
- not referenced by a model.
-
- It is attached to each instance of the delegate.
-*/
-
-/*!
- \qmlattachedproperty int QtQuick2::VisualDataModel::persistedItemsIndex
-
- This attached property holds the index of the item in the \l persistedItems VisualDataGroup.
-
- It is attached to each instance of the delegate.
-*/
-
-void QQuickVisualDataModelAttached::emitChanges()
-{
- if (m_modelChanged) {
- m_modelChanged = false;
- emit modelChanged();
- }
-
- const int groupChanges = m_previousGroups ^ m_cacheItem->groups;
- m_previousGroups = m_cacheItem->groups;
-
- int indexChanges = 0;
- for (int i = 1; i < m_cacheItem->metaType->groupCount; ++i) {
- if (m_previousIndex[i] != m_cacheItem->index[i]) {
- m_previousIndex[i] = m_cacheItem->index[i];
- indexChanges |= (1 << i);
- }
- }
-
- int notifierId = 0;
- const QMetaObject *meta = metaObject();
- for (int i = 1; i < m_cacheItem->metaType->groupCount; ++i, ++notifierId) {
- if (groupChanges & (1 << i))
- QMetaObject::activate(this, meta, notifierId, 0);
- }
- for (int i = 1; i < m_cacheItem->metaType->groupCount; ++i, ++notifierId) {
- if (indexChanges & (1 << i))
- QMetaObject::activate(this, meta, notifierId, 0);
- }
-
- if (groupChanges)
- emit groupsChanged();
-}
-
-//============================================================================
-
-void QQuickVisualDataGroupPrivate::setModel(QQuickVisualDataModel *m, Compositor::Group g)
-{
- Q_ASSERT(!model);
- model = m;
- group = g;
-}
-
-void QQuickVisualDataGroupPrivate::emitChanges(QV8Engine *engine)
-{
- Q_Q(QQuickVisualDataGroup);
- static int idx = signalIndex("changed(QDeclarativeV8Handle,QDeclarativeV8Handle)");
- if (isSignalConnected(idx) && !changeSet.isEmpty()) {
- v8::HandleScope handleScope;
- v8::Context::Scope contextScope(engine->context());
- v8::Local<v8::Array> removed = QQuickVisualDataModelPrivate::buildChangeList(changeSet.removes());
- v8::Local<v8::Array> inserted = QQuickVisualDataModelPrivate::buildChangeList(changeSet.inserts());
- emit q->changed(
- QDeclarativeV8Handle::fromHandle(removed), QDeclarativeV8Handle::fromHandle(inserted));
- }
- if (changeSet.difference() != 0)
- emit q->countChanged();
-}
-
-void QQuickVisualDataGroupPrivate::emitModelUpdated(bool reset)
-{
- for (QQuickVisualDataGroupEmitterList::iterator it = emitters.begin(); it != emitters.end(); ++it)
- it->emitModelUpdated(changeSet, reset);
- changeSet.clear();
-}
-
-void QQuickVisualDataGroupPrivate::createdPackage(int index, QDeclarativePackage *package)
-{
- for (QQuickVisualDataGroupEmitterList::iterator it = emitters.begin(); it != emitters.end(); ++it)
- it->createdPackage(index, package);
-}
-
-void QQuickVisualDataGroupPrivate::initPackage(int index, QDeclarativePackage *package)
-{
- for (QQuickVisualDataGroupEmitterList::iterator it = emitters.begin(); it != emitters.end(); ++it)
- it->initPackage(index, package);
-}
-
-void QQuickVisualDataGroupPrivate::destroyingPackage(QDeclarativePackage *package)
-{
- for (QQuickVisualDataGroupEmitterList::iterator it = emitters.begin(); it != emitters.end(); ++it)
- it->destroyingPackage(package);
-}
-
-/*!
- \qmlclass VisualDataGroup QQuickVisualDataGroup
- \inqmlmodule QtQuick 2
- \ingroup qml-working-with-data
- \brief The VisualDataGroup encapsulates a filtered set of visual data items.
-
-*/
-
-QQuickVisualDataGroup::QQuickVisualDataGroup(QObject *parent)
- : QObject(*new QQuickVisualDataGroupPrivate, parent)
-{
-}
-
-QQuickVisualDataGroup::QQuickVisualDataGroup(
- const QString &name, QQuickVisualDataModel *model, int index, QObject *parent)
- : QObject(*new QQuickVisualDataGroupPrivate, parent)
-{
- Q_D(QQuickVisualDataGroup);
- d->name = name;
- d->setModel(model, Compositor::Group(index));
-}
-
-QQuickVisualDataGroup::~QQuickVisualDataGroup()
-{
-}
-
-/*!
- \qmlproperty string QtQuick2::VisualDataGroup::name
-
- This property holds the name of the group.
-
- Each group in a model must have a unique name starting with a lower case letter.
-*/
-
-QString QQuickVisualDataGroup::name() const
-{
- Q_D(const QQuickVisualDataGroup);
- return d->name;
-}
-
-void QQuickVisualDataGroup::setName(const QString &name)
-{
- Q_D(QQuickVisualDataGroup);
- if (d->model)
- return;
- if (d->name != name) {
- d->name = name;
- emit nameChanged();
- }
-}
-
-/*!
- \qmlproperty int QtQuick2::VisualDataGroup::count
-
- This property holds the number of items in the group.
-*/
-
-int QQuickVisualDataGroup::count() const
-{
- Q_D(const QQuickVisualDataGroup);
- if (!d->model)
- return 0;
- return QQuickVisualDataModelPrivate::get(d->model)->m_compositor.count(d->group);
-}
-
-/*!
- \qmlproperty bool QtQuick2::VisualDataGroup::includeByDefault
-
- This property holds whether new items are assigned to this group by default.
-*/
-
-bool QQuickVisualDataGroup::defaultInclude() const
-{
- Q_D(const QQuickVisualDataGroup);
- return d->defaultInclude;
-}
-
-void QQuickVisualDataGroup::setDefaultInclude(bool include)
-{
- Q_D(QQuickVisualDataGroup);
- if (d->defaultInclude != include) {
- d->defaultInclude = include;
-
- if (d->model) {
- if (include)
- QQuickVisualDataModelPrivate::get(d->model)->m_compositor.setDefaultGroup(d->group);
- else
- QQuickVisualDataModelPrivate::get(d->model)->m_compositor.clearDefaultGroup(d->group);
- }
- emit defaultIncludeChanged();
- }
-}
-
-/*!
- \qmlmethod var QtQuick2::VisualDataGroup::get(int index)
-
- Returns a javascript object describing the item at \a index in the group.
-
- The returned object contains the same information that is available to a delegate from the
- VisualDataModel attached as well as the model for that item. It has the properties:
-
- \list
- \o \b model The model data of the item. This is the same as the model context property in
- a delegate
- \o \b groups A list the of names of groups the item is a member of. This property can be
- written to change the item's membership.
- \o \b inItems Whether the item belongs to the \l {QtQuick2::VisualDataModel::items}{items} group.
- Writing to this property will add or remove the item from the group.
- \o \b itemsIndex The index of the item within the \l {QtQuick2::VisualDataModel::items}{items} group.
- \o \b {in\i{GroupName}} Whether the item belongs to the dynamic group \i groupName. Writing to
- this property will add or remove the item from the group.
- \o \b {\i{groupName}Index} The index of the item within the dynamic group \i groupName.
- \endlist
-*/
-
-QDeclarativeV8Handle QQuickVisualDataGroup::get(int index)
-{
- Q_D(QQuickVisualDataGroup);
- if (!d->model)
- return QDeclarativeV8Handle::fromHandle(v8::Undefined());;
-
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(d->model);
- if (index < 0 || index >= model->m_compositor.count(d->group)) {
- qmlInfo(this) << tr("get: index out of range");
- return QDeclarativeV8Handle::fromHandle(v8::Undefined());
- }
-
- Compositor::iterator it = model->m_compositor.find(d->group, index);
- QQuickVisualDataModelCacheItem *cacheItem = it->inCache()
- ? model->m_cache.at(it.cacheIndex)
- : 0;
-
- if (!cacheItem) {
- cacheItem = new QQuickVisualDataModelCacheItem(model->m_cacheMetaType);
- for (int i = 0; i < model->m_groupCount; ++i)
- cacheItem->index[i] = it.index[i];
- cacheItem->groups = it->flags & Compositor::GroupMask;
-
- model->m_cache.insert(it.cacheIndex, cacheItem);
- model->m_compositor.setFlags(it, 1, Compositor::CacheFlag);
- }
-
- ++cacheItem->scriptRef;
-
- v8::Local<v8::Object> rv = model->m_cacheMetaType->constructor->NewInstance();
- rv->SetExternalResource(cacheItem);
- return QDeclarativeV8Handle::fromHandle(rv);
-}
-
-/*!
- \qmlmethod QtQuick2::VisualDataGroup::create(int index)
-
- Returns a reference to the instantiated item at \a index in the group.
-
- All items returned by create are added to the persistedItems group. Items in this
- group remain instantiated when not referenced by any view.
-*/
-
-QObject *QQuickVisualDataGroup::create(int index)
-{
- Q_D(QQuickVisualDataGroup);
- if (!d->model)
- return 0;
-
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(d->model);
- if (index < 0 || index >= model->m_compositor.count(d->group)) {
- qmlInfo(this) << tr("create: index out of range");
- return 0;
- }
-
- QObject *object = model->object(d->group, index, false, false);
- if (object)
- model->addGroups(d->group, index, 1, Compositor::PersistedFlag);
- return object;
-}
-
-/*!
- \qmlmethod QtQuick2::VisualDataGroup::remove(int index, int count)
-
- Removes \a count items starting at \a index from the group.
-*/
-
-void QQuickVisualDataGroup::remove(QDeclarativeV8Function *args)
-{
- Q_D(QQuickVisualDataGroup);
- if (!d->model)
- return;
- int index = -1;
- int count = 1;
-
- if (args->Length() == 0)
- return;
-
- int i = 0;
- v8::Local<v8::Value> v = (*args)[i];
- if (!v->IsInt32())
- return;
- index = v->Int32Value();
-
- if (++i < args->Length()) {
- v = (*args)[i];
- if (v->IsInt32())
- count = v->Int32Value();
- }
-
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(d->model);
- if (count < 0) {
- qmlInfo(this) << tr("remove: invalid count");
- } else if (index < 0 || index + count > model->m_compositor.count(d->group)) {
- qmlInfo(this) << tr("remove: index out of range");
- } else if (count > 0) {
- model->removeGroups(d->group, index, count, 1 << d->group);
- }
-}
-
-bool QQuickVisualDataGroupPrivate::parseGroupArgs(
- QDeclarativeV8Function *args, int *index, int *count, int *groups) const
-{
- if (!model || !QQuickVisualDataModelPrivate::get(model)->m_cacheMetaType)
- return false;
-
- if (args->Length() < 2)
- return false;
-
- int i = 0;
- v8::Local<v8::Value> v = (*args)[i];
- if (!v->IsInt32())
- return false;
- *index = v->Int32Value();
-
- v = (*args)[++i];
- if (v->IsInt32()) {
- *count = v->Int32Value();
-
- if (++i == args->Length())
- return false;
- v = (*args)[i];
- }
-
- *groups = QQuickVisualDataModelPrivate::get(model)->m_cacheMetaType->parseGroups(args->engine(), v);
-
- return true;
-}
-
-/*!
- \qmlmethod QtQuick2::VisualDataGroup::addGroups(int index, int count, stringlist groups)
-
- Adds \a count items starting at \a index to \a groups.
-*/
-
-void QQuickVisualDataGroup::addGroups(QDeclarativeV8Function *args)
-{
- Q_D(QQuickVisualDataGroup);
- int index = -1;
- int count = 1;
- int groups = 0;
-
- if (!d->parseGroupArgs(args, &index, &count, &groups))
- return;
-
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(d->model);
- if (count < 0) {
- qmlInfo(this) << tr("addGroups: invalid count");
- } else if (index < 0 || index + count > model->m_compositor.count(d->group)) {
- qmlInfo(this) << tr("addGroups: index out of range");
- } else if (count > 0 && groups) {
- model->addGroups(d->group, index, count, groups);
- }
-}
-
-/*!
- \qmlmethod QtQuick2::VisualDataGroup::removeGroups(int index, int count, stringlist groups)
-
- Removes \a count items starting at \a index from \a groups.
-*/
-
-void QQuickVisualDataGroup::removeGroups(QDeclarativeV8Function *args)
-{
- Q_D(QQuickVisualDataGroup);
- int index = -1;
- int count = 1;
- int groups = 0;
-
- if (!d->parseGroupArgs(args, &index, &count, &groups))
- return;
-
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(d->model);
- if (count < 0) {
- qmlInfo(this) << tr("removeGroups: invalid count");
- } else if (index < 0 || index + count > model->m_compositor.count(d->group)) {
- qmlInfo(this) << tr("removeGroups: index out of range");
- } else if (count > 0 && groups) {
- model->removeGroups(d->group, index, count, groups);
- }
-}
-
-/*!
- \qmlmethod QtQuick2::VisualDataGroup::setGroups(int index, int count, stringlist groups)
-
- Sets the \a groups \a count items starting at \a index belong to.
-*/
-
-void QQuickVisualDataGroup::setGroups(QDeclarativeV8Function *args)
-{
- Q_D(QQuickVisualDataGroup);
- int index = -1;
- int count = 1;
- int groups = 0;
-
- if (!d->parseGroupArgs(args, &index, &count, &groups))
- return;
-
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(d->model);
- if (count < 0) {
- qmlInfo(this) << tr("setGroups: invalid count");
- } else if (index < 0 || index + count > model->m_compositor.count(d->group)) {
- qmlInfo(this) << tr("setGroups: index out of range");
- } else if (count > 0) {
- model->setGroups(d->group, index, count, groups);
- }
-}
-
-/*!
- \qmlmethod QtQuick2::VisualDataGroup::setGroups(int index, int count, stringlist groups)
-
- Sets the \a groups \a count items starting at \a index belong to.
-*/
-
-/*!
- \qmlmethod QtQuick2::VisualDataGroup::move(int from, int to, int count)
-
- Moves \a count at \a from in a group \a to a new position.
-*/
-
-void QQuickVisualDataGroup::move(QDeclarativeV8Function *args)
-{
- Q_D(QQuickVisualDataGroup);
-
- if (args->Length() < 2)
- return;
-
- Compositor::Group fromGroup = d->group;
- Compositor::Group toGroup = d->group;
- int from = -1;
- int to = -1;
- int count = 1;
-
- int i = 0;
- v8::Local<v8::Value> v = (*args)[i];
- if (QQuickVisualDataGroup *group = qobject_cast<QQuickVisualDataGroup *>(args->engine()->toQObject(v))) {
- QQuickVisualDataGroupPrivate *g_d = QQuickVisualDataGroupPrivate::get(group);
- if (g_d->model != d->model)
- return;
- fromGroup = g_d->group;
- v = (*args)[++i];
- }
-
- if (!v->IsInt32())
- return;
- from = v->Int32Value();
-
- if (++i == args->Length())
- return;
- v = (*args)[i];
-
- if (QQuickVisualDataGroup *group = qobject_cast<QQuickVisualDataGroup *>(args->engine()->toQObject(v))) {
- QQuickVisualDataGroupPrivate *g_d = QQuickVisualDataGroupPrivate::get(group);
- if (g_d->model != d->model)
- return;
- toGroup = g_d->group;
-
- if (++i == args->Length())
- return;
- v = (*args)[i];
- }
-
- if (!v->IsInt32())
- return;
- to = v->Int32Value();
-
- if (++i < args->Length()) {
- v = (*args)[i];
- if (v->IsInt32())
- count = v->Int32Value();
- }
-
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(d->model);
-
- if (count < 0) {
- qmlInfo(this) << tr("move: invalid count");
- } else if (from < 0 || from + count > model->m_compositor.count(fromGroup)) {
- qmlInfo(this) << tr("move: from index out of range");
- } else if (!model->m_compositor.verifyMoveTo(fromGroup, from, toGroup, to, count)) {
- qmlInfo(this) << tr("move: to index out of range");
- } else if (count > 0) {
- QVector<Compositor::Remove> removes;
- QVector<Compositor::Insert> inserts;
-
- model->m_compositor.move(fromGroup, from, toGroup, to, count, &removes, &inserts);
- model->itemsMoved(removes, inserts);
- model->emitChanges();
- }
-
-}
-
-/*!
- \qmlsignal QtQuick2::VisualDataGroup::onChanged(array removed, array inserted)
-
- This handler is called when items have been removed from or inserted into the group.
-
- Each object in the \a removed and \a inserted arrays has two values; the \e index of the first
- item inserted or removed and a \e count of the number of consecutive items inserted or removed.
-
- Each index is adjusted for previous changes with all removed items preceding any inserted
- items.
-*/
-
-//============================================================================
-
-QQuickVisualPartsModel::QQuickVisualPartsModel(QQuickVisualDataModel *model, const QString &part, QObject *parent)
- : QQuickVisualModel(*new QObjectPrivate, parent)
- , m_model(model)
- , m_part(part)
- , m_compositorGroup(Compositor::Cache)
- , m_inheritGroup(true)
-{
- QQuickVisualDataModelPrivate *d = QQuickVisualDataModelPrivate::get(m_model);
- if (d->m_cacheMetaType) {
- QQuickVisualDataGroupPrivate::get(d->m_groups[1])->emitters.insert(this);
- m_compositorGroup = Compositor::Default;
- } else {
- d->m_pendingParts.insert(this);
- }
-}
-
-QQuickVisualPartsModel::~QQuickVisualPartsModel()
-{
-}
-
-QString QQuickVisualPartsModel::filterGroup() const
-{
- if (m_inheritGroup)
- return m_model->filterGroup();
- return m_filterGroup;
-}
-
-void QQuickVisualPartsModel::setFilterGroup(const QString &group)
-{
- if (QQuickVisualDataModelPrivate::get(m_model)->m_transaction) {
- qmlInfo(this) << tr("The group of a VisualDataModel cannot be changed within onChanged");
- return;
- }
-
- if (m_filterGroup != group || m_inheritGroup) {
- m_filterGroup = group;
- m_inheritGroup = false;
- updateFilterGroup();
-
- emit filterGroupChanged();
- }
-}
-
-void QQuickVisualPartsModel::resetFilterGroup()
-{
- if (!m_inheritGroup) {
- m_inheritGroup = true;
- updateFilterGroup();
- emit filterGroupChanged();
- }
-}
-
-void QQuickVisualPartsModel::updateFilterGroup()
-{
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(m_model);
- if (!model->m_cacheMetaType)
- return;
-
- if (m_inheritGroup) {
- if (m_filterGroup == model->m_filterGroup)
- return;
- m_filterGroup = model->m_filterGroup;
- }
-
- QDeclarativeListCompositor::Group previousGroup = m_compositorGroup;
- m_compositorGroup = Compositor::Default;
- QQuickVisualDataGroupPrivate::get(model->m_groups[Compositor::Default])->emitters.insert(this);
- for (int i = 1; i < model->m_groupCount; ++i) {
- if (m_filterGroup == model->m_cacheMetaType->groupNames.at(i - 1)) {
- m_compositorGroup = Compositor::Group(i);
- break;
- }
- }
-
- QQuickVisualDataGroupPrivate::get(model->m_groups[m_compositorGroup])->emitters.insert(this);
- if (m_compositorGroup != previousGroup) {
- QVector<QDeclarativeChangeSet::Remove> removes;
- QVector<QDeclarativeChangeSet::Insert> inserts;
- model->m_compositor.transition(previousGroup, m_compositorGroup, &removes, &inserts);
-
- QDeclarativeChangeSet changeSet;
- changeSet.apply(removes, inserts);
- if (!changeSet.isEmpty())
- emit modelUpdated(changeSet, false);
-
- if (changeSet.difference() != 0)
- emit countChanged();
- }
-}
-
-void QQuickVisualPartsModel::updateFilterGroup(
- Compositor::Group group, const QDeclarativeChangeSet &changeSet)
-{
- if (!m_inheritGroup)
- return;
-
- m_compositorGroup = group;
- QQuickVisualDataGroupPrivate::get(QQuickVisualDataModelPrivate::get(m_model)->m_groups[m_compositorGroup])->emitters.insert(this);
-
- if (!changeSet.isEmpty())
- emit modelUpdated(changeSet, false);
-
- if (changeSet.difference() != 0)
- emit countChanged();
-
- emit filterGroupChanged();
-}
-
-int QQuickVisualPartsModel::count() const
-{
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(m_model);
- return model->m_delegate
- ? model->m_compositor.count(m_compositorGroup)
- : 0;
-}
-
-bool QQuickVisualPartsModel::isValid() const
-{
- return m_model->isValid();
-}
-
-QQuickItem *QQuickVisualPartsModel::item(int index, bool asynchronous)
-{
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(m_model);
-
- if (!model->m_delegate || index < 0 || index >= model->m_compositor.count(m_compositorGroup)) {
- qWarning() << "VisualDataModel::item: index out range" << index << model->m_compositor.count(m_compositorGroup);
- return 0;
- }
-
- QObject *object = model->object(m_compositorGroup, index, asynchronous, true);
-
- if (QDeclarativePackage *package = qobject_cast<QDeclarativePackage *>(object)) {
- QObject *part = package->part(m_part);
- if (!part)
- return 0;
- if (QQuickItem *item = qobject_cast<QQuickItem *>(part)) {
- m_packaged.insertMulti(item, package);
- return item;
- }
- }
-
- model->release(object);
- if (!model->m_delegateValidated) {
- if (object)
- qmlInfo(model->m_delegate) << tr("Delegate component must be Package type.");
- model->m_delegateValidated = true;
- }
-
- return 0;
-}
-
-QQuickVisualModel::ReleaseFlags QQuickVisualPartsModel::release(QQuickItem *item)
-{
- QQuickVisualModel::ReleaseFlags flags = 0;
-
- QHash<QObject *, QDeclarativePackage *>::iterator it = m_packaged.find(item);
- if (it != m_packaged.end()) {
- QDeclarativePackage *package = *it;
- QDeclarative_setParent_noEvent(item, package);
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(m_model);
- flags = model->release(package);
- m_packaged.erase(it);
- if (!m_packaged.contains(item))
- flags &= ~Referenced;
- if (flags & Destroyed) {
- QQuickVisualDataModelPrivate::get(m_model)->emitDestroyingPackage(package);
- item->setParentItem(0);
- }
- }
- return flags;
-}
-
-QString QQuickVisualPartsModel::stringValue(int index, const QString &role)
-{
- return QQuickVisualDataModelPrivate::get(m_model)->stringValue(m_compositorGroup, index, role);
-}
-
-void QQuickVisualPartsModel::setWatchedRoles(QList<QByteArray> roles)
-{
- QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(m_model);
- model->m_adaptorModel->replaceWatchedRoles(m_watchedRoles, roles);
- m_watchedRoles = roles;
-}
-
-int QQuickVisualPartsModel::indexOf(QQuickItem *item, QObject *) const
-{
- QHash<QObject *, QDeclarativePackage *>::const_iterator it = m_packaged.find(item);
- if (it != m_packaged.end()) {
- const QQuickVisualDataModelPrivate *model = QQuickVisualDataModelPrivate::get(m_model);
- const int cacheIndex = model->cacheIndexOf(*it);
- return cacheIndex != -1
- ? model->m_cache.at(cacheIndex)->index[m_compositorGroup]
- : -1;
- }
- return -1;
-}
-
-void QQuickVisualPartsModel::createdPackage(int index, QDeclarativePackage *package)
-{
- if (QQuickItem *item = qobject_cast<QQuickItem *>(package->part(m_part)))
- emit createdItem(index, item);
-}
-
-void QQuickVisualPartsModel::initPackage(int index, QDeclarativePackage *package)
-{
- if (QQuickItem *item = qobject_cast<QQuickItem *>(package->part(m_part)))
- emit initItem(index, item);
-}
-
-void QQuickVisualPartsModel::destroyingPackage(QDeclarativePackage *package)
-{
- if (QQuickItem *item = qobject_cast<QQuickItem *>(package->part(m_part))) {
- Q_ASSERT(!m_packaged.contains(item));
- emit destroyingItem(item);
- }
-}
-
-void QQuickVisualPartsModel::emitModelUpdated(const QDeclarativeChangeSet &changeSet, bool reset)
-{
- emit modelUpdated(changeSet, reset);
- if (changeSet.difference() != 0)
- emit countChanged();
-}
-
-
-QT_END_NAMESPACE
-
-#include <qquickvisualdatamodel.moc>
diff --git a/src/declarative/items/qquickvisualdatamodel_p.h b/src/declarative/items/qquickvisualdatamodel_p.h
deleted file mode 100644
index a5a384f67b..0000000000
--- a/src/declarative/items/qquickvisualdatamodel_p.h
+++ /dev/null
@@ -1,242 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKVISUALDATAMODEL_P_H
-#define QQUICKVISUALDATAMODEL_P_H
-
-#include <private/qdeclarativelistcompositor_p.h>
-#include <private/qquickvisualitemmodel_p.h>
-
-
-#include <QtCore/qabstractitemmodel.h>
-#include <QtCore/qstringlist.h>
-
-#include <private/qv8engine_p.h>
-
-QT_BEGIN_HEADER
-
-Q_DECLARE_METATYPE(QModelIndex)
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QDeclarativeChangeSet;
-class QDeclarativeComponent;
-class QDeclarativePackage;
-class QDeclarativeV8Function;
-class QQuickVisualDataGroup;
-class QQuickVisualDataModelAttached;
-class QQuickVisualDataModelPrivate;
-
-
-class Q_DECLARATIVE_EXPORT QQuickVisualDataModel : public QQuickVisualModel, public QDeclarativeParserStatus
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickVisualDataModel)
-
- Q_PROPERTY(QVariant model READ model WRITE setModel)
- Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate)
- Q_PROPERTY(QString filterOnGroup READ filterGroup WRITE setFilterGroup NOTIFY filterGroupChanged RESET resetFilterGroup)
- Q_PROPERTY(QQuickVisualDataGroup *items READ items CONSTANT)
- Q_PROPERTY(QQuickVisualDataGroup *persistedItems READ persistedItems CONSTANT)
- Q_PROPERTY(QDeclarativeListProperty<QQuickVisualDataGroup> groups READ groups CONSTANT)
- Q_PROPERTY(QObject *parts READ parts CONSTANT)
- Q_PROPERTY(QVariant rootIndex READ rootIndex WRITE setRootIndex NOTIFY rootIndexChanged)
- Q_CLASSINFO("DefaultProperty", "delegate")
- Q_INTERFACES(QDeclarativeParserStatus)
-public:
- QQuickVisualDataModel();
- QQuickVisualDataModel(QDeclarativeContext *, QObject *parent=0);
- virtual ~QQuickVisualDataModel();
-
- void classBegin();
- void componentComplete();
-
- QVariant model() const;
- void setModel(const QVariant &);
-
- QDeclarativeComponent *delegate() const;
- void setDelegate(QDeclarativeComponent *);
-
- QVariant rootIndex() const;
- void setRootIndex(const QVariant &root);
-
- Q_INVOKABLE QVariant modelIndex(int idx) const;
- Q_INVOKABLE QVariant parentModelIndex() const;
-
- int count() const;
- bool isValid() const { return delegate() != 0; }
- QQuickItem *item(int index, bool asynchronous=false);
- ReleaseFlags release(QQuickItem *item);
- virtual QString stringValue(int index, const QString &role);
- virtual void setWatchedRoles(QList<QByteArray> roles);
-
- int indexOf(QQuickItem *item, QObject *objectContext) const;
-
- QString filterGroup() const;
- void setFilterGroup(const QString &group);
- void resetFilterGroup();
-
- QQuickVisualDataGroup *items();
- QQuickVisualDataGroup *persistedItems();
- QDeclarativeListProperty<QQuickVisualDataGroup> groups();
- QObject *parts();
-
- bool event(QEvent *);
-
- static QQuickVisualDataModelAttached *qmlAttachedProperties(QObject *obj);
-
-Q_SIGNALS:
- void filterGroupChanged();
- void defaultGroupsChanged();
- void rootIndexChanged();
-
-private Q_SLOTS:
- void _q_itemsChanged(int index, int count);
- void _q_itemsInserted(int index, int count);
- void _q_itemsRemoved(int index, int count);
- void _q_itemsMoved(int from, int to, int count);
- void _q_modelReset(int oldCount, int newCount);
-private:
- Q_DISABLE_COPY(QQuickVisualDataModel)
-};
-
-class QQuickVisualDataGroupPrivate;
-class Q_AUTOTEST_EXPORT QQuickVisualDataGroup : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(int count READ count NOTIFY countChanged)
- Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
- Q_PROPERTY(bool includeByDefault READ defaultInclude WRITE setDefaultInclude NOTIFY defaultIncludeChanged)
-public:
- QQuickVisualDataGroup(QObject *parent = 0);
- QQuickVisualDataGroup(const QString &name, QQuickVisualDataModel *model, int compositorType, QObject *parent = 0);
- ~QQuickVisualDataGroup();
-
- QString name() const;
- void setName(const QString &name);
-
- int count() const;
-
- bool defaultInclude() const;
- void setDefaultInclude(bool include);
-
- Q_INVOKABLE QDeclarativeV8Handle get(int index);
- Q_INVOKABLE QObject *create(int index);
-
-public Q_SLOTS:
- void remove(QDeclarativeV8Function *);
- void addGroups(QDeclarativeV8Function *);
- void removeGroups(QDeclarativeV8Function *);
- void setGroups(QDeclarativeV8Function *);
- void move(QDeclarativeV8Function *);
-
-Q_SIGNALS:
- void countChanged();
- void nameChanged();
- void defaultIncludeChanged();
- void changed(const QDeclarativeV8Handle &removed, const QDeclarativeV8Handle &inserted);
-private:
- Q_DECLARE_PRIVATE(QQuickVisualDataGroup)
-};
-
-class QQuickVisualDataModelCacheItem;
-class QQuickVisualDataModelAttachedMetaObject;
-class QQuickVisualDataModelAttached : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QQuickVisualDataModel *model READ model NOTIFY modelChanged)
- Q_PROPERTY(QStringList groups READ groups WRITE setGroups NOTIFY groupsChanged)
-public:
- QQuickVisualDataModelAttached(QObject *parent)
- : QObject(parent)
- , m_cacheItem(0)
- , m_previousGroups(0)
- , m_modelChanged(false)
- {}
- ~QQuickVisualDataModelAttached() { attachedProperties.remove(parent()); }
-
- void setCacheItem(QQuickVisualDataModelCacheItem *item);
-
- QQuickVisualDataModel *model() const;
-
- QStringList groups() const;
- void setGroups(const QStringList &groups);
-
- void emitChanges();
-
- static QQuickVisualDataModelAttached *properties(QObject *obj)
- {
- QQuickVisualDataModelAttached *rv = attachedProperties.value(obj);
- if (!rv) {
- rv = new QQuickVisualDataModelAttached(obj);
- attachedProperties.insert(obj, rv);
- }
- return rv;
- }
-
-Q_SIGNALS:
- void modelChanged();
- void groupsChanged();
-
-public:
- QQuickVisualDataModelCacheItem *m_cacheItem;
- int m_previousGroups;
- int m_previousIndex[QDeclarativeListCompositor::MaximumGroupCount];
- bool m_modelChanged;
-
- static QHash<QObject*, QQuickVisualDataModelAttached*> attachedProperties;
-
- friend class QQuickVisualDataModelAttachedMetaObject;
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickVisualDataModel)
-QML_DECLARE_TYPEINFO(QQuickVisualDataModel, QML_HAS_ATTACHED_PROPERTIES)
-QML_DECLARE_TYPE(QQuickVisualDataGroup)
-
-QT_END_HEADER
-
-#endif // QQUICKVISUALDATAMODEL_P_H
diff --git a/src/declarative/items/qquickvisualitemmodel.cpp b/src/declarative/items/qquickvisualitemmodel.cpp
deleted file mode 100644
index 78c4f8868b..0000000000
--- a/src/declarative/items/qquickvisualitemmodel.cpp
+++ /dev/null
@@ -1,235 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickvisualitemmodel_p.h"
-#include "qquickitem.h"
-
-#include <QtCore/qcoreapplication.h>
-#include <QtDeclarative/qdeclarativecontext.h>
-#include <QtDeclarative/qdeclarativeengine.h>
-
-#include <private/qdeclarativechangeset_p.h>
-#include <private/qdeclarativeglobal_p.h>
-#include <private/qobject_p.h>
-
-#include <QtCore/qhash.h>
-#include <QtCore/qlist.h>
-
-QT_BEGIN_NAMESPACE
-
-QHash<QObject*, QQuickVisualItemModelAttached*> QQuickVisualItemModelAttached::attachedProperties;
-
-
-class QQuickVisualItemModelPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QQuickVisualItemModel)
-public:
- QQuickVisualItemModelPrivate() : QObjectPrivate() {}
-
- static void children_append(QDeclarativeListProperty<QQuickItem> *prop, QQuickItem *item) {
- QDeclarative_setParent_noEvent(item, prop->object);
- static_cast<QQuickVisualItemModelPrivate *>(prop->data)->children.append(Item(item));
- static_cast<QQuickVisualItemModelPrivate *>(prop->data)->itemAppended();
- static_cast<QQuickVisualItemModelPrivate *>(prop->data)->emitChildrenChanged();
- }
-
- static int children_count(QDeclarativeListProperty<QQuickItem> *prop) {
- return static_cast<QQuickVisualItemModelPrivate *>(prop->data)->children.count();
- }
-
- static QQuickItem *children_at(QDeclarativeListProperty<QQuickItem> *prop, int index) {
- return static_cast<QQuickVisualItemModelPrivate *>(prop->data)->children.at(index).item;
- }
-
- void itemAppended() {
- Q_Q(QQuickVisualItemModel);
- QQuickVisualItemModelAttached *attached = QQuickVisualItemModelAttached::properties(children.last().item);
- attached->setIndex(children.count()-1);
- QDeclarativeChangeSet changeSet;
- changeSet.insert(children.count() - 1, 1);
- emit q->modelUpdated(changeSet, false);
- emit q->countChanged();
- }
-
- void emitChildrenChanged() {
- Q_Q(QQuickVisualItemModel);
- emit q->childrenChanged();
- }
-
- int indexOf(QQuickItem *item) const {
- for (int i = 0; i < children.count(); ++i)
- if (children.at(i).item == item)
- return i;
- return -1;
- }
-
- class Item {
- public:
- Item(QQuickItem *i) : item(i), ref(0) {}
-
- void addRef() { ++ref; }
- bool deref() { return --ref == 0; }
-
- QQuickItem *item;
- int ref;
- };
-
- QList<Item> children;
-};
-
-
-/*!
- \qmlclass VisualItemModel QQuickVisualItemModel
- \inqmlmodule QtQuick 2
- \ingroup qml-working-with-data
- \brief The VisualItemModel allows items to be provided to a view.
-
- A VisualItemModel contains the visual items to be used in a view.
- When a VisualItemModel is used in a view, the view does not require
- a delegate since the VisualItemModel already contains the visual
- delegate (items).
-
- An item can determine its index within the
- model via the \l{VisualItemModel::index}{index} attached property.
-
- The example below places three colored rectangles in a ListView.
- \code
- import QtQuick 1.0
-
- Rectangle {
- VisualItemModel {
- id: itemModel
- Rectangle { height: 30; width: 80; color: "red" }
- Rectangle { height: 30; width: 80; color: "green" }
- Rectangle { height: 30; width: 80; color: "blue" }
- }
-
- ListView {
- anchors.fill: parent
- model: itemModel
- }
- }
- \endcode
-
- \image visualitemmodel.png
-
- \sa {declarative/modelviews/visualitemmodel}{VisualItemModel example}
-*/
-QQuickVisualItemModel::QQuickVisualItemModel(QObject *parent)
- : QQuickVisualModel(*(new QQuickVisualItemModelPrivate), parent)
-{
-}
-
-/*!
- \qmlattachedproperty int QtQuick2::VisualItemModel::index
- This attached property holds the index of this delegate's item within the model.
-
- It is attached to each instance of the delegate.
-*/
-
-QDeclarativeListProperty<QQuickItem> QQuickVisualItemModel::children()
-{
- Q_D(QQuickVisualItemModel);
- return QDeclarativeListProperty<QQuickItem>(this, d, d->children_append,
- d->children_count, d->children_at);
-}
-
-/*!
- \qmlproperty int QtQuick2::VisualItemModel::count
-
- The number of items in the model. This property is readonly.
-*/
-int QQuickVisualItemModel::count() const
-{
- Q_D(const QQuickVisualItemModel);
- return d->children.count();
-}
-
-bool QQuickVisualItemModel::isValid() const
-{
- return true;
-}
-
-QQuickItem *QQuickVisualItemModel::item(int index, bool)
-{
- Q_D(QQuickVisualItemModel);
- QQuickVisualItemModelPrivate::Item &item = d->children[index];
- item.addRef();
- emit initItem(index, item.item);
- emit createdItem(index, item.item);
- return item.item;
-}
-
-QQuickVisualModel::ReleaseFlags QQuickVisualItemModel::release(QQuickItem *item)
-{
- Q_D(QQuickVisualItemModel);
- int idx = d->indexOf(item);
- if (idx >= 0) {
- if (d->children[idx].deref()) {
- // XXX todo - the original did item->scene()->removeItem(). Why?
- item->setParentItem(0);
- QDeclarative_setParent_noEvent(item, this);
- }
- }
- return 0;
-}
-
-QString QQuickVisualItemModel::stringValue(int index, const QString &name)
-{
- Q_D(QQuickVisualItemModel);
- if (index < 0 || index >= d->children.count())
- return QString();
- return QDeclarativeEngine::contextForObject(d->children.at(index).item)->contextProperty(name).toString();
-}
-
-int QQuickVisualItemModel::indexOf(QQuickItem *item, QObject *) const
-{
- Q_D(const QQuickVisualItemModel);
- return d->indexOf(item);
-}
-
-QQuickVisualItemModelAttached *QQuickVisualItemModel::qmlAttachedProperties(QObject *obj)
-{
- return QQuickVisualItemModelAttached::properties(obj);
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/items/qquickvisualitemmodel_p.h b/src/declarative/items/qquickvisualitemmodel_p.h
deleted file mode 100644
index 3d9610abe9..0000000000
--- a/src/declarative/items/qquickvisualitemmodel_p.h
+++ /dev/null
@@ -1,175 +0,0 @@
-// Commit: ac5c099cc3c5b8c7eec7a49fdeb8a21037230350
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKVISUALITEMMODEL_P_H
-#define QQUICKVISUALITEMMODEL_P_H
-
-#include <QtDeclarative/qdeclarative.h>
-#include <QtCore/qobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickItem;
-class QDeclarativeChangeSet;
-
-class Q_DECLARATIVE_EXPORT QQuickVisualModel : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(int count READ count NOTIFY countChanged)
-
-public:
- virtual ~QQuickVisualModel() {}
-
- enum ReleaseFlag { Referenced = 0x01, Destroyed = 0x02 };
- Q_DECLARE_FLAGS(ReleaseFlags, ReleaseFlag)
-
- virtual int count() const = 0;
- virtual bool isValid() const = 0;
- virtual QQuickItem *item(int index, bool asynchronous=false) = 0;
- virtual ReleaseFlags release(QQuickItem *item) = 0;
- virtual QString stringValue(int, const QString &) = 0;
- virtual void setWatchedRoles(QList<QByteArray> roles) = 0;
-
- virtual int indexOf(QQuickItem *item, QObject *objectContext) const = 0;
-
-Q_SIGNALS:
- void countChanged();
- void modelUpdated(const QDeclarativeChangeSet &changeSet, bool reset);
- void createdItem(int index, QQuickItem *item);
- void initItem(int index, QQuickItem *item);
- void destroyingItem(QQuickItem *item);
-
-protected:
- QQuickVisualModel(QObjectPrivate &dd, QObject *parent = 0)
- : QObject(dd, parent) {}
-
-private:
- Q_DISABLE_COPY(QQuickVisualModel)
-};
-
-class QQuickVisualItemModelAttached;
-class QQuickVisualItemModelPrivate;
-class Q_DECLARATIVE_EXPORT QQuickVisualItemModel : public QQuickVisualModel
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QQuickVisualItemModel)
-
- Q_PROPERTY(QDeclarativeListProperty<QQuickItem> children READ children NOTIFY childrenChanged DESIGNABLE false)
- Q_CLASSINFO("DefaultProperty", "children")
-
-public:
- QQuickVisualItemModel(QObject *parent=0);
- virtual ~QQuickVisualItemModel() {}
-
- virtual int count() const;
- virtual bool isValid() const;
- virtual QQuickItem *item(int index, bool asynchronous=false);
- virtual ReleaseFlags release(QQuickItem *item);
- virtual QString stringValue(int index, const QString &role);
- virtual void setWatchedRoles(QList<QByteArray>) {}
-
- virtual int indexOf(QQuickItem *item, QObject *objectContext) const;
-
- QDeclarativeListProperty<QQuickItem> children();
-
- static QQuickVisualItemModelAttached *qmlAttachedProperties(QObject *obj);
-
-Q_SIGNALS:
- void childrenChanged();
-
-private:
- Q_DISABLE_COPY(QQuickVisualItemModel)
-};
-
-class QQuickVisualItemModelAttached : public QObject
-{
- Q_OBJECT
-
-public:
- QQuickVisualItemModelAttached(QObject *parent)
- : QObject(parent), m_index(0) {}
- ~QQuickVisualItemModelAttached() {
- attachedProperties.remove(parent());
- }
-
- Q_PROPERTY(int index READ index NOTIFY indexChanged)
- int index() const { return m_index; }
- void setIndex(int idx) {
- if (m_index != idx) {
- m_index = idx;
- emit indexChanged();
- }
- }
-
- static QQuickVisualItemModelAttached *properties(QObject *obj) {
- QQuickVisualItemModelAttached *rv = attachedProperties.value(obj);
- if (!rv) {
- rv = new QQuickVisualItemModelAttached(obj);
- attachedProperties.insert(obj, rv);
- }
- return rv;
- }
-
-Q_SIGNALS:
- void indexChanged();
-
-public:
- int m_index;
-
- static QHash<QObject*, QQuickVisualItemModelAttached*> attachedProperties;
-};
-
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QQuickVisualModel)
-QML_DECLARE_TYPE(QQuickVisualItemModel)
-QML_DECLARE_TYPEINFO(QQuickVisualItemModel, QML_HAS_ATTACHED_PROPERTIES)
-
-QT_END_HEADER
-
-#endif // QQUICKVISUALITEMMODEL_P_H
diff --git a/src/declarative/items/qquickwindowmodule.cpp b/src/declarative/items/qquickwindowmodule.cpp
deleted file mode 100644
index 7a7f28cb43..0000000000
--- a/src/declarative/items/qquickwindowmodule.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickwindowmodule_p.h"
-#include <QQuickCanvas>
-
-QT_BEGIN_NAMESPACE
-
-void QQuickWindowModule::defineModule()
-{
- const char* uri = "QtQuick.Window";
-
- qmlRegisterType<QQuickCanvas>(uri, 2, 0, "Window");
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/items/qquickwindowmodule_p.h b/src/declarative/items/qquickwindowmodule_p.h
deleted file mode 100644
index ead15942b9..0000000000
--- a/src/declarative/items/qquickwindowmodule_p.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQUICKWINDOWMODULE_H
-#define QQUICKWINDOWMODULE_H
-
-#include <qdeclarative.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickWindowModule
-{
-public:
- static void defineModule();
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/items/syncexcludes b/src/declarative/items/syncexcludes
deleted file mode 100644
index ab7a374a5b..0000000000
--- a/src/declarative/items/syncexcludes
+++ /dev/null
@@ -1,11 +0,0 @@
-qdeclarativegraphicswidget.cpp
-qdeclarativegraphicswidget_p.h
-qdeclarativetextlayout_p.h
-qdeclarativetextlayout.cpp
-qdeclarativelayoutitem.cpp
-qdeclarativelayoutitem_p.h
-qdeclarativefocuspanel.cpp
-qdeclarativefocuspanel_p.h
-qdeclarativepath_p.h
-qdeclarativepath_p_p.h
-qdeclarativepath.cpp
diff --git a/src/declarative/particles/particleresources/noise.png b/src/declarative/particles/particleresources/noise.png
deleted file mode 100644
index 3c723e1a5a..0000000000
--- a/src/declarative/particles/particleresources/noise.png
+++ /dev/null
Binary files differ
diff --git a/src/declarative/particles/particles.pri b/src/declarative/particles/particles.pri
deleted file mode 100644
index 3a40a3b911..0000000000
--- a/src/declarative/particles/particles.pri
+++ /dev/null
@@ -1,69 +0,0 @@
-HEADERS += \
- $$PWD/qquickangledirection_p.h \
- $$PWD/qquickcustomparticle_p.h \
- $$PWD/qquickcustomaffector_p.h \
- $$PWD/qquickellipseextruder_p.h \
- $$PWD/qquicktrailemitter_p.h \
- $$PWD/qquickfriction_p.h \
- $$PWD/qquickgravity_p.h \
- $$PWD/qquickimageparticle_p.h \
- $$PWD/qquickitemparticle_p.h \
- $$PWD/qquickage_p.h \
- $$PWD/qquicklineextruder_p.h \
- $$PWD/qquickmaskextruder_p.h \
- $$PWD/qquickparticleaffector_p.h \
- $$PWD/qquickparticleemitter_p.h \
- $$PWD/qquickparticleextruder_p.h \
- $$PWD/qquickparticlepainter_p.h \
- $$PWD/qquickparticlesmodule_p.h \
- $$PWD/qquickparticlesystem_p.h \
- $$PWD/qquickpointattractor_p.h \
- $$PWD/qquickpointdirection_p.h \
- $$PWD/qquickspritegoal_p.h \
- $$PWD/qquickdirection_p.h \
- $$PWD/qquicktargetdirection_p.h \
- $$PWD/qquickturbulence_p.h \
- $$PWD/qquickwander_p.h \
- $$PWD/qquickcumulativedirection_p.h \
- $$PWD/qquickv8particledata_p.h \
- $$PWD/qquickrectangleextruder_p.h \
- $$PWD/qquickparticlegroup_p.h \
- $$PWD/qquickgroupgoal_p.h
-
-SOURCES += \
- $$PWD/qquickangledirection.cpp \
- $$PWD/qquickcustomparticle.cpp \
- $$PWD/qquickcustomaffector.cpp \
- $$PWD/qquickellipseextruder.cpp \
- $$PWD/qquicktrailemitter.cpp \
- $$PWD/qquickfriction.cpp \
- $$PWD/qquickgravity.cpp \
- $$PWD/qquickimageparticle.cpp \
- $$PWD/qquickitemparticle.cpp \
- $$PWD/qquickage.cpp \
- $$PWD/qquicklineextruder.cpp \
- $$PWD/qquickmaskextruder.cpp \
- $$PWD/qquickparticleaffector.cpp \
- $$PWD/qquickparticleemitter.cpp \
- $$PWD/qquickparticleextruder.cpp \
- $$PWD/qquickparticlepainter.cpp \
- $$PWD/qquickparticlesmodule.cpp \
- $$PWD/qquickparticlesystem.cpp \
- $$PWD/qquickpointattractor.cpp \
- $$PWD/qquickpointdirection.cpp \
- $$PWD/qquickspritegoal.cpp \
- $$PWD/qquickdirection.cpp \
- $$PWD/qquicktargetdirection.cpp \
- $$PWD/qquickturbulence.cpp \
- $$PWD/qquickwander.cpp \
- $$PWD/qquickcumulativedirection.cpp \
- $$PWD/qquickv8particledata.cpp \
- $$PWD/qquickrectangleextruder.cpp \
- $$PWD/qquickparticlegroup.cpp \
- $$PWD/qquickgroupgoal.cpp
-
-RESOURCES += \
- $$PWD/particles.qrc
-
-
-
diff --git a/src/declarative/particles/particles.qrc b/src/declarative/particles/particles.qrc
deleted file mode 100644
index 344f9489a4..0000000000
--- a/src/declarative/particles/particles.qrc
+++ /dev/null
@@ -1,5 +0,0 @@
-<RCC>
- <qresource prefix="/">
- <file>particleresources/noise.png</file>
- </qresource>
-</RCC>
diff --git a/src/declarative/particles/qquickage.cpp b/src/declarative/particles/qquickage.cpp
deleted file mode 100644
index a71b9e2088..0000000000
--- a/src/declarative/particles/qquickage.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickage_p.h"
-#include "qquickparticleemitter_p.h"
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass Age QQuickAgeAffector
- \inqmlmodule QtQuick.Particles 2
- \inherits Affector
- \brief The Age affector allows you to prematurely age particles
-
- The Age affector allows you to alter where the particle is in its lifecycle. Common uses
- are to expire particles prematurely, possibly giving them time to animate out.
-
- The Age affector only applies to particles which are still alive.
-*/
-/*!
- \qmlproperty int QtQuick.Particles2::Age::lifeLeft
-
- The amount of life to set the particle to have. Affected particles
- will advance to a point in their life where they will have this many
- milliseconds left to live.
-*/
-
-/*!
- \qmlproperty bool QtQuick.Particles2::Age::advancePosition
-
- advancePosition determines whether position, veclocity and acceleration are included in
- the simulated aging done by the affector. If advancePosition is false,
- then the position, velocity and acceleration will remain the same and only
- other attributes (such as opacity) will advance in the simulation to where
- it would normally be for that point in the particle's life. With advancePosition set to
- true the position, velocity and acceleration will also advance to where it would
- normally be by that point in the particle's life, making it advance its position
- on screen.
-
- Default value is true.
-*/
-
-QQuickAgeAffector::QQuickAgeAffector(QQuickItem *parent) :
- QQuickParticleAffector(parent), m_lifeLeft(0), m_advancePosition(true)
-{
-}
-
-
-bool QQuickAgeAffector::affectParticle(QQuickParticleData *d, qreal dt)
-{
- Q_UNUSED(dt);
- if (d->stillAlive()){
- qreal curT = (qreal)m_system->timeInt/1000.0;
- qreal ttl = (qreal)m_lifeLeft/1000.0;
- if (!m_advancePosition && ttl > 0){
- qreal x = d->curX();
- qreal vx = d->curVX();
- qreal ax = d->curAX();
- qreal y = d->curY();
- qreal vy = d->curVY();
- qreal ay = d->curAY();
- d->t = curT - (d->lifeSpan - ttl);
- d->setInstantaneousX(x);
- d->setInstantaneousVX(vx);
- d->setInstantaneousAX(ax);
- d->setInstantaneousY(y);
- d->setInstantaneousVY(vy);
- d->setInstantaneousAY(ay);
- } else {
- d->t = curT - (d->lifeSpan - ttl);
- }
- return true;
- }
- return false;
-}
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickage_p.h b/src/declarative/particles/qquickage_p.h
deleted file mode 100644
index 0adbddabe9..0000000000
--- a/src/declarative/particles/qquickage_p.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef KILLAFFECTOR_H
-#define KILLAFFECTOR_H
-#include "qquickparticleaffector_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QQuickAgeAffector : public QQuickParticleAffector
-{
- Q_OBJECT
- Q_PROPERTY(int lifeLeft READ lifeLeft WRITE setLifeLeft NOTIFY lifeLeftChanged)
- Q_PROPERTY(bool advancePosition READ advancePosition WRITE setAdvancePosition NOTIFY advancePositionChanged)
-
-public:
- explicit QQuickAgeAffector(QQuickItem *parent = 0);
-
- int lifeLeft() const
- {
- return m_lifeLeft;
- }
-
- bool advancePosition() const
- {
- return m_advancePosition;
- }
-
-protected:
- virtual bool affectParticle(QQuickParticleData *d, qreal dt);
-signals:
- void lifeLeftChanged(int arg);
- void advancePositionChanged(bool arg);
-
-public slots:
- void setLifeLeft(int arg)
- {
- if (m_lifeLeft != arg) {
- m_lifeLeft = arg;
- emit lifeLeftChanged(arg);
- }
- }
-
- void setAdvancePosition(bool arg)
- {
- if (m_advancePosition != arg) {
- m_advancePosition = arg;
- emit advancePositionChanged(arg);
- }
- }
-
-private:
- int m_lifeLeft;
- bool m_advancePosition;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // KILLAFFECTOR_H
diff --git a/src/declarative/particles/qquickangledirection.cpp b/src/declarative/particles/qquickangledirection.cpp
deleted file mode 100644
index 9ce422e8d1..0000000000
--- a/src/declarative/particles/qquickangledirection.cpp
+++ /dev/null
@@ -1,116 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickangledirection_p.h"
-#include <cmath>
-QT_BEGIN_NAMESPACE
-const qreal CONV = 0.017453292519943295;
-/*!
- \qmlclass AngleDirection QQuickAngleDirection
- \inqmlmodule QtQuick.Particles 2
- \inherits Direction
- \brief The AngleDirection element allows you to specify a direction that varies in angle
-
- The AngledDirection element allows both the specification of a direction by angle and magnitude,
- as well as varying the parameters by angle or magnitude.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::AngleDirection::angle
- This property specifies the base angle for the direction.
- The angle of this direction will vary by no more than angleVariation
- from this angle.
-
- Angle is specified by degrees clockwise from straight right.
-
- The default value is zero.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::AngleDirection::magnitude
- This property specifies the base magnitude for the direction.
- The magnitude of this direction will vary by no more than magnitudeVariation
- from this magnitude.
-
- Magnitude is specified in units of pixels per second.
-
- The default value is zero.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::AngleDirection::angleVariation
- This property specifies the maximum angle variation for the direction.
- The angle of the direction will vary by up to angleVariation clockwise
- and anticlockwise from the value specified in angle.
-
- Angle is specified by degrees clockwise from straight right.
-
- The default value is zero.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::AngleDirection::magnitudeVariation
- This property specifies the base magnitude for the direction.
- The magnitude of this direction will vary by no more than magnitudeVariation
- from the base magnitude.
-
- Magnitude is specified in units of pixels per second.
-
- The default value is zero.
-*/
-QQuickAngleDirection::QQuickAngleDirection(QObject *parent) :
- QQuickDirection(parent)
- , m_angle(0)
- , m_magnitude(0)
- , m_angleVariation(0)
- , m_magnitudeVariation(0)
-{
-
-}
-
-const QPointF QQuickAngleDirection::sample(const QPointF &from)
-{
- Q_UNUSED(from);
- QPointF ret;
- qreal theta = m_angle*CONV - m_angleVariation*CONV + rand()/float(RAND_MAX) * m_angleVariation*CONV * 2;
- qreal mag = m_magnitude- m_magnitudeVariation + rand()/float(RAND_MAX) * m_magnitudeVariation * 2;
- ret.setX(mag * cos(theta));
- ret.setY(mag * sin(theta));
- return ret;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickangledirection_p.h b/src/declarative/particles/qquickangledirection_p.h
deleted file mode 100644
index 7baf1a6c60..0000000000
--- a/src/declarative/particles/qquickangledirection_p.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQuickANGLEDDIRECTION_H
-#define QQuickANGLEDDIRECTION_H
-#include "qquickdirection_p.h"
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickAngleDirection : public QQuickDirection
-{
- Q_OBJECT
- Q_PROPERTY(qreal angle READ angle WRITE setAngle NOTIFY angleChanged)
- Q_PROPERTY(qreal magnitude READ magnitude WRITE setMagnitude NOTIFY magnitudeChanged)
- Q_PROPERTY(qreal angleVariation READ angleVariation WRITE setAngleVariation NOTIFY angleVariationChanged)
- Q_PROPERTY(qreal magnitudeVariation READ magnitudeVariation WRITE setMagnitudeVariation NOTIFY magnitudeVariationChanged)
-public:
- explicit QQuickAngleDirection(QObject *parent = 0);
- const QPointF sample(const QPointF &from);
- qreal angle() const
- {
- return m_angle;
- }
-
- qreal magnitude() const
- {
- return m_magnitude;
- }
-
- qreal angleVariation() const
- {
- return m_angleVariation;
- }
-
- qreal magnitudeVariation() const
- {
- return m_magnitudeVariation;
- }
-
-signals:
-
- void angleChanged(qreal arg);
-
- void magnitudeChanged(qreal arg);
-
- void angleVariationChanged(qreal arg);
-
- void magnitudeVariationChanged(qreal arg);
-
-public slots:
-void setAngle(qreal arg)
-{
- if (m_angle != arg) {
- m_angle = arg;
- emit angleChanged(arg);
- }
-}
-
-void setMagnitude(qreal arg)
-{
- if (m_magnitude != arg) {
- m_magnitude = arg;
- emit magnitudeChanged(arg);
- }
-}
-
-void setAngleVariation(qreal arg)
-{
- if (m_angleVariation != arg) {
- m_angleVariation = arg;
- emit angleVariationChanged(arg);
- }
-}
-
-void setMagnitudeVariation(qreal arg)
-{
- if (m_magnitudeVariation != arg) {
- m_magnitudeVariation = arg;
- emit magnitudeVariationChanged(arg);
- }
-}
-
-private:
-qreal m_angle;
-qreal m_magnitude;
-qreal m_angleVariation;
-qreal m_magnitudeVariation;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // QQuickANGLEDDIRECTION_H
diff --git a/src/declarative/particles/qquickcumulativedirection.cpp b/src/declarative/particles/qquickcumulativedirection.cpp
deleted file mode 100644
index 2f09ea4505..0000000000
--- a/src/declarative/particles/qquickcumulativedirection.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickcumulativedirection_p.h"
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass CumulativeDirection QQuickCumulativeDirection
- \inqmlmodule QtQuick.Particles 2
- \inherits Direction
- \brief The CumulativeDirection element allows you to specify a direction made of other directions
-
- The CumulativeDirection element will act as a direction that sums the directions within it.
-*/
-QQuickCumulativeDirection::QQuickCumulativeDirection(QObject *parent):QQuickDirection(parent)
-{
-}
-
-QDeclarativeListProperty<QQuickDirection> QQuickCumulativeDirection::directions()
-{
- return QDeclarativeListProperty<QQuickDirection>(this, m_directions);//TODO: Proper list property
-}
-
-const QPointF QQuickCumulativeDirection::sample(const QPointF &from)
-{
- QPointF ret;
- foreach (QQuickDirection* dir, m_directions)
- ret += dir->sample(from);
- return ret;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickcumulativedirection_p.h b/src/declarative/particles/qquickcumulativedirection_p.h
deleted file mode 100644
index af657821c2..0000000000
--- a/src/declarative/particles/qquickcumulativedirection_p.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQuickCUMULATIVEDIRECTION_P_H
-#define QQuickCUMULATIVEDIRECTION_P_H
-#include "qquickdirection_p.h"
-#include <QDeclarativeListProperty>
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickCumulativeDirection : public QQuickDirection
-{
- Q_OBJECT
- Q_PROPERTY(QDeclarativeListProperty<QQuickDirection> directions READ directions)
- Q_CLASSINFO("DefaultProperty", "directions")
-public:
- explicit QQuickCumulativeDirection(QObject *parent = 0);
- QDeclarativeListProperty<QQuickDirection> directions();
- const QPointF sample(const QPointF &from);
-private:
- QList<QQuickDirection*> m_directions;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQuickCUMULATIVEDIRECTION_P_H
diff --git a/src/declarative/particles/qquickcustomaffector.cpp b/src/declarative/particles/qquickcustomaffector.cpp
deleted file mode 100644
index 80e2eaf268..0000000000
--- a/src/declarative/particles/qquickcustomaffector.cpp
+++ /dev/null
@@ -1,211 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickcustomaffector_p.h"
-#include <private/qv8engine_p.h>
-#include <private/qdeclarativeengine_p.h>
-#include <QDeclarativeEngine>
-#include <QDebug>
-QT_BEGIN_NAMESPACE
-
-//TODO: Move docs (and inheritence) to real base when docs can propagate. Currently this pretends to be the base class!
-/*!
- \qmlsignal QtQuick.Particles2::Affector::affectParticles(Array particles, real dt)
-
- This handler is called when particles are selected to be affected. particles contains
- an array of particle objects which can be directly manipulated.
-
- dt is the time since the last time it was affected. Use dt to normalize
- trajectory manipulations to real time.
-
- Note that JS is slower to execute, so it is not recommended to use this in
- high-volume particle systems.
-*/
-
-/*!
- \qmlproperty StochasticDirection QtQuick.Particles2::Affector::position
-
- Affected particles will have their position set to this direction,
- relative to the ParticleSystem. When interpreting directions as points,
- imagine it as an arrow with the base at the 0,0 of the ParticleSystem and the
- tip at where the specified position will be.
-*/
-
-/*!
- \qmlproperty StochasticDirection QtQuick.Particles2::Affector::speed
-
- Affected particles will have their speed set to this direction.
-*/
-
-
-/*!
- \qmlproperty StochasticDirection QtQuick.Particles2::Affector::acceleration
-
- Affected particles will have their acceleration set to this direction.
-*/
-
-
-/*!
- \qmlproperty bool QtQuick.Particles2::Affector::relative
-
- Whether the affected particles have their existing position/speed/acceleration added
- to the new one.
-
- Default is true.
-*/
-QQuickCustomAffector::QQuickCustomAffector(QQuickItem *parent) :
- QQuickParticleAffector(parent)
- , m_position(&m_nullVector)
- , m_speed(&m_nullVector)
- , m_acceleration(&m_nullVector)
- , m_relative(true)
-{
-}
-
-bool QQuickCustomAffector::isAffectConnected()
-{
- static int idx = QObjectPrivate::get(this)->signalIndex("affectParticles(QDeclarativeV8Handle,qreal)");
- return QObjectPrivate::get(this)->isSignalConnected(idx);
-}
-
-void QQuickCustomAffector::affectSystem(qreal dt)
-{
- if (!isAffectConnected()) {
- QQuickParticleAffector::affectSystem(dt);
- return;
- }
- if (!m_enabled)
- return;
- updateOffsets();
-
- QList<QQuickParticleData*> toAffect;
- foreach (QQuickParticleGroupData* gd, m_system->groupData)
- if (activeGroup(m_system->groupData.key(gd)))
- foreach (QQuickParticleData* d, gd->data)
- if (shouldAffect(d))
- toAffect << d;
-
- if (toAffect.isEmpty())
- return;
-
- if (m_onceOff)
- dt = 1.0;
-
- v8::HandleScope handle_scope;
- v8::Context::Scope scope(QDeclarativeEnginePrivate::getV8Engine(qmlEngine(this))->context());
- v8::Handle<v8::Array> array = v8::Array::New(toAffect.size());
- for (int i=0; i<toAffect.size(); i++)
- array->Set(i, toAffect[i]->v8Value().toHandle());
-
- if (dt >= simulationCutoff || dt <= simulationDelta) {
- affectProperties(toAffect, dt);
- emit affectParticles(QDeclarativeV8Handle::fromHandle(array), dt);
- } else {
- int realTime = m_system->timeInt;
- m_system->timeInt -= dt * 1000.0;
- while (dt > simulationDelta) {
- m_system->timeInt += simulationDelta * 1000.0;
- dt -= simulationDelta;
- affectProperties(toAffect, simulationDelta);
- emit affectParticles(QDeclarativeV8Handle::fromHandle(array), simulationDelta);
- }
- m_system->timeInt = realTime;
- if (dt > 0.0) {
- affectProperties(toAffect, dt);
- emit affectParticles(QDeclarativeV8Handle::fromHandle(array), dt);
- }
- }
-
- foreach (QQuickParticleData* d, toAffect)
- if (d->update == 1.0)
- postAffect(d);
-}
-
-bool QQuickCustomAffector::affectParticle(QQuickParticleData *d, qreal dt)
-{
- //This does the property based affecting, called by superclass if signal isn't hooked up.
- bool changed = false;
- QPointF curPos(d->curX(), d->curY());
-
- if (m_acceleration != &m_nullVector){
- QPointF pos = m_acceleration->sample(curPos);
- if (m_relative) {
- pos *= dt;
- pos += QPointF(d->curAX(), d->curAY());
- }
- d->setInstantaneousAX(pos.x());
- d->setInstantaneousAY(pos.y());
- changed = true;
- }
-
- if (m_speed != &m_nullVector){
- QPointF pos = m_speed->sample(curPos);
- if (m_relative) {
- pos *= dt;
- pos += QPointF(d->curVX(), d->curVY());
- }
- d->setInstantaneousVX(pos.x());
- d->setInstantaneousVY(pos.y());
- changed = true;
- }
-
- if (m_position != &m_nullVector){
- QPointF pos = m_position->sample(curPos);
- if (m_relative) {
- pos *= dt;
- pos += curPos;
- }
- d->setInstantaneousX(pos.x());
- d->setInstantaneousY(pos.y());
- changed = true;
- }
-
- return changed;
-}
-
-void QQuickCustomAffector::affectProperties(const QList<QQuickParticleData*> particles, qreal dt)
-{
- foreach (QQuickParticleData* d, particles)
- if ( affectParticle(d, dt) )
- d->update = 1.0;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickcustomaffector_p.h b/src/declarative/particles/qquickcustomaffector_p.h
deleted file mode 100644
index e347107f50..0000000000
--- a/src/declarative/particles/qquickcustomaffector_p.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CUSTOMAFFECTOR_H
-#define CUSTOMAFFECTOR_H
-
-#include <QObject>
-#include "qquickparticlesystem_p.h"
-#include "qquickparticleextruder_p.h"
-#include "qquickparticleaffector_p.h"
-#include "qquickdirection_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickCustomAffector : public QQuickParticleAffector
-{
- Q_OBJECT
- Q_PROPERTY(bool relative READ relative WRITE setRelative NOTIFY relativeChanged)
- Q_PROPERTY(QQuickDirection *position READ position WRITE setPosition NOTIFY positionChanged RESET positionReset)
- Q_PROPERTY(QQuickDirection *speed READ speed WRITE setSpeed NOTIFY speedChanged RESET speedReset)
- Q_PROPERTY(QQuickDirection *acceleration READ acceleration WRITE setAcceleration NOTIFY accelerationChanged RESET accelerationReset)
-
-public:
- explicit QQuickCustomAffector(QQuickItem *parent = 0);
- virtual void affectSystem(qreal dt);
-
- QQuickDirection * position() const
- {
- return m_position;
- }
-
- QQuickDirection * speed() const
- {
- return m_speed;
- }
-
- QQuickDirection * acceleration() const
- {
- return m_acceleration;
- }
-
- void positionReset()
- {
- m_position = &m_nullVector;
- }
-
- void speedReset()
- {
- m_speed = &m_nullVector;
- }
-
- void accelerationReset()
- {
- m_acceleration = &m_nullVector;
- }
-
- bool relative() const
- {
- return m_relative;
- }
-
-
-signals:
- void affectParticles(QDeclarativeV8Handle particles, qreal dt);
-
- void positionChanged(QQuickDirection * arg);
-
- void speedChanged(QQuickDirection * arg);
-
- void accelerationChanged(QQuickDirection * arg);
-
- void relativeChanged(bool arg);
-
-public slots:
- void setPosition(QQuickDirection * arg)
- {
- if (m_position != arg) {
- m_position = arg;
- emit positionChanged(arg);
- }
- }
-
- void setSpeed(QQuickDirection * arg)
- {
- if (m_speed != arg) {
- m_speed = arg;
- emit speedChanged(arg);
- }
- }
-
- void setAcceleration(QQuickDirection * arg)
- {
- if (m_acceleration != arg) {
- m_acceleration = arg;
- emit accelerationChanged(arg);
- }
- }
-
- void setRelative(bool arg)
- {
- if (m_relative != arg) {
- m_relative = arg;
- emit relativeChanged(arg);
- }
- }
-
-protected:
- bool isAffectConnected();
- virtual bool affectParticle(QQuickParticleData *d, qreal dt);
-private:
- void affectProperties(const QList<QQuickParticleData*> particles, qreal dt);
- QQuickDirection * m_position;
- QQuickDirection * m_speed;
- QQuickDirection * m_acceleration;
-
- QQuickDirection m_nullVector;
- bool m_relative;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // CUSTOMAFFECTOR_H
diff --git a/src/declarative/particles/qquickcustomparticle.cpp b/src/declarative/particles/qquickcustomparticle.cpp
deleted file mode 100644
index 153dd273b6..0000000000
--- a/src/declarative/particles/qquickcustomparticle.cpp
+++ /dev/null
@@ -1,596 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickcustomparticle_p.h"
-#include <private/qquickshadereffectmesh_p.h>
-#include <cstdlib>
-
-QT_BEGIN_NAMESPACE
-
-//Includes comments because the code isn't self explanatory
-static const char qt_particles_template_vertex_code[] =
- "attribute highp vec2 qt_ParticlePos;\n"
- "attribute highp vec2 qt_ParticleTex;\n"
- "attribute highp vec4 qt_ParticleData; // x = time, y = lifeSpan, z = size, w = endSize\n"
- "attribute highp vec4 qt_ParticleVec; // x,y = constant speed, z,w = acceleration\n"
- "attribute highp float qt_ParticleR;\n"
- "uniform highp mat4 qt_Matrix;\n"
- "uniform highp float qt_Timestamp;\n"
- "varying highp vec2 qt_TexCoord0;\n"
- "void defaultMain() {\n"
- " qt_TexCoord0 = qt_ParticleTex;\n"
- " highp float size = qt_ParticleData.z;\n"
- " highp float endSize = qt_ParticleData.w;\n"
- " highp float t = (qt_Timestamp - qt_ParticleData.x) / qt_ParticleData.y;\n"
- " highp float currentSize = mix(size, endSize, t * t);\n"
- " if (t < 0. || t > 1.)\n"
- " currentSize = 0.;\n"
- " highp vec2 pos = qt_ParticlePos\n"
- " - currentSize / 2. + currentSize * qt_ParticleTex // adjust size\n"
- " + qt_ParticleVec.xy * t * qt_ParticleData.y // apply speed vector..\n"
- " + 0.5 * qt_ParticleVec.zw * pow(t * qt_ParticleData.y, 2.);\n"
- " gl_Position = qt_Matrix * vec4(pos.x, pos.y, 0, 1);\n"
- "}";
-static const char qt_particles_default_vertex_code[] =
- "void main() { \n"
- " defaultMain(); \n"
- "}";
-
-static const char qt_particles_default_fragment_code[] =
- "uniform sampler2D source; \n"
- "varying highp vec2 qt_TexCoord0; \n"
- "uniform lowp float qt_Opacity; \n"
- "void main() { \n"
- " gl_FragColor = texture2D(source, qt_TexCoord0) * qt_Opacity; \n"
- "}";
-
-static QSGGeometry::Attribute PlainParticle_Attributes[] = {
- QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true), // Position
- QSGGeometry::Attribute::create(1, 2, GL_FLOAT), // TexCoord
- QSGGeometry::Attribute::create(2, 4, GL_FLOAT), // Data
- QSGGeometry::Attribute::create(3, 4, GL_FLOAT), // Vectors
- QSGGeometry::Attribute::create(4, 1, GL_FLOAT) // r
-};
-
-static QSGGeometry::AttributeSet PlainParticle_AttributeSet =
-{
- 5, // Attribute Count
- (2 + 2 + 4 + 4 + 1) * sizeof(float),
- PlainParticle_Attributes
-};
-
-struct PlainVertex {
- float x;
- float y;
- float tx;
- float ty;
- float t;
- float lifeSpan;
- float size;
- float endSize;
- float vx;
- float vy;
- float ax;
- float ay;
- float r;
-};
-
-struct PlainVertices {
- PlainVertex v1;
- PlainVertex v2;
- PlainVertex v3;
- PlainVertex v4;
-};
-
-/*!
- \qmlclass CustomParticle QQuickCustomParticle
- \inqmlmodule QtQuick.Particles 2
- \inherits ParticlePainter
- \brief The CustomParticle element allows you to specify your own shader to paint particles.
-
-*/
-
-QQuickCustomParticle::QQuickCustomParticle(QQuickItem* parent)
- : QQuickParticlePainter(parent)
- , m_dirtyData(true)
- , m_material(0)
- , m_rootNode(0)
-{
- setFlag(QQuickItem::ItemHasContents);
-}
-
-class QQuickShaderEffectMaterialObject : public QObject, public QQuickShaderEffectMaterial { };
-
-QQuickCustomParticle::~QQuickCustomParticle()
-{
- if (m_material)
- m_material->deleteLater();
-}
-
-void QQuickCustomParticle::componentComplete()
-{
- reset();
- QQuickParticlePainter::componentComplete();
-}
-
-
-//Trying to keep the shader conventions the same as in qsgshadereffectitem
-/*!
- \qmlproperty string QtQuick.Particles2::CustomParticle::fragmentShader
-
- This property holds the fragment shader's GLSL source code.
- The default shader expects the texture coordinate to be passed from the
- vertex shader as "varying highp vec2 qt_TexCoord0", and it samples from a
- sampler2D named "source".
-*/
-
-void QQuickCustomParticle::setFragmentShader(const QByteArray &code)
-{
- if (m_source.fragmentCode.constData() == code.constData())
- return;
- m_source.fragmentCode = code;
- if (isComponentComplete()) {
- reset();
- }
- emit fragmentShaderChanged();
-}
-
-/*!
- \qmlproperty string QtQuick.Particles2::CustomParticle::vertexShader
-
- This property holds the vertex shader's GLSL source code.
-
- The default shader passes the texture coordinate along to the fragment
- shader as "varying highp vec2 qt_TexCoord0".
-
- To aid writing a particle vertex shader, the following GLSL code is prepended
- to your vertex shader:
- \code
- attribute highp vec2 qt_ParticlePos;
- attribute highp vec2 qt_ParticleTex;
- attribute highp vec4 qt_ParticleData; // x = time, y = lifeSpan, z = size, w = endSize
- attribute highp vec4 qt_ParticleVec; // x,y = constant speed, z,w = acceleration
- attribute highp float qt_ParticleR;
- uniform highp mat4 qt_Matrix;
- uniform highp float qt_Timestamp;
- varying highp vec2 qt_TexCoord0;
- void defaultMain() {
- qt_TexCoord0 = qt_ParticleTex;
- highp float size = qt_ParticleData.z;
- highp float endSize = qt_ParticleData.w;
- highp float t = (qt_Timestamp - qt_ParticleData.x) / qt_ParticleData.y;
- highp float currentSize = mix(size, endSize, t * t);
- if (t < 0. || t > 1.)
- currentSize = 0.;
- highp vec2 pos = qt_ParticlePos
- - currentSize / 2. + currentSize * qt_ParticleTex // adjust size
- + qt_ParticleVec.xy * t * qt_ParticleData.y // apply speed vector..
- + 0.5 * qt_ParticleVec.zw * pow(t * qt_ParticleData.y, 2.);
- gl_Position = qt_Matrix * vec4(pos.x, pos.y, 0, 1);
- }
- \endcode
-
- defaultMain() is the same code as in the default shader, you can call this for basic
- particle functions and then add additional variables for custom effects. Note that
- the vertex shader for particles is responsible for simulating the movement of particles
- over time, the particle data itself only has the starting position and spawn time.
-*/
-
-void QQuickCustomParticle::setVertexShader(const QByteArray &code)
-{
- if (m_source.vertexCode.constData() == code.constData())
- return;
- m_source.vertexCode = code;
- if (isComponentComplete()) {
- reset();
- }
- emit vertexShaderChanged();
-}
-
-void QQuickCustomParticle::reset()
-{
- disconnectPropertySignals();
-
- m_source.attributeNames.clear();
- m_source.uniformNames.clear();
- m_source.respectsOpacity = false;
- m_source.respectsMatrix = false;
- m_source.className = metaObject()->className();
-
- for (int i = 0; i < m_sources.size(); ++i) {
- const SourceData &source = m_sources.at(i);
- delete source.mapper;
- if (source.item && source.item->parentItem() == this)
- source.item->setParentItem(0);
- }
- m_sources.clear();
-
- QQuickParticlePainter::reset();
- m_pleaseReset = true;
- update();
-}
-
-
-void QQuickCustomParticle::changeSource(int index)
-{
- Q_ASSERT(index >= 0 && index < m_sources.size());
- QVariant v = property(m_sources.at(index).name.constData());
- setSource(v, index);
-}
-
-void QQuickCustomParticle::updateData()
-{
- m_dirtyData = true;
- update();
-}
-
-void QQuickCustomParticle::setSource(const QVariant &var, int index)
-{
- Q_ASSERT(index >= 0 && index < m_sources.size());
-
- SourceData &source = m_sources[index];
-
- source.item = 0;
- if (var.isNull()) {
- return;
- } else if (!qVariantCanConvert<QObject *>(var)) {
- qWarning("Could not assign source of type '%s' to property '%s'.", var.typeName(), source.name.constData());
- return;
- }
-
- QObject *obj = qVariantValue<QObject *>(var);
- source.item = qobject_cast<QQuickItem *>(obj);
- if (!source.item || !source.item->isTextureProvider()) {
- qWarning("ShaderEffect: source uniform [%s] is not assigned a valid texture provider: %s [%s]",
- source.name.constData(), qPrintable(obj->objectName()), obj->metaObject()->className());
- return;
- }
-
- // TODO: Copy better solution in QQuickShaderEffect when they find it.
- // 'source.item' needs a canvas to get a scenegraph node.
- // The easiest way to make sure it gets a canvas is to
- // make it a part of the same item tree as 'this'.
- if (source.item && source.item->parentItem() == 0) {
- source.item->setParentItem(this);
- source.item->setVisible(false);
- }
-}
-
-void QQuickCustomParticle::disconnectPropertySignals()
-{
- disconnect(this, 0, this, SLOT(updateData()));
- for (int i = 0; i < m_sources.size(); ++i) {
- SourceData &source = m_sources[i];
- disconnect(this, 0, source.mapper, 0);
- disconnect(source.mapper, 0, this, 0);
- }
-}
-
-void QQuickCustomParticle::connectPropertySignals()
-{
- QSet<QByteArray>::const_iterator it;
- for (it = m_source.uniformNames.begin(); it != m_source.uniformNames.end(); ++it) {
- int pi = metaObject()->indexOfProperty(it->constData());
- if (pi >= 0) {
- QMetaProperty mp = metaObject()->property(pi);
- if (!mp.hasNotifySignal())
- qWarning("QQuickCustomParticle: property '%s' does not have notification method!", it->constData());
- QByteArray signalName("2");
- signalName.append(mp.notifySignal().signature());
- connect(this, signalName, this, SLOT(updateData()));
- } else {
- qWarning("QQuickCustomParticle: '%s' does not have a matching property!", it->constData());
- }
- }
- for (int i = 0; i < m_sources.size(); ++i) {
- SourceData &source = m_sources[i];
- int pi = metaObject()->indexOfProperty(source.name.constData());
- if (pi >= 0) {
- QMetaProperty mp = metaObject()->property(pi);
- QByteArray signalName("2");
- signalName.append(mp.notifySignal().signature());
- connect(this, signalName, source.mapper, SLOT(map()));
- source.mapper->setMapping(this, i);
- connect(source.mapper, SIGNAL(mapped(int)), this, SLOT(changeSource(int)));
- } else {
- qWarning("QQuickCustomParticle: '%s' does not have a matching source!", source.name.constData());
- }
- }
-}
-
-void QQuickCustomParticle::updateProperties()
-{
- QByteArray vertexCode = m_source.vertexCode;
- QByteArray fragmentCode = m_source.fragmentCode;
- if (vertexCode.isEmpty())
- vertexCode = qt_particles_default_vertex_code;
- if (fragmentCode.isEmpty())
- fragmentCode = qt_particles_default_fragment_code;
- vertexCode = qt_particles_template_vertex_code + vertexCode;
-
- m_source.attributeNames.clear();
- m_source.attributeNames << "qt_ParticlePos"
- << "qt_ParticleTex"
- << "qt_ParticleData"
- << "qt_ParticleVec"
- << "qt_ParticleR";
-
- lookThroughShaderCode(vertexCode);
- lookThroughShaderCode(fragmentCode);
-
- if (!m_source.respectsMatrix)
- qWarning("QQuickCustomParticle: Missing reference to \'qt_Matrix\'.");
- if (!m_source.respectsOpacity)
- qWarning("QQuickCustomParticle: Missing reference to \'qt_Opacity\'.");
-
- for (int i = 0; i < m_sources.size(); ++i) {
- QVariant v = property(m_sources.at(i).name);
- setSource(v, i);
- }
-
- connectPropertySignals();
-}
-
-void QQuickCustomParticle::lookThroughShaderCode(const QByteArray &code)
-{
- // Regexp for matching attributes and uniforms.
- // In human readable form: attribute|uniform [lowp|mediump|highp] <type> <name>
- static QRegExp re(QLatin1String("\\b(attribute|uniform)\\b\\s*\\b(?:lowp|mediump|highp)?\\b\\s*\\b(\\w+)\\b\\s*\\b(\\w+)"));
- Q_ASSERT(re.isValid());
-
- int pos = -1;
-
- QString wideCode = QString::fromLatin1(code.constData(), code.size());
-
- while ((pos = re.indexIn(wideCode, pos + 1)) != -1) {
- QByteArray decl = re.cap(1).toLatin1(); // uniform or attribute
- QByteArray type = re.cap(2).toLatin1(); // type
- QByteArray name = re.cap(3).toLatin1(); // variable name
-
- if (decl == "attribute") {
- if (!m_source.attributeNames.contains(name))
- qWarning() << "Custom Particle: Unknown attribute " << name;
- } else {
- Q_ASSERT(decl == "uniform");//TODO: Shouldn't assert
-
- if (name == "qt_Matrix") {
- m_source.respectsMatrix = true;
- } else if (name == "qt_Opacity") {
- m_source.respectsOpacity = true;
- } else if (name == "qt_Timestamp") {
- //Not strictly necessary
- } else {
- m_source.uniformNames.insert(name);
- if (type == "sampler2D") {
- SourceData d;
- d.mapper = new QSignalMapper;
- d.name = name;
- d.item = 0;
- m_sources.append(d);
- }
- }
- }
- }
-}
-
-QSGNode *QQuickCustomParticle::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
-{
- Q_UNUSED(oldNode);
- if (m_pleaseReset){
-
- //delete m_material;//Shader effect item doesn't regen material?
-
- delete m_rootNode;//Automatically deletes children
- m_rootNode = 0;
- m_nodes.clear();
- m_pleaseReset = false;
- m_dirtyData = false;
- }
-
- if (m_system && m_system->isRunning() && !m_system->isPaused()){
- prepareNextFrame();
- if (m_rootNode) {
- update();
- foreach (QSGGeometryNode* node, m_nodes)
- node->markDirty(QSGNode::DirtyGeometry);//done in buildData?
- }
- }
-
- return m_rootNode;
-}
-
-void QQuickCustomParticle::prepareNextFrame(){
- if (!m_rootNode)
- m_rootNode = buildCustomNodes();
- if (!m_rootNode)
- return;
-
- m_lastTime = m_system->systemSync(this) / 1000.;
- if (m_dirtyData || true)//Currently this is how we update timestamp... potentially over expensive.
- buildData();
-}
-
-QQuickShaderEffectNode* QQuickCustomParticle::buildCustomNodes()
-{
-#ifdef QT_OPENGL_ES_2
- if (m_count * 4 > 0xffff) {
- printf("CustomParticle: Too many particles... \n");
- return 0;
- }
-#endif
-
- if (m_count <= 0) {
- printf("CustomParticle: Too few particles... \n");
- return 0;
- }
-
- updateProperties();
-
- QQuickShaderEffectProgram s = m_source;
- if (s.fragmentCode.isEmpty())
- s.fragmentCode = qt_particles_default_fragment_code;
- if (s.vertexCode.isEmpty())
- s.vertexCode = qt_particles_default_vertex_code;
-
- if (!m_material) {
- m_material = new QQuickShaderEffectMaterialObject;
- }
-
- s.vertexCode = qt_particles_template_vertex_code + s.vertexCode;
- m_material->setProgramSource(s);
- foreach (const QString &str, m_groups){
- int gIdx = m_system->groupIds[str];
- int count = m_system->groupData[gIdx]->size();
-
- QQuickShaderEffectNode* node = new QQuickShaderEffectNode();
- m_nodes.insert(gIdx, node);
-
- node->setMaterial(m_material);
- node->markDirty(QSGNode::DirtyMaterial);
-
- //Create Particle Geometry
- int vCount = count * 4;
- int iCount = count * 6;
- QSGGeometry *g = new QSGGeometry(PlainParticle_AttributeSet, vCount, iCount);
- g->setDrawingMode(GL_TRIANGLES);
- node->setGeometry(g);
- PlainVertex *vertices = (PlainVertex *) g->vertexData();
- for (int p=0; p < count; ++p) {
- commit(gIdx, p);
- vertices[0].tx = 0;
- vertices[0].ty = 0;
-
- vertices[1].tx = 1;
- vertices[1].ty = 0;
-
- vertices[2].tx = 0;
- vertices[2].ty = 1;
-
- vertices[3].tx = 1;
- vertices[3].ty = 1;
- vertices += 4;
- }
- quint16 *indices = g->indexDataAsUShort();
- for (int i=0; i < count; ++i) {
- int o = i * 4;
- indices[0] = o;
- indices[1] = o + 1;
- indices[2] = o + 2;
- indices[3] = o + 1;
- indices[4] = o + 3;
- indices[5] = o + 2;
- indices += 6;
- }
- }
- foreach (QQuickShaderEffectNode* node, m_nodes){
- if (node == *(m_nodes.begin()))
- continue;
- (*(m_nodes.begin()))->appendChildNode(node);
- }
-
- return *(m_nodes.begin());
-}
-
-
-void QQuickCustomParticle::buildData()
-{
- if (!m_rootNode)
- return;
- const QByteArray timestampName("qt_Timestamp");
- QVector<QPair<QByteArray, QVariant> > values;
- QVector<QPair<QByteArray, QSGTextureProvider *> > textures;
- const QVector<QPair<QByteArray, QSGTextureProvider *> > &oldTextures = m_material->textureProviders();
- for (int i = 0; i < oldTextures.size(); ++i) {
- QSGTextureProvider *t = oldTextures.at(i).second;
- if (t)
- foreach (QQuickShaderEffectNode* node, m_nodes)
- disconnect(t, SIGNAL(textureChanged()), node, SLOT(markDirtyTexture()));
- }
- for (int i = 0; i < m_sources.size(); ++i) {
- const SourceData &source = m_sources.at(i);
- QSGTextureProvider *t = source.item->textureProvider();
- textures.append(qMakePair(source.name, t));
- if (t)
- foreach (QQuickShaderEffectNode* node, m_nodes)
- connect(t, SIGNAL(textureChanged()), node, SLOT(markDirtyTexture()), Qt::DirectConnection);
- }
- for (QSet<QByteArray>::const_iterator it = m_source.uniformNames.begin();
- it != m_source.uniformNames.end(); ++it) {
- values.append(qMakePair(*it, property(*it)));
- }
- values.append(qMakePair(timestampName, QVariant(m_lastTime)));
- m_material->setUniforms(values);
- m_material->setTextureProviders(textures);
- m_dirtyData = false;
- foreach (QQuickShaderEffectNode* node, m_nodes)
- node->markDirty(QSGNode::DirtyMaterial);
-}
-
-void QQuickCustomParticle::initialize(int gIdx, int pIdx)
-{
- QQuickParticleData* datum = m_system->groupData[gIdx]->data[pIdx];
- datum->r = rand()/(qreal)RAND_MAX;
-}
-
-void QQuickCustomParticle::commit(int gIdx, int pIdx)
-{
- if (m_nodes[gIdx] == 0)
- return;
-
- QQuickParticleData* datum = m_system->groupData[gIdx]->data[pIdx];
- PlainVertices *particles = (PlainVertices *) m_nodes[gIdx]->geometry()->vertexData();
- PlainVertex *vertices = (PlainVertex *)&particles[pIdx];
- for (int i=0; i<4; ++i) {
- vertices[i].x = datum->x - m_systemOffset.x();
- vertices[i].y = datum->y - m_systemOffset.y();
- vertices[i].t = datum->t;
- vertices[i].lifeSpan = datum->lifeSpan;
- vertices[i].size = datum->size;
- vertices[i].endSize = datum->endSize;
- vertices[i].vx = datum->vx;
- vertices[i].vy = datum->vy;
- vertices[i].ax = datum->ax;
- vertices[i].ay = datum->ay;
- vertices[i].r = datum->r;
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickcustomparticle_p.h b/src/declarative/particles/qquickcustomparticle_p.h
deleted file mode 100644
index b3cf6d3e42..0000000000
--- a/src/declarative/particles/qquickcustomparticle_p.h
+++ /dev/null
@@ -1,121 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CUSTOM_PARTICLE_H
-#define CUSTOM_PARTICLE_H
-#include "qquickparticlepainter_p.h"
-#include <private/qquickshadereffectnode_p.h>
-#include <QSignalMapper>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGNode;
-struct PlainVertices;
-
-class QQuickShaderEffectMaterialObject;
-
-//Genealogy: Hybrid of UltraParticle and ShaderEffect
-class QQuickCustomParticle : public QQuickParticlePainter
-{
- Q_OBJECT
- Q_PROPERTY(QByteArray fragmentShader READ fragmentShader WRITE setFragmentShader NOTIFY fragmentShaderChanged)
- Q_PROPERTY(QByteArray vertexShader READ vertexShader WRITE setVertexShader NOTIFY vertexShaderChanged)
-
-public:
- explicit QQuickCustomParticle(QQuickItem* parent=0);
- ~QQuickCustomParticle();
-
- QByteArray fragmentShader() const { return m_source.fragmentCode; }
- void setFragmentShader(const QByteArray &code);
-
- QByteArray vertexShader() const { return m_source.vertexCode; }
- void setVertexShader(const QByteArray &code);
-public Q_SLOTS:
- void updateData();
- void changeSource(int);
-Q_SIGNALS:
- void fragmentShaderChanged();
- void vertexShaderChanged();
-protected:
- virtual void initialize(int gIdx, int pIdx);
- virtual void commit(int gIdx, int pIdx);
-
- QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
- void prepareNextFrame();
- void setSource(const QVariant &var, int index);
- void disconnectPropertySignals();
- void connectPropertySignals();
- void reset();
- void resize(int oldCount, int newCount);
- void updateProperties();
- void lookThroughShaderCode(const QByteArray &code);
- virtual void componentComplete();
- QQuickShaderEffectNode *buildCustomNodes();
- void performPendingResize();
-
-private:
- void buildData();
-
- bool m_dirtyData;
- QQuickShaderEffectProgram m_source;
- struct SourceData
- {
- QSignalMapper *mapper;
- QPointer<QQuickItem> item;
- QByteArray name;
- };
- QVector<SourceData> m_sources;
- QQuickShaderEffectMaterialObject *m_material;
- QQuickShaderEffectNode* m_rootNode;
- QHash<int, QQuickShaderEffectNode*> m_nodes;
- qreal m_lastTime;
-
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif //HEADER_GUARD
diff --git a/src/declarative/particles/qquickdirection.cpp b/src/declarative/particles/qquickdirection.cpp
deleted file mode 100644
index babd35de9f..0000000000
--- a/src/declarative/particles/qquickdirection.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickdirection_p.h"
-
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass Direction QQuickDirection
- \inqmlmodule QtQuick.Particles 2
- \brief The Direction elements allow you to specify a vector space.
-
-*/
-
-
-QQuickDirection::QQuickDirection(QObject *parent) :
- QObject(parent)
-{
-}
-
-const QPointF QQuickDirection::sample(const QPointF &from)
-{
- Q_UNUSED(from);
- return QPointF();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickdirection_p.h b/src/declarative/particles/qquickdirection_p.h
deleted file mode 100644
index ac2ecdf9c1..0000000000
--- a/src/declarative/particles/qquickdirection_p.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef VARYINGVECTOR_H
-#define VARYINGVECTOR_H
-
-#include <QObject>
-#include <QPointF>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QQuickDirection : public QObject
-{
- Q_OBJECT
-public:
- explicit QQuickDirection(QObject *parent = 0);
-
- virtual const QPointF sample(const QPointF &from);
-signals:
-
-public slots:
-
-protected:
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // VARYINGVECTOR_H
diff --git a/src/declarative/particles/qquickellipseextruder.cpp b/src/declarative/particles/qquickellipseextruder.cpp
deleted file mode 100644
index 479bbb4aa7..0000000000
--- a/src/declarative/particles/qquickellipseextruder.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickellipseextruder_p.h"
-#include <cmath>
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass EllipseShape QQuickEllipseExtruder
- \inqmlmodule QtQuick.Particles 2
- \inherits Shape
- \brief The EllipseShape represents an ellipse to other particle system elements
-
- This shape can be used by Emitter subclasses and Affector subclasses to have
- them act upon an ellipse shaped area.
-*/
-QQuickEllipseExtruder::QQuickEllipseExtruder(QObject *parent) :
- QQuickParticleExtruder(parent)
- , m_fill(true)
-{
-}
-
-/*!
- \qmlproperty bool QtQuick.Particles2::EllipseShape::fill
- If fill is true the ellipse is filled; otherwise it is just a border.
-
- Default is true.
-*/
-
-QPointF QQuickEllipseExtruder::extrude(const QRectF & r)
-{
- qreal theta = ((qreal)rand()/RAND_MAX) * 6.2831853071795862;
- qreal mag = m_fill ? ((qreal)rand()/RAND_MAX) : 1;
- return QPointF(r.x() + r.width()/2 + mag * (r.width()/2) * cos(theta),
- r.y() + r.height()/2 + mag * (r.height()/2) * sin(theta));
-}
-
-bool QQuickEllipseExtruder::contains(const QRectF &bounds, const QPointF &point)
-{
- return bounds.contains(point);//TODO: Ellipse
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickellipseextruder_p.h b/src/declarative/particles/qquickellipseextruder_p.h
deleted file mode 100644
index 08e7e73d18..0000000000
--- a/src/declarative/particles/qquickellipseextruder_p.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ELLIPSEEXTRUDER_H
-#define ELLIPSEEXTRUDER_H
-#include "qquickparticleextruder_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QQuickEllipseExtruder : public QQuickParticleExtruder
-{
- Q_OBJECT
- Q_PROPERTY(bool fill READ fill WRITE setFill NOTIFY fillChanged)//###Use base class? If it's still box
-public:
- explicit QQuickEllipseExtruder(QObject *parent = 0);
- virtual QPointF extrude(const QRectF &);
- virtual bool contains(const QRectF &bounds, const QPointF &point);
-
- bool fill() const
- {
- return m_fill;
- }
-
-signals:
-
- void fillChanged(bool arg);
-
-public slots:
-
- void setFill(bool arg)
- {
- if (m_fill != arg) {
- m_fill = arg;
- emit fillChanged(arg);
- }
- }
-private:
- bool m_fill;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // ELLIPSEEXTRUDER_H
diff --git a/src/declarative/particles/qquickfriction.cpp b/src/declarative/particles/qquickfriction.cpp
deleted file mode 100644
index c060deb95f..0000000000
--- a/src/declarative/particles/qquickfriction.cpp
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickfriction_p.h"
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass Friction QQuickFrictionAffector
- \inqmlmodule QtQuick.Particles 2
- \inherits Affector
- \brief The Friction affector slows down movement proportional to the particle's current speed.
-
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Friction::factor
-
- A drag will be applied to moving objects which is this factor of their current velocity.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Friction::threshold
-
- The drag will only be applied to objects with a velocity above the threshold velocity. The
- drag applied will bring objects down to the threshold velocity, but no further.
-
- The default threshold is 0
-*/
-static qreal sign(qreal a)
-{
- return a >= 0 ? 1 : -1;
-}
-
-static const qreal epsilon = 0.00001;
-
-QQuickFrictionAffector::QQuickFrictionAffector(QQuickItem *parent) :
- QQuickParticleAffector(parent), m_factor(0.0), m_threshold(0.0)
-{
-}
-
-bool QQuickFrictionAffector::affectParticle(QQuickParticleData *d, qreal dt)
-{
- if (!m_factor)
- return false;
- qreal curVX = d->curVX();
- qreal curVY = d->curVY();
- if (!curVX && !curVY)
- return false;
- qreal newVX = curVX + (curVX * m_factor * -1 * dt);
- qreal newVY = curVY + (curVY * m_factor * -1 * dt);
-
- if (!m_threshold) {
- if (sign(curVX) != sign(newVX))
- newVX = 0;
- if (sign(curVY) != sign(newVY))
- newVY = 0;
- } else {
- qreal curMag = sqrt(curVX*curVX + curVY*curVY);
- if (curMag <= m_threshold + epsilon)
- return false;
- qreal newMag = sqrt(newVX*newVX + newVY*newVY);
- if (newMag <= m_threshold + epsilon || //went past the threshold, stop there instead
- sign(curVX) != sign(newVX) || //went so far past maybe it came out the other side!
- sign(curVY) != sign(newVY)) {
- qreal theta = atan2(curVY, curVX);
- newVX = m_threshold * cos(theta);
- newVY = m_threshold * sin(theta);
- }
- }
-
- d->setInstantaneousVX(newVX);
- d->setInstantaneousVY(newVY);
- return true;
-}
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickfriction_p.h b/src/declarative/particles/qquickfriction_p.h
deleted file mode 100644
index c2f227692c..0000000000
--- a/src/declarative/particles/qquickfriction_p.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef FRICTIONAFFECTOR_H
-#define FRICTIONAFFECTOR_H
-#include "qquickparticleaffector_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QQuickFrictionAffector : public QQuickParticleAffector
-{
- Q_OBJECT
- Q_PROPERTY(qreal factor READ factor WRITE setFactor NOTIFY factorChanged)
- Q_PROPERTY(qreal threshold READ threshold WRITE setThreshold NOTIFY thresholdChanged)
-public:
- explicit QQuickFrictionAffector(QQuickItem *parent = 0);
-
- qreal factor() const
- {
- return m_factor;
- }
-
- qreal threshold() const
- {
- return m_threshold;
- }
-
-protected:
- virtual bool affectParticle(QQuickParticleData *d, qreal dt);
-
-signals:
-
- void factorChanged(qreal arg);
- void thresholdChanged(qreal arg);
-
-public slots:
-
- void setFactor(qreal arg)
- {
- if (m_factor != arg) {
- m_factor = arg;
- emit factorChanged(arg);
- }
- }
-
- void setThreshold(qreal arg)
- {
- if (m_threshold != arg) {
- m_threshold = arg;
- emit thresholdChanged(arg);
- }
- }
-
-private:
- qreal m_factor;
- qreal m_threshold;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // FRICTIONAFFECTOR_H
diff --git a/src/declarative/particles/qquickgravity.cpp b/src/declarative/particles/qquickgravity.cpp
deleted file mode 100644
index fd2fb92a53..0000000000
--- a/src/declarative/particles/qquickgravity.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickgravity_p.h"
-#include <cmath>
-QT_BEGIN_NAMESPACE
-const qreal CONV = 0.017453292520444443;
-/*!
- \qmlclass Gravity QQuickGravityAffector
- \inqmlmodule QtQuick.Particles 2
- \inherits Affector
- \brief The Gravity element allows you to set an accleration in an angle
-
- This element will accelerate all affected particles to a vector of
- the specified magnitude in the specified angle. If the angle and acceleration do
- not vary, it is more efficient to set the specified acceleration on the Emitter.
-
- This element models the gravity of a massive object whose center of
- gravity is far away (and thus the gravitational pull is effectively constant
- across the scene). To model the gravity of an object near or inside the scene,
- use PointAttractor.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Gravity::magnitude
-
- Pixels per second that objects will be accelerated by.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Gravity::acceleration
-
- Name changed to magnitude, will be removed soon.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Gravity::angle
-
- Angle of acceleration.
-*/
-
-QQuickGravityAffector::QQuickGravityAffector(QQuickItem *parent) :
- QQuickParticleAffector(parent), m_magnitude(-10), m_angle(90), m_needRecalc(true)
-{
-}
-
-bool QQuickGravityAffector::affectParticle(QQuickParticleData *d, qreal dt)
-{
- if (!m_magnitude)
- return false;
- if (m_needRecalc) {
- m_needRecalc = false;
- m_dx = m_magnitude * cos(m_angle * CONV);
- m_dy = m_magnitude * sin(m_angle * CONV);
- }
-
- d->setInstantaneousVX(d->curVX() + m_dx*dt);
- d->setInstantaneousVY(d->curVY() + m_dy*dt);
- return true;
-}
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickgravity_p.h b/src/declarative/particles/qquickgravity_p.h
deleted file mode 100644
index 65f8e5a19d..0000000000
--- a/src/declarative/particles/qquickgravity_p.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef GRAVITYAFFECTOR_H
-#define GRAVITYAFFECTOR_H
-#include "qquickparticleaffector_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QQuickGravityAffector : public QQuickParticleAffector
-{
- Q_OBJECT
- Q_PROPERTY(qreal magnitude READ magnitude WRITE setMagnitude NOTIFY magnitudeChanged)
- Q_PROPERTY(qreal acceleration READ magnitude WRITE setAcceleration NOTIFY magnitudeChanged)
- Q_PROPERTY(qreal angle READ angle WRITE setAngle NOTIFY angleChanged)
-public:
- explicit QQuickGravityAffector(QQuickItem *parent = 0);
- qreal magnitude() const
- {
- return m_magnitude;
- }
-
- qreal angle() const
- {
- return m_angle;
- }
-protected:
- virtual bool affectParticle(QQuickParticleData *d, qreal dt);
-signals:
-
- void magnitudeChanged(qreal arg);
-
- void angleChanged(qreal arg);
-
-public slots:
-void setAcceleration(qreal arg)
-{
- qWarning() << "Gravity::acceleration has been renamed Gravity::magnitude";
- if (m_magnitude != arg) {
- m_magnitude = arg;
- m_needRecalc = true;
- emit magnitudeChanged(arg);
- }
-}
-
-void setMagnitude(qreal arg)
-{
- if (m_magnitude != arg) {
- m_magnitude = arg;
- m_needRecalc = true;
- emit magnitudeChanged(arg);
- }
-}
-
-void setAngle(qreal arg)
-{
- if (m_angle != arg) {
- m_angle = arg;
- m_needRecalc = true;
- emit angleChanged(arg);
- }
-}
-
-private:
- qreal m_magnitude;
- qreal m_angle;
-
- bool m_needRecalc;
- qreal m_dx;
- qreal m_dy;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // GRAVITYAFFECTOR_H
diff --git a/src/declarative/particles/qquickgroupgoal.cpp b/src/declarative/particles/qquickgroupgoal.cpp
deleted file mode 100644
index 1d8a3d980c..0000000000
--- a/src/declarative/particles/qquickgroupgoal.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickgroupgoal_p.h"
-#include <private/qquickspriteengine_p.h>
-#include <private/qquicksprite_p.h>
-#include "qquickimageparticle_p.h"
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass GroupGoal QQuickGroupGoalAffector
- \inqmlmodule QtQuick.Particles 2
- \inherits Affector
- \brief The GroupGoal Affector allows you to change the state of a group of a particle.
-
-*/
-/*!
- \qmlproperty string QtQuick.Particles2::GroupGoal::goalState
-
- The name of the group which the affected particles should move to.
-
- Groups can have defined durations and transitions between them, setting goalState
- will cause it to disregard any path weightings (including 0) and head down the path
- which will reach the goalState quickest. It will pass through intermediate groups
- on that path for their respective durations.
-*/
-/*!
- \qmlproperty bool QtQuick.Particles2::GroupGoal::jump
-
- If true, affected particles will jump directly to the target group instead of taking the
- the shortest valid path to get there. They will also not finish their current state,
- but immediately move to the beginning of the goal state.
-
- Default is false.
-*/
-
-QQuickGroupGoalAffector::QQuickGroupGoalAffector(QQuickItem *parent) :
- QQuickParticleAffector(parent), m_jump(false)
-{
- m_ignoresTime = true;
-}
-
-void QQuickGroupGoalAffector::setGoalState(QString arg)
-{
- if (m_goalState != arg) {
- m_goalState = arg;
- emit goalStateChanged(arg);
- }
-}
-
-bool QQuickGroupGoalAffector::affectParticle(QQuickParticleData *d, qreal dt)
-{
- Q_UNUSED(dt);
- QQuickStochasticEngine *engine = m_system->stateEngine;
- bool notUsingEngine = false;
- if (!engine)
- notUsingEngine = true;
-
- int index = d->systemIndex;
- int goalIdx = m_system->groupIds[m_goalState];
- if (notUsingEngine){//no stochastic states defined. So cut out the engine
- //TODO: It's possible to move to a group that is intermediate and not used by painters or emitters - but right now that will redirect to the default group
- m_system->moveGroups(d, goalIdx);
- return true;
- }else if (engine->curState(index) != goalIdx){
- engine->setGoal(goalIdx, index, m_jump);
- return true;
- }
- return false;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickgroupgoal_p.h b/src/declarative/particles/qquickgroupgoal_p.h
deleted file mode 100644
index 51ce1ff24e..0000000000
--- a/src/declarative/particles/qquickgroupgoal_p.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef GROUPGOALAFFECTOR_H
-#define GROUPGOALAFFECTOR_H
-#include "qquickparticleaffector_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickStochasticEngine;
-
-class QQuickGroupGoalAffector : public QQuickParticleAffector
-{
- Q_OBJECT
- Q_PROPERTY(QString goalState READ goalState WRITE setGoalState NOTIFY goalStateChanged)
- Q_PROPERTY(bool jump READ jump WRITE setJump NOTIFY jumpChanged)
-public:
- explicit QQuickGroupGoalAffector(QQuickItem *parent = 0);
-
- QString goalState() const
- {
- return m_goalState;
- }
-
- bool jump() const
- {
- return m_jump;
- }
-
-protected:
- virtual bool affectParticle(QQuickParticleData *d, qreal dt);
-
-signals:
-
- void goalStateChanged(QString arg);
-
- void jumpChanged(bool arg);
-
-public slots:
-
- void setGoalState(QString arg);
-
- void setJump(bool arg)
- {
- if (m_jump != arg) {
- m_jump = arg;
- emit jumpChanged(arg);
- }
- }
-
-private:
- QString m_goalState;
- bool m_jump;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // GROUPGOALAFFECTOR_H
diff --git a/src/declarative/particles/qquickimageparticle.cpp b/src/declarative/particles/qquickimageparticle.cpp
deleted file mode 100644
index 5f31440441..0000000000
--- a/src/declarative/particles/qquickimageparticle.cpp
+++ /dev/null
@@ -1,1803 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <private/qsgcontext_p.h>
-#include <private/qsgadaptationlayer_p.h>
-#include <qsgnode.h>
-#include <qsgtexturematerial.h>
-#include <qsgtexture.h>
-#include <QFile>
-#include "qquickimageparticle_p.h"
-#include "qquickparticleemitter_p.h"
-#include <private/qquicksprite_p.h>
-#include <private/qquickspriteengine_p.h>
-#include <QOpenGLFunctions>
-#include <qsgengine.h>
-#include <private/qsgtexture_p.h>
-
-QT_BEGIN_NAMESPACE
-//###Switch to define later, for now user-friendly (no compilation) debugging is worth it
-DEFINE_BOOL_CONFIG_OPTION(qmlParticlesDebug, QML_PARTICLES_DEBUG)
-
-#ifndef QT_OPENGL_ES_2
-#define SHADER_DEFINES "#version 120\n"
-#else
-#define SHADER_DEFINES ""
-#endif
-
-//TODO: Make it larger on desktop? Requires fixing up shader code with the same define
-#define UNIFORM_ARRAY_SIZE 64
-
-static const char vertexShaderCode[] =
- "attribute highp vec2 vPos;\n"
- "attribute highp vec4 vData; // x = time, y = lifeSpan, z = size, w = endSize\n"
- "attribute highp vec4 vVec; // x,y = constant speed, z,w = acceleration\n"
- "uniform highp float entry;\n"
- "#ifdef COLOR\n"
- "attribute lowp vec4 vColor;\n"
- "#endif\n"
- "#ifdef DEFORM\n"
- "attribute highp vec2 vTex;\n"
- "attribute highp vec4 vDeformVec; //x,y x unit vector; z,w = y unit vector\n"
- "attribute highp vec3 vRotation; //x = radians of rotation, y=rotation speed, z= bool autoRotate\n"
- "#endif\n"
- "#ifdef SPRITE\n"
- "attribute highp vec4 vAnimData;// interpolate(bool), duration, frameCount (this anim), timestamp (this anim)\n"
- "attribute highp vec4 vAnimPos;//sheet x,y, width/height of this anim\n"
- "uniform highp vec2 animSheetSize; //width/height of whole sheet\n"
- "#endif\n"
- "\n"
- "uniform highp mat4 qt_Matrix;\n"
- "uniform highp float timestamp;\n"
- "#ifdef TABLE\n"
- "varying lowp vec2 tt;//y is progress if Sprite mode\n"
- "uniform highp float sizetable[64];\n"
- "uniform highp float opacitytable[64];\n"
- "#endif\n"
- "#ifdef SPRITE\n"
- "varying highp vec4 fTexS;\n"
- "#else\n"
- "#ifdef DEFORM\n"
- "varying highp vec2 fTex;\n"
- "#endif\n"
- "#endif\n"
- "#ifdef COLOR\n"
- "varying lowp vec4 fColor;\n"
- "#else\n"
- "varying lowp float fFade;\n"
- "#endif\n"
- "\n"
- "\n"
- "void main() {\n"
- "\n"
- " highp float t = (timestamp - vData.x) / vData.y;\n"
- " if (t < 0. || t > 1.){\n"
- "#ifdef DEFORM //Not point sprites\n"
- " gl_Position = qt_Matrix * vec4(vPos.x, vPos.y, 0., 1.);\n"
- "#else\n"
- " gl_PointSize = 0.;\n"
- "#endif\n"
- " return;\n"
- " }\n"
- "#ifdef SPRITE\n"
- " //Calculate frame location in texture\n"
- " highp float frameIndex = mod((((timestamp - vAnimData.w)*1000.)/vAnimData.y),vAnimData.z);\n"
- " tt.y = mod((timestamp - vAnimData.w)*1000., vAnimData.y) / vAnimData.y;\n"
- "\n"
- " frameIndex = floor(frameIndex);\n"
- " fTexS.xy = vec2(((frameIndex + vTex.x) * vAnimPos.z / animSheetSize.x), ((vAnimPos.y + vTex.y * vAnimPos.w) / animSheetSize.y));\n"
- "\n"
- " //Next frame is also passed, for interpolation\n"
- " //### Should the next anim be precalculated to allow for interpolation there?\n"
- " if (vAnimData.x == 1.0 && frameIndex != vAnimData.z - 1.)//Can't do it for the last frame though, this anim may not loop\n"
- " frameIndex = mod(frameIndex+1., vAnimData.z);\n"
- " fTexS.zw = vec2(((frameIndex + vTex.x) * vAnimPos.z / animSheetSize.x), ((vAnimPos.y + vTex.y * vAnimPos.w) / animSheetSize.y));\n"
- "#else\n"
- "#ifdef DEFORM\n"
- " fTex = vTex;\n"
- "#endif\n"
- "#endif\n"
- " highp float currentSize = mix(vData.z, vData.w, t * t);\n"
- " lowp float fade = 1.;\n"
- " highp float fadeIn = min(t * 10., 1.);\n"
- " highp float fadeOut = 1. - clamp((t - 0.75) * 4.,0., 1.);\n"
- "\n"
- "#ifdef TABLE\n"
- " currentSize = currentSize * sizetable[int(floor(t*64.))];\n"
- " fade = fade * opacitytable[int(floor(t*64.))];\n"
- "#endif\n"
- "\n"
- " if (entry == 1.)\n"
- " fade = fade * fadeIn * fadeOut;\n"
- " else if (entry == 2.)\n"
- " currentSize = currentSize * fadeIn * fadeOut;\n"
- "\n"
- " if (currentSize <= 0.){\n"
- "#ifdef DEFORM //Not point sprites\n"
- " gl_Position = qt_Matrix * vec4(vPos.x, vPos.y, 0., 1.);\n"
- "#else\n"
- " gl_PointSize = 0.;\n"
- "#endif\n"
- " return;\n"
- " }\n"
- " if (currentSize < 3.)//Sizes too small look jittery as they move\n"
- " currentSize = 3.;\n"
- "\n"
- " highp vec2 pos;\n"
- "#ifdef DEFORM\n"
- " highp float rotation = vRotation.x + vRotation.y * t * vData.y;\n"
- " if (vRotation.z == 1.0){\n"
- " highp vec2 curVel = vVec.zw * t * vData.y + vVec.xy;\n"
- " rotation += atan(curVel.y, curVel.x);\n"
- " }\n"
- " highp vec2 trigCalcs = vec2(cos(rotation), sin(rotation));\n"
- " highp vec4 deform = vDeformVec * currentSize * (vTex.xxyy - 0.5);\n"
- " highp vec4 rotatedDeform = deform.xxzz * trigCalcs.xyxy;\n"
- " rotatedDeform = rotatedDeform + (deform.yyww * trigCalcs.yxyx * vec4(-1.,1.,-1.,1.));\n"
- " /* The readable version:\n"
- " highp vec2 xDeform = vDeformVec.xy * currentSize * (vTex.x-0.5);\n"
- " highp vec2 yDeform = vDeformVec.zw * currentSize * (vTex.y-0.5);\n"
- " highp vec2 xRotatedDeform;\n"
- " xRotatedDeform.x = trigCalcs.x*xDeform.x - trigCalcs.y*xDeform.y;\n"
- " xRotatedDeform.y = trigCalcs.y*xDeform.x + trigCalcs.x*xDeform.y;\n"
- " highp vec2 yRotatedDeform;\n"
- " yRotatedDeform.x = trigCalcs.x*yDeform.x - trigCalcs.y*yDeform.y;\n"
- " yRotatedDeform.y = trigCalcs.y*yDeform.x + trigCalcs.x*yDeform.y;\n"
- " */\n"
- " pos = vPos\n"
- " + rotatedDeform.xy\n"
- " + rotatedDeform.zw\n"
- " + vVec.xy * t * vData.y // apply speed\n"
- " + 0.5 * vVec.zw * pow(t * vData.y, 2.); // apply acceleration\n"
- "#else\n"
- " pos = vPos\n"
- " + vVec.xy * t * vData.y // apply speed vector..\n"
- " + 0.5 * vVec.zw * pow(t * vData.y, 2.);\n"
- " gl_PointSize = currentSize;\n"
- "#endif\n"
- " gl_Position = qt_Matrix * vec4(pos.x, pos.y, 0, 1);\n"
- "\n"
- "#ifdef COLOR\n"
- " fColor = vColor * fade;\n"
- "#else\n"
- " fFade = fade;\n"
- "#endif\n"
- "#ifdef TABLE\n"
- " tt.x = t;\n"
- "#endif\n"
- "}\n";
-
-static const char fragmentShaderCode[] =
- "uniform sampler2D texture;\n"
- "uniform lowp float qt_Opacity;\n"
- "\n"
- "#ifdef SPRITE\n"
- "varying highp vec4 fTexS;\n"
- "#else\n"
- "#ifdef DEFORM //First non-pointsprite\n"
- "varying highp vec2 fTex;\n"
- "#endif\n"
- "#endif\n"
- "#ifdef COLOR\n"
- "varying lowp vec4 fColor;\n"
- "#else\n"
- "varying lowp float fFade;\n"
- "#endif\n"
- "#ifdef TABLE\n"
- "varying lowp vec2 tt;\n"
- "uniform sampler2D colortable;\n"
- "#endif\n"
- "\n"
- "void main() {\n"
- "#ifdef SPRITE\n"
- " gl_FragColor = mix(texture2D(texture, fTexS.xy), texture2D(texture, fTexS.zw), tt.y)\n"
- " * fColor\n"
- " * texture2D(colortable, tt)\n"
- " * qt_Opacity;\n"
- "#else\n"
- "#ifdef TABLE\n"
- " gl_FragColor = texture2D(texture, fTex)\n"
- " * fColor\n"
- " * texture2D(colortable, tt)\n"
- " * qt_Opacity;\n"
- "#else\n"
- "#ifdef DEFORM\n"
- " gl_FragColor = (texture2D(texture, fTex)) * fColor * qt_Opacity;\n"
- "#else\n"
- "#ifdef COLOR\n"
- " gl_FragColor = (texture2D(texture, gl_PointCoord)) * fColor * qt_Opacity;\n"
- "#else\n"
- " gl_FragColor = texture2D(texture, gl_PointCoord) * (fFade * qt_Opacity);\n"
- "#endif //COLOR\n"
- "#endif //DEFORM\n"
- "#endif //TABLE\n"
- "#endif //SPRITE\n"
- "}\n";
-
-const qreal CONV = 0.017453292519943295;
-class ImageMaterialData
-{
- public:
- ImageMaterialData()
- : texture(0), colorTable(0)
- {}
-
- ~ImageMaterialData(){
- delete texture;
- delete colorTable;
- }
-
- QSGTexture *texture;
- QSGTexture *colorTable;
- float sizeTable[UNIFORM_ARRAY_SIZE];
- float opacityTable[UNIFORM_ARRAY_SIZE];
-
- qreal timestamp;
- qreal entry;
- QSizeF animSheetSize;
-};
-
-class TabledMaterialData : public ImageMaterialData {};
-class TabledMaterial : public QSGSimpleMaterialShader<TabledMaterialData>
-{
- QSG_DECLARE_SIMPLE_SHADER(TabledMaterial, TabledMaterialData)
-
-public:
- TabledMaterial()
- {
- m_vertex_code = QByteArray(SHADER_DEFINES)
- + QByteArray("#define TABLE\n#define DEFORM\n#define COLOR\n")
- + vertexShaderCode;
-
- m_fragment_code = QByteArray(SHADER_DEFINES)
- + QByteArray("#define TABLE\n#define DEFORM\n#define COLOR\n")
- + fragmentShaderCode;
-
- Q_ASSERT(!m_vertex_code.isNull());
- Q_ASSERT(!m_fragment_code.isNull());
- }
-
- const char *vertexShader() const { return m_vertex_code.constData(); }
- const char *fragmentShader() const { return m_fragment_code.constData(); }
-
- QList<QByteArray> attributes() const {
- return QList<QByteArray>() << "vPos" << "vTex" << "vData" << "vVec"
- << "vColor" << "vDeformVec" << "vRotation";
- };
-
- void initialize() {
- QSGSimpleMaterialShader<TabledMaterialData>::initialize();
- program()->bind();
- program()->setUniformValue("texture", 0);
- program()->setUniformValue("colortable", 1);
- glFuncs = QOpenGLContext::currentContext()->functions();
- m_timestamp_id = program()->uniformLocation("timestamp");
- m_entry_id = program()->uniformLocation("entry");
- m_sizetable_id = program()->uniformLocation("sizetable");
- m_opacitytable_id = program()->uniformLocation("opacitytable");
- }
-
- void updateState(const TabledMaterialData* d, const TabledMaterialData*) {
- glFuncs->glActiveTexture(GL_TEXTURE1);
- d->colorTable->bind();
-
- glFuncs->glActiveTexture(GL_TEXTURE0);
- d->texture->bind();
-
- program()->setUniformValue(m_timestamp_id, (float) d->timestamp);
- program()->setUniformValue(m_entry_id, (float) d->entry);
- program()->setUniformValueArray(m_sizetable_id, (float*) d->sizeTable, UNIFORM_ARRAY_SIZE, 1);
- program()->setUniformValueArray(m_opacitytable_id, (float*) d->opacityTable, UNIFORM_ARRAY_SIZE, 1);
- }
-
- int m_entry_id;
- int m_timestamp_id;
- int m_sizetable_id;
- int m_opacitytable_id;
- QByteArray m_vertex_code;
- QByteArray m_fragment_code;
- QOpenGLFunctions* glFuncs;
-};
-
-class DeformableMaterialData : public ImageMaterialData {};
-class DeformableMaterial : public QSGSimpleMaterialShader<DeformableMaterialData>
-{
- QSG_DECLARE_SIMPLE_SHADER(DeformableMaterial, DeformableMaterialData)
-
-public:
- DeformableMaterial()
- {
- m_vertex_code = QByteArray(SHADER_DEFINES)
- + QByteArray("#define DEFORM\n#define COLOR\n")
- + vertexShaderCode;
-
- m_fragment_code = QByteArray(SHADER_DEFINES)
- + QByteArray("#define DEFORM\n#define COLOR\n")
- + fragmentShaderCode;
-
- Q_ASSERT(!m_vertex_code.isNull());
- Q_ASSERT(!m_fragment_code.isNull());
- }
-
- const char *vertexShader() const { return m_vertex_code.constData(); }
- const char *fragmentShader() const { return m_fragment_code.constData(); }
-
- QList<QByteArray> attributes() const {
- return QList<QByteArray>() << "vPos" << "vTex" << "vData" << "vVec"
- << "vColor" << "vDeformVec" << "vRotation";
- };
-
- void initialize() {
- QSGSimpleMaterialShader<DeformableMaterialData>::initialize();
- program()->bind();
- program()->setUniformValue("texture", 0);
- glFuncs = QOpenGLContext::currentContext()->functions();
- m_timestamp_id = program()->uniformLocation("timestamp");
- m_entry_id = program()->uniformLocation("entry");
- }
-
- void updateState(const DeformableMaterialData* d, const DeformableMaterialData*) {
- glFuncs->glActiveTexture(GL_TEXTURE0);
- d->texture->bind();
-
- program()->setUniformValue(m_timestamp_id, (float) d->timestamp);
- program()->setUniformValue(m_entry_id, (float) d->entry);
- }
-
- int m_entry_id;
- int m_timestamp_id;
- QByteArray m_vertex_code;
- QByteArray m_fragment_code;
- QOpenGLFunctions* glFuncs;
-};
-
-class SpriteMaterialData : public ImageMaterialData {};
-class SpriteMaterial : public QSGSimpleMaterialShader<SpriteMaterialData>
-{
- QSG_DECLARE_SIMPLE_SHADER(SpriteMaterial, SpriteMaterialData)
-
-public:
- SpriteMaterial()
- {
- m_vertex_code = QByteArray(SHADER_DEFINES)
- + QByteArray("#define SPRITE\n#define TABLE\n#define DEFORM\n#define COLOR\n")
- + vertexShaderCode;
-
- m_fragment_code = QByteArray(SHADER_DEFINES)
- + QByteArray("#define SPRITE\n#define TABLE\n#define DEFORM\n#define COLOR\n")
- + fragmentShaderCode;
-
- Q_ASSERT(!m_vertex_code.isNull());
- Q_ASSERT(!m_fragment_code.isNull());
- }
-
- const char *vertexShader() const { return m_vertex_code.constData(); }
- const char *fragmentShader() const { return m_fragment_code.constData(); }
-
- QList<QByteArray> attributes() const {
- return QList<QByteArray>() << "vPos" << "vTex" << "vData" << "vVec"
- << "vColor" << "vDeformVec" << "vRotation" << "vAnimData" << "vAnimPos";
- };
-
- void initialize() {
- QSGSimpleMaterialShader<SpriteMaterialData>::initialize();
- program()->bind();
- program()->setUniformValue("texture", 0);
- program()->setUniformValue("colortable", 1);
- glFuncs = QOpenGLContext::currentContext()->functions();
- m_timestamp_id = program()->uniformLocation("timestamp");
- m_animsize_id = program()->uniformLocation("animSheetSize");
- m_entry_id = program()->uniformLocation("entry");
- m_sizetable_id = program()->uniformLocation("sizetable");
- m_opacitytable_id = program()->uniformLocation("opacitytable");
- }
-
- void updateState(const SpriteMaterialData* d, const SpriteMaterialData*) {
- glFuncs->glActiveTexture(GL_TEXTURE1);
- d->colorTable->bind();
-
- // make sure we end by setting GL_TEXTURE0 as active texture
- glFuncs->glActiveTexture(GL_TEXTURE0);
- d->texture->bind();
-
- program()->setUniformValue(m_timestamp_id, (float) d->timestamp);
- program()->setUniformValue(m_animsize_id, d->animSheetSize);
- program()->setUniformValue(m_entry_id, (float) d->entry);
- program()->setUniformValueArray(m_sizetable_id, (float*) d->sizeTable, 64, 1);
- program()->setUniformValueArray(m_opacitytable_id, (float*) d->opacityTable, UNIFORM_ARRAY_SIZE, 1);
- }
-
- int m_timestamp_id;
- int m_animsize_id;
- int m_entry_id;
- int m_sizetable_id;
- int m_opacitytable_id;
- QByteArray m_vertex_code;
- QByteArray m_fragment_code;
- QOpenGLFunctions* glFuncs;
-};
-
-class ColoredMaterialData : public ImageMaterialData {};
-class ColoredMaterial : public QSGSimpleMaterialShader<ColoredMaterialData>
-{
- QSG_DECLARE_SIMPLE_SHADER(ColoredMaterial, ColoredMaterialData)
-
-public:
- ColoredMaterial()
- {
- m_vertex_code = QByteArray(SHADER_DEFINES)
- + QByteArray("#define COLOR\n")
- + vertexShaderCode;
-
- m_fragment_code = QByteArray(SHADER_DEFINES)
- + QByteArray("#define COLOR\n")
- + fragmentShaderCode;
-
- Q_ASSERT(!m_vertex_code.isNull());
- Q_ASSERT(!m_fragment_code.isNull());
- }
-
- const char *vertexShader() const { return m_vertex_code.constData(); }
- const char *fragmentShader() const { return m_fragment_code.constData(); }
-
- void activate() {
- QSGSimpleMaterialShader<ColoredMaterialData>::activate();
-#if !defined(QT_OPENGL_ES_2) && !defined(Q_OS_WIN)
- glEnable(GL_POINT_SPRITE);
- glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
-#endif
- }
-
- void deactivate() {
- QSGSimpleMaterialShader<ColoredMaterialData>::deactivate();
-#if !defined(QT_OPENGL_ES_2) && !defined(Q_OS_WIN)
- glDisable(GL_POINT_SPRITE);
- glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
-#endif
- }
-
- QList<QByteArray> attributes() const {
- return QList<QByteArray>() << "vPos" << "vData" << "vVec" << "vColor";
- }
-
- void initialize() {
- QSGSimpleMaterialShader<ColoredMaterialData>::initialize();
- program()->bind();
- program()->setUniformValue("texture", 0);
- glFuncs = QOpenGLContext::currentContext()->functions();
- m_timestamp_id = program()->uniformLocation("timestamp");
- m_entry_id = program()->uniformLocation("entry");
- }
-
- void updateState(const ColoredMaterialData* d, const ColoredMaterialData*) {
- glFuncs->glActiveTexture(GL_TEXTURE0);
- d->texture->bind();
-
- program()->setUniformValue(m_timestamp_id, (float) d->timestamp);
- program()->setUniformValue(m_entry_id, (float) d->entry);
- }
-
- int m_timestamp_id;
- int m_entry_id;
- QByteArray m_vertex_code;
- QByteArray m_fragment_code;
- QOpenGLFunctions* glFuncs;
-};
-
-class SimpleMaterialData : public ImageMaterialData {};
-class SimpleMaterial : public QSGSimpleMaterialShader<SimpleMaterialData>
-{
- QSG_DECLARE_SIMPLE_SHADER(SimpleMaterial, SimpleMaterialData)
-
-public:
- SimpleMaterial()
- {
- m_vertex_code = QByteArray(SHADER_DEFINES)
- + vertexShaderCode;
-
- m_fragment_code = QByteArray(SHADER_DEFINES)
- + fragmentShaderCode;
-
- Q_ASSERT(!m_vertex_code.isNull());
- Q_ASSERT(!m_fragment_code.isNull());
- }
-
- const char *vertexShader() const { return m_vertex_code.constData(); }
- const char *fragmentShader() const { return m_fragment_code.constData(); }
-
- void activate() {
- QSGSimpleMaterialShader<SimpleMaterialData>::activate();
-#if !defined(QT_OPENGL_ES_2) && !defined(Q_OS_WIN)
- glEnable(GL_POINT_SPRITE);
- glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
-#endif
- }
-
- void deactivate() {
- QSGSimpleMaterialShader<SimpleMaterialData>::deactivate();
-#if !defined(QT_OPENGL_ES_2) && !defined(Q_OS_WIN)
- glDisable(GL_POINT_SPRITE);
- glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
-#endif
- }
-
- QList<QByteArray> attributes() const {
- return QList<QByteArray>() << "vPos" << "vData" << "vVec";
- }
-
- void initialize() {
- QSGSimpleMaterialShader<SimpleMaterialData>::initialize();
- program()->bind();
- program()->setUniformValue("texture", 0);
- glFuncs = QOpenGLContext::currentContext()->functions();
- m_timestamp_id = program()->uniformLocation("timestamp");
- m_entry_id = program()->uniformLocation("entry");
- }
-
- void updateState(const SimpleMaterialData* d, const SimpleMaterialData*) {
- glFuncs->glActiveTexture(GL_TEXTURE0);
- d->texture->bind();
-
- program()->setUniformValue(m_timestamp_id, (float) d->timestamp);
- program()->setUniformValue(m_entry_id, (float) d->entry);
- }
-
- int m_timestamp_id;
- int m_entry_id;
- QByteArray m_vertex_code;
- QByteArray m_fragment_code;
- QOpenGLFunctions* glFuncs;
-};
-
-void fillUniformArrayFromImage(float* array, const QImage& img, int size)
-{
- if (img.isNull()){
- for (int i=0; i<size; i++)
- array[i] = 1.0;
- return;
- }
- QImage scaled = img.scaled(size,1);
- for (int i=0; i<size; i++)
- array[i] = qAlpha(scaled.pixel(i,0))/255.0;
-}
-
-/*!
- \qmlclass ImageParticle QQuickImageParticle
- \inqmlmodule QtQuick.Particles 2
- \inherits ParticlePainter
- \brief The ImageParticle element visualizes logical particles using an image
-
- This element renders a logical particle as an image. The image can be
- \list
- \o colorized
- \o rotated
- \o deformed
- \o a sprite-based animation
- \endlist
-
- ImageParticles implictly share data on particles if multiple ImageParticles are painting
- the same logical particle group. This is broken down along the four capabilities listed
- above. So if one ImageParticle defines data for rendering the particles in one of those
- capabilities, and the other does not, then both will draw the particles the same in that
- aspect automatically. This is primarily useful when there is some random variation on
- the particle which is supposed to stay with it when switching painters. If both ImageParticles
- define how they should appear for that aspect, they diverge and each appears as it is defined.
-
- This sharing of data happens behind the scenes based off of whether properties were implicitly or explicitly
- set. One drawback of the current implementation is that it is only possible to reset the capabilities as a whole.
- So if you explicity set an attribute affecting color, such as redVariation, and then reset it (by setting redVariation
- to undefined), all color data will be reset and it will begin to have an implicit value of any shared color from
- other ImageParticles.
-*/
-/*!
- \qmlproperty url QtQuick.Particles2::ImageParticle::source
-
- The source image to be used.
-
- If the image is a sprite animation, use the sprite property instead.
-*/
-/*!
- \qmlproperty list<Sprite> QtQuick.Particles2::ImageParticle::sprites
-
- The sprite or sprites used to draw this particle.
-
- Note that the sprite image will be scaled to a square based on the size of
- the particle being rendered.
-*/
-/*!
- \qmlproperty url QtQuick.Particles2::ImageParticle::colorTable
-
- An image whose color will be used as a 1D texture to determine color over life. E.g. when
- the particle is halfway through its lifetime, it will have the color specified halfway
- across the image.
-
- This color is blended with the color property and the color of the source image.
-*/
-/*!
- \qmlproperty url QtQuick.Particles2::ImageParticle::sizeTable
-
- An image whose opacity will be used as a 1D texture to determine size over life.
-
- This property is expected to be removed shortly, in favor of custom easing curves to determine size over life.
-*/
-/*!
- \qmlproperty url QtQuick.Particles2::ImageParticle::opacityTable
-
- An image whose opacity will be used as a 1D texture to determine size over life.
-
- This property is expected to be removed shortly, in favor of custom easing curves to determine opacity over life.
-*/
-/*!
- \qmlproperty color QtQuick.Particles2::ImageParticle::color
-
- If a color is specified, the provided image will be colorized with it.
-
- Default is white (no change).
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::ImageParticle::colorVariation
-
- This number represents the color variation applied to individual particles.
- Setting colorVariation is the same as setting redVariation, greenVariation,
- and blueVariation to the same number.
-
- Each channel can vary between particle by up to colorVariation from its usual color.
-
- Color is measured, per channel, from 0.0 to 1.0.
-
- Default is 0.0
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::ImageParticle::redVariation
- The variation in the red color channel between particles.
-
- Color is measured, per channel, from 0.0 to 1.0.
-
- Default is 0.0
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::ImageParticle::greenVariation
- The variation in the green color channel between particles.
-
- Color is measured, per channel, from 0.0 to 1.0.
-
- Default is 0.0
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::ImageParticle::blueVariation
- The variation in the blue color channel between particles.
-
- Color is measured, per channel, from 0.0 to 1.0.
-
- Default is 0.0
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::ImageParticle::alpha
- An alpha to be applied to the image. This value is multiplied by the value in
- the image, and the value in the color property.
-
- Particles have additive blending, so lower alpha on single particles leads
- to stronger effects when multiple particles overlap.
-
- Alpha is measured from 0.0 to 1.0.
-
- Default is 1.0
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::ImageParticle::alphaVariation
- The variation in the alpha channel between particles.
-
- Alpha is measured from 0.0 to 1.0.
-
- Default is 0.0
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::ImageParticle::rotation
-
- If set the image will be rotated by this many degrees before it is drawn.
-
- The particle coordinates are not transformed.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::ImageParticle::rotationVariation
-
- If set the rotation of individual particles will vary by up to this much
- between particles.
-
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::ImageParticle::rotationSpeed
-
- If set particles will rotate at this speed in degrees/second.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::ImageParticle::rotationSpeedVariation
-
- If set the rotationSpeed of individual particles will vary by up to this much
- between particles.
-
-*/
-/*!
- \qmlproperty bool QtQuick.Particles2::ImageParticle::autoRotation
-
- If set to true then a rotation will be applied on top of the particles rotation, so
- that it faces the direction of travel. So to face away from the direction of travel,
- set autoRotation to true and rotation to 180.
-
- Default is false
-*/
-/*!
- \qmlproperty StochasticDirection QtQuick.Particles2::ImageParticle::xVector
-
- Allows you to deform the particle image when drawn. The rectangular image will
- be deformed so that the horizontal sides are in the shape of this vector instead
- of (1,0).
-*/
-/*!
- \qmlproperty StochasticDirection QtQuick.Particles2::ImageParticle::yVector
-
- Allows you to deform the particle image when drawn. The rectangular image will
- be deformed so that the vertical sides are in the shape of this vector instead
- of (0,1).
-*/
-/*!
- \qmlproperty EntryEffect QtQuick.Particles2::ImageParticle::entryEffect
-
- This property provides basic and cheap entrance and exit effects for the particles.
- For fine-grained control, see sizeTable and opacityTable.
-
- Acceptable values are
- \list
- \o None: Particles just appear and disappear.
- \o Fade: Particles fade in from 0 opacity at the start of their life, and fade out to 0 at the end.
- \o Scale: Particles scale in from 0 size at the start of their life, and scale back to 0 at the end.
- \endlist
-
- Default value is Fade.
-*/
-/*!
- \qmlproperty bool QtQuick.Particles2::ImageParticle::spritesInterpolate
-
- If set to true, sprite particles will interpolate between sprite frames each rendered frame, making
- the sprites look smoother.
-
- Default is true.
-*/
-
-
-QQuickImageParticle::QQuickImageParticle(QQuickItem* parent)
- : QQuickParticlePainter(parent)
- , m_color_variation(0.0)
- , m_rootNode(0)
- , m_material(0)
- , m_alphaVariation(0.0)
- , m_alpha(1.0)
- , m_redVariation(0.0)
- , m_greenVariation(0.0)
- , m_blueVariation(0.0)
- , m_rotation(0)
- , m_rotationVariation(0)
- , m_rotationSpeed(0)
- , m_rotationSpeedVariation(0)
- , m_autoRotation(false)
- , m_xVector(0)
- , m_yVector(0)
- , m_spriteEngine(0)
- , m_spritesInterpolate(true)
- , m_explicitColor(false)
- , m_explicitRotation(false)
- , m_explicitDeformation(false)
- , m_explicitAnimation(false)
- , m_bloat(false)
- , perfLevel(Unknown)
- , m_lastLevel(Unknown)
- , m_debugMode(false)
- , m_entryEffect(Fade)
-{
- setFlag(ItemHasContents);
- m_debugMode = qmlParticlesDebug();
-}
-
-QQuickImageParticle::~QQuickImageParticle()
-{
-}
-
-QDeclarativeListProperty<QQuickSprite> QQuickImageParticle::sprites()
-{
- return QDeclarativeListProperty<QQuickSprite>(this, &m_sprites, spriteAppend, spriteCount, spriteAt, spriteClear);
-}
-
-void QQuickImageParticle::setImage(const QUrl &image)
-{
- if (image == m_image_name)
- return;
- m_image_name = image;
- emit imageChanged();
- reset();
-}
-
-
-void QQuickImageParticle::setColortable(const QUrl &table)
-{
- if (table == m_colortable_name)
- return;
- m_colortable_name = table;
- emit colortableChanged();
- reset();
-}
-
-void QQuickImageParticle::setSizetable(const QUrl &table)
-{
- if (table == m_sizetable_name)
- return;
- m_sizetable_name = table;
- emit sizetableChanged();
- reset();
-}
-
-void QQuickImageParticle::setOpacitytable(const QUrl &table)
-{
- if (table == m_opacitytable_name)
- return;
- m_opacitytable_name = table;
- emit opacitytableChanged();
- reset();
-}
-
-void QQuickImageParticle::setColor(const QColor &color)
-{
- if (color == m_color)
- return;
- m_color = color;
- emit colorChanged();
- m_explicitColor = true;
- if (perfLevel < Colored)
- reset();
-}
-
-void QQuickImageParticle::setColorVariation(qreal var)
-{
- if (var == m_color_variation)
- return;
- m_color_variation = var;
- emit colorVariationChanged();
- m_explicitColor = true;
- if (perfLevel < Colored)
- reset();
-}
-
-void QQuickImageParticle::setAlphaVariation(qreal arg)
-{
- if (m_alphaVariation != arg) {
- m_alphaVariation = arg;
- emit alphaVariationChanged(arg);
- }
- m_explicitColor = true;
- if (perfLevel < Colored)
- reset();
-}
-
-void QQuickImageParticle::setAlpha(qreal arg)
-{
- if (m_alpha != arg) {
- m_alpha = arg;
- emit alphaChanged(arg);
- }
- m_explicitColor = true;
- if (perfLevel < Colored)
- reset();
-}
-
-void QQuickImageParticle::setRedVariation(qreal arg)
-{
- if (m_redVariation != arg) {
- m_redVariation = arg;
- emit redVariationChanged(arg);
- }
- m_explicitColor = true;
- if (perfLevel < Colored)
- reset();
-}
-
-void QQuickImageParticle::setGreenVariation(qreal arg)
-{
- if (m_greenVariation != arg) {
- m_greenVariation = arg;
- emit greenVariationChanged(arg);
- }
- m_explicitColor = true;
- if (perfLevel < Colored)
- reset();
-}
-
-void QQuickImageParticle::setBlueVariation(qreal arg)
-{
- if (m_blueVariation != arg) {
- m_blueVariation = arg;
- emit blueVariationChanged(arg);
- }
- m_explicitColor = true;
- if (perfLevel < Colored)
- reset();
-}
-
-void QQuickImageParticle::setRotation(qreal arg)
-{
- if (m_rotation != arg) {
- m_rotation = arg;
- emit rotationChanged(arg);
- }
- m_explicitRotation = true;
- if (perfLevel < Deformable)
- reset();
-}
-
-void QQuickImageParticle::setRotationVariation(qreal arg)
-{
- if (m_rotationVariation != arg) {
- m_rotationVariation = arg;
- emit rotationVariationChanged(arg);
- }
- m_explicitRotation = true;
- if (perfLevel < Deformable)
- reset();
-}
-
-void QQuickImageParticle::setRotationSpeed(qreal arg)
-{
- if (m_rotationSpeed != arg) {
- m_rotationSpeed = arg;
- emit rotationSpeedChanged(arg);
- }
- m_explicitRotation = true;
- if (perfLevel < Deformable)
- reset();
-}
-
-void QQuickImageParticle::setRotationSpeedVariation(qreal arg)
-{
- if (m_rotationSpeedVariation != arg) {
- m_rotationSpeedVariation = arg;
- emit rotationSpeedVariationChanged(arg);
- }
- m_explicitRotation = true;
- if (perfLevel < Deformable)
- reset();
-}
-
-void QQuickImageParticle::setAutoRotation(bool arg)
-{
- if (m_autoRotation != arg) {
- m_autoRotation = arg;
- emit autoRotationChanged(arg);
- }
- m_explicitRotation = true;
- if (perfLevel < Deformable)
- reset();
-}
-
-void QQuickImageParticle::setXVector(QQuickDirection* arg)
-{
- if (m_xVector != arg) {
- m_xVector = arg;
- emit xVectorChanged(arg);
- }
- m_explicitDeformation = true;
- if (perfLevel < Deformable)
- reset();
-}
-
-void QQuickImageParticle::setYVector(QQuickDirection* arg)
-{
- if (m_yVector != arg) {
- m_yVector = arg;
- emit yVectorChanged(arg);
- }
- m_explicitDeformation = true;
- if (perfLevel < Deformable)
- reset();
-}
-
-void QQuickImageParticle::setSpritesInterpolate(bool arg)
-{
- if (m_spritesInterpolate != arg) {
- m_spritesInterpolate = arg;
- emit spritesInterpolateChanged(arg);
- }
-}
-
-void QQuickImageParticle::setBloat(bool arg)
-{
- if (m_bloat != arg) {
- m_bloat = arg;
- emit bloatChanged(arg);
- }
- if (perfLevel < 9999)
- reset();
-}
-
-void QQuickImageParticle::setEntryEffect(EntryEffect arg)
-{
- if (m_entryEffect != arg) {
- m_entryEffect = arg;
- if (m_material)
- getState<ImageMaterialData>(m_material)->entry = (qreal) m_entryEffect;
- emit entryEffectChanged(arg);
- }
-}
-
-void QQuickImageParticle::resetColor()
-{
- m_explicitColor = false;
- foreach (const QString &str, m_groups)
- foreach (QQuickParticleData* d, m_system->groupData[m_system->groupIds[str]]->data)
- if (d->colorOwner == this)
- d->colorOwner = 0;
- m_color = QColor();
- m_color_variation = 0.0f;
- m_redVariation = 0.0f;
- m_blueVariation = 0.0f;
- m_greenVariation = 0.0f;
- m_alpha = 1.0f;
- m_alphaVariation = 0.0f;
-}
-
-void QQuickImageParticle::resetRotation()
-{
- m_explicitRotation = false;
- foreach (const QString &str, m_groups)
- foreach (QQuickParticleData* d, m_system->groupData[m_system->groupIds[str]]->data)
- if (d->rotationOwner == this)
- d->rotationOwner = 0;
- m_rotation = 0;
- m_rotationVariation = 0;
- m_rotationSpeed = 0;
- m_rotationSpeedVariation = 0;
- m_autoRotation = false;
-}
-
-void QQuickImageParticle::resetDeformation()
-{
- m_explicitDeformation = false;
- foreach (const QString &str, m_groups)
- foreach (QQuickParticleData* d, m_system->groupData[m_system->groupIds[str]]->data)
- if (d->deformationOwner == this)
- d->deformationOwner = 0;
- if (m_xVector)
- delete m_xVector;
- if (m_yVector)
- delete m_yVector;
- m_xVector = 0;
- m_yVector = 0;
-}
-
-void QQuickImageParticle::reset()
-{
- QQuickParticlePainter::reset();
- m_pleaseReset = true;
- update();
-}
-
-void QQuickImageParticle::createEngine()
-{
- if (m_spriteEngine)
- delete m_spriteEngine;
- if (m_sprites.count()) {
- m_spriteEngine = new QQuickSpriteEngine(m_sprites, this);
- connect(m_spriteEngine, SIGNAL(stateChanged(int)),
- this, SLOT(spriteAdvance(int)));
- m_explicitAnimation = true;
- } else {
- m_spriteEngine = 0;
- m_explicitAnimation = false;
- }
- reset();
-}
-
-static QSGGeometry::Attribute SimpleParticle_Attributes[] = {
- QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true), // Position
- QSGGeometry::Attribute::create(1, 4, GL_FLOAT), // Data
- QSGGeometry::Attribute::create(2, 4, GL_FLOAT) // Vectors
-};
-
-static QSGGeometry::AttributeSet SimpleParticle_AttributeSet =
-{
- 3, // Attribute Count
- ( 2 + 4 + 4 ) * sizeof(float),
- SimpleParticle_Attributes
-};
-
-static QSGGeometry::Attribute ColoredParticle_Attributes[] = {
- QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true), // Position
- QSGGeometry::Attribute::create(1, 4, GL_FLOAT), // Data
- QSGGeometry::Attribute::create(2, 4, GL_FLOAT), // Vectors
- QSGGeometry::Attribute::create(3, 4, GL_UNSIGNED_BYTE), // Colors
-};
-
-static QSGGeometry::AttributeSet ColoredParticle_AttributeSet =
-{
- 4, // Attribute Count
- ( 2 + 4 + 4 ) * sizeof(float) + 4 * sizeof(uchar),
- ColoredParticle_Attributes
-};
-
-static QSGGeometry::Attribute DeformableParticle_Attributes[] = {
- QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true), // Position
- QSGGeometry::Attribute::create(1, 2, GL_FLOAT), // TexCoord
- QSGGeometry::Attribute::create(2, 4, GL_FLOAT), // Data
- QSGGeometry::Attribute::create(3, 4, GL_FLOAT), // Vectors
- QSGGeometry::Attribute::create(4, 4, GL_UNSIGNED_BYTE), // Colors
- QSGGeometry::Attribute::create(5, 4, GL_FLOAT), // DeformationVectors
- QSGGeometry::Attribute::create(6, 3, GL_FLOAT), // Rotation
-};
-
-static QSGGeometry::AttributeSet DeformableParticle_AttributeSet =
-{
- 7, // Attribute Count
- (2 + 2 + 4 + 4 + 4 + 3) * sizeof(float) + 4 * sizeof(uchar),
- DeformableParticle_Attributes
-};
-
-static QSGGeometry::Attribute SpriteParticle_Attributes[] = {
- QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true), // Position
- QSGGeometry::Attribute::create(1, 2, GL_FLOAT), // TexCoord
- QSGGeometry::Attribute::create(2, 4, GL_FLOAT), // Data
- QSGGeometry::Attribute::create(3, 4, GL_FLOAT), // Vectors
- QSGGeometry::Attribute::create(4, 4, GL_UNSIGNED_BYTE), // Colors
- QSGGeometry::Attribute::create(5, 4, GL_FLOAT), // DeformationVectors
- QSGGeometry::Attribute::create(6, 3, GL_FLOAT), // Rotation
- QSGGeometry::Attribute::create(7, 4, GL_FLOAT), // Anim Data
- QSGGeometry::Attribute::create(8, 4, GL_FLOAT) // Anim Pos
-};
-
-static QSGGeometry::AttributeSet SpriteParticle_AttributeSet =
-{
- 9, // Attribute Count
- (2 + 2 + 4 + 4 + 4 + 4 + 4 + 3) * sizeof(float) + 4 * sizeof(uchar),
- SpriteParticle_Attributes
-};
-
-void QQuickImageParticle::clearShadows()
-{
- foreach (const QVector<QQuickParticleData*> data, m_shadowData)
- qDeleteAll(data);
- m_shadowData.clear();
-}
-
-//Only call if you need to, may initialize the whole array first time
-QQuickParticleData* QQuickImageParticle::getShadowDatum(QQuickParticleData* datum)
-{
- QQuickParticleGroupData* gd = m_system->groupData[datum->group];
- if (!m_shadowData.contains(datum->group)) {
- QVector<QQuickParticleData*> data;
- for (int i=0; i<gd->size(); i++){
- QQuickParticleData* datum = new QQuickParticleData(m_system);
- *datum = *(gd->data[i]);
- data << datum;
- }
- m_shadowData.insert(datum->group, data);
- }
- //### If dynamic resize is added, remember to potentially resize the shadow data on out-of-bounds access request
-
- return m_shadowData[datum->group][datum->index];
-}
-
-QSGGeometryNode* QQuickImageParticle::buildParticleNodes()
-{
-#ifdef QT_OPENGL_ES_2
- if (m_count * 4 > 0xffff) {
- printf("ImageParticle: Too many particles - maximum 16,000 per ImageParticle.\n");//ES 2 vertex count limit is ushort
- return 0;
- }
-#endif
-
- if (count() <= 0)
- return 0;
-
- if (m_sprites.count() || m_bloat) {
- perfLevel = Sprites;
- } else if (!m_colortable_name.isEmpty() || !m_sizetable_name.isEmpty()
- || !m_opacitytable_name.isEmpty()) {
- perfLevel = Tabled;
- } else if (m_autoRotation || m_rotation || m_rotationVariation
- || m_rotationSpeed || m_rotationSpeedVariation
- || m_xVector || m_yVector) {
- perfLevel = Deformable;
- } else if (m_alphaVariation || m_alpha != 1.0 || m_color.isValid() || m_color_variation
- || m_redVariation || m_blueVariation || m_greenVariation) {
- perfLevel = Colored;
- } else {
- perfLevel = Simple;
- }
-
- foreach (const QString &str, m_groups){//For sharing higher levels, need to have highest used so it renders
- int gIdx = m_system->groupIds[str];
- foreach (QQuickParticlePainter* p, m_system->groupData[gIdx]->painters){
- QQuickImageParticle* other = qobject_cast<QQuickImageParticle*>(p);
- if (other){
- if (other->perfLevel > perfLevel) {
- if (other->perfLevel >= Tabled){//Deformable is the highest level needed for this, anything higher isn't shared (or requires your own sprite)
- if (perfLevel < Deformable)
- perfLevel = Deformable;
- } else {
- perfLevel = other->perfLevel;
- }
- } else if (other->perfLevel < perfLevel) {
- other->reset();
- }
- }
- }
- }
-
- if (perfLevel >= Colored && !m_color.isValid())
- m_color = QColor(Qt::white);//Hidden default, but different from unset
-
- QImage image;
- if (perfLevel >= Sprites){
- if (!m_spriteEngine) {
- qWarning() << "ImageParticle: No sprite engine...";
- return 0;
- }
- image = m_spriteEngine->assembledImage();
- if (image.isNull())//Warning is printed in engine
- return 0;
- } else {
- image = QImage(m_image_name.toLocalFile());
- if (image.isNull()) {
- printf("ImageParticle: loading image failed '%s'\n", qPrintable(m_image_name.toLocalFile()));
- return 0;
- }
- }
-
- clearShadows();
- if (m_material)
- m_material = 0;
-
- //Setup material
- QImage colortable;
- QImage sizetable;
- QImage opacitytable;
- switch (perfLevel) {//Fallthrough intended
- case Sprites:
- m_material = SpriteMaterial::createMaterial();
- getState<ImageMaterialData>(m_material)->animSheetSize = QSizeF(image.size());
- m_spriteEngine->setCount(m_count);
- case Tabled:
- if (!m_material)
- m_material = TabledMaterial::createMaterial();
- colortable = QImage(m_colortable_name.toLocalFile());
- sizetable = QImage(m_sizetable_name.toLocalFile());
- opacitytable = QImage(m_opacitytable_name.toLocalFile());
- if (colortable.isNull()){
- colortable = QImage(1,1,QImage::Format_ARGB32);
- colortable.fill(Qt::white);
- }
- Q_ASSERT(!colortable.isNull());
- getState<ImageMaterialData>(m_material)->colorTable = QSGPlainTexture::fromImage(colortable);
- fillUniformArrayFromImage(getState<ImageMaterialData>(m_material)->sizeTable, sizetable, UNIFORM_ARRAY_SIZE);
- fillUniformArrayFromImage(getState<ImageMaterialData>(m_material)->opacityTable, opacitytable, UNIFORM_ARRAY_SIZE);
- case Deformable:
- if (!m_material)
- m_material = DeformableMaterial::createMaterial();
- case Colored:
- if (!m_material)
- m_material = ColoredMaterial::createMaterial();
- default://Also Simple
- if (!m_material)
- m_material = SimpleMaterial::createMaterial();
- getState<ImageMaterialData>(m_material)->texture = QSGPlainTexture::fromImage(image);
- getState<ImageMaterialData>(m_material)->texture->setFiltering(QSGTexture::Linear);
- getState<ImageMaterialData>(m_material)->entry = (qreal) m_entryEffect;
- m_material->setFlag(QSGMaterial::Blending);
- }
-
- foreach (const QString &str, m_groups){
- int gIdx = m_system->groupIds[str];
- int count = m_system->groupData[gIdx]->size();
- QSGGeometryNode* node = new QSGGeometryNode();
- node->setMaterial(m_material);
- node->markDirty(QSGNode::DirtyMaterial);
-
- m_nodes.insert(gIdx, node);
- m_idxStarts.insert(gIdx, m_lastIdxStart);
- m_startsIdx.append(qMakePair<int,int>(m_lastIdxStart, gIdx));
- m_lastIdxStart += count;
-
- //Create Particle Geometry
- int vCount = count * 4;
- int iCount = count * 6;
-
- QSGGeometry *g;
- if (perfLevel == Sprites)
- g = new QSGGeometry(SpriteParticle_AttributeSet, vCount, iCount);
- else if (perfLevel == Tabled)
- g = new QSGGeometry(DeformableParticle_AttributeSet, vCount, iCount);
- else if (perfLevel == Deformable)
- g = new QSGGeometry(DeformableParticle_AttributeSet, vCount, iCount);
- else if (perfLevel == Colored)
- g = new QSGGeometry(ColoredParticle_AttributeSet, count, 0);
- else //Simple
- g = new QSGGeometry(SimpleParticle_AttributeSet, count, 0);
-
- node->setGeometry(g);
- if (perfLevel <= Colored){
- g->setDrawingMode(GL_POINTS);
- if (m_debugMode){
- GLfloat pointSizeRange[2];
- glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, pointSizeRange);
- qDebug() << "Using point sprites, GL_ALIASED_POINT_SIZE_RANGE " <<pointSizeRange[0] << ":" << pointSizeRange[1];
- }
- }else
- g->setDrawingMode(GL_TRIANGLES);
-
- for (int p=0; p < count; ++p)
- commit(gIdx, p);//commit sets geometry for the node, has its own perfLevel switch
-
- if (perfLevel == Sprites)
- initTexCoords<SpriteVertex>((SpriteVertex*)g->vertexData(), vCount);
- else if (perfLevel == Tabled)
- initTexCoords<DeformableVertex>((DeformableVertex*)g->vertexData(), vCount);
- else if (perfLevel == Deformable)
- initTexCoords<DeformableVertex>((DeformableVertex*)g->vertexData(), vCount);
-
- if (perfLevel > Colored){
- quint16 *indices = g->indexDataAsUShort();
- for (int i=0; i < count; ++i) {
- int o = i * 4;
- indices[0] = o;
- indices[1] = o + 1;
- indices[2] = o + 2;
- indices[3] = o + 1;
- indices[4] = o + 3;
- indices[5] = o + 2;
- indices += 6;
- }
- }
-
- }
-
- foreach (QSGGeometryNode* node, m_nodes){
- if (node == *(m_nodes.begin()))
- node->setFlag(QSGGeometryNode::OwnsMaterial);//Root node owns the material for memory management purposes
- else
- (*(m_nodes.begin()))->appendChildNode(node);
- }
-
- return *(m_nodes.begin());
-}
-
-QSGNode *QQuickImageParticle::updatePaintNode(QSGNode *, UpdatePaintNodeData *)
-{
- if (m_pleaseReset){
- m_lastLevel = perfLevel;
-
- delete m_rootNode;//Automatically deletes children, and SG manages material lifetime
- m_rootNode = 0;
- m_nodes.clear();
-
- m_idxStarts.clear();
- m_startsIdx.clear();
- m_lastIdxStart = 0;
-
- m_material = 0;
-
- m_pleaseReset = false;
- }
-
- if (m_system && m_system->isRunning() && !m_system->isPaused()){
- prepareNextFrame();
- if (m_rootNode) {
- update();
- foreach (QSGGeometryNode* node, m_nodes)
- node->markDirty(QSGNode::DirtyGeometry);
- }
- }
-
- return m_rootNode;
-}
-
-void QQuickImageParticle::prepareNextFrame()
-{
- if (m_rootNode == 0){//TODO: Staggered loading (as emitted)
- m_rootNode = buildParticleNodes();
- if (m_rootNode == 0)
- return;
- if (m_debugMode) {
- qDebug() << "QQuickImageParticle Feature level: " << perfLevel;
- qDebug() << "QQuickImageParticle Nodes: ";
- int count = 0;
- foreach (int i, m_nodes.keys()) {
- qDebug() << "Group " << i << " (" << m_system->groupData[i]->size() << " particles)";
- count += m_system->groupData[i]->size();
- }
- qDebug() << "Total count: " << count;
- }
- }
- qint64 timeStamp = m_system->systemSync(this);
-
- qreal time = timeStamp / 1000.;
-
- switch (perfLevel){//Fall-through intended
- case Sprites:
- //Advance State
- m_spriteEngine->updateSprites(timeStamp);
- case Tabled:
- case Deformable:
- case Colored:
- case Simple:
- default: //Also Simple
- getState<ImageMaterialData>(m_material)->timestamp = time;
- break;
- }
-
- foreach (QSGGeometryNode* node, m_nodes)
- node->markDirty(QSGNode::DirtyMaterial);
-}
-
-void QQuickImageParticle::spriteAdvance(int spriteIdx)
-{
- if (!m_startsIdx.count())//Probably overly defensive
- return;
-
- int gIdx = -1;
- int i;
- for (i = 0; i<m_startsIdx.count(); i++) {
- if (spriteIdx < m_startsIdx[i].first) {
- gIdx = m_startsIdx[i-1].second;
- break;
- }
- }
- if (gIdx == -1)
- gIdx = m_startsIdx[i-1].second;
- int pIdx = spriteIdx - m_startsIdx[i-1].first;
-
- QQuickParticleData* datum = m_system->groupData[gIdx]->data[pIdx];
- QQuickParticleData* d = (datum->animationOwner == this ? datum : getShadowDatum(datum));
-
- d->animIdx = m_spriteEngine->spriteState(spriteIdx);
- Vertices<SpriteVertex>* particles = (Vertices<SpriteVertex> *) m_nodes[gIdx]->geometry()->vertexData();
- Vertices<SpriteVertex> &p = particles[pIdx];
- d->animT = p.v1.animT = p.v2.animT = p.v3.animT = p.v4.animT = m_spriteEngine->spriteStart(spriteIdx)/1000.0;
- d->frameCount = p.v1.frameCount = p.v2.frameCount = p.v3.frameCount = p.v4.frameCount = m_spriteEngine->spriteFrames(spriteIdx);
- d->frameDuration = p.v1.frameDuration = p.v2.frameDuration = p.v3.frameDuration = p.v4.frameDuration = m_spriteEngine->spriteDuration(spriteIdx);
- d->animX = p.v1.animX = p.v2.animX = p.v3.animX = p.v4.animX = m_spriteEngine->spriteX(spriteIdx);
- d->animY = p.v1.animY = p.v2.animY = p.v3.animY = p.v4.animY = m_spriteEngine->spriteY(spriteIdx);
- d->animWidth = p.v1.animWidth = p.v2.animWidth = p.v3.animWidth = p.v4.animWidth = m_spriteEngine->spriteWidth(spriteIdx);
- d->animHeight = p.v1.animHeight = p.v2.animHeight = p.v3.animHeight = p.v4.animHeight = m_spriteEngine->spriteHeight(spriteIdx);
-}
-
-void QQuickImageParticle::reloadColor(const Color4ub &c, QQuickParticleData* d)
-{
- d->color = c;
- //TODO: get index for reload - or make function take an index
-}
-
-void QQuickImageParticle::initialize(int gIdx, int pIdx)
-{
- Color4ub color;
- QQuickParticleData* datum = m_system->groupData[gIdx]->data[pIdx];
- qreal redVariation = m_color_variation + m_redVariation;
- qreal greenVariation = m_color_variation + m_greenVariation;
- qreal blueVariation = m_color_variation + m_blueVariation;
- int spriteIdx = 0;
- if (m_spriteEngine) {
- spriteIdx = m_idxStarts[gIdx] + datum->index;
- if (spriteIdx >= m_spriteEngine->count())
- m_spriteEngine->setCount(spriteIdx+1);
- }
-
- float rotation;
- float rotationSpeed;
- float autoRotate;
- switch (perfLevel){//Fall-through is intended on all of them
- case Sprites:
- // Initial Sprite State
- if (m_explicitAnimation){
- if (!datum->animationOwner)
- datum->animationOwner = this;
- QQuickParticleData* writeTo = (datum->animationOwner == this ? datum : getShadowDatum(datum));
- writeTo->animT = writeTo->t;
- //writeTo->animInterpolate = m_spritesInterpolate;
- if (m_spriteEngine){
- m_spriteEngine->start(spriteIdx);
- writeTo->frameCount = m_spriteEngine->spriteFrames(spriteIdx);
- writeTo->frameDuration = m_spriteEngine->spriteDuration(spriteIdx);
- writeTo->animX = m_spriteEngine->spriteX(spriteIdx);
- writeTo->animY = m_spriteEngine->spriteY(spriteIdx);
- writeTo->animWidth = m_spriteEngine->spriteWidth(spriteIdx);
- writeTo->animHeight = m_spriteEngine->spriteHeight(spriteIdx);
- }else{
- writeTo->frameCount = 1;
- writeTo->frameDuration = 9999;
- writeTo->animX = writeTo->animY = 0;
- writeTo->animWidth = writeTo->animHeight = 1;
- }
- }
- case Tabled:
- case Deformable:
- //Initial Rotation
- if (m_explicitDeformation){
- if (!datum->deformationOwner)
- datum->deformationOwner = this;
- if (m_xVector){
- const QPointF &ret = m_xVector->sample(QPointF(datum->x, datum->y));
- if (datum->deformationOwner == this) {
- datum->xx = ret.x();
- datum->xy = ret.y();
- } else {
- getShadowDatum(datum)->xx = ret.x();
- getShadowDatum(datum)->xy = ret.y();
- }
- }
- if (m_yVector){
- const QPointF &ret = m_yVector->sample(QPointF(datum->x, datum->y));
- if (datum->deformationOwner == this) {
- datum->yx = ret.x();
- datum->yy = ret.y();
- } else {
- getShadowDatum(datum)->yx = ret.x();
- getShadowDatum(datum)->yy = ret.y();
- }
- }
- }
-
- if (m_explicitRotation){
- if (!datum->rotationOwner)
- datum->rotationOwner = this;
- rotation =
- (m_rotation + (m_rotationVariation - 2*((qreal)rand()/RAND_MAX)*m_rotationVariation) ) * CONV;
- rotationSpeed =
- (m_rotationSpeed + (m_rotationSpeedVariation - 2*((qreal)rand()/RAND_MAX)*m_rotationSpeedVariation) ) * CONV;
- autoRotate = m_autoRotation?1.0:0.0;
- if (datum->rotationOwner == this) {
- datum->rotation = rotation;
- datum->rotationSpeed = rotationSpeed;
- datum->autoRotate = autoRotate;
- } else {
- getShadowDatum(datum)->rotation = rotation;
- getShadowDatum(datum)->rotationSpeed = rotationSpeed;
- getShadowDatum(datum)->autoRotate = autoRotate;
- }
- }
- case Colored:
- //Color initialization
- // Particle color
- if (m_explicitColor) {
- if (!datum->colorOwner)
- datum->colorOwner = this;
- color.r = m_color.red() * (1 - redVariation) + rand() % 256 * redVariation;
- color.g = m_color.green() * (1 - greenVariation) + rand() % 256 * greenVariation;
- color.b = m_color.blue() * (1 - blueVariation) + rand() % 256 * blueVariation;
- color.a = m_alpha * m_color.alpha() * (1 - m_alphaVariation) + rand() % 256 * m_alphaVariation;
- if (datum->colorOwner == this)
- datum->color = color;
- else
- getShadowDatum(datum)->color = color;
- }
- default:
- break;
- }
-}
-
-void QQuickImageParticle::commit(int gIdx, int pIdx)
-{
- if (m_pleaseReset)
- return;
- QSGGeometryNode *node = m_nodes[gIdx];
- if (!node)
- return;
- QQuickParticleData* datum = m_system->groupData[gIdx]->data[pIdx];
- node->setFlag(QSGNode::OwnsGeometry, false);
- SpriteVertex *spriteVertices = (SpriteVertex *) node->geometry()->vertexData();
- DeformableVertex *deformableVertices = (DeformableVertex *) node->geometry()->vertexData();
- ColoredVertex *coloredVertices = (ColoredVertex *) node->geometry()->vertexData();
- SimpleVertex *simpleVertices = (SimpleVertex *) node->geometry()->vertexData();
- switch (perfLevel){//No automatic fall through intended on this one
- case Sprites:
- spriteVertices += pIdx*4;
- for (int i=0; i<4; i++){
- spriteVertices[i].x = datum->x - m_systemOffset.x();
- spriteVertices[i].y = datum->y - m_systemOffset.y();
- spriteVertices[i].t = datum->t;
- spriteVertices[i].lifeSpan = datum->lifeSpan;
- spriteVertices[i].size = datum->size;
- spriteVertices[i].endSize = datum->endSize;
- spriteVertices[i].vx = datum->vx;
- spriteVertices[i].vy = datum->vy;
- spriteVertices[i].ax = datum->ax;
- spriteVertices[i].ay = datum->ay;
- if (m_explicitDeformation && datum->deformationOwner != this) {
- QQuickParticleData* shadow = getShadowDatum(datum);
- spriteVertices[i].xx = shadow->xx;
- spriteVertices[i].xy = shadow->xy;
- spriteVertices[i].yx = shadow->yx;
- spriteVertices[i].yy = shadow->yy;
- } else {
- spriteVertices[i].xx = datum->xx;
- spriteVertices[i].xy = datum->xy;
- spriteVertices[i].yx = datum->yx;
- spriteVertices[i].yy = datum->yy;
- }
- if (m_explicitRotation && datum->rotationOwner != this) {
- QQuickParticleData* shadow = getShadowDatum(datum);
- spriteVertices[i].rotation = shadow->rotation;
- spriteVertices[i].rotationSpeed = shadow->rotationSpeed;
- spriteVertices[i].autoRotate = shadow->autoRotate;
- } else {
- spriteVertices[i].rotation = datum->rotation;
- spriteVertices[i].rotationSpeed = datum->rotationSpeed;
- spriteVertices[i].autoRotate = datum->autoRotate;
- }
- spriteVertices[i].animInterpolate = m_spritesInterpolate ? 1.0 : 0.0;//### Shadow? In particleData? Or uniform?
- if (m_explicitAnimation && datum->animationOwner != this) {
- QQuickParticleData* shadow = getShadowDatum(datum);
- spriteVertices[i].frameDuration = shadow->frameDuration;
- spriteVertices[i].frameCount = shadow->frameCount;
- spriteVertices[i].animT = shadow->animT;
- spriteVertices[i].animX = shadow->animX;
- spriteVertices[i].animY = shadow->animY;
- spriteVertices[i].animWidth = shadow->animWidth;
- spriteVertices[i].animHeight = shadow->animHeight;
- } else {
- spriteVertices[i].frameDuration = datum->frameDuration;
- spriteVertices[i].frameCount = datum->frameCount;
- spriteVertices[i].animT = datum->animT;
- spriteVertices[i].animX = datum->animX;
- spriteVertices[i].animY = datum->animY;
- spriteVertices[i].animWidth = datum->animWidth;
- spriteVertices[i].animHeight = datum->animHeight;
- }
- if (m_explicitColor && datum->colorOwner != this) {
- QQuickParticleData* shadow = getShadowDatum(datum);
- spriteVertices[i].color.r = shadow->color.r;
- spriteVertices[i].color.g = shadow->color.g;
- spriteVertices[i].color.b = shadow->color.b;
- spriteVertices[i].color.a = shadow->color.a;
- } else {
- spriteVertices[i].color.r = datum->color.r;
- spriteVertices[i].color.g = datum->color.g;
- spriteVertices[i].color.b = datum->color.b;
- spriteVertices[i].color.a = datum->color.a;
- }
- }
- break;
- case Tabled: //Fall through until it has its own vertex class
- case Deformable:
- deformableVertices += pIdx*4;
- for (int i=0; i<4; i++){
- deformableVertices[i].x = datum->x - m_systemOffset.x();
- deformableVertices[i].y = datum->y - m_systemOffset.y();
- deformableVertices[i].t = datum->t;
- deformableVertices[i].lifeSpan = datum->lifeSpan;
- deformableVertices[i].size = datum->size;
- deformableVertices[i].endSize = datum->endSize;
- deformableVertices[i].vx = datum->vx;
- deformableVertices[i].vy = datum->vy;
- deformableVertices[i].ax = datum->ax;
- deformableVertices[i].ay = datum->ay;
- if (m_explicitDeformation && datum->deformationOwner != this) {
- QQuickParticleData* shadow = getShadowDatum(datum);
- deformableVertices[i].xx = shadow->xx;
- deformableVertices[i].xy = shadow->xy;
- deformableVertices[i].yx = shadow->yx;
- deformableVertices[i].yy = shadow->yy;
- } else {
- deformableVertices[i].xx = datum->xx;
- deformableVertices[i].xy = datum->xy;
- deformableVertices[i].yx = datum->yx;
- deformableVertices[i].yy = datum->yy;
- }
- if (m_explicitRotation && datum->rotationOwner != this) {
- QQuickParticleData* shadow = getShadowDatum(datum);
- deformableVertices[i].rotation = shadow->rotation;
- deformableVertices[i].rotationSpeed = shadow->rotationSpeed;
- deformableVertices[i].autoRotate = shadow->autoRotate;
- } else {
- deformableVertices[i].rotation = datum->rotation;
- deformableVertices[i].rotationSpeed = datum->rotationSpeed;
- deformableVertices[i].autoRotate = datum->autoRotate;
- }
- if (m_explicitColor && datum->colorOwner != this) {
- QQuickParticleData* shadow = getShadowDatum(datum);
- deformableVertices[i].color.r = shadow->color.r;
- deformableVertices[i].color.g = shadow->color.g;
- deformableVertices[i].color.b = shadow->color.b;
- deformableVertices[i].color.a = shadow->color.a;
- } else {
- deformableVertices[i].color.r = datum->color.r;
- deformableVertices[i].color.g = datum->color.g;
- deformableVertices[i].color.b = datum->color.b;
- deformableVertices[i].color.a = datum->color.a;
- }
- }
- break;
- case Colored:
- coloredVertices += pIdx*1;
- for (int i=0; i<1; i++){
- coloredVertices[i].x = datum->x - m_systemOffset.x();
- coloredVertices[i].y = datum->y - m_systemOffset.y();
- coloredVertices[i].t = datum->t;
- coloredVertices[i].lifeSpan = datum->lifeSpan;
- coloredVertices[i].size = datum->size;
- coloredVertices[i].endSize = datum->endSize;
- coloredVertices[i].vx = datum->vx;
- coloredVertices[i].vy = datum->vy;
- coloredVertices[i].ax = datum->ax;
- coloredVertices[i].ay = datum->ay;
- if (m_explicitColor && datum->colorOwner != this) {
- QQuickParticleData* shadow = getShadowDatum(datum);
- coloredVertices[i].color.r = shadow->color.r;
- coloredVertices[i].color.g = shadow->color.g;
- coloredVertices[i].color.b = shadow->color.b;
- coloredVertices[i].color.a = shadow->color.a;
- } else {
- coloredVertices[i].color.r = datum->color.r;
- coloredVertices[i].color.g = datum->color.g;
- coloredVertices[i].color.b = datum->color.b;
- coloredVertices[i].color.a = datum->color.a;
- }
- }
- break;
- case Simple:
- simpleVertices += pIdx*1;
- for (int i=0; i<1; i++){
- simpleVertices[i].x = datum->x - m_systemOffset.x();
- simpleVertices[i].y = datum->y - m_systemOffset.y();
- simpleVertices[i].t = datum->t;
- simpleVertices[i].lifeSpan = datum->lifeSpan;
- simpleVertices[i].size = datum->size;
- simpleVertices[i].endSize = datum->endSize;
- simpleVertices[i].vx = datum->vx;
- simpleVertices[i].vy = datum->vy;
- simpleVertices[i].ax = datum->ax;
- simpleVertices[i].ay = datum->ay;
- }
- break;
- default:
- break;
- }
-
- node->setFlag(QSGNode::OwnsGeometry, true);
-}
-
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickimageparticle_p.h b/src/declarative/particles/qquickimageparticle_p.h
deleted file mode 100644
index c7da7cfce6..0000000000
--- a/src/declarative/particles/qquickimageparticle_p.h
+++ /dev/null
@@ -1,429 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ULTRAPARTICLE_H
-#define ULTRAPARTICLE_H
-#include "qquickparticlepainter_p.h"
-#include "qquickdirection_p.h"
-#include <QDeclarativeListProperty>
-#include <qsgsimplematerial.h>
-#include <QtGui/qcolor.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class ImageMaterialData;
-class QSGGeometryNode;
-
-class QQuickSprite;
-class QQuickStochasticEngine;
-
-struct SimpleVertex {
- float x;
- float y;
- float t;
- float lifeSpan;
- float size;
- float endSize;
- float vx;
- float vy;
- float ax;
- float ay;
-};
-
-struct ColoredVertex {
- float x;
- float y;
- float t;
- float lifeSpan;
- float size;
- float endSize;
- float vx;
- float vy;
- float ax;
- float ay;
- Color4ub color;
-};
-
-struct DeformableVertex {
- float x;
- float y;
- float tx;
- float ty;
- float t;
- float lifeSpan;
- float size;
- float endSize;
- float vx;
- float vy;
- float ax;
- float ay;
- Color4ub color;
- float xx;
- float xy;
- float yx;
- float yy;
- float rotation;
- float rotationSpeed;
- float autoRotate;//Assumed that GPUs prefer floats to bools
-};
-
-struct SpriteVertex {
- float x;
- float y;
- float tx;
- float ty;
- float t;
- float lifeSpan;
- float size;
- float endSize;
- float vx;
- float vy;
- float ax;
- float ay;
- Color4ub color;
- float xx;
- float xy;
- float yx;
- float yy;
- float rotation;
- float rotationSpeed;
- float autoRotate;//Assumed that GPUs prefer floats to bools
- float animInterpolate;
- float frameDuration;
- float frameCount;
- float animT;
- float animX;
- float animY;
- float animWidth;
- float animHeight;
-};
-
-template <typename Vertex>
-struct Vertices {
- Vertex v1;
- Vertex v2;
- Vertex v3;
- Vertex v4;
-};
-
-class QQuickImageParticle : public QQuickParticlePainter
-{
- Q_OBJECT
- Q_PROPERTY(QUrl source READ image WRITE setImage NOTIFY imageChanged)
- Q_PROPERTY(QUrl colorTable READ colortable WRITE setColortable NOTIFY colortableChanged)
- Q_PROPERTY(QUrl sizeTable READ sizetable WRITE setSizetable NOTIFY sizetableChanged)
- Q_PROPERTY(QUrl opacityTable READ opacitytable WRITE setOpacitytable NOTIFY opacitytableChanged)
-
- //###Now just colorize - add a flag for 'solid' color particles(where the img is just a mask?)?
- Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged RESET resetColor)
- //Stacks (added) with individual colorVariations
- Q_PROPERTY(qreal colorVariation READ colorVariation WRITE setColorVariation NOTIFY colorVariationChanged RESET resetColor)
- Q_PROPERTY(qreal redVariation READ redVariation WRITE setRedVariation NOTIFY redVariationChanged RESET resetColor)
- Q_PROPERTY(qreal greenVariation READ greenVariation WRITE setGreenVariation NOTIFY greenVariationChanged RESET resetColor)
- Q_PROPERTY(qreal blueVariation READ blueVariation WRITE setBlueVariation NOTIFY blueVariationChanged RESET resetColor)
- //Stacks (multiplies) with the Alpha in the color, mostly here so you can use svg color names (which have full alpha)
- Q_PROPERTY(qreal alpha READ alpha WRITE setAlpha NOTIFY alphaChanged RESET resetColor)
- Q_PROPERTY(qreal alphaVariation READ alphaVariation WRITE setAlphaVariation NOTIFY alphaVariationChanged RESET resetColor)
-
- Q_PROPERTY(qreal rotation READ rotation WRITE setRotation NOTIFY rotationChanged RESET resetRotation)
- Q_PROPERTY(qreal rotationVariation READ rotationVariation WRITE setRotationVariation NOTIFY rotationVariationChanged RESET resetRotation)
- Q_PROPERTY(qreal rotationSpeed READ rotationSpeed WRITE setRotationSpeed NOTIFY rotationSpeedChanged RESET resetRotation)
- Q_PROPERTY(qreal rotationSpeedVariation READ rotationSpeedVariation WRITE setRotationSpeedVariation NOTIFY rotationSpeedVariationChanged RESET resetRotation)
- //If true, then will face the direction of motion. Stacks with rotation, e.g. setting rotation
- //to 180 will lead to facing away from the direction of motion
- Q_PROPERTY(bool autoRotation READ autoRotation WRITE setAutoRotation NOTIFY autoRotationChanged RESET resetRotation)
-
- //###Call i/j? Makes more sense to those with vector calculus experience, and I could even add the cirumflex in QML?
- //xVector is the vector from the top-left point to the top-right point, and is multiplied by current size
- Q_PROPERTY(QQuickDirection* xVector READ xVector WRITE setXVector NOTIFY xVectorChanged RESET resetDeformation)
- //yVector is the same, but top-left to bottom-left. The particle is always a parallelogram.
- Q_PROPERTY(QQuickDirection* yVector READ yVector WRITE setYVector NOTIFY yVectorChanged RESET resetDeformation)
- Q_PROPERTY(QDeclarativeListProperty<QQuickSprite> sprites READ sprites)
- Q_PROPERTY(bool spritesInterpolate READ spritesInterpolate WRITE setSpritesInterpolate NOTIFY spritesInterpolateChanged)
-
- Q_PROPERTY(EntryEffect entryEffect READ entryEffect WRITE setEntryEffect NOTIFY entryEffectChanged)
- Q_PROPERTY(bool bloat READ bloat WRITE setBloat NOTIFY bloatChanged)//Just a debugging property to bypass optimizations
- Q_ENUMS(EntryEffect)
-public:
- explicit QQuickImageParticle(QQuickItem *parent = 0);
- virtual ~QQuickImageParticle();
-
-
- QDeclarativeListProperty<QQuickSprite> sprites();
- QQuickStochasticEngine* spriteEngine() {return m_spriteEngine;}
-
- enum EntryEffect {
- None = 0,
- Fade = 1,
- Scale = 2
- };
-
- enum PerformanceLevel{//TODO: Expose?
- Unknown = 0,
- Simple,
- Colored,
- Deformable,
- Tabled,
- Sprites
- };
-
- QUrl image() const { return m_image_name; }
- void setImage(const QUrl &image);
-
- QUrl colortable() const { return m_colortable_name; }
- void setColortable(const QUrl &table);
-
- QUrl sizetable() const { return m_sizetable_name; }
- void setSizetable (const QUrl &table);
-
- QUrl opacitytable() const { return m_opacitytable_name; }
- void setOpacitytable(const QUrl &table);
-
- QColor color() const { return m_color; }
- void setColor(const QColor &color);
-
- qreal colorVariation() const { return m_color_variation; }
- void setColorVariation(qreal var);
-
- qreal alphaVariation() const { return m_alphaVariation; }
-
- qreal alpha() const { return m_alpha; }
-
- qreal redVariation() const { return m_redVariation; }
-
- qreal greenVariation() const { return m_greenVariation; }
-
- qreal blueVariation() const { return m_blueVariation; }
-
- qreal rotation() const { return m_rotation; }
-
- qreal rotationVariation() const { return m_rotationVariation; }
-
- qreal rotationSpeed() const { return m_rotationSpeed; }
-
- qreal rotationSpeedVariation() const { return m_rotationSpeedVariation; }
-
- bool autoRotation() const { return m_autoRotation; }
-
- QQuickDirection* xVector() const { return m_xVector; }
-
- QQuickDirection* yVector() const { return m_yVector; }
-
- bool spritesInterpolate() const { return m_spritesInterpolate; }
-
- bool bloat() const { return m_bloat; }
-
- EntryEffect entryEffect() const { return m_entryEffect; }
-
- void resetColor();
- void resetRotation();
- void resetDeformation();
-
-signals:
-
- void imageChanged();
- void colortableChanged();
- void sizetableChanged();
- void opacitytableChanged();
-
- void colorChanged();
- void colorVariationChanged();
-
- void alphaVariationChanged(qreal arg);
-
- void alphaChanged(qreal arg);
-
- void redVariationChanged(qreal arg);
-
- void greenVariationChanged(qreal arg);
-
- void blueVariationChanged(qreal arg);
-
- void rotationChanged(qreal arg);
-
- void rotationVariationChanged(qreal arg);
-
- void rotationSpeedChanged(qreal arg);
-
- void rotationSpeedVariationChanged(qreal arg);
-
- void autoRotationChanged(bool arg);
-
- void xVectorChanged(QQuickDirection* arg);
-
- void yVectorChanged(QQuickDirection* arg);
-
- void spritesInterpolateChanged(bool arg);
-
- void bloatChanged(bool arg);
-
- void entryEffectChanged(EntryEffect arg);
-
-public slots:
- void reloadColor(const Color4ub &c, QQuickParticleData* d);
- void setAlphaVariation(qreal arg);
-
- void setAlpha(qreal arg);
-
- void setRedVariation(qreal arg);
-
- void setGreenVariation(qreal arg);
-
- void setBlueVariation(qreal arg);
-
- void setRotation(qreal arg);
-
- void setRotationVariation(qreal arg);
-
- void setRotationSpeed(qreal arg);
-
- void setRotationSpeedVariation(qreal arg);
-
- void setAutoRotation(bool arg);
-
- void setXVector(QQuickDirection* arg);
-
- void setYVector(QQuickDirection* arg);
-
- void setSpritesInterpolate(bool arg);
-
- void setBloat(bool arg);
-
- void setEntryEffect(EntryEffect arg);
-
-protected:
- void reset();
- virtual void initialize(int gIdx, int pIdx);
- virtual void commit(int gIdx, int pIdx);
-
- QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
- void prepareNextFrame();
- QSGGeometryNode* buildParticleNodes();
-
-private slots:
- void createEngine(); //### method invoked by sprite list changing (in engine.h) - pretty nasty
-
- void spriteAdvance(int spriteIndex);
-private:
- QUrl m_image_name;
- QUrl m_colortable_name;
- QUrl m_sizetable_name;
- QUrl m_opacitytable_name;
-
-
- QColor m_color;
- qreal m_color_variation;
-
- QSGGeometryNode *m_rootNode;
- QHash<int, QSGGeometryNode *> m_nodes;
- QHash<int, int> m_idxStarts;//TODO: Proper resizing will lead to needing a spriteEngine per particle - do this after sprite engine gains transparent sharing?
- QList<QPair<int, int> > m_startsIdx;//Same data, optimized for alternate retrieval
-
- int m_lastIdxStart;
- QSGMaterial *m_material;
-
- // derived values...
-
- qreal m_alphaVariation;
- qreal m_alpha;
- qreal m_redVariation;
- qreal m_greenVariation;
- qreal m_blueVariation;
- qreal m_rotation;
- qreal m_rotationVariation;
- qreal m_rotationSpeed;
- qreal m_rotationSpeedVariation;
- bool m_autoRotation;
- QQuickDirection* m_xVector;
- QQuickDirection* m_yVector;
-
- QList<QQuickSprite*> m_sprites;
- QQuickSpriteEngine* m_spriteEngine;
- bool m_spritesInterpolate;
-
- bool m_explicitColor;
- bool m_explicitRotation;
- bool m_explicitDeformation;
- bool m_explicitAnimation;
- QHash<int, QVector<QQuickParticleData*> > m_shadowData;
- void clearShadows();
- QQuickParticleData* getShadowDatum(QQuickParticleData* datum);
-
- bool m_bloat;
- PerformanceLevel perfLevel;
-
- PerformanceLevel m_lastLevel;
- bool m_debugMode;
-
- template<class Vertex>
- void initTexCoords(Vertex* v, int count){
- Vertex* end = v + count;
- while (v < end){
- v[0].tx = 0;
- v[0].ty = 0;
-
- v[1].tx = 1;
- v[1].ty = 0;
-
- v[2].tx = 0;
- v[2].ty = 1;
-
- v[3].tx = 1;
- v[3].ty = 1;
-
- v += 4;
- }
- }
-
- template<class MaterialData>
- MaterialData* getState(QSGMaterial* m){
- return static_cast<QSGSimpleMaterial<MaterialData> *>(m)->state();
- }
- EntryEffect m_entryEffect;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // ULTRAPARTICLE_H
diff --git a/src/declarative/particles/qquickitemparticle.cpp b/src/declarative/particles/qquickitemparticle.cpp
deleted file mode 100644
index 8b39ac3abd..0000000000
--- a/src/declarative/particles/qquickitemparticle.cpp
+++ /dev/null
@@ -1,269 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickitemparticle_p.h"
-#include <private/qquickvisualitemmodel_p.h>
-#include <qsgnode.h>
-#include <QTimer>
-#include <QDeclarativeComponent>
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass ItemParticle QQuickItemParticle
- \inqmlmodule QtQuick.Particles 2
- \inherits ParticlePainter
- \brief The ItemParticle element allows you to specify your own delegate to paint particles.
-
-*/
-
-
-/*!
- \qmlmethod void QtQuick.Particles2::ItemParticle::freeze(Item item)
-
- Suspends the flow of time for the logical particle which item represents, allowing you to control its movement.
-*/
-
-/*!
- \qmlmethod void QtQuick.Particles2::ItemParticle::unfreeze(Item item)
-
- Restarts the flow of time for the logical particle which item represents, allowing it to be moved by the particle system again.
-*/
-
-/*!
- \qmlmethod void QtQuick.Particles2::ItemParticle::take(Item item, bool prioritize)
-
- Asks the ItemParticle to take over control of item. It will be emitted when there is a logical particle available.
-
- By default items form a queue when waiting for a logical particle, but if prioritize is true then it will go immediately to the
- head of the queue.
-*/
-/*!
- \qmlmethod void QtQuick.Particles2::ItemParticle::give(Item item)
-
- Orders the ItemParticle to give you control of the item. It will cease controlling it and the item will lose its association to the logical particle.
-*/
-
-/*!
- \qmlproperty bool QtQuick.Particles2::ItemParticle::fade
-
- If true, the item will automatically be faded in and out
- at the ends of its lifetime. If false, you will have to
- implement any entry effect yourself.
-
- Default is true.
-*/
-/*!
- \qmlproperty Component QtQuick.Particles2::ItemParticle::delegate
-
- An instance of the delegate will be created for every logical
- particle, and moved along with it.
-*/
-
-QQuickItemParticle::QQuickItemParticle(QQuickItem *parent) :
- QQuickParticlePainter(parent), m_fade(true), m_delegate(0)
-{
- setFlag(QQuickItem::ItemHasContents);
- QTimer* manageDelegates = new QTimer(this);//TODO: don't leak
- connect(manageDelegates, SIGNAL(timeout()),
- this, SLOT(tick()));
- manageDelegates->setInterval(16);
- manageDelegates->setSingleShot(false);
- manageDelegates->start();
-}
-
-
-void QQuickItemParticle::freeze(QQuickItem* item)
-{
- m_stasis << item;
-}
-
-
-void QQuickItemParticle::unfreeze(QQuickItem* item)
-{
- m_stasis.remove(item);
-}
-
-void QQuickItemParticle::take(QQuickItem *item, bool prioritize)
-{
- if (prioritize)
- m_pendingItems.push_front(item);
- else
- m_pendingItems.push_back(item);
-}
-
-void QQuickItemParticle::give(QQuickItem *item)
-{
- //TODO: This
- Q_UNUSED(item);
-}
-
-void QQuickItemParticle::initialize(int gIdx, int pIdx)
-{
- m_loadables << m_system->groupData[gIdx]->data[pIdx];//defer to other thread
-}
-
-void QQuickItemParticle::commit(int, int)
-{
-}
-
-void QQuickItemParticle::tick()
-{
- foreach (QQuickItem* item, m_deletables){
- if (m_fade)
- item->setOpacity(0.);
- item->setVisible(false);
- QQuickItemParticleAttached* mpa;
- if ((mpa = qobject_cast<QQuickItemParticleAttached*>(qmlAttachedPropertiesObject<QQuickItemParticle>(item))))
- mpa->detach();//reparent as well?
- //TODO: Delete iff we created it
- m_activeCount--;
- }
- m_deletables.clear();
-
- foreach (QQuickParticleData* d, m_loadables){
- if (m_stasis.contains(d->delegate))
- qWarning() << "Current model particles prefers overwrite:false";
- //remove old item from the particle that is dying to make room for this one
- if (d->delegate)
- m_deletables << d->delegate;
- d->delegate = 0;
- if (!m_pendingItems.isEmpty()){
- d->delegate = m_pendingItems.front();
- m_pendingItems.pop_front();
- }else if (m_delegate){
- d->delegate = qobject_cast<QQuickItem*>(m_delegate->create(qmlContext(this)));
- }
- if (d->delegate && d){//###Data can be zero if creating an item leads to a reset - this screws things up.
- d->delegate->setX(d->curX() - d->delegate->width()/2);//TODO: adjust for system?
- d->delegate->setY(d->curY() - d->delegate->height()/2);
- QQuickItemParticleAttached* mpa = qobject_cast<QQuickItemParticleAttached*>(qmlAttachedPropertiesObject<QQuickItemParticle>(d->delegate));
- if (mpa){
- mpa->m_mp = this;
- mpa->attach();
- }
- d->delegate->setParentItem(this);
- if (m_fade)
- d->delegate->setOpacity(0.);
- d->delegate->setVisible(false);//Will be set to true when we prepare the next frame
- m_activeCount++;
- }
- }
- m_loadables.clear();
-}
-
-void QQuickItemParticle::reset()
-{
- QQuickParticlePainter::reset();
- //TODO: Cleanup items?
- m_loadables.clear();
- //deletables?
-}
-
-
-QSGNode* QQuickItemParticle::updatePaintNode(QSGNode* n, UpdatePaintNodeData* d)
-{
- //Dummy update just to get painting tick
- if (m_pleaseReset){
- m_pleaseReset = false;
- reset();
- }
- prepareNextFrame();
-
- update();//Get called again
- if (n)
- n->markDirty(QSGNode::DirtyMaterial);
- return QQuickItem::updatePaintNode(n,d);
-}
-
-void QQuickItemParticle::prepareNextFrame()
-{
- if (!m_system)
- return;
- qint64 timeStamp = m_system->systemSync(this);
- qreal curT = timeStamp/1000.0;
- qreal dt = curT - m_lastT;
- m_lastT = curT;
- if (!m_activeCount)
- return;
-
- //TODO: Size, better fade?
- foreach (const QString &str, m_groups){
- int gIdx = m_system->groupIds[str];
- int count = m_system->groupData[gIdx]->size();
-
- for (int i=0; i<count; i++){
- QQuickParticleData* data = m_system->groupData[gIdx]->data[i];
- QQuickItem* item = data->delegate;
- if (!item)
- continue;
- qreal t = ((timeStamp/1000.0) - data->t) / data->lifeSpan;
- if (m_stasis.contains(item)) {
- data->t += dt;//Stasis effect
- continue;
- }
- if (t >= 1.0){//Usually happens from load
- m_deletables << item;
- data->delegate = 0;
- }else{//Fade
- data->delegate->setVisible(true);
- if (m_fade){
- qreal o = 1.;
- if (t<0.2)
- o = t*5;
- if (t>0.8)
- o = (1-t)*5;
- item->setOpacity(o);
- }
- }
- item->setX(data->curX() - item->width()/2 - m_systemOffset.x());
- item->setY(data->curY() - item->height()/2 - m_systemOffset.y());
- }
- }
-}
-
-QQuickItemParticleAttached *QQuickItemParticle::qmlAttachedProperties(QObject *object)
-{
- return new QQuickItemParticleAttached(object);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickitemparticle_p.h b/src/declarative/particles/qquickitemparticle_p.h
deleted file mode 100644
index 2e92b9c9ae..0000000000
--- a/src/declarative/particles/qquickitemparticle_p.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ITEMPARTICLE_H
-#define ITEMPARTICLE_H
-#include "qquickparticlepainter_p.h"
-#include <QPointer>
-#include <QSet>
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-class QQuickVisualDataModel;
-class QQuickItemParticleAttached;
-
-class QQuickItemParticle : public QQuickParticlePainter
-{
- Q_OBJECT
- Q_PROPERTY(bool fade READ fade WRITE setFade NOTIFY fadeChanged)
- Q_PROPERTY(QDeclarativeComponent* delegate READ delegate WRITE setDelegate NOTIFY delegateChanged)
-public:
- explicit QQuickItemParticle(QQuickItem *parent = 0);
-
- bool fade() const { return m_fade; }
-
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
-
- static QQuickItemParticleAttached *qmlAttachedProperties(QObject *object);
- QDeclarativeComponent* delegate() const
- {
- return m_delegate;
- }
-
-signals:
- void fadeChanged();
-
- void delegateChanged(QDeclarativeComponent* arg);
-
-public slots:
- //TODO: Add a follow mode, where moving the delegate causes the logical particle to go with it?
- void freeze(QQuickItem* item);
- void unfreeze(QQuickItem* item);
- void take(QQuickItem* item,bool prioritize=false);//take by modelparticle
- void give(QQuickItem* item);//give from modelparticle
-
- void setFade(bool arg){if (arg == m_fade) return; m_fade = arg; emit fadeChanged();}
- void setDelegate(QDeclarativeComponent* arg)
- {
- if (m_delegate != arg) {
- m_delegate = arg;
- emit delegateChanged(arg);
- }
- }
-
-protected:
- virtual void reset();
- virtual void commit(int gIdx, int pIdx);
- virtual void initialize(int gIdx, int pIdx);
- void prepareNextFrame();
-private slots:
- void tick();
-private:
- QList<QQuickItem* > m_deletables;
- QList< QQuickParticleData* > m_loadables;
- bool m_fade;
-
- QList<QQuickItem*> m_pendingItems;
- QList<int> m_available;
- QSet<QQuickItem*> m_stasis;
- qreal m_lastT;
- int m_activeCount;
- QDeclarativeComponent* m_delegate;
-};
-
-class QQuickItemParticleAttached : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QQuickItemParticle* particle READ particle CONSTANT);
-public:
- QQuickItemParticleAttached(QObject* parent)
- : QObject(parent), m_mp(0)
- {;}
- QQuickItemParticle* particle() {return m_mp;}
- void detach(){emit detached();}
- void attach(){emit attached();}
-private:
- QQuickItemParticle* m_mp;
- friend class QQuickItemParticle;
-Q_SIGNALS:
- void detached();
- void attached();
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPEINFO(QQuickItemParticle, QML_HAS_ATTACHED_PROPERTIES)
-
-QT_END_HEADER
-#endif // ITEMPARTICLE_H
diff --git a/src/declarative/particles/qquicklineextruder.cpp b/src/declarative/particles/qquicklineextruder.cpp
deleted file mode 100644
index 73413537cc..0000000000
--- a/src/declarative/particles/qquicklineextruder.cpp
+++ /dev/null
@@ -1,84 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#include "qquicklineextruder_p.h"
-#include <cmath>
-
-/*!
- \qmlclass LineShape QQuickLineExtruder
- \inqmlmodule QtQuick.Particles 2
- \inherits Shape
- \brief The LineShape represents a line to Affectors and Emitter
-
-*/
-
-/*!
- \qmlproperty bool QtQuick.Particles2::LineShape::mirrored
-
- By default, the line goes from (0,0) to (width, height) of the item that
- this shape is being applied to.
-
- If mirrored is set to true, this will be mirrored along the y axis.
- The line will then go from (0,height) to (width, 0).
-*/
-
-QQuickLineExtruder::QQuickLineExtruder(QObject *parent) :
- QQuickParticleExtruder(parent), m_mirrored(false)
-{
-}
-
-QPointF QQuickLineExtruder::extrude(const QRectF &r)
-{
- qreal x,y;
- if (!r.height()){
- x = r.width() * ((qreal)rand())/RAND_MAX;
- y = 0;
- }else{
- y = r.height() * ((qreal)rand())/RAND_MAX;
- if (!r.width()){
- x = 0;
- }else{
- x = r.width()/r.height() * y;
- if (m_mirrored)
- x = r.width() - x;
- }
- }
- return QPointF(x,y);
-}
diff --git a/src/declarative/particles/qquicklineextruder_p.h b/src/declarative/particles/qquicklineextruder_p.h
deleted file mode 100644
index 8258b26043..0000000000
--- a/src/declarative/particles/qquicklineextruder_p.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef LINEEXTRUDER_H
-#define LINEEXTRUDER_H
-#include "qquickparticleextruder_p.h"
-
-class QQuickLineExtruder : public QQuickParticleExtruder
-{
- Q_OBJECT
- //Default is topleft to bottom right. Flipped makes it topright to bottom left
- Q_PROPERTY(bool mirrored READ mirrored WRITE setmirrored NOTIFY mirroredChanged)
-
-public:
- explicit QQuickLineExtruder(QObject *parent = 0);
- virtual QPointF extrude(const QRectF &);
- bool mirrored() const
- {
- return m_mirrored;
- }
-
-signals:
-
- void mirroredChanged(bool arg);
-
-public slots:
-
- void setmirrored(bool arg)
- {
- if (m_mirrored != arg) {
- m_mirrored = arg;
- emit mirroredChanged(arg);
- }
- }
-private:
- bool m_mirrored;
-};
-
-#endif // LINEEXTRUDER_H
diff --git a/src/declarative/particles/qquickmaskextruder.cpp b/src/declarative/particles/qquickmaskextruder.cpp
deleted file mode 100644
index f4850712f0..0000000000
--- a/src/declarative/particles/qquickmaskextruder.cpp
+++ /dev/null
@@ -1,113 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickmaskextruder_p.h"
-#include <QImage>
-#include <QDebug>
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass MaskShape QQuickMaskExtruder
- \inqmlmodule QtQuick.Particles 2
- \inherits Shape
- \brief The MaskShape element allows you to represent an image as a shape to affectors and emitters.
-
-*/
-/*!
- \qmlproperty url QtQuick.Particles2::MaskShape::source
-
- The image to use as the mask. Areas with non-zero opacity
- will be considered inside the shape.
-*/
-
-
-QQuickMaskExtruder::QQuickMaskExtruder(QObject *parent) :
- QQuickParticleExtruder(parent)
- , m_lastWidth(-1)
- , m_lastHeight(-1)
-{
-}
-
-QPointF QQuickMaskExtruder::extrude(const QRectF &r)
-{
- ensureInitialized(r);
- if (!m_mask.count() || m_img.isNull())
- return r.topLeft();
- const QPointF p = m_mask[rand() % m_mask.count()];
- //### Should random sub-pixel positioning be added?
- return p + r.topLeft();
-}
-
-bool QQuickMaskExtruder::contains(const QRectF &bounds, const QPointF &point)
-{
- ensureInitialized(bounds);//###Current usage patterns WILL lead to different bounds/r calls. Separate list?
- if (m_img.isNull())
- return false;
- QPoint p = point.toPoint() - bounds.topLeft().toPoint();
- return m_img.rect().contains(p) && (bool)m_img.pixelIndex(p);
-}
-
-void QQuickMaskExtruder::ensureInitialized(const QRectF &r)
-{
- if (m_lastWidth == r.width() && m_lastHeight == r.height())
- return;//Same as before
- m_lastWidth = r.width();
- m_lastHeight = r.height();
-
- m_img = QImage();
- m_mask.clear();
- if (m_source.isEmpty())
- return;
- m_img = QImage(m_source.toLocalFile());
- if (m_img.isNull()){
- qWarning() << "MaskShape: Cannot load" << qPrintable(m_source.toLocalFile());
- return;
- }
- m_img = m_img.createAlphaMask();
- m_img = m_img.convertToFormat(QImage::Format_Mono);//Else LSB, but I think that's easier
- m_img = m_img.scaled(r.size().toSize());//TODO: Do they need aspect ratio stuff? Or tiling?
- for (int i=0; i<r.width(); i++){
- for (int j=0; j<r.height(); j++){
- if (m_img.pixelIndex(i,j))//Direct bit manipulation is presumably more efficient
- m_mask << QPointF(i,j);
- }
- }
-}
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickmaskextruder_p.h b/src/declarative/particles/qquickmaskextruder_p.h
deleted file mode 100644
index 9430321e50..0000000000
--- a/src/declarative/particles/qquickmaskextruder_p.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MASKEXTRUDER_H
-#define MASKEXTRUDER_H
-#include "qquickparticleextruder_p.h"
-#include <QUrl>
-#include <QImage>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickMaskExtruder : public QQuickParticleExtruder
-{
- Q_OBJECT
- Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
-public:
- explicit QQuickMaskExtruder(QObject *parent = 0);
- virtual QPointF extrude(const QRectF &);
- virtual bool contains(const QRectF &bounds, const QPointF &point);
-
- QUrl source() const
- {
- return m_source;
- }
-
-signals:
-
- void sourceChanged(QUrl arg);
-
-public slots:
-
- void setSource(QUrl arg)
- {
- if (m_source != arg) {
- m_source = arg;
- m_lastHeight = -1;//Trigger reset
- m_lastWidth = -1;
- emit sourceChanged(arg);
- }
- }
-private:
- QUrl m_source;
-
- void ensureInitialized(const QRectF &r);
- int m_lastWidth;
- int m_lastHeight;
- QImage m_img;
- QList<QPointF> m_mask;//TODO: More memory efficient datastructures
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // MASKEXTRUDER_H
diff --git a/src/declarative/particles/qquickparticleaffector.cpp b/src/declarative/particles/qquickparticleaffector.cpp
deleted file mode 100644
index 5bfc699548..0000000000
--- a/src/declarative/particles/qquickparticleaffector.cpp
+++ /dev/null
@@ -1,279 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickparticleaffector_p.h"
-#include <QDebug>
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass Affector QQuickParticleAffector
- \inqmlmodule QtQuick.Particles 2
- \brief Affector elements can alter the attributes of logical particles at any point in their lifetime.
-
- The base Affector does not alter any attributes, but can be used to emit a signal
- when a particle meets certain conditions.
-
- If an affector has a defined size, then it will only affect particles within its size and position on screen.
-
- Affectors have different performance characteristics to the other particle system elements. In particular,
- they have some simplifications to try to maintain a simulation at real-time or faster. When running a system
- with Affectors, irregular frame timings that grow too large ( > one second per frame) will cause the Affectors
- to try and cut corners with a faster but less accurate simulation. If the system has multiple affectors the order
- in which they are applied is not guaranteed, and when simulating larger time shifts they will simulate the whole
- shift each, which can lead to different results compared to smaller time shifts.
-
- Accurate simulation for large numbers of particles (hundreds) with multiple affectors may be possible on some hardware,
- but on less capable hardware you should expect small irregularties in the simulation as simulates with worse granularity.
-*/
-/*!
- \qmlproperty ParticleSystem QtQuick.Particles2::Affector::system
- This is the system which will be affected by the element.
- If the Affector is a direct child of a ParticleSystem, it will automatically be associated with it.
-*/
-/*!
- \qmlproperty list<string> QtQuick.Particles2::Affector::groups
- Which logical particle groups will be affected.
-
- If empty, it will affect all particles.
-*/
-/*!
- \qmlproperty list<string> QtQuick.Particles2::Affector::whenCollidingWith
- If any logical particle groups are specified here, then the affector
- will only be triggered if the particle being examined intersects with
- a particle of one of these groups.
-
- This is different from the groups property. The groups property selects which
- particles might be examined, and if they meet other criteria (including being
- within the bounds of the Affector, modified by shape) then they will be tested
- again to see if they intersect with a particles from one of the particle groups
- in whenCollidingWith.
-
- By default, no groups are specified.
-*/
-/*!
- \qmlproperty bool QtQuick.Particles2::Affector::enabled
- If enabled is set to false, this affector will not affect any particles.
-
- Usually this is used to conditionally turn an affector on or off.
-
- Default value is true.
-*/
-/*!
- \qmlproperty bool QtQuick.Particles2::Affector::once
- If once is set to true, this affector will only affect each particle
- once in their lifetimes. If the affector normally simulates a continuous
- effect over time, then it will simulate the effect of one second of time
- the one instant it affects the particle.
-
- Default value is false.
-*/
-/*!
- \qmlproperty Shape QtQuick.Particles2::Affector::shape
- If a size has been defined, the shape property can be used to affect a
- non-rectangular area.
-*/
-/*!
- \qmlsignal QtQuick.Particles2::Affector::onAffected(x, y)
-
- This signal is emitted each time the affector actually affects a particle.
-
- x,y are the coordinates of the affected particle, relative to the ParticleSystem.
-
-*/
-
-/*!
- \qmlsignal QtQuick.Particles2::Affector::affectParticle(particle particle, real dt)
-
- This handler is called when particles are selected to be affected.
-
- dt is the time since the last time it was affected. Use dt to normalize
- trajectory manipulations to real time.
-
- Note that JS is slower to execute, so it is not recommended to use this in
- high-volume particle systems.
-*/
-/*!
- \qmlsignal QtQuick.Particles2::Affector::affected(real x, real y)
-
- This handler is called when a particle is selected to be affected. It will
- only be called if signal is set to true.
-
- x,y is the particles current position.
-*/
-QQuickParticleAffector::QQuickParticleAffector(QQuickItem *parent) :
- QQuickItem(parent), m_needsReset(false), m_ignoresTime(false), m_onceOff(false), m_enabled(true)
- , m_system(0), m_updateIntSet(false), m_shape(new QQuickParticleExtruder(this))
-{
-}
-
-bool QQuickParticleAffector::isAffectedConnected()
-{
- static int idx = QObjectPrivate::get(this)->signalIndex("affected(qreal,qreal)");
- return QObjectPrivate::get(this)->isSignalConnected(idx);
-}
-
-
-void QQuickParticleAffector::componentComplete()
-{
- if (!m_system && qobject_cast<QQuickParticleSystem*>(parentItem()))
- setSystem(qobject_cast<QQuickParticleSystem*>(parentItem()));
- QQuickItem::componentComplete();
-}
-
-bool QQuickParticleAffector::activeGroup(int g) {
- if (m_updateIntSet){
- m_groupIds.clear();
- foreach (const QString &p, m_groups)
- m_groupIds << m_system->groupIds[p];//###Can this occur before group ids are properly assigned?
- m_updateIntSet = false;
- }
- return m_groupIds.isEmpty() || m_groupIds.contains(g);
-}
-
-bool QQuickParticleAffector::shouldAffect(QQuickParticleData* d)
-{
- if (!d)
- return false;
- if (activeGroup(d->group)){
- if ((m_onceOff && m_onceOffed.contains(qMakePair(d->group, d->index)))
- || !d->stillAlive())
- return false;
- //Need to have previous location for affected anyways
- if (width() == 0 || height() == 0
- || m_shape->contains(QRectF(m_offset.x(), m_offset.y(), width(), height()), QPointF(d->curX(), d->curY()))){
- if (m_whenCollidingWith.isEmpty() || isColliding(d)){
- return true;
- }
- }
- }
- return false;
-
-}
-
-void QQuickParticleAffector::postAffect(QQuickParticleData* d)
-{
- m_system->needsReset << d;
- if (m_onceOff)
- m_onceOffed << qMakePair(d->group, d->index);
- if (isAffectedConnected())
- emit affected(d->curX(), d->curY());
-}
-
-const qreal QQuickParticleAffector::simulationDelta = 0.020;
-const qreal QQuickParticleAffector::simulationCutoff = 1.000;//If this goes above 1.0, then m_once behaviour needs special codepath
-
-void QQuickParticleAffector::affectSystem(qreal dt)
-{
- if (!m_enabled)
- return;
- //If not reimplemented, calls affectParticle per particle
- //But only on particles in targeted system/area
- updateOffsets();//### Needed if an ancestor is transformed.
- if (m_onceOff)
- dt = 1.0;
- foreach (QQuickParticleGroupData* gd, m_system->groupData) {
- if (activeGroup(m_system->groupData.key(gd))) {
- foreach (QQuickParticleData* d, gd->data) {
- if (shouldAffect(d)) {
- bool affected = false;
- qreal myDt = dt;
- if (!m_ignoresTime && myDt < simulationCutoff) {
- int realTime = m_system->timeInt;
- m_system->timeInt -= myDt * 1000.0;
- while (myDt > simulationDelta) {
- m_system->timeInt += simulationDelta * 1000.0;
- if (d->alive())//Only affect during the parts it was alive for
- affected = affectParticle(d, simulationDelta) || affected;
- myDt -= simulationDelta;
- }
- m_system->timeInt = realTime;
- }
- if (myDt > 0.0)
- affected = affectParticle(d, myDt) || affected;
- if (affected)
- postAffect(d);
- }
- }
- }
- }
-}
-
-bool QQuickParticleAffector::affectParticle(QQuickParticleData *, qreal )
-{
- return true;
-}
-
-void QQuickParticleAffector::reset(QQuickParticleData* pd)
-{//TODO: This, among other ones, should be restructured so they don't all need to remember to call the superclass
- if (m_onceOff)
- if (activeGroup(pd->group))
- m_onceOffed.remove(qMakePair(pd->group, pd->index));
-}
-
-void QQuickParticleAffector::updateOffsets()
-{
- if (m_system)
- m_offset = m_system->mapFromItem(this, QPointF(0, 0));
-}
-
-bool QQuickParticleAffector::isColliding(QQuickParticleData *d)
-{
- qreal myCurX = d->curX();
- qreal myCurY = d->curY();
- qreal myCurSize = d->curSize()/2;
- foreach (const QString &group, m_whenCollidingWith){
- foreach (QQuickParticleData* other, m_system->groupData[m_system->groupIds[group]]->data){
- if (!other->stillAlive())
- continue;
- qreal otherCurX = other->curX();
- qreal otherCurY = other->curY();
- qreal otherCurSize = other->curSize()/2;
- if ((myCurX + myCurSize > otherCurX - otherCurSize
- && myCurX - myCurSize < otherCurX + otherCurSize)
- && (myCurY + myCurSize > otherCurY - otherCurSize
- && myCurY - myCurSize < otherCurY + otherCurSize))
- return true;
- }
- }
- return false;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickparticleaffector_p.h b/src/declarative/particles/qquickparticleaffector_p.h
deleted file mode 100644
index d254759ff6..0000000000
--- a/src/declarative/particles/qquickparticleaffector_p.h
+++ /dev/null
@@ -1,201 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PARTICLEAFFECTOR_H
-#define PARTICLEAFFECTOR_H
-
-#include <QObject>
-#include "qquickparticlesystem_p.h"
-#include "qquickparticleextruder_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickParticleAffector : public QQuickItem
-{
- Q_OBJECT
- Q_PROPERTY(QQuickParticleSystem* system READ system WRITE setSystem NOTIFY systemChanged)
- Q_PROPERTY(QStringList groups READ groups WRITE setGroups NOTIFY groupsChanged)
- Q_PROPERTY(QStringList whenCollidingWith READ whenCollidingWith WRITE setWhenCollidingWith NOTIFY whenCollidingWithChanged)
- Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
- Q_PROPERTY(bool once READ onceOff WRITE setOnceOff NOTIFY onceChanged)
- Q_PROPERTY(QQuickParticleExtruder* shape READ shape WRITE setShape NOTIFY shapeChanged)
-
-public:
- explicit QQuickParticleAffector(QQuickItem *parent = 0);
- virtual void affectSystem(qreal dt);
- virtual void reset(QQuickParticleData*);//As some store their own data per particle?
- QQuickParticleSystem* system() const
- {
- return m_system;
- }
-
- QStringList groups() const
- {
- return m_groups;
- }
-
- bool enabled() const
- {
- return m_enabled;
- }
-
- bool onceOff() const
- {
- return m_onceOff;
- }
-
- QQuickParticleExtruder* shape() const
- {
- return m_shape;
- }
-
- QStringList whenCollidingWith() const
- {
- return m_whenCollidingWith;
- }
-
-signals:
-
- void systemChanged(QQuickParticleSystem* arg);
-
- void groupsChanged(QStringList arg);
-
- void enabledChanged(bool arg);
-
- void onceChanged(bool arg);
-
- void shapeChanged(QQuickParticleExtruder* arg);
-
- void affected(qreal x, qreal y);
-
- void whenCollidingWithChanged(QStringList arg);
-
-public slots:
-void setSystem(QQuickParticleSystem* arg)
-{
- if (m_system != arg) {
- m_system = arg;
- m_system->registerParticleAffector(this);
- emit systemChanged(arg);
- }
-}
-
-void setGroups(QStringList arg)
-{
- if (m_groups != arg) {
- m_groups = arg;
- m_updateIntSet = true;
- emit groupsChanged(arg);
- }
-}
-
-void setEnabled(bool arg)
-{
- if (m_enabled != arg) {
- m_enabled = arg;
- emit enabledChanged(arg);
- }
-}
-
-void setOnceOff(bool arg)
-{
- if (m_onceOff != arg) {
- m_onceOff = arg;
- m_needsReset = true;
- emit onceChanged(arg);
- }
-}
-
-void setShape(QQuickParticleExtruder* arg)
-{
- if (m_shape != arg) {
- m_shape = arg;
- emit shapeChanged(arg);
- }
-}
-
-void setWhenCollidingWith(QStringList arg)
-{
- if (m_whenCollidingWith != arg) {
- m_whenCollidingWith = arg;
- emit whenCollidingWithChanged(arg);
- }
-}
-public slots:
- void updateOffsets();
-
-protected:
- friend class QQuickParticleSystem;
- virtual bool affectParticle(QQuickParticleData *d, qreal dt);
- bool m_needsReset:1;//### What is this really saving?
- bool m_ignoresTime:1;
- bool m_onceOff:1;
- bool m_enabled:1;
-
- QQuickParticleSystem* m_system;
- QStringList m_groups;
- bool activeGroup(int g);
- bool shouldAffect(QQuickParticleData* datum);//Call to do the logic on whether it is affecting that datum
- void postAffect(QQuickParticleData* datum);//Call to do the post-affect logic on particles which WERE affected(once off, needs reset, affected signal)
- virtual void componentComplete();
- QPointF m_offset;
- bool isAffectedConnected();
- static const qreal simulationDelta;
- static const qreal simulationCutoff;
-private:
- QSet<int> m_groupIds;
- QSet<QPair<int, int> > m_onceOffed;
- bool m_updateIntSet;
-
- QQuickParticleExtruder* m_shape;
-
- QStringList m_whenCollidingWith;
-
- bool isColliding(QQuickParticleData* d);
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // PARTICLEAFFECTOR_H
diff --git a/src/declarative/particles/qquickparticleemitter.cpp b/src/declarative/particles/qquickparticleemitter.cpp
deleted file mode 100644
index f227256f1b..0000000000
--- a/src/declarative/particles/qquickparticleemitter.cpp
+++ /dev/null
@@ -1,501 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickparticleemitter_p.h"
-#include <private/qdeclarativeengine_p.h>
-QT_BEGIN_NAMESPACE
-
-
-/*!
- \qmlclass Emitter QQuickParticleEmitter
- \inqmlmodule QtQuick.Particles 2
- \brief The Emitter element allows you to emit logical particles.
-
- This element emits logical particles into the ParticleSystem, with the
- given starting attributes.
-
- Note that logical particles are not
- automatically rendered, you will need to have one or more
- ParticlePainter elements visualizing them.
-
- Note that the given starting attributes can be modified at any point
- in the particle's lifetime by any Affector element in the same
- ParticleSystem. This includes attributes like lifespan.
-*/
-
-
-/*!
- \qmlproperty ParticleSystem QtQuick.Particles2::Emitter::system
-
- This is the Particle system that the Emitter will emit into.
- This can be omitted if the Emitter is a direct child of the ParticleSystem
-*/
-/*!
- \qmlproperty string QtQuick.Particles2::Emitter::group
-
- This is the logical particle group which it will emit into.
-
- Default value is "" (empty string).
-*/
-/*!
- \qmlproperty Shape QtQuick.Particles2::Emitter::shape
-
- This shape is applied with the size of the Emitter. Particles will be emitted
- randomly from any area covered by the shape.
-
- The default shape is a filled in rectangle, which corresponds to the full bounding
- box of the Emitter.
-*/
-/*!
- \qmlproperty bool QtQuick.Particles2::Emitter::emitting
-
- If set to false, the emitter will cease emissions until it is set to true.
-
- Default value is true.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Emitter::emitRate
-
- Number of particles emitted per second.
-
- Default value is 10 particles per second.
-*/
-/*!
- \qmlproperty int QtQuick.Particles2::Emitter::lifeSpan
-
- The time in milliseconds each emitted particle should last for.
-
- If you do not want particles to automatically die after a time, for example if
- you wish to dispose of them manually, set lifeSpan to Emitter.InfiniteLife.
-
- lifeSpans greater than or equal to 600000 (10 minutes) will be treated as infinite.
- Particles with lifeSpans less than or equal to 0 will start out dead.
-
- Default value is 1000 (one second).
-*/
-/*!
- \qmlproperty int QtQuick.Particles2::Emitter::lifeSpanVariation
-
- Particle lifespans will vary by up to this much in either direction.
-
- Default value is 0.
-*/
-
-/*!
- \qmlproperty int QtQuick.Particles2::Emitter::maximumEmitted
-
- The maximum number of particles at a time that this emitter will have alive.
-
- This can be set as a performance optimization (when using burst and pulse) or
- to stagger emissions.
-
- If this is set to a number below zero, then there is no maximum limit on the number
- of particles this emitter can have alive.
-
- The default value is -1.
-*/
-/*!
- \qmlproperty int QtQuick.Particles2::Emitter::startTime
-
- If this value is set when the emitter is loaded, then it will emit particles from the
- past, up to startTime milliseconds ago. These will simulate as if they were emitted then,
- but will not have any affectors applied to them. Affectors will take effect from the present time.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Emitter::size
-
- The size in pixels of the particles at the start of their life.
-
- Default value is 16.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Emitter::endSize
-
- The size in pixels of the particles at the end of their life. Size will
- be linearly interpolated during the life of the particle from this value and
- size. If endSize is -1, then the size of the particle will remain constant at
- the starting size.
-
- Default value is -1.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Emitter::sizeVariation
-
- The size of a particle can vary by this much up or down from size/endSize. The same
- random addition is made to both size and endSize for a single particle.
-
- Default value is 0.
-*/
-/*!
- \qmlproperty StochasticDirection QtQuick.Particles2::Emitter::speed
-
- The starting speed of the particles emitted.
-*/
-/*!
- \qmlproperty StochasticDirection QtQuick.Particles2::Emitter::acceleration
-
- The starting acceleraton of the particles emitted.
-*/
-/*!
- \qmlproperty qreal QtQuick.Particles2::Emitter::speedFromMovement
-
- If this value is non-zero, then any movement of the emitter will provide additional
- starting velocity to the particles based on the movement. The additional vector will be the
- same angle as the emitter's movement, with a magnitude that is the magnitude of the emitters
- movement multiplied by speedFromMovement.
-
- Default value is 0.
-*/
-
-/*!
- \qmlsignal QtQuick.Particles2::Emitter::onEmitParticles(Array particles)
-
- This handler is called when particles are emitted. particles is a javascript
- array of Particle objects. You can modify particle attributes directly within the handler.
-
- Note that JS is slower to execute, so it is not recommended to use this in
- high-volume particle systems.
-*/
-
-/*! \qmlmethod QtQuick.Particles2::Emitter::burst(int count)
-
- Emits count particles from this emitter immediately.
-*/
-
-/*! \qmlmethod QtQuick.Particles2::Emitter::burst(int x, int y, int count)
-
- Emits count particles from this emitter immediately. The particles are emitted
- as if the Emitter was positioned at x,y but all other properties are the same.
-*/
-
-/*! \qmlmethod QtQuick.Particles2::Emitter::pulse(int duration)
-
- If the emitter is not enabled, enables it for duration milliseconds and then switches
- it back off.
-*/
-
-QQuickParticleEmitter::QQuickParticleEmitter(QQuickItem *parent) :
- QQuickItem(parent)
- , m_particlesPerSecond(10)
- , m_particleDuration(1000)
- , m_particleDurationVariation(0)
- , m_enabled(true)
- , m_system(0)
- , m_extruder(0)
- , m_defaultExtruder(0)
- , m_speed(&m_nullVector)
- , m_acceleration(&m_nullVector)
- , m_particleSize(16)
- , m_particleEndSize(-1)
- , m_particleSizeVariation(0)
- , m_startTime(0)
- , m_overwrite(true)
- , m_pulseLeft(0)
- , m_maxParticleCount(-1)
- , m_speed_from_movement(0)
- , m_reset_last(true)
- , m_last_timestamp(-1)
- , m_last_emission(0)
-
-{
- //TODO: Reset speed/acc back to null vector? Or allow null pointer?
- connect(this, SIGNAL(maximumEmittedChanged(int)),
- this, SIGNAL(particleCountChanged()));
- connect(this, SIGNAL(particlesPerSecondChanged(qreal)),
- this, SIGNAL(particleCountChanged()));
- connect(this, SIGNAL(particleDurationChanged(int)),
- this, SIGNAL(particleCountChanged()));
-}
-
-QQuickParticleEmitter::~QQuickParticleEmitter()
-{
- if (m_defaultExtruder)
- delete m_defaultExtruder;
-}
-
-bool QQuickParticleEmitter::isEmitConnected()
-{
- static int idx = QObjectPrivate::get(this)->signalIndex("emitParticles(QDeclarativeV8Handle)");
- return QObjectPrivate::get(this)->isSignalConnected(idx);
-}
-
-void QQuickParticleEmitter::componentComplete()
-{
- if (!m_system && qobject_cast<QQuickParticleSystem*>(parentItem()))
- setSystem(qobject_cast<QQuickParticleSystem*>(parentItem()));
- QQuickItem::componentComplete();
-}
-
-void QQuickParticleEmitter::setEnabled(bool arg)
-{
- if (m_enabled != arg) {
- m_enabled = arg;
- emit enabledChanged(arg);
- }
-}
-
-
-QQuickParticleExtruder* QQuickParticleEmitter::effectiveExtruder()
-{
- if (m_extruder)
- return m_extruder;
- if (!m_defaultExtruder)
- m_defaultExtruder = new QQuickParticleExtruder;
- return m_defaultExtruder;
-}
-
-void QQuickParticleEmitter::pulse(int milliseconds)
-{
- if (!particleCount())
- qWarning() << "pulse called on an emitter with a particle count of zero";
- if (!m_enabled)
- m_pulseLeft = milliseconds;
-}
-
-void QQuickParticleEmitter::burst(int num)
-{
- if (!particleCount())
- qWarning() << "burst called on an emitter with a particle count of zero";
- m_burstQueue << qMakePair(num, QPointF(x(), y()));
-}
-
-void QQuickParticleEmitter::burst(int num, qreal x, qreal y)
-{
- if (!particleCount())
- qWarning() << "burst called on an emitter with a particle count of zero";
- m_burstQueue << qMakePair(num, QPointF(x, y));
-}
-
-void QQuickParticleEmitter::setMaxParticleCount(int arg)
-{
- if (m_maxParticleCount != arg) {
- if (arg < 0 && m_maxParticleCount >= 0){
- connect(this, SIGNAL(particlesPerSecondChanged(qreal)),
- this, SIGNAL(particleCountChanged()));
- connect(this, SIGNAL(particleDurationChanged(int)),
- this, SIGNAL(particleCountChanged()));
- }else if (arg >= 0 && m_maxParticleCount < 0){
- disconnect(this, SIGNAL(particlesPerSecondChanged(qreal)),
- this, SIGNAL(particleCountChanged()));
- disconnect(this, SIGNAL(particleDurationChanged(int)),
- this, SIGNAL(particleCountChanged()));
- }
- m_overwrite = arg < 0;
- m_maxParticleCount = arg;
- emit maximumEmittedChanged(arg);
- }
-}
-
-int QQuickParticleEmitter::particleCount() const
-{
- if (m_maxParticleCount >= 0)
- return m_maxParticleCount;
- return m_particlesPerSecond*((m_particleDuration+m_particleDurationVariation)/1000.0);
-}
-
-void QQuickParticleEmitter::setSpeedFromMovement(qreal t)
-{
- if (t == m_speed_from_movement)
- return;
- m_speed_from_movement = t;
- emit speedFromMovementChanged();
-}
-
-void QQuickParticleEmitter::reset()
-{
- m_reset_last = true;
-}
-
-void QQuickParticleEmitter::emitWindow(int timeStamp)
-{
- if (m_system == 0)
- return;
- if ((!m_enabled || !m_particlesPerSecond)&& !m_pulseLeft && m_burstQueue.isEmpty()){
- m_reset_last = true;
- return;
- }
-
- if (m_reset_last) {
- m_last_emitter = m_last_last_emitter = QPointF(x(), y());
- if (m_last_timestamp == -1)
- m_last_timestamp = (timeStamp - m_startTime)/1000.;
- else
- m_last_timestamp = timeStamp/1000.;
- m_last_emission = m_last_timestamp;
- m_reset_last = false;
- m_emitCap = particleCount();
- }
-
- if (m_pulseLeft){
- m_pulseLeft -= timeStamp - m_last_timestamp * 1000.;
- if (m_pulseLeft < 0){
- if (!m_enabled)
- timeStamp += m_pulseLeft;
- m_pulseLeft = 0;
- }
- }
- qreal time = timeStamp / 1000.;
- qreal particleRatio = 1. / m_particlesPerSecond;
- qreal pt = m_last_emission;
- qreal maxLife = (m_particleDuration + m_particleDurationVariation)/1000.0;
- if (pt + maxLife < time)//We missed so much, that we should skip emiting particles that are dead by now
- pt = time - maxLife;
-
- qreal opt = pt; // original particle time
- qreal dt = time - m_last_timestamp; // timestamp delta...
- if (!dt)
- dt = 0.000001;
-
- // emitter difference since last...
- qreal dex = (x() - m_last_emitter.x());
- qreal dey = (y() - m_last_emitter.y());
-
- qreal ax = (m_last_last_emitter.x() + m_last_emitter.x()) / 2;
- qreal bx = m_last_emitter.x();
- qreal cx = (x() + m_last_emitter.x()) / 2;
- qreal ay = (m_last_last_emitter.y() + m_last_emitter.y()) / 2;
- qreal by = m_last_emitter.y();
- qreal cy = (y() + m_last_emitter.y()) / 2;
-
- qreal sizeAtEnd = m_particleEndSize >= 0 ? m_particleEndSize : m_particleSize;
- qreal emitter_x_offset = m_last_emitter.x() - x();
- qreal emitter_y_offset = m_last_emitter.y() - y();
- if (!m_burstQueue.isEmpty() && !m_pulseLeft && !m_enabled)//'outside time' emissions only
- pt = time;
-
- QList<QQuickParticleData*> toEmit;
-
- while ((pt < time && m_emitCap) || !m_burstQueue.isEmpty()) {
- //int pos = m_last_particle % m_particle_count;
- QQuickParticleData* datum = m_system->newDatum(m_system->groupIds[m_group], !m_overwrite);
- if (datum){//actually emit(otherwise we've been asked to skip this one)
- datum->e = this;//###useful?
- qreal t = 1 - (pt - opt) / dt;
- qreal vx =
- - 2 * ax * (1 - t)
- + 2 * bx * (1 - 2 * t)
- + 2 * cx * t;
- qreal vy =
- - 2 * ay * (1 - t)
- + 2 * by * (1 - 2 * t)
- + 2 * cy * t;
-
-
- // Particle timestamp
- datum->t = pt;
- datum->lifeSpan =
- (m_particleDuration
- + ((rand() % ((m_particleDurationVariation*2) + 1)) - m_particleDurationVariation))
- / 1000.0;
-
- if (datum->lifeSpan >= m_system->maxLife){
- datum->lifeSpan = m_system->maxLife;
- m_emitCap--;//emitCap keeps us from reemitting 'infinite' particles after their life. Unless you reset the emitter.
- }
-
- // Particle position
- QRectF boundsRect;
- if (!m_burstQueue.isEmpty()){
- boundsRect = QRectF(m_burstQueue.first().second.x() - x(), m_burstQueue.first().second.y() - y(),
- width(), height());
- } else {
- boundsRect = QRectF(emitter_x_offset + dex * (pt - opt) / dt, emitter_y_offset + dey * (pt - opt) / dt
- , width(), height());
- }
- QPointF newPos = effectiveExtruder()->extrude(boundsRect);
- datum->x = newPos.x();
- datum->y = newPos.y();
-
- // Particle speed
- const QPointF &speed = m_speed->sample(newPos);
- datum->vx = speed.x()
- + m_speed_from_movement * vx;
- datum->vy = speed.y()
- + m_speed_from_movement * vy;
-
- // Particle acceleration
- const QPointF &accel = m_acceleration->sample(newPos);
- datum->ax = accel.x();
- datum->ay = accel.y();
-
- // Particle size
- float sizeVariation = -m_particleSizeVariation
- + rand() / float(RAND_MAX) * m_particleSizeVariation * 2;
-
- float size = qMax((qreal)0.0 , m_particleSize + sizeVariation);
- float endSize = qMax((qreal)0.0 , sizeAtEnd + sizeVariation);
-
- datum->size = size;// * float(m_emitting);
- datum->endSize = endSize;// * float(m_emitting);
-
- toEmit << datum;
- }
- if (m_burstQueue.isEmpty()){
- pt += particleRatio;
- }else{
- m_burstQueue.first().first--;
- if (m_burstQueue.first().first <= 0)
- m_burstQueue.pop_front();
- }
- }
-
- if (isEmitConnected()) {
- v8::HandleScope handle_scope;
- v8::Context::Scope scope(QDeclarativeEnginePrivate::getV8Engine(qmlEngine(this))->context());
- v8::Handle<v8::Array> array = v8::Array::New(toEmit.size());
- for (int i=0; i<toEmit.size(); i++)
- array->Set(i, toEmit[i]->v8Value().toHandle());
-
- emitParticles(QDeclarativeV8Handle::fromHandle(array));//A chance for arbitrary JS changes
- }
- foreach (QQuickParticleData* d, toEmit)
- m_system->emitParticle(d);
-
- m_last_emission = pt;
-
- m_last_last_last_emitter = m_last_last_emitter;
- m_last_last_emitter = m_last_emitter;
- m_last_emitter = QPointF(x(), y());
- m_last_timestamp = time;
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickparticleemitter_p.h b/src/declarative/particles/qquickparticleemitter_p.h
deleted file mode 100644
index 2d725e5c9e..0000000000
--- a/src/declarative/particles/qquickparticleemitter_p.h
+++ /dev/null
@@ -1,351 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PARTICLEEMITTER_H
-#define PARTICLEEMITTER_H
-
-#include <QQuickItem>
-#include <QDebug>
-#include "qquickparticlesystem_p.h"
-#include "qquickparticleextruder_p.h"
-#include "qquickdirection_p.h"
-
-#include <QList>
-#include <QPair>
-#include <QPointF>
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickParticleEmitter : public QQuickItem
-{
- Q_OBJECT
- Q_PROPERTY(QQuickParticleSystem* system READ system WRITE setSystem NOTIFY systemChanged)
- Q_PROPERTY(QString group READ group WRITE setGroup NOTIFY groupChanged)
- Q_PROPERTY(QQuickParticleExtruder* shape READ extruder WRITE setExtruder NOTIFY extruderChanged)
- Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
- Q_PROPERTY(int startTime READ startTime WRITE setStartTime NOTIFY startTimeChanged)
-
- Q_PROPERTY(qreal emitRate READ particlesPerSecond WRITE setParticlesPerSecond NOTIFY particlesPerSecondChanged)
- Q_PROPERTY(int lifeSpan READ particleDuration WRITE setParticleDuration NOTIFY particleDurationChanged)
- Q_PROPERTY(int lifeSpanVariation READ particleDurationVariation WRITE setParticleDurationVariation NOTIFY particleDurationVariationChanged)
- Q_PROPERTY(int maximumEmitted READ maxParticleCount WRITE setMaxParticleCount NOTIFY maximumEmittedChanged)
-
- Q_PROPERTY(qreal size READ particleSize WRITE setParticleSize NOTIFY particleSizeChanged)
- Q_PROPERTY(qreal endSize READ particleEndSize WRITE setParticleEndSize NOTIFY particleEndSizeChanged)
- Q_PROPERTY(qreal sizeVariation READ particleSizeVariation WRITE setParticleSizeVariation NOTIFY particleSizeVariationChanged)
-
- Q_PROPERTY(QQuickDirection *speed READ speed WRITE setSpeed NOTIFY speedChanged)
- Q_PROPERTY(QQuickDirection *acceleration READ acceleration WRITE setAcceleration NOTIFY accelerationChanged)
- Q_PROPERTY(qreal speedFromMovement READ speedFromMovement WRITE setSpeedFromMovement NOTIFY speedFromMovementChanged)
-
- Q_ENUMS(Lifetime)
-public:
- explicit QQuickParticleEmitter(QQuickItem *parent = 0);
- virtual ~QQuickParticleEmitter();
- virtual void emitWindow(int timeStamp);
-
- enum Lifetime {
- InfiniteLife = QQuickParticleSystem::maxLife
- };
-
- bool enabled() const
- {
- return m_enabled;
- }
-
- qreal particlesPerSecond() const
- {
- return m_particlesPerSecond;
- }
-
- int particleDuration() const
- {
- return m_particleDuration;
- }
-
- QQuickParticleSystem* system() const
- {
- return m_system;
- }
-
- QString group() const
- {
- return m_group;
- }
-
- int particleDurationVariation() const
- {
- return m_particleDurationVariation;
- }
-
- qreal speedFromMovement() const { return m_speed_from_movement; }
- void setSpeedFromMovement(qreal s);
- virtual void componentComplete();
-signals:
- void emitParticles(QDeclarativeV8Handle particles);
- void particlesPerSecondChanged(qreal);
- void particleDurationChanged(int);
- void enabledChanged(bool);
-
- void systemChanged(QQuickParticleSystem* arg);
-
- void groupChanged(QString arg);
-
- void particleDurationVariationChanged(int arg);
-
- void extruderChanged(QQuickParticleExtruder* arg);
-
- void particleSizeChanged(qreal arg);
-
- void particleEndSizeChanged(qreal arg);
-
- void particleSizeVariationChanged(qreal arg);
-
- void speedChanged(QQuickDirection * arg);
-
- void accelerationChanged(QQuickDirection * arg);
-
- void maximumEmittedChanged(int arg);
- void particleCountChanged();
-
- void speedFromMovementChanged();
-
- void startTimeChanged(int arg);
-
-public slots:
- void pulse(int milliseconds);
- void burst(int num);
- void burst(int num, qreal x, qreal y);
-
- void setEnabled(bool arg);
-
- void setParticlesPerSecond(qreal arg)
- {
- if (m_particlesPerSecond != arg) {
- m_particlesPerSecond = arg;
- emit particlesPerSecondChanged(arg);
- }
- }
-
- void setParticleDuration(int arg)
- {
- if (m_particleDuration != arg) {
- m_particleDuration = arg;
- emit particleDurationChanged(arg);
- }
- }
-
- void setSystem(QQuickParticleSystem* arg)
- {
- if (m_system != arg) {
- m_system = arg;
- m_system->registerParticleEmitter(this);
- emit systemChanged(arg);
- }
- }
-
- void setGroup(QString arg)
- {
- if (m_group != arg) {
- m_group = arg;
- emit groupChanged(arg);
- }
- }
-
- void setParticleDurationVariation(int arg)
- {
- if (m_particleDurationVariation != arg) {
- m_particleDurationVariation = arg;
- emit particleDurationVariationChanged(arg);
- }
- }
- void setExtruder(QQuickParticleExtruder* arg)
- {
- if (m_extruder != arg) {
- m_extruder = arg;
- emit extruderChanged(arg);
- }
- }
-
- void setParticleSize(qreal arg)
- {
- if (m_particleSize != arg) {
- m_particleSize = arg;
- emit particleSizeChanged(arg);
- }
- }
-
- void setParticleEndSize(qreal arg)
- {
- if (m_particleEndSize != arg) {
- m_particleEndSize = arg;
- emit particleEndSizeChanged(arg);
- }
- }
-
- void setParticleSizeVariation(qreal arg)
- {
- if (m_particleSizeVariation != arg) {
- m_particleSizeVariation = arg;
- emit particleSizeVariationChanged(arg);
- }
- }
-
- void setSpeed(QQuickDirection * arg)
- {
- if (m_speed != arg) {
- m_speed = arg;
- emit speedChanged(arg);
- }
- }
-
- void setAcceleration(QQuickDirection * arg)
- {
- if (m_acceleration != arg) {
- m_acceleration = arg;
- emit accelerationChanged(arg);
- }
- }
-
- void setMaxParticleCount(int arg);
-
- void setStartTime(int arg)
- {
- if (m_startTime != arg) {
- m_startTime = arg;
- emit startTimeChanged(arg);
- }
- }
-
- virtual void reset();
-public:
- int particleCount() const;
-
- QQuickParticleExtruder* extruder() const
- {
- return m_extruder;
- }
-
- qreal particleSize() const
- {
- return m_particleSize;
- }
-
- qreal particleEndSize() const
- {
- return m_particleEndSize;
- }
-
- qreal particleSizeVariation() const
- {
- return m_particleSizeVariation;
- }
-
- QQuickDirection * speed() const
- {
- return m_speed;
- }
-
- QQuickDirection * acceleration() const
- {
- return m_acceleration;
- }
-
- int maxParticleCount() const
- {
- return m_maxParticleCount;
- }
-
- int startTime() const
- {
- return m_startTime;
- }
-
-protected:
- qreal m_particlesPerSecond;
- int m_particleDuration;
- int m_particleDurationVariation;
- bool m_enabled;
- QQuickParticleSystem* m_system;
- QString m_group;
- QQuickParticleExtruder* m_extruder;
- QQuickParticleExtruder* m_defaultExtruder;
- QQuickParticleExtruder* effectiveExtruder();
- QQuickDirection * m_speed;
- QQuickDirection * m_acceleration;
- qreal m_particleSize;
- qreal m_particleEndSize;
- qreal m_particleSizeVariation;
-
- qreal m_speedFromMovement;
- int m_startTime;
- bool m_overwrite;
-
- int m_pulseLeft;
- QList<QPair<int, QPointF > > m_burstQueue;
- int m_maxParticleCount;
-
- //Used in default implementation, but might be useful
- qreal m_speed_from_movement;
-
- int m_emitCap;
- bool m_reset_last;
- qreal m_last_timestamp;
- qreal m_last_emission;
-
- QPointF m_last_emitter;
- QPointF m_last_last_emitter;
- QPointF m_last_last_last_emitter;
-
- bool isEmitConnected();
-private:
- QQuickDirection m_nullVector;
-
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // PARTICLEEMITTER_H
diff --git a/src/declarative/particles/qquickparticleextruder.cpp b/src/declarative/particles/qquickparticleextruder.cpp
deleted file mode 100644
index 8b25de26be..0000000000
--- a/src/declarative/particles/qquickparticleextruder.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickparticleextruder_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass Shape QQuickParticleExtruder
- \inqmlmodule QtQuick.Particles 2
- \brief The Shape element allows you to specify an area for affectors and emitter.
-
- The base class is just a rectangle.
-*/
-
-QQuickParticleExtruder::QQuickParticleExtruder(QObject *parent) :
- QObject(parent)
-{
-}
-
-QPointF QQuickParticleExtruder::extrude(const QRectF &rect)
-{
- return QPointF(((qreal)rand() / RAND_MAX) * rect.width() + rect.x(),
- ((qreal)rand() / RAND_MAX) * rect.height() + rect.y());
-}
-
-bool QQuickParticleExtruder::contains(const QRectF &bounds, const QPointF &point)
-{
- return bounds.contains(point);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickparticleextruder_p.h b/src/declarative/particles/qquickparticleextruder_p.h
deleted file mode 100644
index 7969abad7c..0000000000
--- a/src/declarative/particles/qquickparticleextruder_p.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PARTICLEEXTRUDER_H
-#define PARTICLEEXTRUDER_H
-
-#include <QObject>
-#include <QRectF>
-#include <QPointF>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickParticleExtruder : public QObject
-{
- Q_OBJECT
-
-public:
- explicit QQuickParticleExtruder(QObject *parent = 0);
- virtual QPointF extrude(const QRectF &);
- virtual bool contains(const QRectF &bounds, const QPointF &point);
-
-signals:
-public slots:
-protected:
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // PARTICLEEXTRUDER_H
diff --git a/src/declarative/particles/qquickparticlegroup.cpp b/src/declarative/particles/qquickparticlegroup.cpp
deleted file mode 100644
index 5486339611..0000000000
--- a/src/declarative/particles/qquickparticlegroup.cpp
+++ /dev/null
@@ -1,143 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickparticlegroup_p.h"
-
-/*!
- \qmlclass ParticleGroup QQuickParticleGroup
- \inqmlmodule QtQuick.Particles 2
- \brief ParticleGroup elements allow you to set attributes on a logical particle group.
-
- This element allows you to set timed transitions on particle groups.
-
- You can also use this element to group particle system elements related to the logical
- particle group. Emitters, Affectors and Painters set as direct children of a ParticleGroup
- will automatically apply to that logical particle group. TrailEmitters will automatically follow
- the group.
-
- If a ParticleGroup element is not defined for a group, the group will function normally as if
- none of the transition properties were set.
-*/
-/*!
- \qmlproperty ParticleSystem QtQuick.Particles2::ParticleGroup::system
- This is the system which will contain the group.
-
- If the ParticleGroup is a direct child of a ParticleSystem, it will automatically be associated with it.
-*/
-/*!
- \qmlproperty string QtQuick.Particles2::ParticleGroup::name
- This is the name of the particle group, and how it is generally referred to by other elements.
-
- If elements refer to a name which does not have an explicit ParticleGroup created, it will
- work normally (with no transitions specified for the group). If you do not need to assign
- duration based transitions to a group, you do not need to create a ParticleGroup with that name (although you may).
-*/
-/*!
- \qmlproperty int QtQuick.Particles2::ParticleGroup::duration
- The time in milliseconds before the group will attempt to transition.
-
-*/
-/*!
- \qmlproperty ParticleSystem QtQuick.Particles2::ParticleGroup::durationVariation
- The maximum number of milliseconds that the duration of the transition cycle varies per particle in the group.
-
- Default value is zero.
-*/
-/*!
- \qmlproperty ParticleSystem QtQuick.Particles2::ParticleGroup::to
- The weighted list of transitions valid for this group.
-
- If the chosen transition stays in this group, another duration (+/- up to durationVariation)
- milliseconds will occur before another transition is attempted.
-*/
-
-QQuickParticleGroup::QQuickParticleGroup(QObject* parent)
- : QQuickStochasticState(parent)
- , m_system(0)
-{
-
-}
-
-void delayedRedirect(QDeclarativeListProperty<QObject> *prop, QObject *value)
-{
- QQuickParticleGroup* pg = qobject_cast<QQuickParticleGroup*>(prop->object);
- if (pg)
- pg->delayRedirect(value);
-}
-
-QDeclarativeListProperty<QObject> QQuickParticleGroup::particleChildren()
-{
- QQuickParticleSystem* system = qobject_cast<QQuickParticleSystem*>(parent());
- if (system)
- return QDeclarativeListProperty<QObject>(this, 0, &QQuickParticleSystem::statePropertyRedirect);
- else
- return QDeclarativeListProperty<QObject>(this, 0, &delayedRedirect);
-}
-
-void QQuickParticleGroup::setSystem(QQuickParticleSystem* arg)
-{
- if (m_system != arg) {
- m_system = arg;
- m_system->registerParticleGroup(this);
- performDelayedRedirects();
- emit systemChanged(arg);
- }
-}
-
-void QQuickParticleGroup::delayRedirect(QObject *obj)
-{
- m_delayedRedirects << obj;
-}
-
-void QQuickParticleGroup::performDelayedRedirects()
-{
- if (!m_system)
- return;
- foreach (QObject* obj, m_delayedRedirects)
- m_system->stateRedirect(this, m_system, obj);
-
- m_delayedRedirects.clear();
-}
-
-void QQuickParticleGroup::componentComplete(){
- if (!m_system && qobject_cast<QQuickParticleSystem*>(parent()))
- setSystem(qobject_cast<QQuickParticleSystem*>(parent()));
-}
diff --git a/src/declarative/particles/qquickparticlegroup_p.h b/src/declarative/particles/qquickparticlegroup_p.h
deleted file mode 100644
index 547e7fc597..0000000000
--- a/src/declarative/particles/qquickparticlegroup_p.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef QQuickPARTICLEGROUP
-#define QQuickPARTICLEGROUP
-#include <private/qquickspriteengine_p.h>
-#include "qquickparticlesystem_p.h"
-#include "qdeclarativeparserstatus.h"
-
-QT_BEGIN_NAMESPACE
-
-class QQuickParticleGroup : public QQuickStochasticState, public QDeclarativeParserStatus
-{
- Q_OBJECT
- //### Would setting limits per group be useful? Or clutter the API?
- //Q_PROPERTY(int maximumAlive READ maximumAlive WRITE setMaximumAlive NOTIFY maximumAliveChanged)
-
- Q_PROPERTY(QQuickParticleSystem* system READ system WRITE setSystem NOTIFY systemChanged)
-
- //Intercept children requests and assign to the group & system
- Q_PROPERTY(QDeclarativeListProperty<QObject> particleChildren READ particleChildren DESIGNABLE false)//### Hidden property for in-state system definitions - ought not to be used in actual "Sprite" states
- Q_CLASSINFO("DefaultProperty", "particleChildren")
- Q_INTERFACES(QDeclarativeParserStatus)
-
-public:
- explicit QQuickParticleGroup(QObject* parent = 0);
-
- QDeclarativeListProperty<QObject> particleChildren();
-
- int maximumAlive() const
- {
- return m_maximumAlive;
- }
-
- QQuickParticleSystem* system() const
- {
- return m_system;
- }
-
-public slots:
-
- void setMaximumAlive(int arg)
- {
- if (m_maximumAlive != arg) {
- m_maximumAlive = arg;
- emit maximumAliveChanged(arg);
- }
- }
-
- void setSystem(QQuickParticleSystem* arg);
-
- void delayRedirect(QObject* obj);
-
-signals:
-
- void maximumAliveChanged(int arg);
-
- void systemChanged(QQuickParticleSystem* arg);
-
-protected:
- virtual void componentComplete();
- virtual void classBegin(){;}
-
-private:
-
- void performDelayedRedirects();
-
- int m_maximumAlive;
- QQuickParticleSystem* m_system;
- QList<QObject*> m_delayedRedirects;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/declarative/particles/qquickparticlepainter.cpp b/src/declarative/particles/qquickparticlepainter.cpp
deleted file mode 100644
index 812c4b86dc..0000000000
--- a/src/declarative/particles/qquickparticlepainter.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickparticlepainter_p.h"
-#include <QDebug>
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass ParticlePainter QQuickParticlePainter
- \inqmlmodule QtQuick.Particles 2
- \inherits ParticlePainter
- \brief ParticlePainter elements allow you to specify how to paint particles.
-
- The default implementation paints nothing. See the subclasses if you want to
- paint something visible.
-
-*/
-/*!
- \qmlproperty ParticleSystem QtQuick.Particles2::ParticlePainter::system
- This is the system whose particles can be painted by the element.
- If the ParticlePainter is a direct child of a ParticleSystem, it will automatically be associated with it.
-*/
-/*!
- \qmlproperty list<string> QtQuick.Particles2::ParticlePainter::groups
- Which logical particle groups will be painted.
-
- If empty, it will paint the default particle group ("").
-*/
-QQuickParticlePainter::QQuickParticlePainter(QQuickItem *parent) :
- QQuickItem(parent),
- m_system(0), m_count(0), m_pleaseReset(true)
-{
-}
-
-void QQuickParticlePainter::componentComplete()
-{
- if (!m_system && qobject_cast<QQuickParticleSystem*>(parentItem()))
- setSystem(qobject_cast<QQuickParticleSystem*>(parentItem()));
- QQuickItem::componentComplete();
-}
-
-
-void QQuickParticlePainter::setSystem(QQuickParticleSystem *arg)
-{
- if (m_system != arg) {
- m_system = arg;
- if (m_system){
- m_system->registerParticlePainter(this);
- reset();
- }
- emit systemChanged(arg);
- }
-}
-
-void QQuickParticlePainter::load(QQuickParticleData* d)
-{
- initialize(d->group, d->index);
- if (m_pleaseReset)
- return;
- m_pendingCommits << qMakePair<int, int>(d->group, d->index);
-}
-
-void QQuickParticlePainter::reload(QQuickParticleData* d)
-{
- if (m_pleaseReset)
- return;
- m_pendingCommits << qMakePair<int, int>(d->group, d->index);
-}
-
-void QQuickParticlePainter::reset()
-{
-}
-
-void QQuickParticlePainter::setCount(int c)//### TODO: some resizeing so that particles can reallocate on size change instead of recreate
-{
- Q_ASSERT(c >= 0); //XXX
- if (c == m_count)
- return;
- m_count = c;
- emit countChanged();
- reset();
-}
-
-int QQuickParticlePainter::count()
-{
- return m_count;
-}
-
-void QQuickParticlePainter::calcSystemOffset(bool resetPending)
-{
- if (!m_system || !parentItem())
- return;
- QPointF lastOffset = m_systemOffset;
- m_systemOffset = -1 * this->mapFromItem(m_system, QPointF(0.0, 0.0));
- if (lastOffset != m_systemOffset && !resetPending){
- //Reload all particles//TODO: Necessary?
- foreach (const QString &g, m_groups){
- int gId = m_system->groupIds[g];
- foreach (QQuickParticleData* d, m_system->groupData[gId]->data)
- reload(d);
- }
- }
-}
-typedef QPair<int,int> intPair;
-void QQuickParticlePainter::performPendingCommits()
-{
- calcSystemOffset();
- foreach (intPair p, m_pendingCommits)
- commit(p.first, p.second);
- m_pendingCommits.clear();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickparticlepainter_p.h b/src/declarative/particles/qquickparticlepainter_p.h
deleted file mode 100644
index e80d68fa09..0000000000
--- a/src/declarative/particles/qquickparticlepainter_p.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PARTICLE_H
-#define PARTICLE_H
-
-#include <QObject>
-#include <QDebug>
-#include <QPair>
-#include "qquickparticlesystem_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QQuickParticlePainter : public QQuickItem
-{
- Q_OBJECT
- Q_PROPERTY(QQuickParticleSystem* system READ system WRITE setSystem NOTIFY systemChanged)
- Q_PROPERTY(QStringList groups READ groups WRITE setGroups NOTIFY groupsChanged)
-
-public:
- explicit QQuickParticlePainter(QQuickItem *parent = 0);
- //Data Interface to system
- void load(QQuickParticleData*);
- void reload(QQuickParticleData*);
- void setCount(int c);
- int count();
- void performPendingCommits();//Called from updatePaintNode
- QQuickParticleSystem* system() const
- {
- return m_system;
- }
-
-
- QStringList groups() const
- {
- return m_groups;
- }
-
-signals:
- void countChanged();
- void systemChanged(QQuickParticleSystem* arg);
-
- void groupsChanged(QStringList arg);
-
-public slots:
- void setSystem(QQuickParticleSystem* arg);
-
- void setGroups(QStringList arg)
- {
- if (m_groups != arg) {
- m_groups = arg;
- emit groupsChanged(arg);
- }
- }
-
- void calcSystemOffset(bool resetPending = false);
-
-protected:
- /* Reset resets all your internal data structures. But anything attached to a particle should
- be in attached data. So reset + reloads should have no visible effect.
- ###Hunt down all cases where we do a complete reset for convenience and be more targeted
- */
- virtual void reset();
-
- virtual void componentComplete();
- virtual void initialize(int gIdx, int pIdx){//Called from main thread
- Q_UNUSED(gIdx);
- Q_UNUSED(pIdx);
- }
- virtual void commit(int gIdx, int pIdx){//Called in Render Thread
- //###If you need to do something on size changed, check m_data size in this? Or we reset you every time?
- Q_UNUSED(gIdx);
- Q_UNUSED(pIdx);
- }
-
- QQuickParticleSystem* m_system;
- friend class QQuickParticleSystem;
- int m_count;
- bool m_pleaseReset;//Used by subclasses, but it's a nice optimization to know when stuff isn't going to matter.
- QStringList m_groups;
- QPointF m_systemOffset;
-
-private:
- QSet<QPair<int,int> > m_pendingCommits;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // PARTICLE_H
diff --git a/src/declarative/particles/qquickparticlesmodule.cpp b/src/declarative/particles/qquickparticlesmodule.cpp
deleted file mode 100644
index 26439c4f50..0000000000
--- a/src/declarative/particles/qquickparticlesmodule.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickangledirection_p.h"
-#include "qquickcustomparticle_p.h"
-#include "qquickellipseextruder_p.h"
-#include "qquicktrailemitter_p.h"
-#include "qquickfriction_p.h"
-#include "qquickgravity_p.h"
-#include "qquickimageparticle_p.h"
-#include "qquickitemparticle_p.h"
-#include "qquickage_p.h"
-#include "qquicklineextruder_p.h"
-#include "qquickmaskextruder_p.h"
-#include "qquickparticleaffector_p.h"
-#include "qquickparticleemitter_p.h"
-#include "qquickparticleextruder_p.h"
-#include "qquickparticlepainter_p.h"
-#include "qquickparticlesmodule_p.h"
-#include "qquickparticlesystem_p.h"
-#include "qquickpointattractor_p.h"
-#include "qquickpointdirection_p.h"
-#include "qquickspritegoal_p.h"
-#include "qquickdirection_p.h"
-#include "qquicktargetdirection_p.h"
-#include "qquickturbulence_p.h"
-#include "qquickwander_p.h"
-#include "qquickcumulativedirection_p.h"
-#include "qquickcustomaffector_p.h"
-#include "qquickrectangleextruder_p.h"
-#include "qquickparticlegroup_p.h"
-#include "qquickgroupgoal_p.h"
-
-QT_BEGIN_NAMESPACE
-
-void QQuickParticlesModule::defineModule()
-{
- const char* uri = "QtQuick.Particles";
-
- qmlRegisterType<QQuickParticleSystem>(uri, 2, 0, "ParticleSystem");
- qmlRegisterType<QQuickParticleGroup>(uri, 2, 0, "ParticleGroup");
-
- qmlRegisterType<QQuickImageParticle>(uri, 2, 0, "ImageParticle");
- qmlRegisterType<QQuickCustomParticle>(uri, 2, 0, "CustomParticle");
- qmlRegisterType<QQuickItemParticle>(uri, 2, 0, "ItemParticle");
-
- qmlRegisterType<QQuickParticleEmitter>(uri, 2, 0, "Emitter");
- qmlRegisterType<QQuickTrailEmitter>(uri, 2, 0, "TrailEmitter");
-
- qmlRegisterType<QQuickEllipseExtruder>(uri, 2, 0, "EllipseShape");
- qmlRegisterType<QQuickRectangleExtruder>(uri, 2, 0, "RectangleShape");
- qmlRegisterType<QQuickLineExtruder>(uri, 2, 0, "LineShape");
- qmlRegisterType<QQuickMaskExtruder>(uri, 2, 0, "MaskShape");
-
- qmlRegisterType<QQuickPointDirection>(uri, 2, 0, "PointDirection");
- qmlRegisterType<QQuickAngleDirection>(uri, 2, 0, "AngleDirection");
- qmlRegisterType<QQuickTargetDirection>(uri, 2, 0, "TargetDirection");
- qmlRegisterType<QQuickCumulativeDirection>(uri, 2, 0, "CumulativeDirection");
-
- qmlRegisterType<QQuickCustomAffector>(uri, 2, 0, "Affector");
- qmlRegisterType<QQuickWanderAffector>(uri, 2, 0, "Wander");
- qmlRegisterType<QQuickFrictionAffector>(uri, 2, 0, "Friction");
- qmlRegisterType<QQuickAttractorAffector>(uri, 2, 0, "Attractor");
- qmlRegisterType<QQuickGravityAffector>(uri, 2, 0, "Gravity");
- qmlRegisterType<QQuickAgeAffector>(uri, 2, 0, "Age");
- qmlRegisterType<QQuickSpriteGoalAffector>(uri, 2, 0, "SpriteGoal");
- qmlRegisterType<QQuickGroupGoalAffector>(uri, 2, 0, "GroupGoal");
- qmlRegisterType<QQuickTurbulenceAffector>(uri, 2, 0 , "Turbulence");
-
- //Exposed just for completeness
- qmlRegisterUncreatableType<QQuickParticleAffector>(uri, 2, 0, "ParticleAffector",
- QStringLiteral("Abstract type. Use one of the inheriting types instead."));
- qmlRegisterUncreatableType<QQuickParticlePainter>(uri, 2, 0, "ParticlePainter",
- QStringLiteral("Abstract type. Use one of the inheriting types instead."));
- qmlRegisterUncreatableType<QQuickParticleExtruder>(uri, 2, 0, "ParticleExtruder",
- QStringLiteral("Abstract type. Use one of the inheriting types instead."));
- qmlRegisterUncreatableType<QQuickDirection>(uri, 2, 0, "NullVector",
- QStringLiteral("Abstract type. Use one of the inheriting types instead."));
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/particles/qquickparticlesmodule_p.h b/src/declarative/particles/qquickparticlesmodule_p.h
deleted file mode 100644
index afea56293b..0000000000
--- a/src/declarative/particles/qquickparticlesmodule_p.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQuickPARTICLESMODULE_H
-#define QQuickPARTICLESMODULE_H
-
-#include <qdeclarative.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickParticlesModule
-{
-public:
- static void defineModule();
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QQuickPARTICLESMODULE_H
diff --git a/src/declarative/particles/qquickparticlesystem.cpp b/src/declarative/particles/qquickparticlesystem.cpp
deleted file mode 100644
index 9e6bafab20..0000000000
--- a/src/declarative/particles/qquickparticlesystem.cpp
+++ /dev/null
@@ -1,1106 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickparticlesystem_p.h"
-#include <qsgnode.h>
-#include "qquickparticleemitter_p.h"
-#include "qquickparticleaffector_p.h"
-#include "qquickparticlepainter_p.h"
-#include <private/qquickspriteengine_p.h>
-#include <private/qquicksprite_p.h>
-#include "qquickv8particledata_p.h"
-#include "qquickparticlegroup_p.h"
-
-#include "qquicktrailemitter_p.h"//###For auto-follow on states, perhaps should be in emitter?
-#include <private/qdeclarativeengine_p.h>
-#include <cmath>
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-//###Switch to define later, for now user-friendly (no compilation) debugging is worth it
-DEFINE_BOOL_CONFIG_OPTION(qmlParticlesDebug, QML_PARTICLES_DEBUG)
-/*!
- \qmlclass ParticleSystem QQuickParticleSystem
- \inqmlmodule QtQuick.Particles 2
- \brief The ParticleSystem brings together ParticlePainter, Emitter and Affector elements.
-
-*/
-
-/*!
- \qmlproperty bool QtQuick.Particles2::ParticleSystem::running
-
- If running is set to false, the particle system will stop the simulation. All particles
- will be destroyed when the system is set to running again.
-
- It can also be controlled with the start() and stop() methods.
-*/
-
-
-/*!
- \qmlproperty bool QtQuick.Particles2::ParticleSystem::paused
-
- If paused is set to true, the particle system will not advance the simulation. When
- paused is set to false again, the simulation will resume from the same point it was
- paused.
-
- The simulation will automatically pause if it detects that there are no live particles
- left, and unpause when new live particles are added.
-
- It can also be controlled with the pause() and resume() methods.
-*/
-
-/*!
- \qmlproperty bool QtQuick.Particles2::ParticleSystem::empty
-
- empty is set to true when there are no live particles left in the system.
-
- You can use this to pause the system, keeping it from spending any time updating,
- but you will need to resume it in order for additional particles to be generated
- by the system.
-
- To kill all the particles in the system, use a Kill affector.
-*/
-
-/*!
- \qmlproperty list<Sprite> QtQuick.Particles2::ParticleSystem::particleStates
-
- You can define a sub-set of particle groups in this property in order to provide them
- with stochastic state transitions.
-
- Each QtQuick2::Sprite in this list is interpreted as corresponding to the particle group
- with ths same name. Any transitions defined in these sprites will take effect on the particle
- groups as well. Additionally TrailEmitters, Affectors and ParticlePainters definined
- inside one of these sprites are automatically associated with the corresponding particle group.
-*/
-
-/*!
- \qmlmethod void QtQuick.Particles2::ParticleSystem::pause
-
- Pauses the simulation if it is running.
-
- \sa resume, paused
-*/
-
-/*!
- \qmlmethod void QtQuick.Particles2::ParticleSystem::resume
-
- Resumes the simulation if it is paused.
-
- \sa pause, paused
-*/
-
-/*!
- \qmlmethod void QtQuick.Particles2::ParticleSystem::start
-
- Starts the simulation if it has not already running.
-
- \sa stop, restart, running
-*/
-
-/*!
- \qmlmethod void QtQuick.Particles2::ParticleSystem::stop
-
- Stops the simulation if it is running.
-
- \sa start, restart, running
-*/
-
-/*!
- \qmlmethod void QtQuick.Particles2::ParticleSystem::restart
-
- Stops the simulation if it is running, and then starts it.
-
- \sa stop, restart, running
-*/
-/*!
- \qmlmethod void QtQuick.Particles2::ParticleSystem::reset
-
- Discards all currently existing particles.
-
-*/
-const qreal EPSILON = 0.001;
-//Utility functions for when within 1ms is close enough
-bool timeEqualOrGreater(qreal a, qreal b)
-{
- return (a+EPSILON >= b);
-}
-
-bool timeLess(qreal a, qreal b)
-{
- return (a-EPSILON < b);
-}
-
-bool timeEqual(qreal a, qreal b)
-{
- return (a+EPSILON > b) && (a-EPSILON < b);
-}
-
-int roundedTime(qreal a)
-{// in ms
- return (int)qRound(a*1000.0);
-}
-
-QQuickParticleDataHeap::QQuickParticleDataHeap()
- : m_data(0)
-{
- m_data.reserve(1000);
- clear();
-}
-
-void QQuickParticleDataHeap::grow() //###Consider automatic growth vs resize() calls from GroupData
-{
- m_data.resize(1 << ++m_size);
-}
-
-void QQuickParticleDataHeap::insert(QQuickParticleData* data)
-{
- insertTimed(data, roundedTime(data->t + data->lifeSpan));
-}
-
-void QQuickParticleDataHeap::insertTimed(QQuickParticleData* data, int time)
-{
- //TODO: Optimize 0 lifespan (or already dead) case
- if (m_lookups.contains(time)) {
- m_data[m_lookups[time]].data << data;
- return;
- }
- if (m_end == (1 << m_size))
- grow();
- m_data[m_end].time = time;
- m_data[m_end].data.clear();
- m_data[m_end].data.insert(data);
- m_lookups.insert(time, m_end);
- bubbleUp(m_end++);
-}
-
-int QQuickParticleDataHeap::top()
-{
- if (m_end == 0)
- return 1 << 30;
- return m_data[0].time;
-}
-
-QSet<QQuickParticleData*> QQuickParticleDataHeap::pop()
-{
- if (!m_end)
- return QSet<QQuickParticleData*> ();
- QSet<QQuickParticleData*> ret = m_data[0].data;
- m_lookups.remove(m_data[0].time);
- if (m_end == 1) {
- --m_end;
- } else {
- m_data[0] = m_data[--m_end];
- bubbleDown(0);
- }
- return ret;
-}
-
-void QQuickParticleDataHeap::clear()
-{
- m_size = 0;
- m_end = 0;
- //m_size is in powers of two. So to start at 0 we have one allocated
- m_data.resize(1);
- m_lookups.clear();
-}
-
-bool QQuickParticleDataHeap::contains(QQuickParticleData* d)
-{
- for (int i=0; i<m_end; i++)
- if (m_data[i].data.contains(d))
- return true;
- return false;
-}
-
-void QQuickParticleDataHeap::swap(int a, int b)
-{
- m_tmp = m_data[a];
- m_data[a] = m_data[b];
- m_data[b] = m_tmp;
- m_lookups[m_data[a].time] = a;
- m_lookups[m_data[b].time] = b;
-}
-
-void QQuickParticleDataHeap::bubbleUp(int idx)//tends to be called once
-{
- if (!idx)
- return;
- int parent = (idx-1)/2;
- if (m_data[idx].time < m_data[parent].time) {
- swap(idx, parent);
- bubbleUp(parent);
- }
-}
-
-void QQuickParticleDataHeap::bubbleDown(int idx)//tends to be called log n times
-{
- int left = idx*2 + 1;
- if (left >= m_end)
- return;
- int lesser = left;
- int right = idx*2 + 2;
- if (right < m_end) {
- if (m_data[left].time > m_data[right].time)
- lesser = right;
- }
- if (m_data[idx].time > m_data[lesser].time) {
- swap(idx, lesser);
- bubbleDown(lesser);
- }
-}
-
-QQuickParticleGroupData::QQuickParticleGroupData(int id, QQuickParticleSystem* sys):index(id),m_size(0),m_system(sys)
-{
- initList();
-}
-
-QQuickParticleGroupData::~QQuickParticleGroupData()
-{
- foreach (QQuickParticleData* d, data)
- delete d;
-}
-
-int QQuickParticleGroupData::size()
-{
- return m_size;
-}
-
-QString QQuickParticleGroupData::name()//### Worth caching as well?
-{
- return m_system->groupIds.key(index);
-}
-
-void QQuickParticleGroupData::setSize(int newSize)
-{
- if (newSize == m_size)
- return;
- Q_ASSERT(newSize > m_size);//XXX allow shrinking
- data.resize(newSize);
- for (int i=m_size; i<newSize; i++) {
- data[i] = new QQuickParticleData(m_system);
- data[i]->group = index;
- data[i]->index = i;
- reusableIndexes << i;
- }
- int delta = newSize - m_size;
- m_size = newSize;
- foreach (QQuickParticlePainter* p, painters)
- p->setCount(p->count() + delta);
-}
-
-void QQuickParticleGroupData::initList()
-{
- dataHeap.clear();
-}
-
-void QQuickParticleGroupData::kill(QQuickParticleData* d)
-{
- Q_ASSERT(d->group == index);
- d->lifeSpan = 0;//Kill off
- foreach (QQuickParticlePainter* p, painters)
- p->reload(d);
- reusableIndexes << d->index;
-}
-
-QQuickParticleData* QQuickParticleGroupData::newDatum(bool respectsLimits)
-{
- //recycle();//Extra recycler round to be sure?
-
- while (!reusableIndexes.empty()) {
- int idx = *(reusableIndexes.begin());
- reusableIndexes.remove(idx);
- if (data[idx]->stillAlive()) {// ### This means resurrection of 'dead' particles. Is that allowed?
- prepareRecycler(data[idx]);
- continue;
- }
- return data[idx];
- }
- if (respectsLimits)
- return 0;
-
- int oldSize = m_size;
- setSize(oldSize + 10);//###+1,10%,+10? Choose something non-arbitrarily
- reusableIndexes.remove(oldSize);
- return data[oldSize];
-}
-
-bool QQuickParticleGroupData::recycle()
-{
- while (dataHeap.top() <= m_system->timeInt) {
- foreach (QQuickParticleData* datum, dataHeap.pop()) {
- if (!datum->stillAlive()) {
- reusableIndexes << datum->index;
- } else {
- prepareRecycler(datum); //ttl has been altered mid-way, put it back
- }
- }
- }
-
- //TODO: If the data is clear, gc (consider shrinking stack size)?
- return reusableIndexes.count() == m_size;
-}
-
-void QQuickParticleGroupData::prepareRecycler(QQuickParticleData* d)
-{
- if (d->lifeSpan*1000 < m_system->maxLife) {
- dataHeap.insert(d);
- } else {
- while ((roundedTime(d->t) + 2*m_system->maxLife/3) <= m_system->timeInt)
- d->extendLife(m_system->maxLife/3000.0);
- dataHeap.insertTimed(d, roundedTime(d->t) + 2*m_system->maxLife/3);
- }
-}
-
-QQuickParticleData::QQuickParticleData(QQuickParticleSystem* sys)
- : group(0)
- , e(0)
- , system(sys)
- , index(0)
- , systemIndex(-1)
- , colorOwner(0)
- , rotationOwner(0)
- , deformationOwner(0)
- , animationOwner(0)
- , v8Datum(0)
-{
- x = 0;
- y = 0;
- t = -1;
- lifeSpan = 0;
- size = 0;
- endSize = 0;
- vx = 0;
- vy = 0;
- ax = 0;
- ay = 0;
- xx = 1;
- xy = 0;
- yx = 0;
- yy = 1;
- rotation = 0;
- rotationSpeed = 0;
- autoRotate = 0;
- animIdx = 0;
- frameDuration = 1;
- frameCount = 1;
- animT = -1;
- animX = 0;
- animY = 0;
- animWidth = 1;
- animHeight = 1;
- color.r = 255;
- color.g = 255;
- color.b = 255;
- color.a = 255;
- r = 0;
- delegate = 0;
- modelIndex = -1;
-}
-
-QQuickParticleData::~QQuickParticleData()
-{
- delete v8Datum;
-}
-
-void QQuickParticleData::clone(const QQuickParticleData& other)
-{
- x = other.x;
- y = other.y;
- t = other.t;
- lifeSpan = other.lifeSpan;
- size = other.size;
- endSize = other.endSize;
- vx = other.vx;
- vy = other.vy;
- ax = other.ax;
- ay = other.ay;
- xx = other.xx;
- xy = other.xy;
- yx = other.yx;
- yy = other.yy;
- rotation = other.rotation;
- rotationSpeed = other.rotationSpeed;
- autoRotate = other.autoRotate;
- animIdx = other.animIdx;
- frameDuration = other.frameDuration;
- frameCount = other.frameCount;
- animT = other.animT;
- animX = other.animX;
- animY = other.animY;
- animWidth = other.animWidth;
- animHeight = other.animHeight;
- color.r = other.color.r;
- color.g = other.color.g;
- color.b = other.color.b;
- color.a = other.color.a;
- r = other.r;
- delegate = other.delegate;
- modelIndex = other.modelIndex;
-
- colorOwner = other.colorOwner;
- rotationOwner = other.rotationOwner;
- deformationOwner = other.deformationOwner;
- animationOwner = other.animationOwner;
-}
-
-QDeclarativeV8Handle QQuickParticleData::v8Value()
-{
- if (!v8Datum)
- v8Datum = new QQuickV8ParticleData(QDeclarativeEnginePrivate::getV8Engine(qmlEngine(system)), this);
- return v8Datum->v8Value();
-}
-//sets the x accleration without affecting the instantaneous x velocity or position
-void QQuickParticleData::setInstantaneousAX(qreal ax)
-{
- qreal t = (system->timeInt / 1000.0) - this->t;
- qreal vx = (this->vx + t*this->ax) - t*ax;
- qreal ex = this->x + this->vx * t + 0.5 * this->ax * t * t;
- qreal x = ex - t*vx - 0.5 * t*t*ax;
-
- this->ax = ax;
- this->vx = vx;
- this->x = x;
-}
-
-//sets the x velocity without affecting the instantaneous x postion
-void QQuickParticleData::setInstantaneousVX(qreal vx)
-{
- qreal t = (system->timeInt / 1000.0) - this->t;
- qreal evx = vx - t*this->ax;
- qreal ex = this->x + this->vx * t + 0.5 * this->ax * t * t;
- qreal x = ex - t*evx - 0.5 * t*t*this->ax;
-
- this->vx = evx;
- this->x = x;
-}
-
-//sets the instantaneous x postion
-void QQuickParticleData::setInstantaneousX(qreal x)
-{
- qreal t = (system->timeInt / 1000.0) - this->t;
- this->x = x - t*this->vx - 0.5 * t*t*this->ax;
-}
-
-//sets the y accleration without affecting the instantaneous y velocity or position
-void QQuickParticleData::setInstantaneousAY(qreal ay)
-{
- qreal t = (system->timeInt / 1000.0) - this->t;
- qreal vy = (this->vy + t*this->ay) - t*ay;
- qreal ey = this->y + this->vy * t + 0.5 * this->ay * t * t;
- qreal y = ey - t*vy - 0.5 * t*t*ay;
-
- this->ay = ay;
- this->vy = vy;
- this->y = y;
-}
-
-//sets the y velocity without affecting the instantaneous y position
-void QQuickParticleData::setInstantaneousVY(qreal vy)
-{
- qreal t = (system->timeInt / 1000.0) - this->t;
- qreal evy = vy - t*this->ay;
- qreal ey = this->y + this->vy * t + 0.5 * this->ay * t * t;
- qreal y = ey - t*evy - 0.5 * t*t*this->ay;
-
- this->vy = evy;
- this->y = y;
-}
-
-//sets the instantaneous Y position
-void QQuickParticleData::setInstantaneousY(qreal y)
-{
- qreal t = (system->timeInt / 1000.0) - this->t;
- this->y = y - t*this->vy - 0.5 * t*t*this->ay;
-}
-
-qreal QQuickParticleData::curX() const
-{
- qreal t = (system->timeInt / 1000.0) - this->t;
- return this->x + this->vx * t + 0.5 * this->ax * t * t;
-}
-
-qreal QQuickParticleData::curVX() const
-{
- qreal t = (system->timeInt / 1000.0) - this->t;
- return this->vx + t*this->ax;
-}
-
-qreal QQuickParticleData::curY() const
-{
- qreal t = (system->timeInt / 1000.0) - this->t;
- return y + vy * t + 0.5 * ay * t * t;
-}
-
-qreal QQuickParticleData::curVY() const
-{
- qreal t = (system->timeInt / 1000.0) - this->t;
- return vy + t*ay;
-}
-
-void QQuickParticleData::debugDump()
-{
- qDebug() << "Particle" << systemIndex << group << "/" << index << stillAlive()
- << "Pos: " << x << "," << y
- << "Vel: " << vx << "," << vy
- << "Acc: " << ax << "," << ay
- << "Size: " << size << "," << endSize
- << "Time: " << t << "," <<lifeSpan << ";" << (system->timeInt / 1000.0) ;
-}
-
-bool QQuickParticleData::stillAlive()
-{
- if (!system)
- return false;
- return (t + lifeSpan - EPSILON) > ((qreal)system->timeInt/1000.0);
-}
-
-bool QQuickParticleData::alive()
-{
- if (!system)
- return false;
- qreal st = ((qreal)system->timeInt/1000.0);
- return (t + EPSILON) < st && (t + lifeSpan - EPSILON) > st;
-}
-
-float QQuickParticleData::curSize()
-{
- if (!system || !lifeSpan)
- return 0.0f;
- return size + (endSize - size) * (1 - (lifeLeft() / lifeSpan));
-}
-
-float QQuickParticleData::lifeLeft()
-{
- if (!system)
- return 0.0f;
- return (t + lifeSpan) - (system->timeInt/1000.0);
-}
-
-void QQuickParticleData::extendLife(float time)
-{
- qreal newX = curX();
- qreal newY = curY();
- qreal newVX = curVX();
- qreal newVY = curVY();
-
- t += time;
- animT += time;
-
- qreal elapsed = (system->timeInt / 1000.0) - t;
- qreal evy = newVY - elapsed*ay;
- qreal ey = newY - elapsed*evy - 0.5 * elapsed*elapsed*ay;
- qreal evx = newVX - elapsed*ax;
- qreal ex = newX - elapsed*evx - 0.5 * elapsed*elapsed*ax;
-
- x = ex;
- vx = evx;
- y = ey;
- vy = evy;
-}
-
-QQuickParticleSystem::QQuickParticleSystem(QQuickItem *parent) :
- QQuickItem(parent),
- stateEngine(0),
- m_running(true),
- particleCount(0),
- m_nextIndex(0),
- m_componentComplete(false),
- m_paused(false)
-{
- connect(&m_painterMapper, SIGNAL(mapped(QObject*)),
- this, SLOT(loadPainter(QObject*)));
-
- m_debugMode = qmlParticlesDebug();
-}
-
-QQuickParticleSystem::~QQuickParticleSystem()
-{
- foreach (QQuickParticleGroupData* gd, groupData)
- delete gd;
-}
-
-void QQuickParticleSystem::initGroups()
-{
- m_reusableIndexes.clear();
- m_nextIndex = 0;
-
- qDeleteAll(groupData);
- groupData.clear();
- groupIds.clear();
-
- QQuickParticleGroupData* gd = new QQuickParticleGroupData(0, this);//Default group
- groupData.insert(0,gd);
- groupIds.insert(QString(), 0);
- m_nextGroupId = 1;
-}
-
-void QQuickParticleSystem::registerParticlePainter(QQuickParticlePainter* p)
-{
- //TODO: a way to Unregister emitters, painters and affectors
- m_painters << QPointer<QQuickParticlePainter>(p);//###Set or uniqueness checking?
- connect(p, SIGNAL(groupsChanged(QStringList)),
- &m_painterMapper, SLOT(map()));
- loadPainter(p);
-}
-
-void QQuickParticleSystem::registerParticleEmitter(QQuickParticleEmitter* e)
-{
- m_emitters << QPointer<QQuickParticleEmitter>(e);//###How to get them out?
- connect(e, SIGNAL(particleCountChanged()),
- this, SLOT(emittersChanged()));
- connect(e, SIGNAL(groupChanged(QString)),
- this, SLOT(emittersChanged()));
- emittersChanged();
- e->reset();//Start, so that starttime factors appropriately
-}
-
-void QQuickParticleSystem::registerParticleAffector(QQuickParticleAffector* a)
-{
- m_affectors << QPointer<QQuickParticleAffector>(a);
-}
-
-void QQuickParticleSystem::registerParticleGroup(QQuickParticleGroup* g)
-{
- m_groups << QPointer<QQuickParticleGroup>(g);
- createEngine();
-}
-
-void QQuickParticleSystem::setRunning(bool arg)
-{
- if (m_running != arg) {
- m_running = arg;
- emit runningChanged(arg);
- setPaused(false);
- if (m_animation)//Not created until componentCompleted
- m_running ? m_animation->start() : m_animation->stop();
- reset();
- }
-}
-
-void QQuickParticleSystem::setPaused(bool arg) {
- if (m_paused != arg) {
- m_paused = arg;
- if (m_animation && m_animation->state() != QAbstractAnimation::Stopped)
- m_paused ? m_animation->pause() : m_animation->resume();
- if (!m_paused) {
- foreach (QQuickParticlePainter *p, m_painters)
- p->update();
- }
- emit pausedChanged(arg);
- }
-}
-
-void QQuickParticleSystem::statePropertyRedirect(QDeclarativeListProperty<QObject> *prop, QObject *value)
-{
- //Hooks up automatic state-associated stuff
- QQuickParticleSystem* sys = qobject_cast<QQuickParticleSystem*>(prop->object->parent());
- QQuickParticleGroup* group = qobject_cast<QQuickParticleGroup*>(prop->object);
- if (!group || !sys || !value)
- return;
- stateRedirect(group, sys, value);
-}
-
-void QQuickParticleSystem::stateRedirect(QQuickParticleGroup* group, QQuickParticleSystem* sys, QObject *value)
-{
- QStringList list;
- list << group->name();
- QQuickParticleAffector* a = qobject_cast<QQuickParticleAffector*>(value);
- if (a) {
- a->setParentItem(sys);
- a->setGroups(list);
- a->setSystem(sys);
- return;
- }
- QQuickTrailEmitter* fe = qobject_cast<QQuickTrailEmitter*>(value);
- if (fe) {
- fe->setParentItem(sys);
- fe->setFollow(group->name());
- fe->setSystem(sys);
- return;
- }
- QQuickParticleEmitter* e = qobject_cast<QQuickParticleEmitter*>(value);
- if (e) {
- e->setParentItem(sys);
- e->setGroup(group->name());
- e->setSystem(sys);
- return;
- }
- QQuickParticlePainter* p = qobject_cast<QQuickParticlePainter*>(value);
- if (p) {
- p->setParentItem(sys);
- p->setGroups(list);
- p->setSystem(sys);
- return;
- }
- qWarning() << value << " was placed inside a particle system state but cannot be taken into the particle system. It will be lost.";
-}
-
-void QQuickParticleSystem::componentComplete()
-
-{
- QQuickItem::componentComplete();
- m_componentComplete = true;
- m_animation = new QQuickParticleSystemAnimation(this);
- reset();//restarts animation as well
-}
-
-void QQuickParticleSystem::reset()
-{
- if (!m_componentComplete)
- return;
-
- timeInt = 0;
- //Clear guarded pointers which have been deleted
- int cleared = 0;
- cleared += m_emitters.removeAll(0);
- cleared += m_painters.removeAll(0);
- cleared += m_affectors.removeAll(0);
-
- bySysIdx.resize(0);
- initGroups();//Also clears all logical particles
-
- if (!m_running)
- return;
-
- foreach (QQuickParticleEmitter* e, m_emitters)
- e->reset();
-
- emittersChanged();
-
- foreach (QQuickParticlePainter *p, m_painters) {
- loadPainter(p);
- p->reset();
- }
-
- //### Do affectors need reset too?
- if (m_animation) {//Animation is explicitly disabled in benchmarks
- //reset restarts animation (if running)
- if ((m_animation->state() == QAbstractAnimation::Running))
- m_animation->stop();
- m_animation->start();
- if (m_paused)
- m_animation->pause();
- }
-
- initialized = true;
-}
-
-
-void QQuickParticleSystem::loadPainter(QObject *p)
-{
- if (!m_componentComplete)
- return;
-
- QQuickParticlePainter* painter = qobject_cast<QQuickParticlePainter*>(p);
- Q_ASSERT(painter);//XXX
- foreach (QQuickParticleGroupData* sg, groupData)
- sg->painters.remove(painter);
- int particleCount = 0;
- if (painter->groups().isEmpty()) {//Uses default particle
- QStringList def;
- def << QString();
- painter->setGroups(def);
- particleCount += groupData[0]->size();
- groupData[0]->painters << painter;
- } else {
- foreach (const QString &group, painter->groups()) {
- if (group != QLatin1String("") && !groupIds[group]) {//new group
- int id = m_nextGroupId++;
- QQuickParticleGroupData* gd = new QQuickParticleGroupData(id, this);
- groupIds.insert(group, id);
- groupData.insert(id, gd);
- }
- particleCount += groupData[groupIds[group]]->size();
- groupData[groupIds[group]]->painters << painter;
- }
- }
- painter->setCount(particleCount);
- painter->update();//Initial update here
- return;
-}
-
-void QQuickParticleSystem::emittersChanged()
-{
- if (!m_componentComplete)
- return;
-
- m_emitters.removeAll(0);
-
-
- QList<int> previousSizes;
- QList<int> newSizes;
- for (int i=0; i<m_nextGroupId; i++) {
- previousSizes << groupData[i]->size();
- newSizes << 0;
- }
-
- foreach (QQuickParticleEmitter* e, m_emitters) {//Populate groups and set sizes.
- if (!groupIds.contains(e->group())
- || (!e->group().isEmpty() && !groupIds[e->group()])) {//or it was accidentally inserted by a failed lookup earlier
- int id = m_nextGroupId++;
- QQuickParticleGroupData* gd = new QQuickParticleGroupData(id, this);
- groupIds.insert(e->group(), id);
- groupData.insert(id, gd);
- previousSizes << 0;
- newSizes << 0;
- }
- newSizes[groupIds[e->group()]] += e->particleCount();
- //###: Cull emptied groups?
- }
-
- //TODO: Garbage collection?
- particleCount = 0;
- for (int i=0; i<m_nextGroupId; i++) {
- groupData[i]->setSize(qMax(newSizes[i], previousSizes[i]));
- particleCount += groupData[i]->size();
- }
-
- if (m_debugMode)
- qDebug() << "Particle system emitters changed. New particle count: " << particleCount;
-
- if (particleCount > bySysIdx.size())//New datum requests haven't updated it
- bySysIdx.resize(particleCount);
-
- foreach (QQuickParticlePainter *p, m_painters)
- loadPainter(p);
-
- if (!m_groups.isEmpty())
- createEngine();
-
-}
-
-void QQuickParticleSystem::createEngine()
-{
- if (!m_componentComplete)
- return;
- if (stateEngine && m_debugMode)
- qDebug() << "Resetting Existing Sprite Engine...";
- //### Solve the losses if size/states go down
- foreach (QQuickParticleGroup* group, m_groups) {
- bool exists = false;
- foreach (const QString &name, groupIds.keys())
- if (group->name() == name)
- exists = true;
- if (!exists) {
- int id = m_nextGroupId++;
- QQuickParticleGroupData* gd = new QQuickParticleGroupData(id, this);
- groupIds.insert(group->name(), id);
- groupData.insert(id, gd);
- }
- }
-
- if (m_groups.count()) {
- //Reorder groups List so as to have the same order as groupData
- QList<QQuickParticleGroup*> newList;
- for (int i=0; i<m_nextGroupId; i++) {
- bool exists = false;
- QString name = groupData[i]->name();
- foreach (QQuickParticleGroup* existing, m_groups) {
- if (existing->name() == name) {
- newList << existing;
- exists = true;
- }
- }
- if (!exists) {
- newList << new QQuickParticleGroup(this);
- newList.back()->setName(name);
- }
- }
- m_groups = newList;
- QList<QQuickStochasticState*> states;
- foreach (QQuickParticleGroup* g, m_groups)
- states << (QQuickStochasticState*)g;
-
- if (!stateEngine)
- stateEngine = new QQuickStochasticEngine(this);
- stateEngine->setCount(particleCount);
- stateEngine->m_states = states;
-
- connect(stateEngine, SIGNAL(stateChanged(int)),
- this, SLOT(particleStateChange(int)));
-
- } else {
- if (stateEngine)
- delete stateEngine;
- stateEngine = 0;
- }
-
-}
-
-void QQuickParticleSystem::particleStateChange(int idx)
-{
- moveGroups(bySysIdx[idx], stateEngine->curState(idx));
-}
-
-void QQuickParticleSystem::moveGroups(QQuickParticleData *d, int newGIdx)
-{
- if (!d || newGIdx == d->group)
- return;
-
- QQuickParticleData* pd = newDatum(newGIdx, false, d->systemIndex);
- if (!pd)
- return;
-
- pd->clone(*d);
- finishNewDatum(pd);
-
- d->systemIndex = -1;
- groupData[d->group]->kill(d);
-}
-
-int QQuickParticleSystem::nextSystemIndex()
-{
- if (!m_reusableIndexes.isEmpty()) {
- int ret = *(m_reusableIndexes.begin());
- m_reusableIndexes.remove(ret);
- return ret;
- }
- if (m_nextIndex >= bySysIdx.size()) {
- bySysIdx.resize(bySysIdx.size() < 10 ? 10 : bySysIdx.size()*1.1);//###+1,10%,+10? Choose something non-arbitrarily
- if (stateEngine)
- stateEngine->setCount(bySysIdx.size());
-
- }
- return m_nextIndex++;
-}
-
-QQuickParticleData* QQuickParticleSystem::newDatum(int groupId, bool respectLimits, int sysIndex)
-{
- Q_ASSERT(groupId < groupData.count());//XXX shouldn't really be an assert
-
- QQuickParticleData* ret = groupData[groupId]->newDatum(respectLimits);
- if (!ret) {
- return 0;
- }
- if (sysIndex == -1) {
- if (ret->systemIndex == -1)
- ret->systemIndex = nextSystemIndex();
- } else {
- if (ret->systemIndex != -1) {
- if (stateEngine)
- stateEngine->stop(ret->systemIndex);
- m_reusableIndexes << ret->systemIndex;
- bySysIdx[ret->systemIndex] = 0;
- }
- ret->systemIndex = sysIndex;
- }
- bySysIdx[ret->systemIndex] = ret;
-
- if (stateEngine)
- stateEngine->start(ret->systemIndex, ret->group);
-
- m_empty = false;
- return ret;
-}
-
-void QQuickParticleSystem::emitParticle(QQuickParticleData* pd)
-{// called from prepareNextFrame()->emitWindow - enforce?
- //Account for relative emitter position
- QPointF offset = this->mapFromItem(pd->e, QPointF(0, 0));
- if (!offset.isNull()) {
- pd->x += offset.x();
- pd->y += offset.y();
- }
-
- finishNewDatum(pd);
-}
-
-void QQuickParticleSystem::finishNewDatum(QQuickParticleData *pd)
-{
- Q_ASSERT(pd);
- groupData[pd->group]->prepareRecycler(pd);
-
- foreach (QQuickParticleAffector *a, m_affectors)
- if (a && a->m_needsReset)
- a->reset(pd);
- foreach (QQuickParticlePainter* p, groupData[pd->group]->painters)
- if (p)
- p->load(pd);
-}
-
-void QQuickParticleSystem::updateCurrentTime( int currentTime )
-{
- if (!initialized)
- return;//error in initialization
-
- //### Elapsed time never shrinks - may cause problems if left emitting for weeks at a time.
- qreal dt = timeInt / 1000.;
- timeInt = currentTime;
- qreal time = timeInt / 1000.;
- dt = time - dt;
- needsReset.clear();
-
- m_emitters.removeAll(0);
- m_painters.removeAll(0);
- m_affectors.removeAll(0);
-
- bool oldClear = m_empty;
- m_empty = true;
- foreach (QQuickParticleGroupData* gd, groupData)//Recycle all groups and see if they're out of live particles
- m_empty = gd->recycle() && m_empty;
-
- if (stateEngine)
- stateEngine->updateSprites(timeInt);
-
- foreach (QQuickParticleEmitter* emitter, m_emitters)
- emitter->emitWindow(timeInt);
- foreach (QQuickParticleAffector* a, m_affectors)
- a->affectSystem(dt);
- foreach (QQuickParticleData* d, needsReset)
- foreach (QQuickParticlePainter* p, groupData[d->group]->painters)
- p->reload(d);
-
- if (oldClear != m_empty)
- emptyChanged(m_empty);
-}
-
-int QQuickParticleSystem::systemSync(QQuickParticlePainter* p)
-{
- if (!m_running)
- return 0;
- if (!initialized)
- return 0;//error in initialization
- p->performPendingCommits();
- return timeInt;
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickparticlesystem_p.h b/src/declarative/particles/qquickparticlesystem_p.h
deleted file mode 100644
index 791770af11..0000000000
--- a/src/declarative/particles/qquickparticlesystem_p.h
+++ /dev/null
@@ -1,380 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PARTICLESYSTEM_H
-#define PARTICLESYSTEM_H
-
-#include <QQuickItem>
-#include <QElapsedTimer>
-#include <QVector>
-#include <QHash>
-#include <QPointer>
-#include <QSignalMapper>
-#include <private/qquicksprite_p.h>
-#include <QAbstractAnimation>
-#include <QtDeclarative/qdeclarative.h>
-#include <private/qv8engine_p.h> //For QDeclarativeV8Handle
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickParticleSystem;
-class QQuickParticleAffector;
-class QQuickParticleEmitter;
-class QQuickParticlePainter;
-class QQuickParticleData;
-class QQuickParticleSystemAnimation;
-class QQuickStochasticEngine;
-class QQuickSprite;
-class QQuickV8ParticleData;
-class QQuickParticleGroup;
-class QQuickImageParticle;
-
-struct QQuickParticleDataHeapNode{
- int time;//in ms
- QSet<QQuickParticleData*> data;//Set ptrs instead?
-};
-
-class QQuickParticleDataHeap {
- //Idea is to do a binary heap, but which also stores a set of int,Node* so that if the int already exists, you can
- //add it to the data* list. Pops return the whole list at once.
-public:
- QQuickParticleDataHeap();
- void insert(QQuickParticleData* data);
- void insertTimed(QQuickParticleData* data, int time);
-
- int top();
-
- QSet<QQuickParticleData*> pop();
-
- void clear();
-
- bool contains(QQuickParticleData*);//O(n), for debugging purposes only
-private:
- void grow();
- void swap(int, int);
- void bubbleUp(int);
- void bubbleDown(int);
- int m_size;
- int m_end;
- QQuickParticleDataHeapNode m_tmp;
- QVector<QQuickParticleDataHeapNode> m_data;
- QHash<int,int> m_lookups;
-};
-
-class Q_AUTOTEST_EXPORT QQuickParticleGroupData {
-public:
- QQuickParticleGroupData(int id, QQuickParticleSystem* sys);
- ~QQuickParticleGroupData();
-
- int size();
- QString name();
-
- void setSize(int newSize);
-
- int index;
- QSet<QQuickParticlePainter*> painters;//TODO: What if they are dynamically removed?
-
- //TODO: Refactor particle data list out into a separate class
- QVector<QQuickParticleData*> data;
- QQuickParticleDataHeap dataHeap;
- QSet<int> reusableIndexes;
- bool recycle(); //Force recycling round, returns true if all indexes are now reusable
-
- void initList();
- void kill(QQuickParticleData* d);
-
- //After calling this, initialize, then call prepareRecycler(d)
- QQuickParticleData* newDatum(bool respectsLimits);
-
- //TODO: Find and clean up those that don't get added to the recycler (currently they get lost)
- void prepareRecycler(QQuickParticleData* d);
-
-private:
- int m_size;
- QQuickParticleSystem* m_system;
-};
-
-struct Color4ub {
- uchar r;
- uchar g;
- uchar b;
- uchar a;
-};
-
-class Q_AUTOTEST_EXPORT QQuickParticleData {
-public:
- //TODO: QObject like memory management (without the cost, just attached to system)
- QQuickParticleData(QQuickParticleSystem* sys);
- ~QQuickParticleData();
-
- //Convenience functions for working backwards, because parameters are from the start of particle life
- //If setting multiple parameters at once, doing the conversion yourself will be faster.
-
- //sets the x accleration without affecting the instantaneous x velocity or position
- void setInstantaneousAX(qreal ax);
- //sets the x velocity without affecting the instantaneous x postion
- void setInstantaneousVX(qreal vx);
- //sets the instantaneous x postion
- void setInstantaneousX(qreal x);
- //sets the y accleration without affecting the instantaneous y velocity or position
- void setInstantaneousAY(qreal ay);
- //sets the y velocity without affecting the instantaneous y postion
- void setInstantaneousVY(qreal vy);
- //sets the instantaneous Y postion
- void setInstantaneousY(qreal y);
-
- //TODO: Slight caching?
- qreal curX() const;
- qreal curVX() const;
- qreal curAX() const { return ax; }
- qreal curY() const;
- qreal curVY() const;
- qreal curAY() const { return ay; }
-
- int group;
- QQuickParticleEmitter* e;//### Needed?
- QQuickParticleSystem* system;
- int index;
- int systemIndex;
-
- //General Position Stuff
- float x;
- float y;
- float t;
- float lifeSpan;
- float size;
- float endSize;
- float vx;
- float vy;
- float ax;
- float ay;
-
- //Other stuff, now universally shared
- Color4ub color;
- float xx;
- float xy;
- float yx;
- float yy;
- float rotation;
- float rotationSpeed;
- float autoRotate;//Assume that GPUs prefer floats to bools
- float animIdx;
- float frameDuration;
- float frameCount;
- float animT;
- float animX;
- float animY;
- float animWidth;
- float animHeight;
- float r;
- QQuickItem* delegate;
- int modelIndex;
- float update;//Used by custom affectors
-
- //Used by image particle
- QQuickImageParticle* colorOwner;
- QQuickImageParticle* rotationOwner;
- QQuickImageParticle* deformationOwner;
- QQuickImageParticle* animationOwner;
-
- void debugDump();
- bool stillAlive();//Only checks end, because usually that's all you need and it's a little faster.
- bool alive();
- float lifeLeft();
- float curSize();
- void clone(const QQuickParticleData& other);//Not =, leaves meta-data like index
- QDeclarativeV8Handle v8Value();
- void extendLife(float time);
-private:
- QQuickV8ParticleData* v8Datum;
-};
-
-class Q_AUTOTEST_EXPORT QQuickParticleSystem : public QQuickItem
-{
- Q_OBJECT
- Q_PROPERTY(bool running READ isRunning WRITE setRunning NOTIFY runningChanged)
- Q_PROPERTY(bool paused READ isPaused WRITE setPaused NOTIFY pausedChanged)
- Q_PROPERTY(bool empty READ isEmpty NOTIFY emptyChanged)
-
-public:
- explicit QQuickParticleSystem(QQuickItem *parent = 0);
- ~QQuickParticleSystem();
-
- bool isRunning() const
- {
- return m_running;
- }
-
- int count(){ return particleCount; }
-
- static const int maxLife = 600000;
-
-signals:
-
- void systemInitialized();
- void runningChanged(bool arg);
- void pausedChanged(bool arg);
- void emptyChanged(bool arg);
-
-public slots:
- void start(){setRunning(true);}
- void stop(){setRunning(false);}
- void restart(){setRunning(false);setRunning(true);}
- void pause(){setPaused(true);}
- void resume(){setPaused(false);}
-
- void reset();
- void setRunning(bool arg);
- void setPaused(bool arg);
-
- virtual int duration() const { return -1; }
-
-
-protected:
- //This one only once per frame (effectively)
- void componentComplete();
-
-private slots:
- void emittersChanged();
- void loadPainter(QObject* p);
- void createEngine(); //Not invoked by sprite engine, unlike Sprite uses
- void particleStateChange(int idx);
-
-public:
- //These can be called multiple times per frame, performance critical
- void emitParticle(QQuickParticleData* p);
- QQuickParticleData* newDatum(int groupId, bool respectLimits = true, int sysIdx = -1);
- void finishNewDatum(QQuickParticleData*);
- void moveGroups(QQuickParticleData *d, int newGIdx);
- int nextSystemIndex();
-
- //This one only once per painter per frame
- int systemSync(QQuickParticlePainter* p);
-
- //Data members here for ease of related class and auto-test usage. Not "public" API. TODO: d_ptrize
- QSet<QQuickParticleData*> needsReset;
- QVector<QQuickParticleData*> bySysIdx; //Another reference to the data (data owned by group), but by sysIdx
- QHash<QString, int> groupIds;
- QHash<int, QQuickParticleGroupData*> groupData;
- QQuickStochasticEngine* stateEngine;
-
- //Also only here for auto-test usage
- void updateCurrentTime( int currentTime );
- QQuickParticleSystemAnimation* m_animation;
- bool m_running;
-
- int timeInt;
- bool initialized;
- int particleCount;
-
- void registerParticlePainter(QQuickParticlePainter* p);
- void registerParticleEmitter(QQuickParticleEmitter* e);
- void registerParticleAffector(QQuickParticleAffector* a);
- void registerParticleGroup(QQuickParticleGroup* g);
-
- static void statePropertyRedirect(QDeclarativeListProperty<QObject> *prop, QObject *value);
- static void stateRedirect(QQuickParticleGroup* group, QQuickParticleSystem* sys, QObject *value);
- bool isPaused() const
- {
- return m_paused;
- }
-
- bool isEmpty() const
- {
- return m_empty;
- }
-
-private:
- void initializeSystem();
- void initGroups();
- QList<QPointer<QQuickParticleEmitter> > m_emitters;
- QList<QPointer<QQuickParticleAffector> > m_affectors;
- QList<QPointer<QQuickParticlePainter> > m_painters;
- QList<QPointer<QQuickParticlePainter> > m_syncList;
- QList<QQuickParticleGroup*> m_groups;
- int m_nextGroupId;
- int m_nextIndex;
- QSet<int> m_reusableIndexes;
- bool m_componentComplete;
-
- QSignalMapper m_painterMapper;
- QSignalMapper m_emitterMapper;
- bool m_paused;
- bool m_debugMode;
- bool m_allDead;
- bool m_empty;
-};
-
-// Internally, this animation drives all the timing. Painters sync up in their updatePaintNode
-class QQuickParticleSystemAnimation : public QAbstractAnimation
-{
- Q_OBJECT
-public:
- QQuickParticleSystemAnimation(QQuickParticleSystem* system)
- : QAbstractAnimation(static_cast<QObject*>(system)), m_system(system)
- { }
-protected:
- virtual void updateCurrentTime( int t )
- {
- m_system->updateCurrentTime(t);
- }
-
- virtual int duration() const
- {
- return -1;
- }
-
-private:
- QQuickParticleSystem* m_system;
-};
-
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // PARTICLESYSTEM_H
-
-
diff --git a/src/declarative/particles/qquickpointattractor.cpp b/src/declarative/particles/qquickpointattractor.cpp
deleted file mode 100644
index d96458c8bb..0000000000
--- a/src/declarative/particles/qquickpointattractor.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickpointattractor_p.h"
-#include <cmath>
-#include <QDebug>
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass Attractor QQuickAttractorAffector
- \inqmlmodule QtQuick.Particles 2
- \inherits Affector
- \brief The Attractor allows you to attract particles towards a specific point.
-
- Note that the size and position of this element affects which particles it affects.
- The size of the point attracted to is always 0x0, and the location of that point
- is specified by the pointX and pointY properties.
-
- Note that Attractor has the standard Item x,y,width and height properties.
- Like other affectors, these represent the affected area. They
- do not represent the 0x0 point which is the target of the attraction.
-*/
-
-
-/*!
- \qmlproperty real QtQuick.Particles2::PointAttractor::pointX
-
- The x coordinate of the attracting point. This is relative
- to the x coordinate of the Attractor.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::PointAttractor::pointY
-
- The y coordinate of the attracting point. This is relative
- to the y coordinate of the Attractor.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::PointAttractor::strength
-
- The pull, in units per second, to be exerted on an item one pixel away.
-
- Depending on how the attraction is proportionalToDistance this may have to
- be very high or very low to have a reasonable effect on particles at a
- distance.
-*/
-/*!
- \qmlproperty AffectableParameter QtQuick.Particles2::Attractor::affectedParameter
-
- What attribute of particles is directly affected.
- \list
- \o Attractor.Position
- \o Attractor.Velocity
- \o Attractor.Acceleration
- \endlist
-*/
-/*!
- \qmlproperty Proportion QtQuick.Particles2::Attractor::proportionalToDistance
-
- How the distance from the particle to the point affects the strength of the attraction.
-
- \list
- \o Attractor.Constant
- \o Attractor.Linear
- \o Attractor.InverseLinear
- \o Attractor.Quadratic
- \o Attractor.InverseQuadratic
- \endlist
-*/
-
-
-QQuickAttractorAffector::QQuickAttractorAffector(QQuickItem *parent) :
- QQuickParticleAffector(parent), m_strength(0.0), m_x(0), m_y(0)
- , m_physics(Velocity), m_proportionalToDistance(Linear)
-{
-}
-
-bool QQuickAttractorAffector::affectParticle(QQuickParticleData *d, qreal dt)
-{
- if (m_strength == 0.0)
- return false;
- qreal dx = m_x+m_offset.x() - d->curX();
- qreal dy = m_y+m_offset.y() - d->curY();
- qreal r = sqrt((dx*dx) + (dy*dy));
- qreal theta = atan2(dy,dx);
- qreal ds = 0;
- switch (m_proportionalToDistance){
- case InverseQuadratic:
- ds = (m_strength / qMax<qreal>(1.,r*r));
- break;
- case InverseLinear:
- ds = (m_strength / qMax<qreal>(1.,r));
- break;
- case Quadratic:
- ds = (m_strength * qMax<qreal>(1.,r*r));
- break;
- case Linear:
- ds = (m_strength * qMax<qreal>(1.,r));
- break;
- default: //also Constant
- ds = m_strength;
- }
- ds *= dt;
- dx = ds * cos(theta);
- dy = ds * sin(theta);
- qreal vx,vy;
- switch (m_physics){
- case Position:
- d->x = (d->x + dx);
- d->y = (d->y + dy);
- break;
- case Acceleration:
- d->setInstantaneousAX(d->ax + dx);
- d->setInstantaneousAY(d->ay + dy);
- break;
- case Velocity: //also default
- default:
- vx = d->curVX();
- vy = d->curVY();
- d->setInstantaneousVX(vx + dx);
- d->setInstantaneousVY(vy + dy);
- }
-
- return true;
-}
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickpointattractor_p.h b/src/declarative/particles/qquickpointattractor_p.h
deleted file mode 100644
index b488e132e3..0000000000
--- a/src/declarative/particles/qquickpointattractor_p.h
+++ /dev/null
@@ -1,169 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ATTRACTORAFFECTOR_H
-#define ATTRACTORAFFECTOR_H
-#include "qquickparticleaffector_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickAttractorAffector : public QQuickParticleAffector
-{
- Q_OBJECT
- Q_PROPERTY(qreal strength READ strength WRITE setStrength NOTIFY strengthChanged)
- Q_PROPERTY(qreal pointX READ pointX WRITE setPointX NOTIFY pointXChanged)
- Q_PROPERTY(qreal pointY READ pointY WRITE setPointY NOTIFY pointYChanged)
- Q_PROPERTY(AffectableParameters affectedParameter READ affectedParameter WRITE setAffectedParameter NOTIFY affectedParameterChanged)
- Q_PROPERTY(Proportion proportionalToDistance READ proportionalToDistance WRITE setProportionalToDistance NOTIFY proportionalToDistanceChanged)
- Q_ENUMS(AffectableParameters)
- Q_ENUMS(Proportion)
-
-public:
- enum Proportion{
- Constant,
- Linear,
- Quadratic,
- InverseLinear,
- InverseQuadratic
- };
-
- enum AffectableParameters {
- Position,
- Velocity,
- Acceleration
- };
-
- explicit QQuickAttractorAffector(QQuickItem *parent = 0);
-
- qreal strength() const
- {
- return m_strength;
- }
-
- qreal pointX() const
- {
- return m_x;
- }
-
- qreal pointY() const
- {
- return m_y;
- }
-
- AffectableParameters affectedParameter() const
- {
- return m_physics;
- }
-
- Proportion proportionalToDistance() const
- {
- return m_proportionalToDistance;
- }
-
-signals:
-
- void strengthChanged(qreal arg);
-
- void pointXChanged(qreal arg);
-
- void pointYChanged(qreal arg);
-
- void affectedParameterChanged(AffectableParameters arg);
-
- void proportionalToDistanceChanged(Proportion arg);
-
-public slots:
-void setStrength(qreal arg)
-{
- if (m_strength != arg) {
- m_strength = arg;
- emit strengthChanged(arg);
- }
-}
-
-void setPointX(qreal arg)
-{
- if (m_x != arg) {
- m_x = arg;
- emit pointXChanged(arg);
- }
-}
-
-void setPointY(qreal arg)
-{
- if (m_y != arg) {
- m_y = arg;
- emit pointYChanged(arg);
- }
-}
-void setAffectedParameter(AffectableParameters arg)
-{
- if (m_physics != arg) {
- m_physics = arg;
- emit affectedParameterChanged(arg);
- }
-}
-
-void setProportionalToDistance(Proportion arg)
-{
- if (m_proportionalToDistance != arg) {
- m_proportionalToDistance = arg;
- emit proportionalToDistanceChanged(arg);
- }
-}
-
-protected:
- virtual bool affectParticle(QQuickParticleData *d, qreal dt);
-private:
-qreal m_strength;
-qreal m_x;
-qreal m_y;
-AffectableParameters m_physics;
-Proportion m_proportionalToDistance;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // ATTRACTORAFFECTOR_H
diff --git a/src/declarative/particles/qquickpointdirection.cpp b/src/declarative/particles/qquickpointdirection.cpp
deleted file mode 100644
index 22c33d9f15..0000000000
--- a/src/declarative/particles/qquickpointdirection.cpp
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickpointdirection_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass PointDirection QQuickPointDirection
- \inqmlmodule QtQuick.Particles 2
- \inherits Direction
- \brief The PointDirection element allows you to specify a direction that varies in x and y components
-
- The PointDirection element allows both the specification of a direction by x and y components,
- as well as varying the parameters by x or y component.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::PointDirection::x
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::PointDirection::y
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::PointDirection::xVariation
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::PointDirection::yVariation
-*/
-
-QQuickPointDirection::QQuickPointDirection(QObject *parent) :
- QQuickDirection(parent)
- , m_x(0)
- , m_y(0)
- , m_xVariation(0)
- , m_yVariation(0)
-{
-}
-
-const QPointF QQuickPointDirection::sample(const QPointF &)
-{
- QPointF ret;
- ret.setX(m_x - m_xVariation + rand() / float(RAND_MAX) * m_xVariation * 2);
- ret.setY(m_y - m_yVariation + rand() / float(RAND_MAX) * m_yVariation * 2);
- return ret;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickpointdirection_p.h b/src/declarative/particles/qquickpointdirection_p.h
deleted file mode 100644
index 29ee7cb613..0000000000
--- a/src/declarative/particles/qquickpointdirection_p.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef POINTVECTOR_H
-#define POINTVECTOR_H
-#include "qquickdirection_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickPointDirection : public QQuickDirection
-{
- Q_OBJECT
- Q_PROPERTY(qreal x READ x WRITE setX NOTIFY xChanged)
- Q_PROPERTY(qreal y READ y WRITE setY NOTIFY yChanged)
- Q_PROPERTY(qreal xVariation READ xVariation WRITE setXVariation NOTIFY xVariationChanged)
- Q_PROPERTY(qreal yVariation READ yVariation WRITE setYVariation NOTIFY yVariationChanged)
-public:
- explicit QQuickPointDirection(QObject *parent = 0);
- virtual const QPointF sample(const QPointF &from);
- qreal x() const
- {
- return m_x;
- }
-
- qreal y() const
- {
- return m_y;
- }
-
- qreal xVariation() const
- {
- return m_xVariation;
- }
-
- qreal yVariation() const
- {
- return m_yVariation;
- }
-
-signals:
-
- void xChanged(qreal arg);
-
- void yChanged(qreal arg);
-
- void xVariationChanged(qreal arg);
-
- void yVariationChanged(qreal arg);
-
-public slots:
- void setX(qreal arg)
- {
- if (m_x != arg) {
- m_x = arg;
- emit xChanged(arg);
- }
- }
-
- void setY(qreal arg)
- {
- if (m_y != arg) {
- m_y = arg;
- emit yChanged(arg);
- }
- }
-
- void setXVariation(qreal arg)
- {
- if (m_xVariation != arg) {
- m_xVariation = arg;
- emit xVariationChanged(arg);
- }
- }
-
- void setYVariation(qreal arg)
- {
- if (m_yVariation != arg) {
- m_yVariation = arg;
- emit yVariationChanged(arg);
- }
- }
-
-private:
-
- qreal m_x;
- qreal m_y;
- qreal m_xVariation;
- qreal m_yVariation;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // POINTVECTOR_H
diff --git a/src/declarative/particles/qquickrectangleextruder.cpp b/src/declarative/particles/qquickrectangleextruder.cpp
deleted file mode 100644
index d840a08d5b..0000000000
--- a/src/declarative/particles/qquickrectangleextruder.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickrectangleextruder_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass RectangleShape QQuickRectangleExtruder
- \inqmlmodule QtQuick.Particles 2
- \brief The RectangleShape element allows you to specify an area for affectors and emitter.
-
- Just a rectangle.
-*/
-
-QQuickRectangleExtruder::QQuickRectangleExtruder(QObject *parent) :
- QQuickParticleExtruder(parent), m_fill(true)
-{
-}
-
-QPointF QQuickRectangleExtruder::extrude(const QRectF &rect)
-{
- if (m_fill)
- return QPointF(((qreal)rand() / RAND_MAX) * rect.width() + rect.x(),
- ((qreal)rand() / RAND_MAX) * rect.height() + rect.y());
- int side = rand() % 4;
- switch (side){//TODO: Doesn't this overlap the corners?
- case 0:
- return QPointF(rect.x(),
- ((qreal)rand() / RAND_MAX) * rect.height() + rect.y());
- case 1:
- return QPointF(rect.width() + rect.x(),
- ((qreal)rand() / RAND_MAX) * rect.height() + rect.y());
- case 2:
- return QPointF(((qreal)rand() / RAND_MAX) * rect.width() + rect.x(),
- rect.y());
- default:
- return QPointF(((qreal)rand() / RAND_MAX) * rect.width() + rect.x(),
- rect.height() + rect.y());
- }
-}
-
-bool QQuickRectangleExtruder::contains(const QRectF &bounds, const QPointF &point)
-{
- return bounds.contains(point);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickrectangleextruder_p.h b/src/declarative/particles/qquickrectangleextruder_p.h
deleted file mode 100644
index ec8caaeec1..0000000000
--- a/src/declarative/particles/qquickrectangleextruder_p.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef RECTANGLEEXTRUDER_H
-#define RECTANGLEEXTRUDER_H
-
-#include "qquickparticleextruder_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickRectangleExtruder : public QQuickParticleExtruder
-{
- Q_OBJECT
- Q_PROPERTY(bool fill READ fill WRITE setFill NOTIFY fillChanged)
-
-public:
- explicit QQuickRectangleExtruder(QObject *parent = 0);
- virtual QPointF extrude(const QRectF &);
- virtual bool contains(const QRectF &bounds, const QPointF &point);
- bool fill() const
- {
- return m_fill;
- }
-
-signals:
-
- void fillChanged(bool arg);
-
-public slots:
-
- void setFill(bool arg)
- {
- if (m_fill != arg) {
- m_fill = arg;
- emit fillChanged(arg);
- }
- }
-protected:
- bool m_fill;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // RectangleEXTRUDER_H
diff --git a/src/declarative/particles/qquickspritegoal.cpp b/src/declarative/particles/qquickspritegoal.cpp
deleted file mode 100644
index 7c839dbf53..0000000000
--- a/src/declarative/particles/qquickspritegoal.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickspritegoal_p.h"
-#include <private/qquickspriteengine_p.h>
-#include <private/qquicksprite_p.h>
-#include "qquickimageparticle_p.h"
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass SpriteGoal QQuickSpriteGoalAffector
- \inqmlmodule QtQuick.Particles 2
- \inherits Affector
- \brief The SpriteGoal Affector allows you to change the state of a sprite particle.
-
-*/
-/*!
- \qmlproperty string QtQuick.Particles2::SpriteGoal::goalState
-
- The name of the Sprite which the affected particles should move to.
-
- Sprite states have defined durations and transitions between them, setting goalState
- will cause it to disregard any path weightings (including 0) and head down the path
- which will reach the goalState quickest. It will pass through intermediate states
- on that path.
-*/
-/*!
- \qmlproperty bool QtQuick.Particles2::SpriteGoal::jump
-
- If true, affected sprites will jump directly to the goal state instead of taking the
- the shortest valid path to get there. They will also not finish their current state,
- but immediately move to the beginning of the goal state.
-
- Default is false.
-*/
-/*!
- \qmlproperty bool QtQuick.Particles2::SpriteGoal::systemStates
-
- deprecated, use GroupGoal instead
-*/
-
-QQuickSpriteGoalAffector::QQuickSpriteGoalAffector(QQuickItem *parent) :
- QQuickParticleAffector(parent),
- m_goalIdx(-1),
- m_lastEngine(0),
- m_jump(false),
- m_systemStates(false),
- m_notUsingEngine(false)
-{
- m_ignoresTime = true;
-}
-
-void QQuickSpriteGoalAffector::updateStateIndex(QQuickStochasticEngine* e)
-{
- if (m_systemStates){
- m_goalIdx = m_system->groupIds[m_goalState];
- }else{
- m_lastEngine = e;
- for (int i=0; i<e->stateCount(); i++){
- if (e->state(i)->name() == m_goalState){
- m_goalIdx = i;
- return;
- }
- }
- m_goalIdx = -1;//Can't find it
- }
-}
-
-void QQuickSpriteGoalAffector::setGoalState(QString arg)
-{
- if (m_goalState != arg) {
- m_goalState = arg;
- emit goalStateChanged(arg);
- if (m_goalState.isEmpty())
- m_goalIdx = -1;
- else
- m_goalIdx = -2;
- }
-}
-
-bool QQuickSpriteGoalAffector::affectParticle(QQuickParticleData *d, qreal dt)
-{
- Q_UNUSED(dt);
- QQuickStochasticEngine *engine = 0;
- if (!m_systemStates){
- //TODO: Affect all engines
- foreach (QQuickParticlePainter *p, m_system->groupData[d->group]->painters)
- if (qobject_cast<QQuickImageParticle*>(p))
- engine = qobject_cast<QQuickImageParticle*>(p)->spriteEngine();
- }else{
- engine = m_system->stateEngine;
- if (!engine)
- m_notUsingEngine = true;
- }
- if (!engine && !m_notUsingEngine)
- return false;
-
- if (m_goalIdx == -2 || engine != m_lastEngine)
- updateStateIndex(engine);
- int index = d->index;
- if (m_systemStates)
- index = d->systemIndex;
- if (m_notUsingEngine){//systemStates && no stochastic states defined. So cut out the engine
- //TODO: It's possible to move to a group that is intermediate and not used by painters or emitters - but right now that will redirect to the default group
- m_system->moveGroups(d, m_goalIdx);
- }else if (engine->curState(index) != m_goalIdx){
- engine->setGoal(m_goalIdx, index, m_jump);
- return true; //Doesn't affect particle data, but necessary for onceOff
- }
- return false;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickspritegoal_p.h b/src/declarative/particles/qquickspritegoal_p.h
deleted file mode 100644
index b979772a78..0000000000
--- a/src/declarative/particles/qquickspritegoal_p.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SPRITEGOALAFFECTOR_H
-#define SPRITEGOALAFFECTOR_H
-#include "qquickparticleaffector_p.h"
-#include <QtDeclarative/qdeclarativeinfo.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickStochasticEngine;
-
-class QQuickSpriteGoalAffector : public QQuickParticleAffector
-{
- Q_OBJECT
- Q_PROPERTY(QString goalState READ goalState WRITE setGoalState NOTIFY goalStateChanged)
- Q_PROPERTY(bool jump READ jump WRITE setJump NOTIFY jumpChanged)
- Q_PROPERTY(bool systemStates READ systemStates WRITE setSystemStates NOTIFY systemStatesChanged)
-public:
- explicit QQuickSpriteGoalAffector(QQuickItem *parent = 0);
-
- QString goalState() const
- {
- return m_goalState;
- }
-
- bool jump() const
- {
- return m_jump;
- }
- bool systemStates() const
- {
- return m_systemStates;
- }
-
-protected:
- virtual bool affectParticle(QQuickParticleData *d, qreal dt);
-signals:
-
- void goalStateChanged(QString arg);
-
- void jumpChanged(bool arg);
-
- void systemStatesChanged(bool arg);
-
-public slots:
-
-void setGoalState(QString arg);
-
-void setJump(bool arg)
-{
- if (m_jump != arg) {
- m_jump = arg;
- emit jumpChanged(arg);
- }
-}
-
-void setSystemStates(bool arg)
-{
- if (m_systemStates != arg) {
- //TODO: GroupGoal was added (and this deprecated) Oct 4 - remove it in a few weeks.
- qmlInfo(this) << "systemStates is deprecated and will be removed soon. Use GroupGoal instead.";
- m_systemStates = arg;
- emit systemStatesChanged(arg);
- }
-}
-
-private:
- void updateStateIndex(QQuickStochasticEngine* e);
- QString m_goalState;
- int m_goalIdx;
- QQuickStochasticEngine* m_lastEngine;
- bool m_jump;
- bool m_systemStates;
-
- bool m_notUsingEngine;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // SPRITEGOALAFFECTOR_H
diff --git a/src/declarative/particles/qquicktargetdirection.cpp b/src/declarative/particles/qquicktargetdirection.cpp
deleted file mode 100644
index eb2eb16c6e..0000000000
--- a/src/declarative/particles/qquicktargetdirection.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquicktargetdirection_p.h"
-#include "qquickparticleemitter_p.h"
-#include <cmath>
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass TargetDirection QQuickTargetDirection
- \inqmlmodule QtQuick.Particles 2
- \inherits Direction
- \brief The TargetDirection element allows you to specify a direction towards the target point
-
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::TargetDirection::targetX
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::TargetDirection::targetY
-*/
-/*!
- \qmlproperty Item QtQuick.Particles2::TargetDirection::targetItem
- If specified, this will take precedence over targetX and targetY.
- The targeted point will be the center of the specified Item
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::TargetDirection::targetVariation
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::TargetDirection::magnitude
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::TargetDirection::magnitudeVariation
-*/
-/*!
- \qmlproperty bool QtQuick.Particles2::TargetDirection::proportionalMagnitude
-
- If true, then the value of magnitude and magnitudeVariation shall be interpreted as multiples
- of the distance between the source point and the target point, per second.
-
- If false(default), then the value of magnitude and magnitudeVariation shall be interpreted as
- pixels per second.
-*/
-
-QQuickTargetDirection::QQuickTargetDirection(QObject *parent) :
- QQuickDirection(parent)
- , m_targetX(0)
- , m_targetY(0)
- , m_targetVariation(0)
- , m_proportionalMagnitude(false)
- , m_magnitude(0)
- , m_magnitudeVariation(0)
- , m_targetItem(0)
-{
-}
-
-const QPointF QQuickTargetDirection::sample(const QPointF &from)
-{
- //###This approach loses interpolating the last position of the target (like we could with the emitter) is it worthwhile?
- QPointF ret;
- qreal targetX;
- qreal targetY;
- if (m_targetItem){
- QQuickParticleEmitter* parentEmitter = qobject_cast<QQuickParticleEmitter*>(parent());
- targetX = m_targetItem->width()/2;
- targetY = m_targetItem->height()/2;
- if (!parentEmitter){
- qWarning() << "Directed vector is not a child of the emitter. Mapping of target item coordinates may fail.";
- targetX += m_targetItem->x();
- targetY += m_targetItem->y();
- }else{
- ret = parentEmitter->mapFromItem(m_targetItem, QPointF(targetX, targetY));
- targetX = ret.x();
- targetY = ret.y();
- }
- }else{
- targetX = m_targetX;
- targetY = m_targetY;
- }
- targetX += 0 - from.x() - m_targetVariation + rand()/(float)RAND_MAX * m_targetVariation*2;
- targetY += 0 - from.y() - m_targetVariation + rand()/(float)RAND_MAX * m_targetVariation*2;
- qreal theta = atan2(targetY, targetX);
- qreal mag = m_magnitude + rand()/(float)RAND_MAX * m_magnitudeVariation * 2 - m_magnitudeVariation;
- if (m_proportionalMagnitude)
- mag *= sqrt(targetX * targetX + targetY * targetY);
- ret.setX(mag * cos(theta));
- ret.setY(mag * sin(theta));
- return ret;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquicktargetdirection_p.h b/src/declarative/particles/qquicktargetdirection_p.h
deleted file mode 100644
index 2fc62b3ad8..0000000000
--- a/src/declarative/particles/qquicktargetdirection_p.h
+++ /dev/null
@@ -1,191 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DIRECTEDVECTOR_H
-#define DIRECTEDVECTOR_H
-#include "qquickdirection_p.h"
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickItem;
-class QQuickTargetDirection : public QQuickDirection
-{
- Q_OBJECT
- Q_PROPERTY(qreal targetX READ targetX WRITE setTargetX NOTIFY targetXChanged)
- Q_PROPERTY(qreal targetY READ targetY WRITE setTargetY NOTIFY targetYChanged)
- //If targetItem is set, X/Y are ignored. Aims at middle of item, use variation for variation
- Q_PROPERTY(QQuickItem* targetItem READ targetItem WRITE setTargetItem NOTIFY targetItemChanged)
-
- Q_PROPERTY(qreal targetVariation READ targetVariation WRITE setTargetVariation NOTIFY targetVariationChanged)
-
- //TODO: An enum would be better
- Q_PROPERTY(bool proportionalMagnitude READ proportionalMagnitude WRITE setProportionalMagnitude NOTIFY proprotionalMagnitudeChanged)
- Q_PROPERTY(qreal magnitude READ magnitude WRITE setMagnitude NOTIFY magnitudeChanged)
- Q_PROPERTY(qreal magnitudeVariation READ magnitudeVariation WRITE setMagnitudeVariation NOTIFY magnitudeVariationChanged)
-
-public:
- explicit QQuickTargetDirection(QObject *parent = 0);
- virtual const QPointF sample(const QPointF &from);
-
- qreal targetX() const
- {
- return m_targetX;
- }
-
- qreal targetY() const
- {
- return m_targetY;
- }
-
- qreal targetVariation() const
- {
- return m_targetVariation;
- }
-
- qreal magnitude() const
- {
- return m_magnitude;
- }
-
- bool proportionalMagnitude() const
- {
- return m_proportionalMagnitude;
- }
-
- qreal magnitudeVariation() const
- {
- return m_magnitudeVariation;
- }
-
- QQuickItem* targetItem() const
- {
- return m_targetItem;
- }
-
-signals:
-
- void targetXChanged(qreal arg);
-
- void targetYChanged(qreal arg);
-
- void targetVariationChanged(qreal arg);
-
- void magnitudeChanged(qreal arg);
-
- void proprotionalMagnitudeChanged(bool arg);
-
- void magnitudeVariationChanged(qreal arg);
-
- void targetItemChanged(QQuickItem* arg);
-
-public slots:
- void setTargetX(qreal arg)
- {
- if (m_targetX != arg) {
- m_targetX = arg;
- emit targetXChanged(arg);
- }
- }
-
- void setTargetY(qreal arg)
- {
- if (m_targetY != arg) {
- m_targetY = arg;
- emit targetYChanged(arg);
- }
- }
-
- void setTargetVariation(qreal arg)
- {
- if (m_targetVariation != arg) {
- m_targetVariation = arg;
- emit targetVariationChanged(arg);
- }
- }
-
- void setMagnitude(qreal arg)
- {
- if (m_magnitude != arg) {
- m_magnitude = arg;
- emit magnitudeChanged(arg);
- }
- }
-
- void setProportionalMagnitude(bool arg)
- {
- if (m_proportionalMagnitude != arg) {
- m_proportionalMagnitude = arg;
- emit proprotionalMagnitudeChanged(arg);
- }
- }
-
- void setMagnitudeVariation(qreal arg)
- {
- if (m_magnitudeVariation != arg) {
- m_magnitudeVariation = arg;
- emit magnitudeVariationChanged(arg);
- }
- }
-
- void setTargetItem(QQuickItem* arg)
- {
- if (m_targetItem != arg) {
- m_targetItem = arg;
- emit targetItemChanged(arg);
- }
- }
-
-private:
- qreal m_targetX;
- qreal m_targetY;
- qreal m_targetVariation;
- bool m_proportionalMagnitude;
- qreal m_magnitude;
- qreal m_magnitudeVariation;
- QQuickItem *m_targetItem;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // DIRECTEDVECTOR_H
diff --git a/src/declarative/particles/qquicktrailemitter.cpp b/src/declarative/particles/qquicktrailemitter.cpp
deleted file mode 100644
index 272a3ebf84..0000000000
--- a/src/declarative/particles/qquicktrailemitter.cpp
+++ /dev/null
@@ -1,285 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquicktrailemitter_p.h"
-#include <private/qdeclarativeengine_p.h>
-#include <cmath>
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass TrailEmitter QQuickTrailEmitter
- \inqmlmodule QtQuick.Particles 2
- \inherits QQuickParticleEmitter
- \brief The TrailEmitter element allows you to emit logical particles from other logical particles.
-
- This element emits logical particles into the ParticleSystem, with the
- starting positions based on those of other logical particles.
-*/
-QQuickTrailEmitter::QQuickTrailEmitter(QQuickItem *parent) :
- QQuickParticleEmitter(parent)
- , m_particlesPerParticlePerSecond(0)
- , m_lastTimeStamp(0)
- , m_emitterXVariation(0)
- , m_emitterYVariation(0)
- , m_followCount(0)
- , m_emissionExtruder(0)
- , m_defaultEmissionExtruder(new QQuickParticleExtruder(this))
-{
- //TODO: If followed increased their size
- connect(this, SIGNAL(followChanged(QString)),
- this, SLOT(recalcParticlesPerSecond()));
- connect(this, SIGNAL(particleDurationChanged(int)),
- this, SLOT(recalcParticlesPerSecond()));
- connect(this, SIGNAL(particlesPerParticlePerSecondChanged(int)),
- this, SLOT(recalcParticlesPerSecond()));
-}
-
-/*!
- \qmlproperty string QtQuick.Particles2::TrailEmitter::follow
-
- The type of logical particle which this is emitting from.
-*/
-/*!
- \qmlproperty qreal QtQuick.Particles2::TrailEmitter::speedFromMovement
-
- If this value is non-zero, then any movement of the emitter will provide additional
- starting velocity to the particles based on the movement. The additional vector will be the
- same angle as the emitter's movement, with a magnitude that is the magnitude of the emitters
- movement multiplied by speedFromMovement.
-
- Default value is 0.
-*/
-/*!
- \qmlproperty Shape QtQuick.Particles2::TrailEmitter::emitShape
-
- As the area of a TrailEmitter is the area it follows, a separate shape can be provided
- to be the shape it emits out of. This shape has width and height specified by emitWidth
- and emitHeight, and is centered on the followed particle's position.
-
- The default shape is a filled Rectangle.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::TrailEmitter::emitWidth
-
- The width in pixels the emitShape is scaled to. If set to TrailEmitter.ParticleSize,
- the width will be the current size of the particle being followed.
-
- Default is 0.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::TrailEmitter::emitHeight
-
- The height in pixels the emitShape is scaled to. If set to TrailEmitter.ParticleSize,
- the height will be the current size of the particle being followed.
-
- Default is 0.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::TrailEmitter::emitRatePerParticle
-*/
-/*!
- \qmlsignal QtQuick.Particles2::TrailEmitter::emitFollowParticles(Array particles, real followed)
-
- This handler is called when particles are emitted from the \a followed particle. \a particles contains an array of particle objects which can be directly manipulated.
-
- If you use this signal handler, emitParticles will not be emitted.
-
-*/
-
-bool QQuickTrailEmitter::isEmitFollowConnected()
-{
- static int idx = QObjectPrivate::get(this)->signalIndex("emitFollowParticles(QDeclarativeV8Handle,QDeclarativeV8Handle)");
- return QObjectPrivate::get(this)->isSignalConnected(idx);
-}
-
-void QQuickTrailEmitter::recalcParticlesPerSecond(){
- if (!m_system)
- return;
- m_followCount = m_system->groupData[m_system->groupIds[m_follow]]->size();
- if (!m_followCount){
- setParticlesPerSecond(1);//XXX: Fix this horrendous hack, needed so they aren't turned off from start (causes crashes - test that when gone you don't crash with 0 PPPS)
- }else{
- setParticlesPerSecond(m_particlesPerParticlePerSecond * m_followCount);
- m_lastEmission.resize(m_followCount);
- m_lastEmission.fill(m_lastTimeStamp);
- }
-}
-
-void QQuickTrailEmitter::reset()
-{
- m_followCount = 0;
-}
-
-void QQuickTrailEmitter::emitWindow(int timeStamp)
-{
- if (m_system == 0)
- return;
- if (!m_enabled && !m_pulseLeft && m_burstQueue.isEmpty())
- return;
- if (m_followCount != m_system->groupData[m_system->groupIds[m_follow]]->size()){
- qreal oldPPS = m_particlesPerSecond;
- recalcParticlesPerSecond();
- if (m_particlesPerSecond != oldPPS)
- return;//system may need to update
- }
-
- if (m_pulseLeft){
- m_pulseLeft -= timeStamp - m_lastTimeStamp * 1000.;
- if (m_pulseLeft < 0){
- timeStamp += m_pulseLeft;
- m_pulseLeft = 0;
- }
- }
-
- //TODO: Implement startTime and speedFromMovement
- qreal time = timeStamp / 1000.;
- qreal particleRatio = 1. / m_particlesPerParticlePerSecond;
- qreal pt;
- qreal maxLife = (m_particleDuration + m_particleDurationVariation)/1000.0;
-
- //Have to map it into this system, because particlesystem automaps it back
- QPointF offset = m_system->mapFromItem(this, QPointF(0, 0));
- qreal sizeAtEnd = m_particleEndSize >= 0 ? m_particleEndSize : m_particleSize;
-
- int gId = m_system->groupIds[m_follow];
- int gId2 = m_system->groupIds[m_group];
- for (int i=0; i<m_system->groupData[gId]->data.count(); i++) {
- QQuickParticleData *d = m_system->groupData[gId]->data[i];
- if (!d->stillAlive()){
- m_lastEmission[i] = time; //Should only start emitting when it returns to life
- continue;
- }
- pt = m_lastEmission[i];
- if (pt < d->t)
- pt = d->t;
- if (pt + maxLife < time)//We missed so much, that we should skip emiting particles that are dead by now
- pt = time - maxLife;
-
- if ((width() || height()) && !effectiveExtruder()->contains(QRectF(offset.x(), offset.y(), width(), height()),QPointF(d->curX(), d->curY()))){
- m_lastEmission[d->index] = time;//jump over this time period without emitting, because it's outside
- continue;
- }
-
- QList<QQuickParticleData*> toEmit;
-
- while (pt < time || !m_burstQueue.isEmpty()){
- QQuickParticleData* datum = m_system->newDatum(gId2, !m_overwrite);
- if (datum){//else, skip this emission
- datum->e = this;//###useful?
-
- // Particle timestamp
- datum->t = pt;
- datum->lifeSpan =
- (m_particleDuration
- + ((rand() % ((m_particleDurationVariation*2) + 1)) - m_particleDurationVariation))
- / 1000.0;
-
- // Particle position
- // Note that burst location doesn't get used for follow emitter
- qreal followT = pt - d->t;
- qreal followT2 = followT * followT * 0.5;
- qreal eW = m_emitterXVariation < 0 ? d->curSize() : m_emitterXVariation;
- qreal eH = m_emitterYVariation < 0 ? d->curSize() : m_emitterYVariation;
- //Subtract offset, because PS expects this in emitter coordinates
- QRectF boundsRect(d->x - offset.x() + d->vx * followT + d->ax * followT2 - eW/2,
- d->y - offset.y() + d->vy * followT + d->ay * followT2 - eH/2,
- eW, eH);
-
- QQuickParticleExtruder* effectiveEmissionExtruder = m_emissionExtruder ? m_emissionExtruder : m_defaultEmissionExtruder;
- const QPointF &newPos = effectiveEmissionExtruder->extrude(boundsRect);
- datum->x = newPos.x();
- datum->y = newPos.y();
-
- // Particle speed
- const QPointF &speed = m_speed->sample(newPos);
- datum->vx = speed.x()
- + m_speed_from_movement * d->vx;
- datum->vy = speed.y()
- + m_speed_from_movement * d->vy;
-
- // Particle acceleration
- const QPointF &accel = m_acceleration->sample(newPos);
- datum->ax = accel.x();
- datum->ay = accel.y();
-
- // Particle size
- float sizeVariation = -m_particleSizeVariation
- + rand() / float(RAND_MAX) * m_particleSizeVariation * 2;
-
- float size = qMax((qreal)0.0, m_particleSize + sizeVariation);
- float endSize = qMax((qreal)0.0, sizeAtEnd + sizeVariation);
-
- datum->size = size * float(m_enabled);
- datum->endSize = endSize * float(m_enabled);
-
- toEmit << datum;
-
- m_system->emitParticle(datum);
- }
- if (!m_burstQueue.isEmpty()){
- m_burstQueue.first().first--;
- if (m_burstQueue.first().first <= 0)
- m_burstQueue.pop_front();
- }else{
- pt += particleRatio;
- }
- }
-
- if (isEmitConnected() || isEmitFollowConnected()) {
- v8::HandleScope handle_scope;
- v8::Context::Scope scope(QDeclarativeEnginePrivate::getV8Engine(qmlEngine(this))->context());
- v8::Handle<v8::Array> array = v8::Array::New(toEmit.size());
- for (int i=0; i<toEmit.size(); i++)
- array->Set(i, toEmit[i]->v8Value().toHandle());
-
- if (isEmitFollowConnected())
- emitFollowParticles(QDeclarativeV8Handle::fromHandle(array), d->v8Value());//A chance for many arbitrary JS changes
- else if (isEmitConnected())
- emitParticles(QDeclarativeV8Handle::fromHandle(array));//A chance for arbitrary JS changes
- }
- foreach (QQuickParticleData* d, toEmit)
- m_system->emitParticle(d);
- m_lastEmission[d->index] = pt;
- }
-
- m_lastTimeStamp = time;
-}
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquicktrailemitter_p.h b/src/declarative/particles/qquicktrailemitter_p.h
deleted file mode 100644
index ad94d7107d..0000000000
--- a/src/declarative/particles/qquicktrailemitter_p.h
+++ /dev/null
@@ -1,171 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef FOLLOWEMITTER_H
-#define FOLLOWEMITTER_H
-#include "qquickparticleemitter_p.h"
-#include "qquickparticleaffector_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QQuickTrailEmitter : public QQuickParticleEmitter
-{
- Q_OBJECT
- Q_PROPERTY(QString follow READ follow WRITE setFollow NOTIFY followChanged)
- Q_PROPERTY(int emitRatePerParticle READ particlesPerParticlePerSecond WRITE setParticlesPerParticlePerSecond NOTIFY particlesPerParticlePerSecondChanged)
-
- Q_PROPERTY(QQuickParticleExtruder* emitShape READ emissonShape WRITE setEmissionShape NOTIFY emissionShapeChanged)
- Q_PROPERTY(qreal emitHeight READ emitterYVariation WRITE setEmitterYVariation NOTIFY emitterYVariationChanged)
- Q_PROPERTY(qreal emitWidth READ emitterXVariation WRITE setEmitterXVariation NOTIFY emitterXVariationChanged)
-
- Q_ENUMS(EmitSize)
-public:
- enum EmitSize {
- ParticleSize = -2//Anything less than 0 will do
- };
- explicit QQuickTrailEmitter(QQuickItem *parent = 0);
- virtual void emitWindow(int timeStamp);
- virtual void reset();
-
- int particlesPerParticlePerSecond() const
- {
- return m_particlesPerParticlePerSecond;
- }
-
- qreal emitterXVariation() const
- {
- return m_emitterXVariation;
- }
-
- qreal emitterYVariation() const
- {
- return m_emitterYVariation;
- }
-
- QString follow() const
- {
- return m_follow;
- }
-
- QQuickParticleExtruder* emissonShape() const
- {
- return m_emissionExtruder;
- }
-
-signals:
- void emitFollowParticles(QDeclarativeV8Handle particles, QDeclarativeV8Handle followed);
-
- void particlesPerParticlePerSecondChanged(int arg);
-
- void emitterXVariationChanged(qreal arg);
-
- void emitterYVariationChanged(qreal arg);
-
- void followChanged(QString arg);
-
- void emissionShapeChanged(QQuickParticleExtruder* arg);
-
-public slots:
-
- void setParticlesPerParticlePerSecond(int arg)
- {
- if (m_particlesPerParticlePerSecond != arg) {
- m_particlesPerParticlePerSecond = arg;
- emit particlesPerParticlePerSecondChanged(arg);
- }
- }
- void setEmitterXVariation(qreal arg)
- {
- if (m_emitterXVariation != arg) {
- m_emitterXVariation = arg;
- emit emitterXVariationChanged(arg);
- }
- }
-
- void setEmitterYVariation(qreal arg)
- {
- if (m_emitterYVariation != arg) {
- m_emitterYVariation = arg;
- emit emitterYVariationChanged(arg);
- }
- }
-
- void setFollow(QString arg)
- {
- if (m_follow != arg) {
- m_follow = arg;
- emit followChanged(arg);
- }
- }
-
- void setEmissionShape(QQuickParticleExtruder* arg)
- {
- if (m_emissionExtruder != arg) {
- m_emissionExtruder = arg;
- emit emissionShapeChanged(arg);
- }
- }
-
-private slots:
- void recalcParticlesPerSecond();
-
-private:
- QSet<QQuickParticleData*> m_pending;
- QVector<qreal> m_lastEmission;
- int m_particlesPerParticlePerSecond;
- qreal m_lastTimeStamp;
- qreal m_emitterXVariation;
- qreal m_emitterYVariation;
- QString m_follow;
- int m_followCount;
- QQuickParticleExtruder* m_emissionExtruder;
- QQuickParticleExtruder* m_defaultEmissionExtruder;
- bool isEmitFollowConnected();
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // FOLLOWEMITTER_H
diff --git a/src/declarative/particles/qquickturbulence.cpp b/src/declarative/particles/qquickturbulence.cpp
deleted file mode 100644
index 0afd827af1..0000000000
--- a/src/declarative/particles/qquickturbulence.cpp
+++ /dev/null
@@ -1,205 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickturbulence_p.h"
-#include "qquickparticlepainter_p.h"//TODO: Why was this needed again?
-#include <cmath>
-#include <cstdlib>
-#include <QDebug>
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass Turbulence QQuickTurbulenceAffector
- \inqmlmodule QtQuick.Particles 2
- \inherits Affector
- \brief Turbulence provides fluid like forces based on a noise image.
-
- The Turbulence Element scales the noise source over the area it affects,
- and uses the curl of that source to generate force vectors.
-
- Turbulence requires a fixed size. Unlike other affectors, a 0x0 Turbulence element
- will affect no particles.
-
- The source should be relatively smooth black and white noise, such as perlin noise.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Turbulence::strength
-
- The magnitude of the velocity vector at any point varies between zero and
- the square root of two. It will then be multiplied by strength to get the
- velocity per second for the particles affected by the turbulence.
-*/
-/*!
- \qmlproperty url QtQuick.Particles2::Turbulence::noiseSource
-
- The source image to generate the turbulence from. It will be scaled to the size of the element,
- so equal or larger sizes will give better results. Tweaking this image is the only way to tweak
- behavior such as where vortices are or how many exist.
-
- The source should be a relatively smooth black and white noise image, such as perlin noise.
- A default image will be used if none is provided.
-*/
-
-QQuickTurbulenceAffector::QQuickTurbulenceAffector(QQuickItem *parent) :
- QQuickParticleAffector(parent),
- m_strength(10), m_lastT(0), m_gridSize(0), m_field(0), m_vectorField(0), m_inited(false)
-{
-}
-
-void QQuickTurbulenceAffector::geometryChanged(const QRectF &, const QRectF &)
-{
- initializeGrid();
-}
-
-QQuickTurbulenceAffector::~QQuickTurbulenceAffector()
-{
- if (m_field) {
- for (int i=0; i<m_gridSize; i++)
- free(m_field[i]);
- free(m_field);
- }
- if (m_vectorField) {
- for (int i=0; i<m_gridSize; i++)
- free(m_vectorField[i]);
- free(m_vectorField);
- }
-}
-
-void QQuickTurbulenceAffector::initializeGrid()
-{
- if (!m_inited)
- return;
-
- int arg = qMax(width(), height());
- if (m_gridSize != arg) {
- if (m_field){ //deallocate and then reallocate grid
- for (int i=0; i<m_gridSize; i++)
- free(m_field[i]);
- free(m_field);
- m_system = 0;
- }
- if (m_vectorField) {
- for (int i=0; i<m_gridSize; i++)
- free(m_vectorField[i]);
- free(m_vectorField);
- }
- m_gridSize = arg;
- }
-
- m_field = (qreal**)malloc(m_gridSize * sizeof(qreal*));
- for (int i=0; i<m_gridSize; i++)
- m_field[i] = (qreal*)malloc(m_gridSize * sizeof(qreal));
- m_vectorField = (QPointF**)malloc(m_gridSize * sizeof(QPointF*));
- for (int i=0; i<m_gridSize; i++)
- m_vectorField[i] = (QPointF*)malloc(m_gridSize * sizeof(QPointF));
-
- QImage image;
- if (!m_noiseSource.isEmpty())
- image = QImage(m_noiseSource.toLocalFile()).scaled(QSize(m_gridSize, m_gridSize));
- if (image.isNull())
- image = QImage(QStringLiteral(":particleresources/noise.png")).scaled(QSize(m_gridSize, m_gridSize));
-
- for (int i=0; i<m_gridSize; i++)
- for (int j=0; j<m_gridSize; j++)
- m_field[i][j] = qRed(image.pixel(QPoint(i,j)));//Red as proxy for Value
- for (int i=0; i<m_gridSize; i++){
- for (int j=0; j<m_gridSize; j++){
- m_vectorField[i][j].setX(boundsRespectingField(i,j) - boundsRespectingField(i,j-1));
- m_vectorField[i][j].setY(boundsRespectingField(i-1,j) - boundsRespectingField(i,j));
- }
- }
-}
-
-qreal QQuickTurbulenceAffector::boundsRespectingField(int x, int y)
-{
- if (x < 0)
- x = 0;
- if (x >= m_gridSize)
- x = m_gridSize - 1;
- if (y < 0)
- y = 0;
- if (y >= m_gridSize)
- y = m_gridSize - 1;
- return m_field[x][y];
-}
-
-void QQuickTurbulenceAffector::ensureInit()
-{
- if (m_inited)
- return;
- m_inited = true;
- initializeGrid();
-}
-
-void QQuickTurbulenceAffector::affectSystem(qreal dt)
-{
- if (!m_system || !m_enabled)
- return;
- ensureInit();
- if (!m_gridSize)
- return;
-
- updateOffsets();//### Needed if an ancestor is transformed.
-
- QRect boundsRect(0,0,m_gridSize,m_gridSize);
- foreach (QQuickParticleGroupData *gd, m_system->groupData){
- if (!activeGroup(m_system->groupData.key(gd)))
- continue;
- foreach (QQuickParticleData *d, gd->data){
- if (!shouldAffect(d))
- continue;
- QPoint pos = (QPointF(d->curX(), d->curY()) - m_offset).toPoint();
- if (!boundsRect.contains(pos,true))//Need to redo bounds checking due to quantization.
- continue;
- qreal fx = 0.0;
- qreal fy = 0.0;
- fx += m_vectorField[pos.x()][pos.y()].x() * m_strength;
- fy += m_vectorField[pos.x()][pos.y()].y() * m_strength;
- if (fx || fy){
- d->setInstantaneousVX(d->curVX()+ fx * dt);
- d->setInstantaneousVY(d->curVY()+ fy * dt);
- postAffect(d);
- }
- }
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickturbulence_p.h b/src/declarative/particles/qquickturbulence_p.h
deleted file mode 100644
index dc72f40eff..0000000000
--- a/src/declarative/particles/qquickturbulence_p.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TURBULENCEAFFECTOR_H
-#define TURBULENCEAFFECTOR_H
-#include "qquickparticleaffector_p.h"
-#include <QDeclarativeListProperty>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QQuickParticlePainter;
-
-class QQuickTurbulenceAffector : public QQuickParticleAffector
-{
- Q_OBJECT
- Q_PROPERTY(qreal strength READ strength WRITE setStrength NOTIFY strengthChanged)
- Q_PROPERTY(QUrl noiseSource READ noiseSource WRITE setNoiseSource NOTIFY noiseSourceChanged)
- public:
- explicit QQuickTurbulenceAffector(QQuickItem *parent = 0);
- ~QQuickTurbulenceAffector();
- virtual void affectSystem(qreal dt);
-
- qreal strength() const
- {
- return m_strength;
- }
-
- QUrl noiseSource() const
- {
- return m_noiseSource;
- }
-signals:
-
- void strengthChanged(qreal arg);
-
- void noiseSourceChanged(QUrl arg);
-
-public slots:
-
- void setStrength(qreal arg)
- {
- if (m_strength != arg) {
- m_strength = arg;
- emit strengthChanged(arg);
- }
- }
-
- void setNoiseSource(QUrl arg)
- {
- if (m_noiseSource != arg) {
- m_noiseSource = arg;
- emit noiseSourceChanged(arg);
- initializeGrid();
- }
- }
-
-protected:
- virtual void geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry);
-private:
- void ensureInit();
- void mapUpdate();
- void initializeGrid();
- qreal boundsRespectingField(int x, int y);
- qreal m_strength;
- qreal m_lastT;
- int m_gridSize;
- qreal** m_field;
- QPointF** m_vectorField;
- bool m_inited;
- QUrl m_noiseSource;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // TURBULENCEAFFECTOR_H
diff --git a/src/declarative/particles/qquickv8particledata.cpp b/src/declarative/particles/qquickv8particledata.cpp
deleted file mode 100644
index 80ce355cd7..0000000000
--- a/src/declarative/particles/qquickv8particledata.cpp
+++ /dev/null
@@ -1,503 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickv8particledata_p.h"
-#include "qquickparticlesystem_p.h"//for QQuickParticleData
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass Particle
- \inqmlmodule QtQuick.Particles 2
- \brief Particle elements can be manipulated in custom emitters and affectors.
-
- Particle elements are always managed internally by the ParticleSystem and cannot be created in QML.
- However, sometimes they are exposed via signals so as to allow arbitrary changes to the particle state
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::initialX
- The x coordinate of the particle at the beginning of its lifetime.
-
- The method of simulation prefers to have the initial values changed, rather
- than determining and changing the value at a given time. Change initial
- values in CustomEmitters instead of the current values.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::initialVX
- The x velocity of the particle at the beginning of its lifetime.
-
- The method of simulation prefers to have the initial values changed, rather
- than determining and changing the value at a given time. Change initial
- values in CustomEmitters instead of the current values.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::initialAX
- The x acceleration of the particle at the beginning of its lifetime.
-
- The method of simulation prefers to have the initial values changed, rather
- than determining and changing the value at a given time. Change initial
- values in CustomEmitters instead of the current values.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::initialY
- The y coordinate of the particle at the beginning of its lifetime.
-
- The method of simulation prefers to have the initial values changed, rather
- than determining and changing the value at a given time. Change initial
- values in CustomEmitters instead of the current values.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::initialVY
- The y velocity of the particle at the beginning of its lifetime.
-
- The method of simulation prefers to have the initial values changed, rather
- than determining and changing the value at a given time. Change initial
- values in CustomEmitters instead of the current values.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::initialAY
- The y acceleration of the particle at the beginning of its lifetime.
-
- The method of simulation prefers to have the initial values changed, rather
- than determining and changing the value at a given time. Change initial
- values in CustomEmitters instead of the current values.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::x
- The current x coordinate of the particle.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::vx
- The current x velocity of the particle.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::ax
- The current x acceleration of the particle.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::y
- The current y coordinate of the particle.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::vy
- The current y velocity of the particle.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::ay
- The current y acceleration of the particle.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::t
- The time, in seconds since the beginning of the simulation, that the particle was born.
-*/
-
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::startSize
- The size in pixels that the particle image is at the start
- of its life.
-*/
-
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::endSize
- The size in pixels that the particle image is at the end
- of its life. If this value is less than 0, then it is
- disregarded and the particle will have its startSize for the
- entire lifetime.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::lifeSpan
- The time in seconds that the particle will live for.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::rotation
- Degrees clockwise that the particle image is rotated at
- the beginning of its life.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::rotationSpeed
- Degrees clockwise per second that the particle image is rotated at while alive.
-*/
-/*!
- \qmlproperty bool QtQuick.Particles2::Particle::autoRotate
- If autoRotate is true, then the particle's rotation will be
- set so that it faces the direction of travel, plus any
- rotation from the rotation or rotationSpeed properties.
-*/
-
-/*!
- \qmlproperty bool QtQuick.Particles2::Particle::update
-
- Inside an Affector, the changes made to the particle will only be
- applied if update is set to true.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::xDeformationVectorX
-
- The x component of the deformation vector along the X axis. ImageParticle
- can draw particles across non-square shapes. It will draw the texture rectangle
- across the parallelogram drawn with the x and y deformation vectors.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::yDeformationVectorX
-
- The y component of the deformation vector along the X axis. ImageParticle
- can draw particles across non-square shapes. It will draw the texture rectangle
- across the parallelogram drawn with the x and y deformation vectors.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::xDeformationVectorY
-
- The x component of the deformation vector along the X axis. ImageParticle
- can draw particles across non-square shapes. It will draw the texture rectangle
- across the parallelogram drawn with the x and y deformation vectors.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::yDeformationVectorY
-
- The y component of the deformation vector along the Y axis. ImageParticle
- can draw particles across non-square shapes. It will draw the texture rectangle
- across the parallelogram drawn with the x and y deformation vectors.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::red
-
- ImageParticle can draw colorized particles. When it does so, red is used
- as the red channel of the color applied to the source image.
-
- Values are from 0.0 to 1.0.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::green
-
- ImageParticle can draw colorized particles. When it does so, green is used
- as the green channel of the color applied to the source image.
-
- Values are from 0.0 to 1.0.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::blue
-
- ImageParticle can draw colorized particles. When it does so, blue is used
- as the blue channel of the color applied to the source image.
-
- Values are from 0.0 to 1.0.
-*/
-
-/*!
- \qmlproperty real QtQuick.Particles2::Particle::alpha
-
- ImageParticle can draw colorized particles. When it does so, alpha is used
- as the alpha channel of the color applied to the source image.
-
- Values are from 0.0 to 1.0.
-*/
-/*!
- \qmlmethod real QtQuick.Particles2::Particle::lifeLeft
- The time in seconds that the particle has left to live at
- the current point in time.
-*/
-/*!
- \qmlmethod real QtQuick.Particles2::Particle::currentSize
- The currentSize of the particle, interpolating between startSize and endSize based on the currentTime.
-*/
-
-
-
-//### Particle data handles are not locked to within certain scopes like QQuickContext2D, but there's no way to reload either...
-class QV8ParticleDataResource : public QV8ObjectResource
-{
- V8_RESOURCE_TYPE(ParticleDataType)
-public:
- QV8ParticleDataResource(QV8Engine *e) : QV8ObjectResource(e) {}
- QQuickParticleData* datum;//TODO: Guard needed?
-};
-
-class QV8ParticleDataDeletable : public QV8Engine::Deletable
-{
-public:
- QV8ParticleDataDeletable(QV8Engine *engine);
- ~QV8ParticleDataDeletable();
-
- v8::Persistent<v8::Function> constructor;
-};
-
-static v8::Handle<v8::Value> particleData_discard(const v8::Arguments &args)
-{
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(args.This());
-
- if (!r || !r->datum)
- V8THROW_ERROR("Not a valid ParticleData object");
-
- r->datum->lifeSpan = 0; //Don't kill(), because it could still be in the middle of being created
- return v8::Undefined();
-}
-
-static v8::Handle<v8::Value> particleData_lifeLeft(const v8::Arguments &args)
-{
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(args.This());
- if (!r || !r->datum)
- V8THROW_ERROR("Not a valid ParticleData object");
-
- return v8::Number::New(r->datum->lifeLeft());
-}
-
-static v8::Handle<v8::Value> particleData_curSize(const v8::Arguments &args)
-{
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(args.This());
- if (!r || !r->datum)
- V8THROW_ERROR("Not a valid ParticleData object");
-
- return v8::Number::New(r->datum->curSize());
-}
-#define COLOR_GETTER_AND_SETTER(VAR, NAME) static v8::Handle<v8::Value> particleData_get_ ## NAME (v8::Local<v8::String>, const v8::AccessorInfo &info) \
-{ \
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(info.This()); \
- if (!r || !r->datum) \
- V8THROW_ERROR("Not a valid ParticleData object"); \
-\
- return v8::Number::New((r->datum->color. VAR )/255.0);\
-}\
-\
-static void particleData_set_ ## NAME (v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)\
-{\
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(info.This());\
- if (!r || !r->datum)\
- V8THROW_ERROR_SETTER("Not a valid ParticleData object");\
-\
- r->datum->color. VAR = qMin(255, qMax(0, (int)floor(value->NumberValue() * 255.0)));\
-}
-
-
-#define SEMIBOOL_GETTER_AND_SETTER(VARIABLE) static v8::Handle<v8::Value> particleData_get_ ## VARIABLE (v8::Local<v8::String>, const v8::AccessorInfo &info) \
-{ \
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(info.This()); \
- if (!r || !r->datum) \
- V8THROW_ERROR("Not a valid ParticleData object"); \
-\
- return v8::Boolean::New(r->datum-> VARIABLE);\
-}\
-\
-static void particleData_set_ ## VARIABLE (v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)\
-{\
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(info.This());\
- if (!r || !r->datum)\
- V8THROW_ERROR_SETTER("Not a valid ParticleData object");\
-\
- r->datum-> VARIABLE = value->BooleanValue() ? 1.0 : 0.0;\
-}
-
-#define FLOAT_GETTER_AND_SETTER(VARIABLE) static v8::Handle<v8::Value> particleData_get_ ## VARIABLE (v8::Local<v8::String>, const v8::AccessorInfo &info) \
-{ \
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(info.This()); \
- if (!r || !r->datum) \
- V8THROW_ERROR("Not a valid ParticleData object"); \
-\
- return v8::Number::New(r->datum-> VARIABLE);\
-}\
-\
-static void particleData_set_ ## VARIABLE (v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)\
-{\
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(info.This());\
- if (!r || !r->datum)\
- V8THROW_ERROR_SETTER("Not a valid ParticleData object");\
-\
- r->datum-> VARIABLE = value->NumberValue();\
-}
-
-#define FAKE_FLOAT_GETTER_AND_SETTER(VARIABLE, GETTER, SETTER) static v8::Handle<v8::Value> particleData_get_ ## VARIABLE (v8::Local<v8::String>, const v8::AccessorInfo &info) \
-{ \
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(info.This()); \
- if (!r || !r->datum) \
- V8THROW_ERROR("Not a valid ParticleData object"); \
-\
- return v8::Number::New(r->datum-> GETTER ());\
-}\
-\
-static void particleData_set_ ## VARIABLE (v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::AccessorInfo &info)\
-{\
- QV8ParticleDataResource *r = v8_resource_cast<QV8ParticleDataResource>(info.This());\
- if (!r || !r->datum)\
- V8THROW_ERROR_SETTER("Not a valid ParticleData object");\
-\
- r->datum-> SETTER ( value->NumberValue() );\
-}
-
-#define REGISTER_ACCESSOR(FT, ENGINE, VARIABLE, NAME) FT ->PrototypeTemplate()->SetAccessor( v8::String::New( #NAME ), particleData_get_ ## VARIABLE , particleData_set_ ## VARIABLE , v8::External::Wrap(ENGINE))
-
-COLOR_GETTER_AND_SETTER(r, red)
-COLOR_GETTER_AND_SETTER(g, green)
-COLOR_GETTER_AND_SETTER(b, blue)
-COLOR_GETTER_AND_SETTER(a, alpha)
-SEMIBOOL_GETTER_AND_SETTER(autoRotate)
-SEMIBOOL_GETTER_AND_SETTER(update)
-FLOAT_GETTER_AND_SETTER(x)
-FLOAT_GETTER_AND_SETTER(y)
-FLOAT_GETTER_AND_SETTER(t)
-FLOAT_GETTER_AND_SETTER(lifeSpan)
-FLOAT_GETTER_AND_SETTER(size)
-FLOAT_GETTER_AND_SETTER(endSize)
-FLOAT_GETTER_AND_SETTER(vx)
-FLOAT_GETTER_AND_SETTER(vy)
-FLOAT_GETTER_AND_SETTER(ax)
-FLOAT_GETTER_AND_SETTER(ay)
-FLOAT_GETTER_AND_SETTER(xx)
-FLOAT_GETTER_AND_SETTER(xy)
-FLOAT_GETTER_AND_SETTER(yx)
-FLOAT_GETTER_AND_SETTER(yy)
-FLOAT_GETTER_AND_SETTER(rotation)
-FLOAT_GETTER_AND_SETTER(rotationSpeed)
-FLOAT_GETTER_AND_SETTER(animIdx)
-FLOAT_GETTER_AND_SETTER(frameDuration)
-FLOAT_GETTER_AND_SETTER(frameCount)
-FLOAT_GETTER_AND_SETTER(animT)
-FLOAT_GETTER_AND_SETTER(r)
-FAKE_FLOAT_GETTER_AND_SETTER(curX, curX, setInstantaneousX)
-FAKE_FLOAT_GETTER_AND_SETTER(curVX, curVX, setInstantaneousVX)
-FAKE_FLOAT_GETTER_AND_SETTER(curAX, curAX, setInstantaneousAX)
-FAKE_FLOAT_GETTER_AND_SETTER(curY, curY, setInstantaneousY)
-FAKE_FLOAT_GETTER_AND_SETTER(curVY, curVY, setInstantaneousVY)
-FAKE_FLOAT_GETTER_AND_SETTER(curAY, curAY, setInstantaneousAY)
-
-QV8ParticleDataDeletable::QV8ParticleDataDeletable(QV8Engine *engine)
-{
- v8::HandleScope handle_scope;
- v8::Context::Scope scope(engine->context());
-
- v8::Local<v8::FunctionTemplate> ft = v8::FunctionTemplate::New();
- ft->InstanceTemplate()->SetHasExternalResource(true);
- ft->PrototypeTemplate()->Set(v8::String::New("discard"), V8FUNCTION(particleData_discard, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("lifeLeft"), V8FUNCTION(particleData_lifeLeft, engine));
- ft->PrototypeTemplate()->Set(v8::String::New("currentSize"), V8FUNCTION(particleData_curSize, engine));
- REGISTER_ACCESSOR(ft, engine, x, initialX);
- REGISTER_ACCESSOR(ft, engine, y, initialY);
- REGISTER_ACCESSOR(ft, engine, t, t);
- REGISTER_ACCESSOR(ft, engine, lifeSpan, lifeSpan);
- REGISTER_ACCESSOR(ft, engine, size, startSize);
- REGISTER_ACCESSOR(ft, engine, endSize, endSize);
- REGISTER_ACCESSOR(ft, engine, vx, initialVX);
- REGISTER_ACCESSOR(ft, engine, vy, initialVY);
- REGISTER_ACCESSOR(ft, engine, ax, initialAX);
- REGISTER_ACCESSOR(ft, engine, ay, initialAY);
- REGISTER_ACCESSOR(ft, engine, xx, xDeformationVectorX);
- REGISTER_ACCESSOR(ft, engine, xy, xDeformationVectorY);
- REGISTER_ACCESSOR(ft, engine, yx, yDeformationVectorX);
- REGISTER_ACCESSOR(ft, engine, yy, yDeformationVectorY);
- REGISTER_ACCESSOR(ft, engine, rotation, rotation);
- REGISTER_ACCESSOR(ft, engine, rotationSpeed, rotationSpeed);
- REGISTER_ACCESSOR(ft, engine, autoRotate, autoRotate);
- REGISTER_ACCESSOR(ft, engine, animIdx, animationIndex);
- REGISTER_ACCESSOR(ft, engine, frameDuration, frameDuration);
- REGISTER_ACCESSOR(ft, engine, frameCount, frameCount);
- REGISTER_ACCESSOR(ft, engine, animT, animationT);
- REGISTER_ACCESSOR(ft, engine, r, r);
- REGISTER_ACCESSOR(ft, engine, update, update);
- REGISTER_ACCESSOR(ft, engine, curX, x);
- REGISTER_ACCESSOR(ft, engine, curVX, vx);
- REGISTER_ACCESSOR(ft, engine, curAX, ax);
- REGISTER_ACCESSOR(ft, engine, curY, y);
- REGISTER_ACCESSOR(ft, engine, curVY, vy);
- REGISTER_ACCESSOR(ft, engine, curAY, ay);
- REGISTER_ACCESSOR(ft, engine, red, red);
- REGISTER_ACCESSOR(ft, engine, green, green);
- REGISTER_ACCESSOR(ft, engine, blue, blue);
- REGISTER_ACCESSOR(ft, engine, alpha, alpha);
-
- constructor = qPersistentNew(ft->GetFunction());
-}
-
-QV8ParticleDataDeletable::~QV8ParticleDataDeletable()
-{
- qPersistentDispose(constructor);
-}
-
-V8_DEFINE_EXTENSION(QV8ParticleDataDeletable, particleV8Data);
-
-
-QQuickV8ParticleData::QQuickV8ParticleData(QV8Engine* engine, QQuickParticleData* datum)
-{
- if (!engine || !datum)
- return;
- v8::HandleScope handle_scope;
- v8::Context::Scope scope(engine->context());
-
- QV8ParticleDataDeletable *d = particleV8Data(engine);
- m_v8Value = qPersistentNew(d->constructor->NewInstance());
- QV8ParticleDataResource *r = new QV8ParticleDataResource(engine);
- r->datum = datum;
- m_v8Value->SetExternalResource(r);
-}
-
-QQuickV8ParticleData::~QQuickV8ParticleData()
-{
- qPersistentDispose(m_v8Value);
-}
-
-QDeclarativeV8Handle QQuickV8ParticleData::v8Value()
-{
- return QDeclarativeV8Handle::fromHandle(m_v8Value);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickv8particledata_p.h b/src/declarative/particles/qquickv8particledata_p.h
deleted file mode 100644
index 811974c132..0000000000
--- a/src/declarative/particles/qquickv8particledata_p.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QQuickV8PARTICLEDATA_H
-#define QQuickV8PARTICLEDATA_H
-
-#include <private/qv8engine_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QQuickParticleData;
-class QQuickV8ParticleData {
-public:
- QQuickV8ParticleData(QV8Engine*,QQuickParticleData*);
- ~QQuickV8ParticleData();
- QDeclarativeV8Handle v8Value();
-private:
- v8::Persistent<v8::Object> m_v8Value;
-};
-
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-
-#endif
diff --git a/src/declarative/particles/qquickwander.cpp b/src/declarative/particles/qquickwander.cpp
deleted file mode 100644
index dfbff36076..0000000000
--- a/src/declarative/particles/qquickwander.cpp
+++ /dev/null
@@ -1,180 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qquickwander_p.h"
-#include "qquickparticlesystem_p.h"//for ParticlesVertices
-QT_BEGIN_NAMESPACE
-/*!
- \qmlclass Wander QQuickWanderAffector
- \inqmlmodule QtQuick.Particles 2
- \inherits Affector
- \brief The Wander affector allows particles to randomly vary their trajectory.
-
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Wander::pace
-
- Maximum attribute change per second.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Wander::xVariance
-
- Maximum attribute x value (as a result of Wander).
-
- If unset, Wander will not affect x values.
-*/
-/*!
- \qmlproperty real QtQuick.Particles2::Wander::yVariance
-
- Maximum attribute y value (as a result of Wander).
-
- If unset, Wander will not affect y values.
-*/
-/*!
- \qmlproperty AffectableParameter QtQuick.Particles2::Wander::affectedParameter
-
- What attribute of particles is directly affected.
- \list
- \o PointAttractor.Position
- \o PointAttractor.Velocity
- \o PointAttractor.Acceleration
- \endlist
-*/
-
-QQuickWanderAffector::QQuickWanderAffector(QQuickItem *parent) :
- QQuickParticleAffector(parent), m_xVariance(0), m_yVariance(0), m_pace(0)
- , m_affectedParameter(Velocity)
-{
- m_needsReset = true;
-}
-
-QQuickWanderAffector::~QQuickWanderAffector()
-{
- for (QHash<int, WanderData*>::const_iterator iter=m_wanderData.constBegin();
- iter != m_wanderData.constEnd(); iter++)
- delete (*iter);
-}
-
-WanderData* QQuickWanderAffector::getData(int idx)
-{
- if (m_wanderData.contains(idx))
- return m_wanderData[idx];
- WanderData* d = new WanderData;
- d->x_vel = 0;
- d->y_vel = 0;
- d->x_peak = m_xVariance;
- d->y_peak = m_yVariance;
- d->x_var = m_pace * qreal(qrand()) / RAND_MAX;
- d->y_var = m_pace * qreal(qrand()) / RAND_MAX;
-
- m_wanderData.insert(idx, d);
- return d;
-}
-
-void QQuickWanderAffector::reset(int systemIdx)
-{
- if (m_wanderData.contains(systemIdx))
- delete m_wanderData[systemIdx];
- m_wanderData.remove(systemIdx);
-}
-
-bool QQuickWanderAffector::affectParticle(QQuickParticleData* data, qreal dt)
-{
- /*TODO: Add a mode which does basically this - picking a direction, going in it (random speed) and then going back
- WanderData* d = getData(data->systemIndex);
- if (m_xVariance != 0.) {
- if ((d->x_vel > d->x_peak && d->x_var > 0.0) || (d->x_vel < -d->x_peak && d->x_var < 0.0)) {
- d->x_var = -d->x_var;
- d->x_peak = m_xVariance + m_xVariance * qreal(qrand()) / RAND_MAX;
- }
- d->x_vel += d->x_var * dt;
- }
- qreal dx = dt * d->x_vel;
-
- if (m_yVariance != 0.) {
- if ((d->y_vel > d->y_peak && d->y_var > 0.0) || (d->y_vel < -d->y_peak && d->y_var < 0.0)) {
- d->y_var = -d->y_var;
- d->y_peak = m_yVariance + m_yVariance * qreal(qrand()) / RAND_MAX;
- }
- d->y_vel += d->y_var * dt;
- }
- qreal dy = dt * d->x_vel;
-
- //### Should we be amending vel instead?
- ParticleVertex* p = &(data->pv);
- p->x += dx;
-
- p->y += dy;
- return true;
- */
- qreal dx = dt * m_pace * (2 * qreal(qrand())/RAND_MAX - 1);
- qreal dy = dt * m_pace * (2 * qreal(qrand())/RAND_MAX - 1);
- qreal newX, newY;
- switch (m_affectedParameter){
- case Position:
- newX = data->curX() + dx;
- if (m_xVariance > qAbs(newX) )
- data->x += dx;
- newY = data->curY() + dy;
- if (m_yVariance > qAbs(newY) )
- data->y += dy;
- break;
- default:
- case Velocity:
- newX = data->curVX() + dx;
- if (m_xVariance > qAbs(newX) )
- data->setInstantaneousVX(newX);
- newY = data->curVY() + dy;
- if (m_yVariance > qAbs(newY) )
- data->setInstantaneousVY(newY);
- break;
- case Acceleration:
- newX = data->ax + dx;
- if (m_xVariance > qAbs(newX) )
- data->setInstantaneousAX(newX);
- newY = data->ay + dy;
- if (m_yVariance > qAbs(newY) )
- data->setInstantaneousAY(newY);
- break;
- }
- return true;
-}
-QT_END_NAMESPACE
diff --git a/src/declarative/particles/qquickwander_p.h b/src/declarative/particles/qquickwander_p.h
deleted file mode 100644
index 99515fe629..0000000000
--- a/src/declarative/particles/qquickwander_p.h
+++ /dev/null
@@ -1,161 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Declarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef WANDERAFFECTOR_H
-#define WANDERAFFECTOR_H
-#include <QHash>
-#include "qquickparticleaffector_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-struct WanderData{
- qreal x_vel;
- qreal y_vel;
- qreal x_peak;
- qreal x_var;
- qreal y_peak;
- qreal y_var;
-};
-
-class QQuickWanderAffector : public QQuickParticleAffector
-{
- Q_OBJECT
- Q_PROPERTY(qreal pace READ pace WRITE setPace NOTIFY paceChanged)
- Q_PROPERTY(qreal xVariance READ xVariance WRITE setXVariance NOTIFY xVarianceChanged)
- Q_PROPERTY(qreal yVariance READ yVariance WRITE setYVariance NOTIFY yVarianceChanged)
- Q_PROPERTY(AffectableParameters affectedParameter READ affectedParameter WRITE setAffectedParameter NOTIFY affectedParameterChanged)
- Q_ENUMS(AffectableParameters)
-
-public:
- enum AffectableParameters {
- Position,
- Velocity,
- Acceleration
- };
-
- explicit QQuickWanderAffector(QQuickItem *parent = 0);
- ~QQuickWanderAffector();
- virtual void reset(int systemIdx);
-
- qreal xVariance() const
- {
- return m_xVariance;
- }
-
- qreal yVariance() const
- {
- return m_yVariance;
- }
-
- qreal pace() const
- {
- return m_pace;
- }
-
- AffectableParameters affectedParameter() const
- {
- return m_affectedParameter;
- }
-
-protected:
- virtual bool affectParticle(QQuickParticleData *d, qreal dt);
-signals:
-
- void xVarianceChanged(qreal arg);
-
- void yVarianceChanged(qreal arg);
-
- void paceChanged(qreal arg);
-
-
- void affectedParameterChanged(AffectableParameters arg);
-
-public slots:
-void setXVariance(qreal arg)
-{
- if (m_xVariance != arg) {
- m_xVariance = arg;
- emit xVarianceChanged(arg);
- }
-}
-
-void setYVariance(qreal arg)
-{
- if (m_yVariance != arg) {
- m_yVariance = arg;
- emit yVarianceChanged(arg);
- }
-}
-
-void setPace(qreal arg)
-{
- if (m_pace != arg) {
- m_pace = arg;
- emit paceChanged(arg);
- }
-}
-
-
-void setAffectedParameter(AffectableParameters arg)
-{
- if (m_affectedParameter != arg) {
- m_affectedParameter = arg;
- emit affectedParameterChanged(arg);
- }
-}
-
-private:
- WanderData* getData(int idx);
- QHash<int, WanderData*> m_wanderData;
- qreal m_xVariance;
- qreal m_yVariance;
- qreal m_pace;
- AffectableParameters m_affectedParameter;
-};
-
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif // WANDERAFFECTOR_H
diff --git a/src/declarative/qml/qdeclarativecomponent_p.h b/src/declarative/qml/qdeclarativecomponent_p.h
index ea68291942..49b3d037ad 100644
--- a/src/declarative/qml/qdeclarativecomponent_p.h
+++ b/src/declarative/qml/qdeclarativecomponent_p.h
@@ -78,7 +78,7 @@ class QDeclarativeEngine;
class QDeclarativeCompiledData;
class QDeclarativeComponentAttached;
-class Q_AUTOTEST_EXPORT QDeclarativeComponentPrivate : public QObjectPrivate, public QDeclarativeTypeData::TypeDataCallback
+class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativeComponentPrivate : public QObjectPrivate, public QDeclarativeTypeData::TypeDataCallback
{
Q_DECLARE_PUBLIC(QDeclarativeComponent)
diff --git a/src/declarative/qml/qdeclarativeengine.cpp b/src/declarative/qml/qdeclarativeengine.cpp
index d0d095567e..ee42f0b7c3 100644
--- a/src/declarative/qml/qdeclarativeengine.cpp
+++ b/src/declarative/qml/qdeclarativeengine.cpp
@@ -83,7 +83,6 @@
#include <private/qobject_p.h>
-#include <private/qtquick2_p.h>
#include <private/qdeclarativelocale_p.h>
#ifdef Q_OS_WIN // for %APPDATA%
@@ -159,7 +158,6 @@ void qmlRegisterBaseTypes(const char *uri, int versionMajor, int versionMinor)
\endcode
*/
-static bool qt_QmlQtModule_registered = false;
bool QDeclarativeEnginePrivate::qml_debugging_enabled = false;
void QDeclarativeEnginePrivate::registerBaseTypes(const char *uri, int versionMajor, int versionMinor)
@@ -343,10 +341,6 @@ QDeclarativeEnginePrivate::QDeclarativeEnginePrivate(QDeclarativeEngine *e)
scarceResourcesRefCount(0), typeLoader(e), importDatabase(e), uniqueId(1),
incubatorCount(0), incubationController(0), mutex(QMutex::Recursive)
{
- if (!qt_QmlQtModule_registered) {
- qt_QmlQtModule_registered = true;
- QDeclarativeQtQuick2Module::defineModule();
- }
}
QDeclarativeEnginePrivate::~QDeclarativeEnginePrivate()
diff --git a/src/declarative/qml/qdeclarativeexpression_p.h b/src/declarative/qml/qdeclarativeexpression_p.h
index 7a2bda218f..7b53bab093 100644
--- a/src/declarative/qml/qdeclarativeexpression_p.h
+++ b/src/declarative/qml/qdeclarativeexpression_p.h
@@ -168,7 +168,7 @@ private:
class QDeclarativeExpression;
class QString;
-class QDeclarativeExpressionPrivate : public QObjectPrivate, public QDeclarativeJavaScriptExpression
+class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativeExpressionPrivate : public QObjectPrivate, public QDeclarativeJavaScriptExpression
{
Q_DECLARE_PUBLIC(QDeclarativeExpression)
public:
diff --git a/src/declarative/qml/qdeclarativemetatype.cpp b/src/declarative/qml/qdeclarativemetatype.cpp
index 46395e15e8..c175d725b8 100644
--- a/src/declarative/qml/qdeclarativemetatype.cpp
+++ b/src/declarative/qml/qdeclarativemetatype.cpp
@@ -1899,7 +1899,6 @@ int QDeclarativeMetaType::QQuickAnchorLineMetaTypeId()
static int id = 0;
if (!id) {
id = QMetaType::type("QQuickAnchorLine");
- Q_ASSERT(id != 0);
}
return id;
}
diff --git a/src/declarative/qtquick2.cpp b/src/declarative/qtquick2.cpp
deleted file mode 100644
index ff49641865..0000000000
--- a/src/declarative/qtquick2.cpp
+++ /dev/null
@@ -1,193 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtquick2_p.h"
-#include <private/qdeclarativeengine_p.h>
-#include <private/qdeclarativeutilmodule_p.h>
-#include <private/qdeclarativevaluetype_p.h>
-#include <private/qquickitemsmodule_p.h>
-#include <private/qquickparticlesmodule_p.h>
-#include <private/qquickwindowmodule_p.h>
-
-#include <private/qdeclarativeenginedebugservice_p.h>
-#include <private/qdeclarativedebugstatesdelegate_p.h>
-#include <private/qdeclarativebinding_p.h>
-#include <private/qdeclarativecontext_p.h>
-#include <private/qdeclarativepropertychanges_p.h>
-#include <private/qdeclarativestate_p.h>
-#include <qdeclarativeproperty.h>
-#include <QtCore/QWeakPointer>
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeQtQuick2DebugStatesDelegate : public QDeclarativeDebugStatesDelegate
-{
-public:
- QDeclarativeQtQuick2DebugStatesDelegate();
- virtual ~QDeclarativeQtQuick2DebugStatesDelegate();
- virtual void buildStatesList(QDeclarativeContext *ctxt, bool cleanList);
- virtual void updateBinding(QDeclarativeContext *context,
- const QDeclarativeProperty &property,
- const QVariant &expression, bool isLiteralValue,
- const QString &fileName, int line,
- bool *isBaseState);
- virtual bool setBindingForInvalidProperty(QObject *object,
- const QString &propertyName,
- const QVariant &expression,
- bool isLiteralValue);
- virtual void resetBindingForInvalidProperty(QObject *object,
- const QString &propertyName);
-
-private:
- void buildStatesList(QObject *obj);
-
- QList<QWeakPointer<QDeclarativeState> > m_allStates;
-};
-
-QDeclarativeQtQuick2DebugStatesDelegate::QDeclarativeQtQuick2DebugStatesDelegate()
-{
-}
-
-QDeclarativeQtQuick2DebugStatesDelegate::~QDeclarativeQtQuick2DebugStatesDelegate()
-{
-}
-
-void QDeclarativeQtQuick2DebugStatesDelegate::buildStatesList(QDeclarativeContext *ctxt, bool cleanList)
-{
- if (cleanList)
- m_allStates.clear();
-
- QDeclarativeContextPrivate *ctxtPriv = QDeclarativeContextPrivate::get(ctxt);
- for (int ii = 0; ii < ctxtPriv->instances.count(); ++ii) {
- buildStatesList(ctxtPriv->instances.at(ii));
- }
-
- QDeclarativeContextData *child = QDeclarativeContextData::get(ctxt)->childContexts;
- while (child) {
- buildStatesList(child->asQDeclarativeContext());
- child = child->nextChild;
- }
-}
-
-void QDeclarativeQtQuick2DebugStatesDelegate::buildStatesList(QObject *obj)
-{
- if (QDeclarativeState *state = qobject_cast<QDeclarativeState *>(obj)) {
- m_allStates.append(state);
- }
-
- QObjectList children = obj->children();
- for (int ii = 0; ii < children.count(); ++ii) {
- buildStatesList(children.at(ii));
- }
-}
-
-void QDeclarativeQtQuick2DebugStatesDelegate::updateBinding(QDeclarativeContext *context,
- const QDeclarativeProperty &property,
- const QVariant &expression, bool isLiteralValue,
- const QString &fileName, int line,
- bool *inBaseState)
-{
- QObject *object = property.object();
- QString propertyName = property.name();
- foreach (QWeakPointer<QDeclarativeState> statePointer, m_allStates) {
- if (QDeclarativeState *state = statePointer.data()) {
- // here we assume that the revert list on itself defines the base state
- if (state->isStateActive() && state->containsPropertyInRevertList(object, propertyName)) {
- *inBaseState = false;
-
- QDeclarativeBinding *newBinding = 0;
- if (!isLiteralValue) {
- newBinding = new QDeclarativeBinding(expression.toString(), object, context);
- newBinding->setTarget(property);
- newBinding->setNotifyOnValueChanged(true);
- newBinding->setSourceLocation(fileName, line);
- }
-
- state->changeBindingInRevertList(object, propertyName, newBinding);
-
- if (isLiteralValue)
- state->changeValueInRevertList(object, propertyName, expression);
- }
- }
- }
-}
-
-bool QDeclarativeQtQuick2DebugStatesDelegate::setBindingForInvalidProperty(QObject *object,
- const QString &propertyName,
- const QVariant &expression,
- bool isLiteralValue)
-{
- if (QDeclarativePropertyChanges *propertyChanges = qobject_cast<QDeclarativePropertyChanges *>(object)) {
- if (isLiteralValue)
- propertyChanges->changeValue(propertyName, expression);
- else
- propertyChanges->changeExpression(propertyName, expression.toString());
- return true;
- } else {
- return false;
- }
-}
-
-void QDeclarativeQtQuick2DebugStatesDelegate::resetBindingForInvalidProperty(QObject *object, const QString &propertyName)
-{
- if (QDeclarativePropertyChanges *propertyChanges = qobject_cast<QDeclarativePropertyChanges *>(object)) {
- propertyChanges->removeProperty(propertyName);
- }
-}
-
-
-void QDeclarativeQtQuick2Module::defineModule()
-{
- QDeclarativeUtilModule::defineModule();
- QDeclarativeEnginePrivate::defineModule();
- QQuickItemsModule::defineModule();
- QQuickParticlesModule::defineModule();
- QQuickWindowModule::defineModule();
- QDeclarativeValueTypeFactory::registerValueTypes();
-
- if (QDeclarativeEngineDebugService::isDebuggingEnabled()) {
- QDeclarativeEngineDebugService::instance()->setStatesDelegate(
- new QDeclarativeQtQuick2DebugStatesDelegate);
- }
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/qtquick2_p.h b/src/declarative/qtquick2_p.h
deleted file mode 100644
index 7e2b334124..0000000000
--- a/src/declarative/qtquick2_p.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTQUICK2_P_H
-#define QTQUICK2_P_H
-
-#include <private/qdeclarativeglobal_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativeQtQuick2Module
-{
-public:
- static void defineModule();
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTQUICK2_P_H
diff --git a/src/declarative/scenegraph/coreapi/qsgdefaultrenderer.cpp b/src/declarative/scenegraph/coreapi/qsgdefaultrenderer.cpp
deleted file mode 100644
index 56a6e0e5d9..0000000000
--- a/src/declarative/scenegraph/coreapi/qsgdefaultrenderer.cpp
+++ /dev/null
@@ -1,527 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#define GL_GLEXT_PROTOTYPES
-
-#include "qsgdefaultrenderer_p.h"
-#include "qsgmaterial.h"
-
-#include <QtCore/qvarlengtharray.h>
-#include <QtGui/qguiapplication.h>
-#include <QtCore/qpair.h>
-#include <QtCore/QElapsedTimer>
-
-//#define FORCE_NO_REORDER
-
-// #define RENDERER_DEBUG
-#ifdef RENDERER_DEBUG
-#define DEBUG_THRESHOLD 0
-QElapsedTimer debugTimer;
-int materialChanges;
-int geometryNodesDrawn;
-#endif
-
-QT_BEGIN_NAMESPACE
-
-static bool nodeLessThan(QSGGeometryNode *a, QSGGeometryNode *b)
-{
- // Sort by clip...
- if (a->clipList() != b->clipList())
- return a->clipList() < b->clipList();
-
- // Sort by material definition
- QSGMaterialType *aDef = a->material()->type();
- QSGMaterialType *bDef = b->material()->type();
-
- if (aDef != bDef)
- return aDef < bDef;
-
- // Sort by material state
- int cmp = a->material()->compare(b->material());
- if (cmp != 0)
- return cmp < 0;
-
- return a->matrix() < b->matrix();
-}
-
-static bool nodeLessThanWithRenderOrder(QSGGeometryNode *a, QSGGeometryNode *b)
-{
- // Sort by clip...
- if (a->clipList() != b->clipList())
- return a->clipList() < b->clipList();
-
- // Sort by material definition
- QSGMaterialType *aDef = a->material()->type();
- QSGMaterialType *bDef = b->material()->type();
-
- if (!(a->material()->flags() & QSGMaterial::Blending)) {
- int aOrder = a->renderOrder();
- int bOrder = b->renderOrder();
- if (aOrder != bOrder)
- return aOrder > bOrder;
- }
-
- if (aDef != bDef)
- return aDef < bDef;
-
- // Sort by material state
- int cmp = a->material()->compare(b->material());
- if (cmp != 0)
- return cmp < 0;
-
- return a->matrix() < b->matrix();
-}
-
-
-QSGDefaultRenderer::IndexGeometryNodePair::IndexGeometryNodePair(int i, QSGGeometryNode *node)
- : QPair<int, QSGGeometryNode *>(i, node)
-{
-}
-
-bool QSGDefaultRenderer::IndexGeometryNodePair::operator < (const QSGDefaultRenderer::IndexGeometryNodePair &other) const
-{
- return nodeLessThan(second, other.second);
-}
-
-
-QSGDefaultRenderer::IndexGeometryNodePairHeap::IndexGeometryNodePairHeap()
- : v(64)
-{
-}
-
-void QSGDefaultRenderer::IndexGeometryNodePairHeap::insert(const QSGDefaultRenderer::IndexGeometryNodePair &x)
-{
- int i = v.size();
- v.add(x);
- while (i != 0 && v.at(i) < v.at(parent(i))) {
- qSwap(v.at(parent(i)), v.at(i));
- i = parent(i);
- }
-}
-
-QSGDefaultRenderer::IndexGeometryNodePair QSGDefaultRenderer::IndexGeometryNodePairHeap::pop()
-{
- IndexGeometryNodePair x = top();
- if (v.size() > 1)
- qSwap(v.first(), v.last());
- v.pop_back();
- int i = 0;
- while (left(i) < v.size()) {
- int low = left(i);
- if (right(i) < v.size() && v.at(right(i)) < v.at(low))
- low = right(i);
- if (!(v.at(low) < v.at(i)))
- break;
- qSwap(v.at(i), v.at(low));
- i = low;
- }
- return x;
-}
-
-
-QSGDefaultRenderer::QSGDefaultRenderer(QSGContext *context)
- : QSGRenderer(context)
- , m_opaqueNodes(64)
- , m_transparentNodes(64)
- , m_tempNodes(64)
- , m_rebuild_lists(false)
- , m_needs_sorting(false)
- , m_sort_front_to_back(false)
- , m_currentRenderOrder(1)
-{
- QStringList args = qApp->arguments();
-#if defined(QML_RUNTIME_TESTING)
- m_render_opaque_nodes = !args.contains(QLatin1String("--no-opaque-nodes"));
- m_render_alpha_nodes = !args.contains(QLatin1String("--no-alpha-nodes"));
-#endif
-}
-
-void QSGDefaultRenderer::nodeChanged(QSGNode *node, QSGNode::DirtyFlags flags)
-{
- QSGRenderer::nodeChanged(node, flags);
-
- quint32 rebuildFlags = QSGNode::DirtyNodeAdded | QSGNode::DirtyNodeRemoved
- | QSGNode::DirtyMaterial | QSGNode::DirtyOpacity
- | QSGNode::DirtyForceUpdate;
-
- if (flags & rebuildFlags)
- m_rebuild_lists = true;
-
- if (flags & (rebuildFlags | QSGNode::DirtyClipList))
- m_needs_sorting = true;
-}
-
-void QSGDefaultRenderer::render()
-{
-#if defined (QML_RUNTIME_TESTING)
- static bool dumpTree = qApp->arguments().contains(QLatin1String("--dump-tree"));
- if (dumpTree) {
- printf("\n\n");
- QSGNodeDumper::dump(rootNode());
- }
-#endif
-
-#ifdef RENDERER_DEBUG
- debugTimer.invalidate();
- debugTimer.start();
- geometryNodesDrawn = 0;
- materialChanges = 0;
-#endif
-
- glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- glDisable(GL_BLEND);
-
- glFrontFace(isMirrored() ? GL_CW : GL_CCW);
- glDisable(GL_CULL_FACE);
-
- glEnable(GL_DEPTH_TEST);
- glDepthMask(true);
- glDepthFunc(GL_GREATER);
-#if defined(QT_OPENGL_ES)
- glClearDepthf(0);
-#else
- glClearDepth(0);
-#endif
-
- glDisable(GL_SCISSOR_TEST);
- glClearColor(m_clear_color.redF(), m_clear_color.greenF(), m_clear_color.blueF(), m_clear_color.alphaF());
-
-#ifdef RENDERER_DEBUG
- int debugtimeSetup = debugTimer.elapsed();
-#endif
-
- bindable()->clear(clearMode());
-
-#ifdef RENDERER_DEBUG
- int debugtimeClear = debugTimer.elapsed();
-#endif
-
- QRect r = viewportRect();
- glViewport(r.x(), deviceRect().bottom() - r.bottom(), r.width(), r.height());
- m_current_projection_matrix = projectionMatrix();
- m_current_model_view_matrix.setToIdentity();
-
- m_currentClip = 0;
- glDisable(GL_STENCIL_TEST);
-
- m_currentMaterial = 0;
- m_currentProgram = 0;
- m_currentMatrix = 0;
-
- if (m_rebuild_lists) {
- m_opaqueNodes.reset();
- m_transparentNodes.reset();
- m_currentRenderOrder = 1;
- buildLists(rootNode());
- m_rebuild_lists = false;
- }
-
-#ifdef RENDERER_DEBUG
- int debugtimeLists = debugTimer.elapsed();
-#endif
-
-
- if (m_needs_sorting) {
- if (!m_opaqueNodes.isEmpty()) {
- qSort(&m_opaqueNodes.first(), &m_opaqueNodes.first() + m_opaqueNodes.size(),
- m_sort_front_to_back
- ? nodeLessThanWithRenderOrder
- : nodeLessThan);
- }
- m_needs_sorting = false;
- }
-
-#ifdef RENDERER_DEBUG
- int debugtimeSorting = debugTimer.elapsed();
-#endif
-
- m_renderOrderMatrix.setToIdentity();
- m_renderOrderMatrix.scale(1, 1, qreal(1) / m_currentRenderOrder);
-
- glDisable(GL_BLEND);
- glDepthMask(true);
-#ifdef QML_RUNTIME_TESTING
- if (m_render_opaque_nodes)
-#endif
- {
-#if defined (QML_RUNTIME_TESTING)
- if (dumpTree)
- qDebug() << "Opaque Nodes:";
-#endif
- renderNodes(m_opaqueNodes);
- }
-
-#ifdef RENDERER_DEBUG
- int debugtimeOpaque = debugTimer.elapsed();
- int opaqueNodes = geometryNodesDrawn;
- int opaqueMaterialChanges = materialChanges;
-#endif
-
- glEnable(GL_BLEND);
- glDepthMask(false);
-#ifdef QML_RUNTIME_TESTING
- if (m_render_alpha_nodes)
-#endif
- {
-#if defined (QML_RUNTIME_TESTING)
- if (dumpTree)
- qDebug() << "Alpha Nodes:";
-#endif
- renderNodes(m_transparentNodes);
- }
-
-#ifdef RENDERER_DEBUG
- int debugtimeAlpha = debugTimer.elapsed();
-#endif
-
-
- if (m_currentProgram)
- m_currentProgram->deactivate();
-
-#ifdef RENDERER_DEBUG
- if (debugTimer.elapsed() > DEBUG_THRESHOLD) {
- printf(" --- Renderer breakdown:\n"
- " - setup=%d, clear=%d, building=%d, sorting=%d, opaque=%d, alpha=%d\n"
- " - material changes: opaque=%d, alpha=%d, total=%d\n"
- " - geometry ndoes: opaque=%d, alpha=%d, total=%d\n",
- debugtimeSetup,
- debugtimeClear - debugtimeSetup,
- debugtimeLists - debugtimeClear,
- debugtimeSorting - debugtimeLists,
- debugtimeOpaque - debugtimeSorting,
- debugtimeAlpha - debugtimeOpaque,
- opaqueMaterialChanges, materialChanges - opaqueMaterialChanges, materialChanges,
- opaqueNodes, geometryNodesDrawn - opaqueNodes, geometryNodesDrawn);
- }
-#endif
-
-}
-
-void QSGDefaultRenderer::setSortFrontToBackEnabled(bool sort)
-{
- printf("setting sorting to... %d\n", sort);
- m_sort_front_to_back = sort;
-}
-
-bool QSGDefaultRenderer::isSortFrontToBackEnabled() const
-{
- return m_sort_front_to_back;
-}
-
-void QSGDefaultRenderer::buildLists(QSGNode *node)
-{
- if (node->isSubtreeBlocked())
- return;
-
- if (node->type() == QSGNode::GeometryNodeType) {
- QSGGeometryNode *geomNode = static_cast<QSGGeometryNode *>(node);
- qreal opacity = geomNode->inheritedOpacity();
- QSGMaterial *m = geomNode->activeMaterial();
-
-#ifdef FORCE_NO_REORDER
- if (true) {
-#else
- if ((m->flags() & QSGMaterial::Blending) || opacity < 1) {
-#endif
- geomNode->setRenderOrder(m_currentRenderOrder - 1);
- m_transparentNodes.add(geomNode);
- } else {
- geomNode->setRenderOrder(m_currentRenderOrder);
- m_opaqueNodes.add(geomNode);
- m_currentRenderOrder += 2;
- }
- }
-
- if (!node->firstChild())
- return;
-
-#ifdef FORCE_NO_REORDER
- static bool reorder = false;
-#else
- static bool reorder = qApp->arguments().contains(QLatin1String("--reorder"));
-#endif
-
- if (reorder && node->firstChild() != node->lastChild() && (node->flags() & QSGNode::ChildrenDoNotOverlap)) {
- QVarLengthArray<int, 16> beginIndices;
- QVarLengthArray<int, 16> endIndices;
- int baseCount = m_transparentNodes.size();
- int count = 0;
- for (QSGNode *c = node->firstChild(); c; c = c->nextSibling()) {
- beginIndices.append(m_transparentNodes.size());
- buildLists(c);
- endIndices.append(m_transparentNodes.size());
- ++count;
- }
-
- int childNodeCount = m_transparentNodes.size() - baseCount;
- if (childNodeCount) {
- m_tempNodes.reset();
- m_tempNodes.reserve(childNodeCount);
- while (childNodeCount) {
- for (int i = 0; i < count; ++i) {
- if (beginIndices[i] != endIndices[i])
- m_heap.insert(IndexGeometryNodePair(i, m_transparentNodes.at(beginIndices[i]++)));
- }
- while (!m_heap.isEmpty()) {
- IndexGeometryNodePair pair = m_heap.pop();
- m_tempNodes.add(pair.second);
- --childNodeCount;
- int i = pair.first;
- if (beginIndices[i] != endIndices[i] && !nodeLessThan(m_transparentNodes.at(beginIndices[i]), pair.second))
- m_heap.insert(IndexGeometryNodePair(i, m_transparentNodes.at(beginIndices[i]++)));
- }
- }
- Q_ASSERT(m_tempNodes.size() == m_transparentNodes.size() - baseCount);
-
- qMemCopy(&m_transparentNodes.at(baseCount), &m_tempNodes.at(0), m_tempNodes.size() * sizeof(QSGGeometryNode *));
- }
- } else {
- for (QSGNode *c = node->firstChild(); c; c = c->nextSibling())
- buildLists(c);
- }
-}
-
-void QSGDefaultRenderer::renderNodes(const QDataBuffer<QSGGeometryNode *> &list)
-{
- const float scale = 1.0f / m_currentRenderOrder;
- int count = list.size();
- int currentRenderOrder = 0x80000000;
- m_current_projection_matrix.setColumn(2, scale * projectionMatrix().column(2));
-
- //int clipChangeCount = 0;
- //int programChangeCount = 0;
- //int materialChangeCount = 0;
-
- for (int i = 0; i < count; ++i) {
- QSGGeometryNode *geomNode = list.at(i);
-
- QSGMaterialShader::RenderState::DirtyStates updates;
-
-#if defined (QML_RUNTIME_TESTING)
- static bool dumpTree = qApp->arguments().contains(QLatin1String("--dump-tree"));
- if (dumpTree)
- qDebug() << geomNode;
-#endif
-
- bool changeMatrix = m_currentMatrix != geomNode->matrix();
-
- if (changeMatrix) {
- m_currentMatrix = geomNode->matrix();
- if (m_currentMatrix)
- m_current_model_view_matrix = *m_currentMatrix;
- else
- m_current_model_view_matrix.setToIdentity();
- updates |= QSGMaterialShader::RenderState::DirtyMatrix;
- }
-
- bool changeOpacity = m_current_opacity != geomNode->inheritedOpacity();
- if (changeOpacity) {
- updates |= QSGMaterialShader::RenderState::DirtyOpacity;
- m_current_opacity = geomNode->inheritedOpacity();
- }
-
- Q_ASSERT(geomNode->activeMaterial());
-
- QSGMaterial *material = geomNode->activeMaterial();
- QSGMaterialShader *program = m_context->prepareMaterial(material);
- Q_ASSERT(program->program()->isLinked());
-
- bool changeClip = geomNode->clipList() != m_currentClip;
- QSGRenderer::ClipType clipType = QSGRenderer::NoClip;
- if (changeClip) {
- // The clip function relies on there not being any depth testing..
- glDisable(GL_DEPTH_TEST);
- clipType = updateStencilClip(geomNode->clipList());
- glEnable(GL_DEPTH_TEST);
- m_currentClip = geomNode->clipList();
-#ifdef FORCE_NO_REORDER
- glDepthMask(false);
-#else
- glDepthMask((material->flags() & QSGMaterial::Blending) == 0 && m_current_opacity == 1);
-#endif
- //++clipChangeCount;
- }
-
- bool changeProgram = (changeClip && clipType == QSGRenderer::StencilClip) || m_currentProgram != program;
- if (changeProgram) {
- if (m_currentProgram)
- m_currentProgram->deactivate();
- m_currentProgram = program;
- m_currentProgram->activate();
- //++programChangeCount;
- updates |= (QSGMaterialShader::RenderState::DirtyMatrix | QSGMaterialShader::RenderState::DirtyOpacity);
-
-#ifdef RENDERER_DEBUG
- materialChanges++;
-#endif
- }
-
- bool changeRenderOrder = currentRenderOrder != geomNode->renderOrder();
- if (changeRenderOrder) {
- currentRenderOrder = geomNode->renderOrder();
- m_current_projection_matrix.setColumn(3, projectionMatrix().column(3)
- + currentRenderOrder
- * m_current_projection_matrix.column(2));
- updates |= QSGMaterialShader::RenderState::DirtyMatrix;
- }
-
- if (changeProgram || m_currentMaterial != material) {
- program->updateState(state(updates), material, changeProgram ? 0 : m_currentMaterial);
- m_currentMaterial = material;
- //++materialChangeCount;
- }
-
- //glDepthRange((geomNode->renderOrder() + 0.1) * scale, (geomNode->renderOrder() + 0.9) * scale);
-
- const QSGGeometry *g = geomNode->geometry();
- draw(program, g);
-
-#ifdef RENDERER_DEBUG
- geometryNodesDrawn++;
-#endif
- }
- //qDebug("Clip: %i, shader program: %i, material: %i times changed while drawing %s items",
- // clipChangeCount, programChangeCount, materialChangeCount,
- // &list == &m_transparentNodes ? "transparent" : "opaque");
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/coreapi/qsgdefaultrenderer_p.h b/src/declarative/scenegraph/coreapi/qsgdefaultrenderer_p.h
deleted file mode 100644
index 45cebdd7b9..0000000000
--- a/src/declarative/scenegraph/coreapi/qsgdefaultrenderer_p.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QMLRENDERER_H
-#define QMLRENDERER_H
-
-#include "qsgrenderer_p.h"
-
-#include <QtGui/private/qdatabuffer_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-
-class QSGDefaultRenderer : public QSGRenderer
-{
- Q_OBJECT
-public:
- class IndexGeometryNodePair : public QPair<int, QSGGeometryNode *>
- {
- public:
- IndexGeometryNodePair(int i, QSGGeometryNode *n);
- bool operator < (const IndexGeometryNodePair &other) const;
- };
-
-
- // Minimum heap.
- class IndexGeometryNodePairHeap
- {
- public:
- IndexGeometryNodePairHeap();
- void insert(const IndexGeometryNodePair &x);
- const IndexGeometryNodePair &top() const { return v.first(); }
- IndexGeometryNodePair pop();
- bool isEmpty() const { return v.isEmpty(); }
- private:
- static int parent(int i) { return (i - 1) >> 1; }
- static int left(int i) { return (i << 1) | 1; }
- static int right(int i) { return (i + 1) << 1; }
- QDataBuffer<IndexGeometryNodePair> v;
- };
-
- QSGDefaultRenderer(QSGContext *context);
-
- void render();
-
- void nodeChanged(QSGNode *node, QSGNode::DirtyFlags flags);
-
- void setSortFrontToBackEnabled(bool sort);
- bool isSortFrontToBackEnabled() const;
-
-private:
- void buildLists(QSGNode *node);
- void renderNodes(const QDataBuffer<QSGGeometryNode *> &list);
-
- const QSGClipNode *m_currentClip;
- QSGMaterial *m_currentMaterial;
- QSGMaterialShader *m_currentProgram;
- const QMatrix4x4 *m_currentMatrix;
- QMatrix4x4 m_renderOrderMatrix;
- QDataBuffer<QSGGeometryNode *> m_opaqueNodes;
- QDataBuffer<QSGGeometryNode *> m_transparentNodes;
- QDataBuffer<QSGGeometryNode *> m_tempNodes;
- IndexGeometryNodePairHeap m_heap;
-
- bool m_rebuild_lists;
- bool m_needs_sorting;
- bool m_sort_front_to_back;
- int m_currentRenderOrder;
-
-#ifdef QML_RUNTIME_TESTING
- bool m_render_opaque_nodes;
- bool m_render_alpha_nodes;
-#endif
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QMLRENDERER_H
diff --git a/src/declarative/scenegraph/coreapi/qsggeometry.cpp b/src/declarative/scenegraph/coreapi/qsggeometry.cpp
deleted file mode 100644
index 8661c9af93..0000000000
--- a/src/declarative/scenegraph/coreapi/qsggeometry.cpp
+++ /dev/null
@@ -1,466 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Qt scene graph research project.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsggeometry.h"
-#include "qsggeometry_p.h"
-
-#include <qopenglcontext.h>
-#include <qopenglfunctions.h>
-#include <private/qopenglextensions_p.h>
-
-QT_BEGIN_NAMESPACE
-
-
-QSGGeometry::Attribute QSGGeometry::Attribute::create(int attributeIndex, int tupleSize, int primitiveType, bool isPrimitive)
-{
- Attribute a = { attributeIndex, tupleSize, primitiveType, isPrimitive, 0 };
- return a;
-}
-
-
-/*!
- Convenience function which returns attributes to be used for 2D solid
- color drawing.
- */
-
-const QSGGeometry::AttributeSet &QSGGeometry::defaultAttributes_Point2D()
-{
- static Attribute data[] = {
- QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true)
- };
- static AttributeSet attrs = { 1, sizeof(float) * 2, data };
- return attrs;
-}
-
-/*!
- Convenience function which returns attributes to be used for textured 2D drawing.
- */
-
-const QSGGeometry::AttributeSet &QSGGeometry::defaultAttributes_TexturedPoint2D()
-{
- static Attribute data[] = {
- QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true),
- QSGGeometry::Attribute::create(1, 2, GL_FLOAT)
- };
- static AttributeSet attrs = { 2, sizeof(float) * 4, data };
- return attrs;
-}
-
-/*!
- Convenience function which returns attributes to be used for per vertex colored 2D drawing.
- */
-
-const QSGGeometry::AttributeSet &QSGGeometry::defaultAttributes_ColoredPoint2D()
-{
- static Attribute data[] = {
- QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true),
- QSGGeometry::Attribute::create(1, 4, GL_UNSIGNED_BYTE)
- };
- static AttributeSet attrs = { 2, 2 * sizeof(float) + 4 * sizeof(char), data };
- return attrs;
-}
-
-
-/*!
- \class QSGGeometry
- \brief The QSGGeometry class provides low-level storage for graphics primitives
- in the QML Scene Graph.
-
- The QSGGeometry class provides a few convenience attributes and attribute accessors
- by default. The defaultAttributes_Point2D() function returns attributes to be used
- in normal solid color rectangles, while the defaultAttributes_TexturedPoint2D function
- returns attributes to be used for the common pixmap usecase.
- */
-
-
-/*!
- Constructs a geometry object based on \a attributes.
-
- The object allocate space for \a vertexCount vertices based on the accumulated
- size in \a attributes and for \a indexCount.
-
- Geometry objects are constructed with GL_TRIANGLE_STRIP as default drawing mode.
-
- The attribute structure is assumed to be POD and the geometry object
- assumes this will not go away. There is no memory management involved.
- */
-
-QSGGeometry::QSGGeometry(const QSGGeometry::AttributeSet &attributes,
- int vertexCount,
- int indexCount,
- int indexType)
- : m_drawing_mode(GL_TRIANGLE_STRIP)
- , m_vertex_count(0)
- , m_index_count(0)
- , m_index_type(indexType)
- , m_attributes(attributes)
- , m_data(0)
- , m_index_data_offset(-1)
- , m_server_data(0)
- , m_owns_data(false)
- , m_index_usage_pattern(AlwaysUploadPattern)
- , m_vertex_usage_pattern(AlwaysUploadPattern)
-{
- Q_ASSERT(m_attributes.count > 0);
- Q_ASSERT(m_attributes.stride > 0);
-
- Q_ASSERT_X(indexType != GL_UNSIGNED_INT
- || static_cast<QOpenGLExtensions *>(QOpenGLContext::currentContext()->functions())
- ->hasOpenGLExtension(QOpenGLExtensions::ElementIndexUint),
- "QSGGeometry::QSGGeometry",
- "GL_UNSIGNED_INT is not supported, geometry will not render"
- );
-
- if (indexType != GL_UNSIGNED_BYTE
- && indexType != GL_UNSIGNED_SHORT
- && indexType != GL_UNSIGNED_INT) {
- qFatal("QSGGeometry: Unsupported index type, %x.\n", indexType);
- }
-
-
- // Because allocate reads m_vertex_count, m_index_count and m_owns_data, these
- // need to be set before calling allocate...
- allocate(vertexCount, indexCount);
-}
-
-/*!
- \fn int QSGGeometry::sizeOfVertex() const
-
- Returns the size in bytes of one vertex.
-
- This value comes from the attributes.
- */
-
-/*!
- \fn int QSGGeometry::sizeOfIndex() const
-
- Returns the byte size of the index type.
-
- This value is either 1 when index type is GL_UNSIGNED_BYTE or 2 when
- index type is GL_UNSIGNED_SHORT. For Desktop OpenGL, GL_UNSIGNED_INT
- with the value 4 is also supported.
- */
-
-QSGGeometry::~QSGGeometry()
-{
- if (m_owns_data)
- qFree(m_data);
-
- if (m_server_data)
- delete m_server_data;
-}
-
-/*!
- \fn int QSGGeometry::vertexCount() const
-
- Returns the number of vertices in this geometry object.
- */
-
-/*!
- \fn int QSGGeometry::indexCount() const
-
- Returns the number of indices in this geometry object.
- */
-
-
-
-/*!
- \fn void *QSGGeometry::vertexData()
-
- Returns a pointer to the raw vertex data of this geometry object.
-
- \sa vertexDataAsPoint2D(), vertexDataAsTexturedPoint2D
- */
-
-/*!
- \fn const void *QSGGeometry::vertexData() const
-
- Returns a pointer to the raw vertex data of this geometry object.
-
- \sa vertexDataAsPoint2D(), vertexDataAsTexturedPoint2D
- */
-
-/*!
- Returns a pointer to the raw index data of this geometry object.
-
- \sa indexDataAsUShort(), indexDataAsUInt()
- */
-void *QSGGeometry::indexData()
-{
- return m_index_data_offset < 0
- ? 0
- : ((char *) m_data + m_index_data_offset);
-}
-
-/*!
- Returns a pointer to the raw index data of this geometry object.
-
- \sa indexDataAsUShort(), indexDataAsUInt()
- */
-const void *QSGGeometry::indexData() const
-{
- return m_index_data_offset < 0
- ? 0
- : ((char *) m_data + m_index_data_offset);
-}
-
-/*!
- Sets the drawing mode to be used for this geometry.
-
- The default value is GL_TRIANGLE_STRIP.
- */
-void QSGGeometry::setDrawingMode(GLenum mode)
-{
- m_drawing_mode = mode;
-}
-
-/*!
- \fn int QSGGeometry::drawingMode() const
-
- Returns the drawing mode of this geometry.
-
- The default value is GL_TRIANGLE_STRIP.
- */
-
-/*!
- \fn int QSGGeometry::indexType() const
-
- Returns the primitive type used for indices in this
- geometry object.
- */
-
-
-/*!
- Resizes the vertex and index data of this geometry object to fit \a vertexCount
- vertices and \a indexCount indices.
-
- Vertex and index data will be invalidated after this call and the caller must
- */
-void QSGGeometry::allocate(int vertexCount, int indexCount)
-{
- if (vertexCount == m_vertex_count && indexCount == m_index_count)
- return;
-
- m_vertex_count = vertexCount;
- m_index_count = indexCount;
-
- bool canUsePrealloc = m_index_count <= 0;
- int vertexByteSize = m_attributes.stride * m_vertex_count;
-
- if (m_owns_data)
- qFree(m_data);
-
- if (canUsePrealloc && vertexByteSize <= (int) sizeof(m_prealloc)) {
- m_data = (void *) &m_prealloc[0];
- m_index_data_offset = -1;
- m_owns_data = false;
- } else {
- Q_ASSERT(m_index_type == GL_UNSIGNED_INT || m_index_type == GL_UNSIGNED_SHORT);
- int indexByteSize = indexCount * (m_index_type == GL_UNSIGNED_SHORT ? sizeof(quint16) : sizeof(quint32));
- m_data = (void *) qMalloc(vertexByteSize + indexByteSize);
- m_index_data_offset = vertexByteSize;
- m_owns_data = true;
- }
-
- // If we have associated vbo data we could potentially crash later if
- // the old buffers are used with the new vertex and index count, so we force
- // an update in the renderer in that case. This is really the users responsibility
- // but it is cheap for us to enforce this, so why not...
- if (m_server_data) {
- markIndexDataDirty();
- markVertexDataDirty();
- }
-
-}
-
-/*!
- Updates the geometry \a g with the coordinates in \a rect.
-
- The function assumes the geometry object contains a single triangle strip
- of QSGGeometry::Point2D vertices
- */
-void QSGGeometry::updateRectGeometry(QSGGeometry *g, const QRectF &rect)
-{
- Point2D *v = g->vertexDataAsPoint2D();
- v[0].x = rect.left();
- v[0].y = rect.top();
-
- v[1].x = rect.left();
- v[1].y = rect.bottom();
-
- v[2].x = rect.right();
- v[2].y = rect.top();
-
- v[3].x = rect.right();
- v[3].y = rect.bottom();
-}
-
-/*!
- Updates the geometry \a g with the coordinates in \a rect and texture
- coordinates from \a textureRect.
-
- \a textureRect should be in normalized coordinates.
-
- \a g is assumed to be a triangle strip of four vertices of type
- QSGGeometry::TexturedPoint2D.
- */
-void QSGGeometry::updateTexturedRectGeometry(QSGGeometry *g, const QRectF &rect, const QRectF &textureRect)
-{
- TexturedPoint2D *v = g->vertexDataAsTexturedPoint2D();
- v[0].x = rect.left();
- v[0].y = rect.top();
- v[0].tx = textureRect.left();
- v[0].ty = textureRect.top();
-
- v[1].x = rect.left();
- v[1].y = rect.bottom();
- v[1].tx = textureRect.left();
- v[1].ty = textureRect.bottom();
-
- v[2].x = rect.right();
- v[2].y = rect.top();
- v[2].tx = textureRect.right();
- v[2].ty = textureRect.top();
-
- v[3].x = rect.right();
- v[3].y = rect.bottom();
- v[3].tx = textureRect.right();
- v[3].ty = textureRect.bottom();
-}
-
-
-
-/*!
- \enum QSGGeometry::DataPattern
-
- The DataPattern enum is used to specify the use pattern for the vertex
- and index data in a geometry object.
-
- \value AlwaysUploadPattern The data is always uploaded. This means that
- the user does not need to explicitly mark index and vertex data as
- dirty after changing it. This is the default.
-
- \value DynamicPattern The data is modified repeatedly and drawn many times.
- This is a hint that may provide better performance. When set
- the user must make sure to mark the data as dirty after changing it.
-
- \value StaticPattern The data is modified once and drawn many times. This is
- a hint that may provide better performance. When set the user must make sure
- to mark the data as dirty after changing it.
- */
-
-
-/*!
- \fn QSGGeometry::DataPattern QSGGeometry::indexDataPattern() const
-
- Returns the usage pattern for indices in this geometry. The default
- pattern is AlwaysUploadPattern.
- */
-
-/*!
- Sets the usage pattern for indices to \a p.
-
- The default is AlwaysUploadPattern. When set to anything other than
- the default, the user must call markIndexDataDirty() after changing
- the index data.
- */
-
-void QSGGeometry::setIndexDataPattern(DataPattern p)
-{
- m_index_usage_pattern = p;
-}
-
-
-
-
-/*!
- \fn QSGGeometry::DataPattern QSGGeometry::vertexDataPattern() const
-
- Returns the usage pattern for vertices in this geometry. The default
- pattern is AlwaysUploadPattern.
- */
-
-/*!
- Sets the usage pattern for vertices to \a p.
-
- The default is AlwaysUploadPattern. When set to anything other than
- the default, the user must call markVertexDataDirty() after changing
- the vertex data.
- */
-
-void QSGGeometry::setVertexDataPattern(DataPattern p)
-{
- m_vertex_usage_pattern = p;
-}
-
-
-
-
-/*!
- Mark that the vertices in this geometry has changed and must be uploaded
- again.
-
- This function only has an effect when the usage pattern for vertices is
- StaticData and the renderer that renders this geometry uploads the geometry
- into Vertex Buffer Objects (VBOs).
- */
-void QSGGeometry::markIndexDataDirty()
-{
- m_dirty_index_data = true;
-}
-
-
-
-/*!
- Mark that the vertices in this geometry has changed and must be uploaded
- again.
-
- This function only has an effect when the usage pattern for vertices is
- StaticData and the renderer that renders this geometry uploads the geometry
- into Vertex Buffer Objects (VBOs).
- */
-void QSGGeometry::markVertexDataDirty()
-{
- m_dirty_vertex_data = true;
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/coreapi/qsggeometry.h b/src/declarative/scenegraph/coreapi/qsggeometry.h
deleted file mode 100644
index d7b343c108..0000000000
--- a/src/declarative/scenegraph/coreapi/qsggeometry.h
+++ /dev/null
@@ -1,295 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the Qt scene graph research project.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGGEOMETRY_H
-#define QSGGEOMETRY_H
-
-#include <QtGui/qopengl.h>
-#include <QRectF>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGGeometryData;
-
-class Q_DECLARATIVE_EXPORT QSGGeometry
-{
-public:
-
- struct Attribute
- {
- int position;
- int tupleSize;
- int type;
-
- uint isVertexCoordinate : 1;
- uint migrateYourCodeToUseTheCreateFunction: 31; // ### Remove before release
-
- static Attribute create(int pos, int tupleSize, int primitiveType, bool isPosition = false);
- };
-
- struct AttributeSet {
- int count;
- int stride;
- const Attribute *attributes;
- };
-
- struct Point2D {
- float x, y;
- void set(float nx, float ny) {
- x = nx; y = ny;
- }
- };
- struct TexturedPoint2D {
- float x, y;
- float tx, ty;
- void set(float nx, float ny, float ntx, float nty) {
- x = nx; y = ny; tx = ntx; ty = nty;
- }
- };
- struct ColoredPoint2D {
- float x, y;
- unsigned char r, g, b, a;
- void set(float nx, float ny, uchar nr, uchar ng, uchar nb, uchar na) {
- x = nx; y = ny;
- r = nr; g = ng, b = nb; a = na;
- }
- };
-
- static const AttributeSet &defaultAttributes_Point2D();
- static const AttributeSet &defaultAttributes_TexturedPoint2D();
- static const AttributeSet &defaultAttributes_ColoredPoint2D();
-
- enum DataPattern {
- AlwaysUploadPattern = 0,
- StreamPattern = 1,
- DynamicPattern = 2,
- StaticPattern = 3
- };
-
- QSGGeometry(const QSGGeometry::AttributeSet &attribs,
- int vertexCount,
- int indexCount = 0,
- int indexType = GL_UNSIGNED_SHORT);
- virtual ~QSGGeometry();
-
- void setDrawingMode(GLenum mode);
- inline GLenum drawingMode() const { return m_drawing_mode; }
-
- void allocate(int vertexCount, int indexCount = 0);
-
- int vertexCount() const { return m_vertex_count; }
-
- void *vertexData() { return m_data; }
- inline Point2D *vertexDataAsPoint2D();
- inline TexturedPoint2D *vertexDataAsTexturedPoint2D();
- inline ColoredPoint2D *vertexDataAsColoredPoint2D();
-
- inline const void *vertexData() const { return m_data; }
- inline const Point2D *vertexDataAsPoint2D() const;
- inline const TexturedPoint2D *vertexDataAsTexturedPoint2D() const;
- inline const ColoredPoint2D *vertexDataAsColoredPoint2D() const;
-
- inline int indexType() const { return m_index_type; }
-
- int indexCount() const { return m_index_count; }
-
- void *indexData();
- inline uint *indexDataAsUInt();
- inline quint16 *indexDataAsUShort();
-
- inline int sizeOfIndex() const;
-
- const void *indexData() const;
- inline const uint *indexDataAsUInt() const;
- inline const quint16 *indexDataAsUShort() const;
-
- inline int attributeCount() const { return m_attributes.count; }
- inline const Attribute *attributes() const { return m_attributes.attributes; }
- inline int sizeOfVertex() const { return m_attributes.stride; }
-
- static void updateRectGeometry(QSGGeometry *g, const QRectF &rect);
- static void updateTexturedRectGeometry(QSGGeometry *g, const QRectF &rect, const QRectF &sourceRect);
-
- void setIndexDataPattern(DataPattern p);
- DataPattern indexDataPattern() const { return (DataPattern) m_index_usage_pattern; }
-
- void setVertexDataPattern(DataPattern p);
- DataPattern vertexDataPattern() const { return (DataPattern) m_vertex_usage_pattern; }
-
- void markIndexDataDirty();
- void markVertexDataDirty();
-
-private:
- friend class QSGGeometryData;
-
- int m_drawing_mode;
- int m_vertex_count;
- int m_index_count;
- int m_index_type;
- const AttributeSet &m_attributes;
- void *m_data;
- int m_index_data_offset;
-
- QSGGeometryData *m_server_data;
-
- uint m_owns_data : 1;
- uint m_index_usage_pattern : 2;
- uint m_vertex_usage_pattern : 2;
- uint m_dirty_index_data : 1;
- uint m_dirty_vertex_data : 1;
- uint m_reserved_bits : 27;
-
- float m_prealloc[16];
-};
-
-inline uint *QSGGeometry::indexDataAsUInt()
-{
- Q_ASSERT(m_index_type == GL_UNSIGNED_INT);
- return (uint *) indexData();
-}
-
-inline quint16 *QSGGeometry::indexDataAsUShort()
-{
- Q_ASSERT(m_index_type == GL_UNSIGNED_SHORT);
- return (quint16 *) indexData();
-}
-
-inline const uint *QSGGeometry::indexDataAsUInt() const
-{
- Q_ASSERT(m_index_type == GL_UNSIGNED_INT);
- return (uint *) indexData();
-}
-
-inline const quint16 *QSGGeometry::indexDataAsUShort() const
-{
- Q_ASSERT(m_index_type == GL_UNSIGNED_SHORT);
- return (quint16 *) indexData();
-}
-
-inline QSGGeometry::Point2D *QSGGeometry::vertexDataAsPoint2D()
-{
- Q_ASSERT(m_attributes.count == 1);
- Q_ASSERT(m_attributes.stride == 2 * sizeof(float));
- Q_ASSERT(m_attributes.attributes[0].tupleSize == 2);
- Q_ASSERT(m_attributes.attributes[0].type == GL_FLOAT);
- Q_ASSERT(m_attributes.attributes[0].position == 0);
- return (Point2D *) m_data;
-}
-
-inline QSGGeometry::TexturedPoint2D *QSGGeometry::vertexDataAsTexturedPoint2D()
-{
- Q_ASSERT(m_attributes.count == 2);
- Q_ASSERT(m_attributes.stride == 4 * sizeof(float));
- Q_ASSERT(m_attributes.attributes[0].position == 0);
- Q_ASSERT(m_attributes.attributes[0].tupleSize == 2);
- Q_ASSERT(m_attributes.attributes[0].type == GL_FLOAT);
- Q_ASSERT(m_attributes.attributes[1].position == 1);
- Q_ASSERT(m_attributes.attributes[1].tupleSize == 2);
- Q_ASSERT(m_attributes.attributes[1].type == GL_FLOAT);
- return (TexturedPoint2D *) m_data;
-}
-
-inline QSGGeometry::ColoredPoint2D *QSGGeometry::vertexDataAsColoredPoint2D()
-{
- Q_ASSERT(m_attributes.count == 2);
- Q_ASSERT(m_attributes.stride == 2 * sizeof(float) + 4 * sizeof(char));
- Q_ASSERT(m_attributes.attributes[0].position == 0);
- Q_ASSERT(m_attributes.attributes[0].tupleSize == 2);
- Q_ASSERT(m_attributes.attributes[0].type == GL_FLOAT);
- Q_ASSERT(m_attributes.attributes[1].position == 1);
- Q_ASSERT(m_attributes.attributes[1].tupleSize == 4);
- Q_ASSERT(m_attributes.attributes[1].type == GL_UNSIGNED_BYTE);
- return (ColoredPoint2D *) m_data;
-}
-
-inline const QSGGeometry::Point2D *QSGGeometry::vertexDataAsPoint2D() const
-{
- Q_ASSERT(m_attributes.count == 1);
- Q_ASSERT(m_attributes.stride == 2 * sizeof(float));
- Q_ASSERT(m_attributes.attributes[0].tupleSize == 2);
- Q_ASSERT(m_attributes.attributes[0].type == GL_FLOAT);
- Q_ASSERT(m_attributes.attributes[0].position == 0);
- return (const Point2D *) m_data;
-}
-
-inline const QSGGeometry::TexturedPoint2D *QSGGeometry::vertexDataAsTexturedPoint2D() const
-{
- Q_ASSERT(m_attributes.count == 2);
- Q_ASSERT(m_attributes.stride == 4 * sizeof(float));
- Q_ASSERT(m_attributes.attributes[0].position == 0);
- Q_ASSERT(m_attributes.attributes[0].tupleSize == 2);
- Q_ASSERT(m_attributes.attributes[0].type == GL_FLOAT);
- Q_ASSERT(m_attributes.attributes[1].position == 1);
- Q_ASSERT(m_attributes.attributes[1].tupleSize == 2);
- Q_ASSERT(m_attributes.attributes[1].type == GL_FLOAT);
- return (const TexturedPoint2D *) m_data;
-}
-
-inline const QSGGeometry::ColoredPoint2D *QSGGeometry::vertexDataAsColoredPoint2D() const
-{
- Q_ASSERT(m_attributes.count == 2);
- Q_ASSERT(m_attributes.stride == 2 * sizeof(float) + 4 * sizeof(char));
- Q_ASSERT(m_attributes.attributes[0].position == 0);
- Q_ASSERT(m_attributes.attributes[0].tupleSize == 2);
- Q_ASSERT(m_attributes.attributes[0].type == GL_FLOAT);
- Q_ASSERT(m_attributes.attributes[1].position == 1);
- Q_ASSERT(m_attributes.attributes[1].tupleSize == 4);
- Q_ASSERT(m_attributes.attributes[1].type == GL_UNSIGNED_BYTE);
- return (const ColoredPoint2D *) m_data;
-}
-
-int QSGGeometry::sizeOfIndex() const
-{
- if (m_index_type == GL_UNSIGNED_SHORT) return 2;
- else if (m_index_type == GL_UNSIGNED_BYTE) return 1;
- else if (m_index_type == GL_UNSIGNED_INT) return 4;
- return 0;
-}
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSGGEOMETRY_H
diff --git a/src/declarative/scenegraph/coreapi/qsggeometry_p.h b/src/declarative/scenegraph/coreapi/qsggeometry_p.h
deleted file mode 100644
index ef2935ae4c..0000000000
--- a/src/declarative/scenegraph/coreapi/qsggeometry_p.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGGEOMETRY_P_H
-#define QSGGEOMETRY_P_H
-
-#include "qsggeometry.h"
-
-QT_BEGIN_NAMESPACE
-
-class QSGGeometryData
-{
-public:
- virtual ~QSGGeometryData() {}
-
- static inline QSGGeometryData *data(const QSGGeometry *g) {
- return g->m_server_data;
- }
-
- static inline void install(const QSGGeometry *g, QSGGeometryData *data) {
- Q_ASSERT(!g->m_server_data);
- const_cast<QSGGeometry *>(g)->m_server_data = data;
- }
-
- static bool inline hasDirtyVertexData(const QSGGeometry *g) { return g->m_dirty_vertex_data; }
- static void inline clearDirtyVertexData(const QSGGeometry *g) { const_cast<QSGGeometry *>(g)->m_dirty_vertex_data = false; }
-
- static bool inline hasDirtyIndexData(const QSGGeometry *g) { return g->m_dirty_vertex_data; }
- static void inline clearDirtyIndexData(const QSGGeometry *g) { const_cast<QSGGeometry *>(g)->m_dirty_index_data = false; }
-
-};
-
-QT_END_NAMESPACE
-
-#endif // QSGGEOMETRY_P_H
diff --git a/src/declarative/scenegraph/coreapi/qsgmaterial.cpp b/src/declarative/scenegraph/coreapi/qsgmaterial.cpp
deleted file mode 100644
index 36b50e89b6..0000000000
--- a/src/declarative/scenegraph/coreapi/qsgmaterial.cpp
+++ /dev/null
@@ -1,535 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgmaterial.h"
-#include "qsgrenderer_p.h"
-
-QT_BEGIN_NAMESPACE
-
-
-/*!
- \class QSGMaterialShader
- \brief The QSGMaterialShader class implements a material renders geometry.
-
- The QSGMaterial and QSGMaterialShader form a tight relationship. For one
- scene graph (including nested graphs), there is one unique QSGMaterialShader
- instance which encapsulates the QOpenGLShaderProgram the scene graph uses
- to render that material, such as a shader to flat coloring of geometry.
- Each QSGGeometryNode can have a unique QSGMaterial containing the
- how the shader should be configured when drawing that node, such as
- the actual color to used to render the geometry.
-
- An instance of QSGMaterialShader is never created explicitely by the user,
- it will be created on demand by the scene graph through
- QSGMaterial::createShader(). The scene graph will make sure that there
- is only one instance of each shader implementation through a scene graph.
-
- The source code returned from vertexShader() is used to control what the
- material does with the vertiex data that comes in from the geometry.
- The source code returned from the fragmentShader() is used to control
- what how the material should fill each individual pixel in the geometry.
- The vertex and fragment source code is queried once during initialization,
- changing what is returned from these functions later will not have
- any effect.
-
- The activate() function is called by the scene graph when a shader is
- is starting to be used. The deactivate function is called by the scene
- graph when the shader is no longer going to be used. While active,
- the scene graph may make one or more calls to updateState() which
- will update the state of the shader for each individual geometry to
- render.
-
- The attributeNames() returns the name of the attributes used in the
- vertexShader(). These are used in the default implementation of
- activate() and deactive() to decide whice vertex registers are enabled.
-
- The initialize() function is called during program creation to allow
- subclasses to prepare for use, such as resolve uniform names in the
- vertexShader() and fragmentShader().
-
- A minimal example:
- \code
- class Shader : public QSGMaterialShader
- {
- public:
- const char *vertexShader() const {
- return
- "attribute highp vec4 vertex; \n"
- "uniform highp mat4 matrix; \n"
- "void main() { \n"
- " gl_Position = matrix * vertex; \n"
- "}";
- }
-
- const char *fragmentShader() const {
- return
- "uniform lowp float opacity; \n"
- "void main() { \n"
- " gl_FragColor = vec4(1, 0, 0, 1) * opacity; \n"
- "}";
- }
-
- char const *const *attributeNames() const
- {
- static char const *const names[] = { "vertex", 0 };
- return names;
- }
-
- void initialize()
- {
- QSGMaterialShader::initialize();
- m_id_matrix = program()->uniformLocation("matrix");
- m_id_opacity = program()->uniformLocation("opacity");
- }
-
- void updateState(const RenderState &state, QSGMaterial *newMaterial, QSGMaterial *oldMaterial)
- {
- Q_ASSERT(program()->isLinked());
- if (state.isMatrixDirty())
- program()->setUniformValue(m_id_matrix, state.combinedMatrix());
- if (state.isOpacityDirty())
- program()->setUniformValue(m_id_opacity, state.opacity());
- }
-
- private:
- int m_id_matrix;
- int m_id_opacity;
- };
- \endcode
-
- \warning Instances of QSGMaterialShader belongs to the Scene Graph rendering
- thread, and cannot be used from the GUI thread.
-
- */
-
-
-
-/*!
- Creates a new QSGMaterialShader.
- */
-QSGMaterialShader::QSGMaterialShader()
-{
-}
-
-
-
-/*!
- \fn QOpenGLShaderProgram *QSGMaterialShader::program() const
-
- Returns the shader program used by this QSGMaterialShader.
- */
-
-
-
-/*!
- This function is called by the scene graph to indicate that geometry is
- about to be rendered using this shader.
-
- State that is global for all uses of the shader, independent of the geometry
- that is being drawn, can be setup in this function.
-
- If reimplemented, make sure to either call the base class implementation to
- enable the vertex attribute registers.
- */
-
-void QSGMaterialShader::activate()
-{
- Q_ASSERT(program()->isLinked());
-
- program()->bind();
- char const *const *attr = attributeNames();
- for (int i = 0; attr[i]; ++i) {
- if (*attr[i])
- program()->enableAttributeArray(i);
- }
-}
-
-
-
-/*!
- This function is called by the scene graph to indicate that geometry will
- no longer to be rendered using this shader.
-
- If reimplemented, make sure to either call the base class implementation to
- disable the vertex attribute registers.
- */
-
-void QSGMaterialShader::deactivate()
-{
- char const *const *attr = attributeNames();
- for (int i = 0; attr[i]; ++i) {
- if (*attr[i])
- program()->disableAttributeArray(i);
- }
-}
-
-
-
-/*!
- This function is called by the scene graph before geometry is rendered
- to make sure the shader is in the right state.
-
- The current rendering \a state is passed from the scene graph. If the state
- indicates that any state is dirty, the updateState implementation must
- update accordingly for the geometry to render correctly.
-
- The subclass specific state, such as the color of a flat color material, should
- be extracted from \a newMaterial to update the color uniforms accordingly.
-
- The \a oldMaterial can be used to minimze state changes when updating
- material states. The \a oldMaterial is 0 if this shader was just activated.
-
- \sa activate(), deactivate()
- */
-
-void QSGMaterialShader::updateState(const RenderState & /* state */, QSGMaterial * /* newMaterial */, QSGMaterial * /* oldMaterial */)
-{
-}
-
-
-
-/*!
- This function is called when the shader is initialized to compile the
- actual QOpenGLShaderProgram. Do not call it explicitely.
-
- The default implementation will extract the vertexShader() and
- fragmentShader() and bind the names returned from attributeNames()
- to consecutive vertex attribute registers starting at 0.
- */
-
-void QSGMaterialShader::compile()
-{
- Q_ASSERT_X(!m_program.isLinked(), "QSGSMaterialShader::compile()", "Compile called multiple times!");
-
- program()->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShader());
- program()->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShader());
-
- char const *const *attr = attributeNames();
-#ifndef QT_NO_DEBUG
- int maxVertexAttribs = 0;
- glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxVertexAttribs);
- for (int i = 0; attr[i]; ++i) {
- if (i >= maxVertexAttribs) {
- qFatal("List of attribute names is either too long or not null-terminated.\n"
- "Maximum number of attributes on this hardware is %i.\n"
- "Vertex shader:\n%s\n"
- "Fragment shader:\n%s\n",
- maxVertexAttribs, vertexShader(), fragmentShader());
- }
- if (*attr[i])
- program()->bindAttributeLocation(attr[i], i);
- }
-#else
- for (int i = 0; attr[i]; ++i) {
- if (*attr[i])
- program()->bindAttributeLocation(attr[i], i);
- }
-#endif
-
- if (!program()->link()) {
- qWarning("QSGMaterialShader: Shader compilation failed:");
- qWarning() << program()->log();
- }
-}
-
-
-
-/*!
- \class QSGMaterialShader::RenderState
- \brief The QSGMaterialShader::RenderState encapsulates the current rendering state
- during a call to QSGMaterialShader::updateState().
-
- The render state contains a number of accessors that the shader needs to respect
- in order to conform to the current state of the scene graph.
-
- The instance is only valid inside a call to QSGMaterialShader::updateState() and
- should not be used outisde this function.
- */
-
-
-
-/*!
- \enum QSGMaterialShader::RenderState::DirtyState
-
- \value DirtyMatrix Used to indicate that the matrix has changed and must be updated.
-
- \value DirtyOpacity Used to indicate that the opacity has changed and must be updated.
- */
-
-
-
-/*!
- \fn bool QSGMaterialShader::RenderState::isMatrixDirty() const
-
- Convenience function to check if the dirtyStates() indicates that the matrix
- needs to be updated.
- */
-
-
-
-/*!
- \fn bool QSGMaterialShader::RenderState::isOpacityDirty() const
-
- Conveience function to check if the dirtyStates() indicates that the opacity
- needs to be updated.
- */
-
-
-
-/*!
- \fn QSGMaterialShader::RenderState::DirtyStates QSGMaterialShader::RenderState::dirtyStates() const
-
- Returns which rendering states that have changed and needs to be updated
- for geometry rendered with this material to conform to the current
- rendering state.
- */
-
-
-
-/*!
- Returns the accumulated opacity to be used for rendering
- */
-
-float QSGMaterialShader::RenderState::opacity() const
-{
- Q_ASSERT(m_data);
- return static_cast<const QSGRenderer *>(m_data)->currentOpacity();
-}
-
-
-
-/*!
- Returns the matrix combined of modelview matrix and project matrix.
- */
-
-QMatrix4x4 QSGMaterialShader::RenderState::combinedMatrix() const
-{
- Q_ASSERT(m_data);
- return static_cast<const QSGRenderer *>(m_data)->currentCombinedMatrix();
-}
-
-
-
-/*!
- Returns the model view matrix.
- */
-
-QMatrix4x4 QSGMaterialShader::RenderState::modelViewMatrix() const
-{
- Q_ASSERT(m_data);
- return static_cast<const QSGRenderer *>(m_data)->currentModelViewMatrix();
-}
-
-
-
-/*!
- Returns the viewport rect of the surface being rendered to.
- */
-
-QRect QSGMaterialShader::RenderState::viewportRect() const
-{
- Q_ASSERT(m_data);
- return static_cast<const QSGRenderer *>(m_data)->viewportRect();
-}
-
-
-
-/*!
- Returns the device rect of the surface being rendered to
- */
-
-QRect QSGMaterialShader::RenderState::deviceRect() const
-{
- Q_ASSERT(m_data);
- return static_cast<const QSGRenderer *>(m_data)->deviceRect();
-}
-
-
-
-/*!
- Returns the QOpenGLContext that is being used for rendering
- */
-
-QOpenGLContext *QSGMaterialShader::RenderState::context() const
-{
- return static_cast<const QSGRenderer *>(m_data)->glContext();
-}
-
-
-#ifndef QT_NO_DEBUG
-static int qt_material_count = 0;
-
-static void qt_print_material_count()
-{
- qDebug("Number of leaked materials: %i", qt_material_count);
- qt_material_count = -1;
-}
-#endif
-
-/*!
- \class QSGMaterialType
- \brief The QSGMaterialType class is used as a unique type token in combination with QSGMaterial.
-
- It serves no purpose outside the QSGMaterial::type() function.
- */
-
-/*!
- \class QSGMaterial
- \brief The QSGMaterial class encapsulates rendering state for a shader program.
-
- The QSGMaterial and QSGMaterialShader subclasses form a tight relationship. For
- one scene graph (including nested graphs), there is one unique QSGMaterialShader
- instance which encapsulates the QOpenGLShaderProgram the scene graph uses
- to render that material, such as a shader to flat coloring of geometry.
- Each QSGGeometryNode can have a unique QSGMaterial containing the
- how the shader should be configured when drawing that node, such as
- the actual color to used to render the geometry.
-
- The QSGMaterial has two virtual functions that both need to be implemented.
- The function type() should return a unique instance for all instances of a
- specific subclass. The createShader() function should return a new instance
- of QSGMaterialShader, specific to the subclass of QSGMaterial.
-
- A minimal QSGMaterial implementation could look like this:
- \code
- class Material : public QSGMaterial
- {
- public:
- QSGMaterialType *type() const { static QSGMaterialType type; return &type; }
- QSGMaterialShader *createShader() const { return new Shader; }
- };
- \endcode
-
- \warning Instances of QSGMaterial belongs to the Scene Graph rendering thread,
- and cannot be used from the GUI thread.
- */
-
-QSGMaterial::QSGMaterial()
- : m_flags(0)
-{
-#ifndef QT_NO_DEBUG
- ++qt_material_count;
- static bool atexit_registered = false;
- if (!atexit_registered) {
- atexit(qt_print_material_count);
- atexit_registered = true;
- }
-#endif
-}
-
-QSGMaterial::~QSGMaterial()
-{
-#ifndef QT_NO_DEBUG
- --qt_material_count;
- if (qt_material_count < 0)
- qDebug("Material destroyed after qt_print_material_count() was called.");
-#endif
-}
-
-
-
-/*!
- \enum QSGMaterial::Flag
-
- \value Blending Set this flag to true if the material requires GL_BLEND to be
- enabled during rendering.
- */
-
-
-
-/*!
- Sets the flags \a flags on this material if \a on is true;
- otherwise clears the attribute.
-*/
-
-void QSGMaterial::setFlag(Flags flags, bool on)
-{
- if (on)
- m_flags |= flags;
- else
- m_flags &= ~flags;
-}
-
-
-
-/*!
- Compares this material to \a other and returns 0 if they are equal; -1 if
- this material should sort before \a other and 1 if \a other should sort
- before.
-
- The scene graph can reorder geometry nodes to minimize state changes.
- The compare function is called during the sorting process so that
- the materials can be sorted to minimize state changes in each
- call to QSGMaterialShader::updateState().
-
- The this pointer and \a other is guaranteed to have the same type().
- */
-
-int QSGMaterial::compare(const QSGMaterial *other) const
-{
- Q_ASSERT(other && type() == other->type());
- return qint64(this) - qint64(other);
-}
-
-
-
-/*!
- \fn QSGMaterialType QSGMaterial::type() const
-
- This function is called by the scene graph to return a unique instance
- per subclass.
- */
-
-
-
-/*!
- \fn QSGMaterialShader *QSGMaterial::createShader() const
-
- This function returns a new instance of a the QSGMaterialShader
- implementatation used to render geometry for a specifc implementation
- of QSGMaterial.
-
- The function will be called only once for each material type that
- exists in the scene graph and will be cached internally.
-*/
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/coreapi/qsgmaterial.h b/src/declarative/scenegraph/coreapi/qsgmaterial.h
deleted file mode 100644
index 084219bfba..0000000000
--- a/src/declarative/scenegraph/coreapi/qsgmaterial.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MATERIAL_H
-#define MATERIAL_H
-
-#include <qopenglshaderprogram.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGMaterial;
-
-class Q_DECLARATIVE_EXPORT QSGMaterialShader
-{
-public:
- class Q_DECLARATIVE_EXPORT RenderState {
- public:
- enum DirtyState
- {
- DirtyMatrix = 0x0001,
- DirtyOpacity = 0x0002
- };
- Q_DECLARE_FLAGS(DirtyStates, DirtyState)
-
- inline DirtyStates dirtyStates() const { return m_dirty; }
-
- inline bool isMatrixDirty() const { return m_dirty & DirtyMatrix; }
- inline bool isOpacityDirty() const { return m_dirty & DirtyOpacity; }
-
- float opacity() const;
- QMatrix4x4 combinedMatrix() const;
- QMatrix4x4 modelViewMatrix() const;
- QRect viewportRect() const;
- QRect deviceRect() const;
-
- QOpenGLContext *context() const;
-
- private:
- friend class QSGRenderer;
- DirtyStates m_dirty;
- const void *m_data;
- };
-
- QSGMaterialShader();
-
- virtual void activate();
- virtual void deactivate();
- // First time a material is used, oldMaterial is null.
- virtual void updateState(const RenderState &state, QSGMaterial *newMaterial, QSGMaterial *oldMaterial);
- virtual char const *const *attributeNames() const = 0; // Array must end with null.
-
- inline QOpenGLShaderProgram *program() { return &m_program; }
-
-protected:
-
- friend class QSGContext;
-
- virtual void compile();
- virtual void initialize() { }
-
- virtual const char *vertexShader() const = 0;
- virtual const char *fragmentShader() const = 0;
-
-private:
- QOpenGLShaderProgram m_program;
- void *m_reserved;
-};
-
-struct QSGMaterialType { };
-
-class Q_DECLARATIVE_EXPORT QSGMaterial
-{
-public:
- enum Flag {
- Blending = 0x0001
- };
- Q_DECLARE_FLAGS(Flags, Flag)
-
- QSGMaterial();
- virtual ~QSGMaterial();
-
- virtual QSGMaterialType *type() const = 0;
- virtual QSGMaterialShader *createShader() const = 0;
- virtual int compare(const QSGMaterial *other) const;
-
- QSGMaterial::Flags flags() const { return m_flags; }
- void setFlag(Flags flags, bool on = true);
-
-private:
- Flags m_flags;
- void *m_reserved;
- Q_DISABLE_COPY(QSGMaterial)
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QSGMaterial::Flags)
-Q_DECLARE_OPERATORS_FOR_FLAGS(QSGMaterialShader::RenderState::DirtyStates)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/scenegraph/coreapi/qsgnode.cpp b/src/declarative/scenegraph/coreapi/qsgnode.cpp
deleted file mode 100644
index 764071c190..0000000000
--- a/src/declarative/scenegraph/coreapi/qsgnode.cpp
+++ /dev/null
@@ -1,1264 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgnode.h"
-#include "qsgrenderer_p.h"
-#include "qsgnodeupdater_p.h"
-#include "qsgmaterial.h"
-
-#include "limits.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_DEBUG
-static int qt_node_count = 0;
-
-static void qt_print_node_count()
-{
- qDebug("Number of leaked nodes: %i", qt_node_count);
- qt_node_count = -1;
-}
-#endif
-
-/*!
- \class QSGNode
- \brief The QSGNode class is the base class for all nodes in the scene graph.
-
- \inmodule QtDeclarative
-
- The QSGNode class can be used as a child container. Children are added with
- the appendChildNode(), prependChildNode(), insertChildNodeBefore() and
- insertChildNodeAfter(). Ordering of nodes is important as geometry nodes
- will be rendered in the order they are added to the scene graph.
- Actually, the scene may reorder nodes freely, but the resulting visual
- order is still guaranteed.
-
- If nodes change every frame, the preprocess() function can be used to
- apply changes to a node for every frame its rendered. The use of preprocess()
- must be explicitly enabled by setting the QSGNode::UsePreprocess flag
- on the node.
-
- The virtual isSubtreeBlocked() function can be used to disable a subtree all
- together. Nodes in a blocked subtree will not be preprocessed() and not
- rendered.
-
- Anything related to QSGNode should happen on the scene graph rendering thread.
- */
-
-QSGNode::QSGNode()
- : m_parent(0)
- , m_type(BasicNodeType)
- , m_firstChild(0)
- , m_lastChild(0)
- , m_nextSibling(0)
- , m_previousSibling(0)
- , m_subtreeGeometryCount(0)
- , m_nodeFlags(OwnedByParent)
- , m_flags(0)
-{
- init();
-}
-
-QSGNode::QSGNode(NodeType type)
- : m_parent(0)
- , m_type(type)
- , m_firstChild(0)
- , m_lastChild(0)
- , m_nextSibling(0)
- , m_previousSibling(0)
- , m_subtreeGeometryCount(type == GeometryNodeType ? 1 : 0)
- , m_nodeFlags(OwnedByParent)
- , m_flags(0)
-{
- init();
-}
-
-void QSGNode::init()
-{
-#ifndef QT_NO_DEBUG
- ++qt_node_count;
- static bool atexit_registered = false;
- if (!atexit_registered) {
- atexit(qt_print_node_count);
- atexit_registered = true;
- }
-#endif
-}
-
-QSGNode::~QSGNode()
-{
-#ifndef QT_NO_DEBUG
- --qt_node_count;
- if (qt_node_count < 0)
- qDebug("Node destroyed after qt_print_node_count() was called.");
-#endif
- destroy();
-}
-
-
-/*!
- \fn void QSGNode::preprocess()
-
- Override this function to do processing on the node before it is rendered.
-
- Preprocessing needs to be explicitly enabled by setting the flag
- QSGNode::UsePreprocess. The flag needs to be set before the node is added
- to the scene graph and will cause the preprocess() function to be called
- for every frame the node is rendered.
-
- The preprocess function is called before the update pass that propegates
- opacity and transformations through the scene graph. That means that
- functions like QSGOpacityNode::combinedOpacity() and
- QSGTransformNode::combinedMatrix() will not contain up-to-date values.
- If such values are changed during the preprocess, these changes will be
- propegated through the scene graph before it is rendered.
-
- \warning Beware of deleting nodes while they are being preprocessed. It is
- possible, with a small performance hit, to delete a single node during its
- own preprocess call. Deleting a subtree which has nodes that also use
- preprocessing may result in a segmentation fault. This is done for
- performance reasons.
- */
-
-
-
-
-/*!
- Returns whether this node and its subtree is available for use.
-
- Blocked subtrees will not get their dirty states updated and they
- will not be rendered.
-
- The QSGOpacityNode will return a blocked subtree when accumulated opacity
- is 0, for instance.
- */
-
-bool QSGNode::isSubtreeBlocked() const
-{
- return m_subtreeGeometryCount == 0;
-}
-
-/*!
- \internal
- Detaches the node from the scene graph and deletes any children it owns.
-
- This function is called from QSGNode's and QSGRootNode's destructor. It
- should not be called explicitly in user code. QSGRootNode needs to call
- destroy() because destroy() calls removeChildNode() which in turn calls
- markDirty() which type-casts the node to QSGRootNode. This type-cast is not
- valid at the time QSGNode's destructor is called because the node will
- already be partially destroyed at that point.
-*/
-
-void QSGNode::destroy()
-{
- if (m_parent) {
- m_parent->removeChildNode(this);
- Q_ASSERT(m_parent == 0);
- }
- while (m_firstChild) {
- QSGNode *child = m_firstChild;
- removeChildNode(child);
- Q_ASSERT(child->m_parent == 0);
- if (child->flags() & OwnedByParent)
- delete child;
- }
-
- Q_ASSERT(m_firstChild == 0 && m_lastChild == 0);
-}
-
-
-/*!
- Prepends \a node to this node's the list of children.
-
- Ordering of nodes is important as geometry nodes will be rendered in the
- order they are added to the scene graph.
- */
-
-void QSGNode::prependChildNode(QSGNode *node)
-{
- //Q_ASSERT_X(!m_children.contains(node), "QSGNode::prependChildNode", "QSGNode is already a child!");
- Q_ASSERT_X(!node->m_parent, "QSGNode::prependChildNode", "QSGNode already has a parent");
-
-#ifndef QT_NO_DEBUG
- if (node->type() == QSGNode::GeometryNodeType) {
- QSGGeometryNode *g = static_cast<QSGGeometryNode *>(node);
- Q_ASSERT_X(g->material(), "QSGNode::prependChildNode", "QSGGeometryNode is missing material");
- Q_ASSERT_X(g->geometry(), "QSGNode::prependChildNode", "QSGGeometryNode is missing geometry");
- }
-#endif
-
- if (m_firstChild)
- m_firstChild->m_previousSibling = node;
- else
- m_lastChild = node;
- node->m_nextSibling = m_firstChild;
- m_firstChild = node;
- node->m_parent = this;
-
- node->markDirty(DirtyNodeAdded);
-}
-
-/*!
- Appends \a node to this node's list of children.
-
- Ordering of nodes is important as geometry nodes will be rendered in the
- order they are added to the scene graph.
- */
-
-void QSGNode::appendChildNode(QSGNode *node)
-{
- //Q_ASSERT_X(!m_children.contains(node), "QSGNode::appendChildNode", "QSGNode is already a child!");
- Q_ASSERT_X(!node->m_parent, "QSGNode::appendChildNode", "QSGNode already has a parent");
-
-#ifndef QT_NO_DEBUG
- if (node->type() == QSGNode::GeometryNodeType) {
- QSGGeometryNode *g = static_cast<QSGGeometryNode *>(node);
- Q_ASSERT_X(g->material(), "QSGNode::appendChildNode", "QSGGeometryNode is missing material");
- Q_ASSERT_X(g->geometry(), "QSGNode::appendChildNode", "QSGGeometryNode is missing geometry");
- }
-#endif
-
- if (m_lastChild)
- m_lastChild->m_nextSibling = node;
- else
- m_firstChild = node;
- node->m_previousSibling = m_lastChild;
- m_lastChild = node;
- node->m_parent = this;
-
- node->markDirty(DirtyNodeAdded);
-}
-
-
-
-/*!
- Inserts \a node to this node's list of children before the node specified with \a before.
-
- Ordering of nodes is important as geometry nodes will be rendered in the
- order they are added to the scene graph.
- */
-
-void QSGNode::insertChildNodeBefore(QSGNode *node, QSGNode *before)
-{
- //Q_ASSERT_X(!m_children.contains(node), "QSGNode::insertChildNodeBefore", "QSGNode is already a child!");
- Q_ASSERT_X(!node->m_parent, "QSGNode::insertChildNodeBefore", "QSGNode already has a parent");
- Q_ASSERT_X(before && before->m_parent == this, "QSGNode::insertChildNodeBefore", "The parent of \'before\' is wrong");
-
-#ifndef QT_NO_DEBUG
- if (node->type() == QSGNode::GeometryNodeType) {
- QSGGeometryNode *g = static_cast<QSGGeometryNode *>(node);
- Q_ASSERT_X(g->material(), "QSGNode::insertChildNodeBefore", "QSGGeometryNode is missing material");
- Q_ASSERT_X(g->geometry(), "QSGNode::insertChildNodeBefore", "QSGGeometryNode is missing geometry");
- }
-#endif
-
- QSGNode *previous = before->m_previousSibling;
- if (previous)
- previous->m_nextSibling = node;
- else
- m_firstChild = node;
- node->m_previousSibling = previous;
- node->m_nextSibling = before;
- before->m_previousSibling = node;
- node->m_parent = this;
-
- node->markDirty(DirtyNodeAdded);
-}
-
-
-
-/*!
- Inserts \a node to this node's list of children after the node specified with \a after.
-
- Ordering of nodes is important as geometry nodes will be rendered in the
- order they are added to the scene graph.
- */
-
-void QSGNode::insertChildNodeAfter(QSGNode *node, QSGNode *after)
-{
- //Q_ASSERT_X(!m_children.contains(node), "QSGNode::insertChildNodeAfter", "QSGNode is already a child!");
- Q_ASSERT_X(!node->m_parent, "QSGNode::insertChildNodeAfter", "QSGNode already has a parent");
- Q_ASSERT_X(after && after->m_parent == this, "QSGNode::insertChildNodeBefore", "The parent of \'before\' is wrong");
-
-#ifndef QT_NO_DEBUG
- if (node->type() == QSGNode::GeometryNodeType) {
- QSGGeometryNode *g = static_cast<QSGGeometryNode *>(node);
- Q_ASSERT_X(g->material(), "QSGNode::insertChildNodeAfter", "QSGGeometryNode is missing material");
- Q_ASSERT_X(g->geometry(), "QSGNode::insertChildNodeAfter", "QSGGeometryNode is missing geometry");
- }
-#endif
-
- QSGNode *next = after->m_nextSibling;
- if (next)
- next->m_previousSibling = node;
- else
- m_lastChild = node;
- node->m_nextSibling = next;
- node->m_previousSibling = after;
- after->m_nextSibling = node;
- node->m_parent = this;
-
- node->markDirty(DirtyNodeAdded);
-}
-
-
-
-/*!
- Removes \a node from this node's list of children.
- */
-
-void QSGNode::removeChildNode(QSGNode *node)
-{
- //Q_ASSERT(m_children.contains(node));
- Q_ASSERT(node->parent() == this);
-
- QSGNode *previous = node->m_previousSibling;
- QSGNode *next = node->m_nextSibling;
- if (previous)
- previous->m_nextSibling = next;
- else
- m_firstChild = next;
- if (next)
- next->m_previousSibling = previous;
- else
- m_lastChild = previous;
- node->m_previousSibling = 0;
- node->m_nextSibling = 0;
-
- node->markDirty(DirtyNodeRemoved);
- node->m_parent = 0;
-}
-
-
-/*!
- Removes all child nodes from this node's list of children.
- */
-
-void QSGNode::removeAllChildNodes()
-{
- while (m_firstChild) {
- QSGNode *node = m_firstChild;
- m_firstChild = node->m_nextSibling;
- node->m_nextSibling = 0;
- if (m_firstChild)
- m_firstChild->m_previousSibling = 0;
- else
- m_lastChild = 0;
- node->markDirty(DirtyNodeRemoved);
- node->m_parent = 0;
- }
-}
-
-
-int QSGNode::childCount() const
-{
- int count = 0;
- QSGNode *n = m_firstChild;
- while (n) {
- ++count;
- n = n->m_nextSibling;
- }
- return count;
-}
-
-
-QSGNode *QSGNode::childAtIndex(int i) const
-{
- QSGNode *n = m_firstChild;
- while (i && n) {
- --i;
- n = n->m_nextSibling;
- }
- return n;
-}
-
-
-/*!
- Sets the flag \a f on this node if \a enabled is true;
- otherwise clears the flag.
-
- \sa flags()
-*/
-
-void QSGNode::setFlag(Flag f, bool enabled)
-{
- if (enabled)
- m_nodeFlags |= f;
- else
- m_nodeFlags &= ~f;
-}
-
-
-/*!
- Sets the flags \a f on this node if \a enabled is true;
- otherwise clears the flags.
-
- \sa flags()
-*/
-
-void QSGNode::setFlags(Flags f, bool enabled)
-{
- if (enabled)
- m_nodeFlags |= f;
- else
- m_nodeFlags &= ~f;
-}
-
-
-
-/*!
- Marks this node with the states in \a flags as dirty.
-
- When a node is marked dirty, it recursively mark the parent chain
- as dirty and notify all connected renderers that the has dirty states.
- */
-
-void QSGNode::markDirty(DirtyFlags flags)
-{
- m_flags |= (flags & DirtyPropagationMask);
-
- DirtyFlags subtreeFlags = DirtyFlags((flags & DirtyPropagationMask) << 16);
-
- int geometryCountDiff = 0;
- if (flags & DirtyNodeAdded)
- geometryCountDiff += m_subtreeGeometryCount;
- if (flags & DirtyNodeRemoved)
- geometryCountDiff -= m_subtreeGeometryCount;
-
- QSGNode *p = m_parent;
- while (p) {
- p->m_flags |= subtreeFlags;
- p->m_subtreeGeometryCount += geometryCountDiff;
- if (p->type() == RootNodeType)
- static_cast<QSGRootNode *>(p)->notifyNodeChange(this, flags);
- p = p->m_parent;
- }
-}
-
-
-
-/*!
- \class QSGBasicGeometryNode
- \brief The QSGBasicGeometryNode class serves as a baseclass for geometry based nodes
-
- \inmodule QtDeclarative
-
- The QSGBasicGeometryNode class should not be used by itself. It is only encapsulates
- shared functionality between the QSGGeometryNode and QSGClipNode classes.
- */
-
-
-/*!
- Creates a new basic geometry node.
- */
-QSGBasicGeometryNode::QSGBasicGeometryNode(NodeType type)
- : QSGNode(type)
- , m_geometry(0)
- , m_matrix(0)
- , m_clip_list(0)
-{
-}
-
-
-/*!
- Deletes this QSGBasicGeometryNode.
-
- If the node has the flag QSGNode::OwnsGeometry set, it will also delete the
- geometry object it is pointing to. This flag is not set by default.
- */
-
-QSGBasicGeometryNode::~QSGBasicGeometryNode()
-{
- if (flags() & OwnsGeometry)
- delete m_geometry;
-}
-
-
-/*!
- \fn QSGGeometry *QSGBasicGeometryNode::geometry() const
-
- Returns this node's geometry.
-
- The geometry is null by default.
- */
-
-
-/*!
- Sets the geometry of this node to \a geometry.
-
- If the node has the flag QSGNode::OwnsGeometry set, it will also delete the
- geometry object it is pointing to. This flag is not set by default.
- */
-
-void QSGBasicGeometryNode::setGeometry(QSGGeometry *geometry)
-{
- if (flags() & OwnsGeometry)
- delete m_geometry;
- m_geometry = geometry;
- markDirty(DirtyGeometry);
-}
-
-
-
-/*!
- \class QSGGeometryNode
- \brief The QSGGeometryNode class is used for all rendered content in the scene graph.
-
- \inmodule QtDeclarative
-
- The QSGGeometryNode consists of geometry and material. The geometry defines the mesh,
- the vertices and their structure, to be drawn. The Material defines how the shape is
- filled.
-
- A geometry node must have both geometry and a normal material before it is added to
- the scene graph.
-
- The geometry node supports two types of materials, the opaqueMaterial and the normal
- material. The opaqueMaterial is used when the accumulated scene graph opacity at the
- time of rendering is 1. The primary usecase is to special case opaque rendering
- to avoid an extra operation in the fragment shader can have significant performance
- impact on embedded graphics chips. The opaque material is optional.
-
- */
-
-
-/*!
- Creates a new geometry node without geometry and material.
- */
-
-QSGGeometryNode::QSGGeometryNode()
- : QSGBasicGeometryNode(GeometryNodeType)
- , m_render_order(0)
- , m_material(0)
- , m_opaque_material(0)
- , m_opacity(1)
-{
-}
-
-
-/*!
- Deletes this geometry node.
-
- The flags QSGNode::OwnsMaterial, QSGNode::OwnsOpaqueMaterial and
- QSGNode::OwnsGeometry decides weither the geometry node should also
- delete the materials and geometry. By default, these flags are disabled.
- */
-
-QSGGeometryNode::~QSGGeometryNode()
-{
- if (flags() & OwnsMaterial)
- delete m_material;
- if (flags() & OwnsOpaqueMaterial)
- delete m_opaque_material;
-}
-
-
-
-/*!
- \fn int QSGGeometryNode::renderOrder() const
-
- Returns the render order of this geometry node.
-
- \internal
- */
-
-
-/*!
- Sets the render order of this node to be \a order.
-
- GeometryNodes are rendered in an order that visually looks like
- low order nodes are rendered prior to high order nodes. For opaque
- geometry there is little difference as z-testing will handle
- the discard, but for translucent objects, the rendering should
- normally be specified in the order of back-to-front.
-
- The default render order is 0.
-
- \internal
- */
-void QSGGeometryNode::setRenderOrder(int order)
-{
- m_render_order = order;
-}
-
-
-
-/*!
- Sets the material of this geometry node to \a material.
-
- Geometry nodes must have a material before they can be added to the
- scene graph.
- */
-void QSGGeometryNode::setMaterial(QSGMaterial *material)
-{
- if (flags() & OwnsMaterial)
- delete m_material;
- m_material = material;
-#ifndef QT_NO_DEBUG
- if (m_material != 0 && m_opaque_material == m_material)
- qWarning("QSGGeometryNode: using same material for both opaque and translucent");
-#endif
- markDirty(DirtyMaterial);
-}
-
-
-
-/*!
- Sets the opaque material of this geometry to \a material.
-
- The opaque material will be preferred by the renderer over the
- default material, as returned by the material() function, if
- it is not null and the geometry item has an inherited opacity of
- 1.
-
- The opaqueness refers to scene graph opacity, the material is still
- allowed to set QSGMaterial::Blending to true and draw transparent
- pixels.
- */
-void QSGGeometryNode::setOpaqueMaterial(QSGMaterial *material)
-{
- if (flags() & OwnsOpaqueMaterial)
- delete m_opaque_material;
- m_opaque_material = material;
-#ifndef QT_NO_DEBUG
- if (m_opaque_material != 0 && m_opaque_material == m_material)
- qWarning("QSGGeometryNode: using same material for both opaque and translucent");
-#endif
-
- markDirty(DirtyMaterial);
-}
-
-
-
-/*!
- Returns the material which should currently be used for geometry node.
-
- If the inherited opacity of the node is 1 and there is an opaque material
- set on this node, it will be returned; otherwise, the default material
- will be returned.
-
- \warning This function requires the scene graph above this item to be
- completely free of dirty states, so it can only be called during rendering
-
- \internal
-
- \sa setMaterial, setOpaqueMaterial
- */
-QSGMaterial *QSGGeometryNode::activeMaterial() const
-{
- Q_ASSERT_X(dirtyFlags() == 0, "QSGGeometryNode::activeMaterial()", "function assumes that all dirty states are cleaned up");
- if (m_opaque_material && m_opacity > 0.999)
- return m_opaque_material;
- return m_material;
-}
-
-
-/*!
- Sets the inherited opacity of this geometry to \a opacity.
-
- This function is meant to be called by the node preprocessing
- prior to rendering the tree, so it will not mark the tree as
- dirty.
-
- \internal
- */
-void QSGGeometryNode::setInheritedOpacity(qreal opacity)
-{
- Q_ASSERT(opacity >= 0 && opacity <= 1);
- m_opacity = opacity;
-}
-
-
-/*!
- \class QSGClipNode
- \brief The QSGClipNode class implements the clipping functionality in the scene graph.
-
- \inmodule QtDeclarative
-
- Clipping applies to the node's subtree and can be nested. Multiple clip nodes will be
- accumulated by intersecting all their geometries. The accumulation happens
- as part of the rendering.
-
- Clip nodes must have a geometry before they can be added to the scene graph.
-
- Clipping is usually implemented by using the stencil buffer.
- */
-
-
-
-/*!
- Creates a new QSGClipNode without a geometry.
-
- The clip node must have a geometry before it can be added to the
- scene graph.
- */
-
-QSGClipNode::QSGClipNode()
- : QSGBasicGeometryNode(ClipNodeType)
-{
-}
-
-
-
-/*!
- Deletes this QSGClipNode.
-
- If the flag QSGNode::OwnsGeometry is set, the geometry will also be
- deleted.
- */
-
-QSGClipNode::~QSGClipNode()
-{
-}
-
-
-
-/*!
- \fn bool QSGClipNode::isRectangular() const
-
- Returns if this clip node has a rectangular clip.
- */
-
-
-
-/*!
- Sets whether this clip node has a rectangular clip to \a rectHint.
-
- This is an optimization hint which means that the renderer can
- use scissoring instead of stencil, which is significnatly faster.
-
- When this hint is and it is applicable, the clip region will be
- generated from clipRect() rather than geometry().
- */
-
-void QSGClipNode::setIsRectangular(bool rectHint)
-{
- m_is_rectangular = rectHint;
-}
-
-
-
-/*!
- \fn void QSGClipNode::clipRect() const
-
- Returns the clip rect of this node.
- */
-
-
-/*!
- Sets the clip rect of this clip node to \a rect.
-
- When a rectangular clip is set in combination with setIsRectangular
- the renderer may in some cases use a more optimal clip method.
- */
-void QSGClipNode::setClipRect(const QRectF &rect)
-{
- m_clip_rect = rect;
-}
-
-
-/*!
- \class QSGTransformNode
- \brief The QSGTransformNode class implements transformations in the scene graph
-
- \inmodule QtDeclarative
-
- Transformations apply the node's subtree and can be nested. Multiple transform nodes
- will be accumulated by intersecting all their matrices. The accumulation happens
- as part of the rendering.
-
- The transform nodes implement a 4x4 matrix which in theory supports full 3D
- transformations. However, because the renderer optimizes for 2D use-cases rather
- than 3D use-cases, rendering a scene with full 3D transformations needs to
- be done with some care.
- */
-
-QSGTransformNode::QSGTransformNode()
- : QSGNode(TransformNodeType)
-{
-}
-
-
-
-/*!
- Deletes this transform node.
- */
-
-QSGTransformNode::~QSGTransformNode()
-{
-}
-
-
-
-/*!
- \fn QMatrix4x4 QSGTransformNode::matrix() const
-
- Returns this transform node's matrix.
- */
-
-
-
-/*!
- Sets this transform node's matrix to \a matrix.
- */
-
-void QSGTransformNode::setMatrix(const QMatrix4x4 &matrix)
-{
- m_matrix = matrix;
- markDirty(DirtyMatrix);
-}
-
-
-/*!
- Sets the combined matrix of this matrix to \a transform.
-
- This function is meant to be called by the node preprocessing
- prior to rendering the tree, so it will not mark the tree as
- dirty.
-
- \internal
- */
-void QSGTransformNode::setCombinedMatrix(const QMatrix4x4 &matrix)
-{
- m_combined_matrix = matrix;
-}
-
-
-
-/*!
- \class QSGRootNode
- \brief The QSGRootNode is the toplevel root of any scene graph.
-
- The root node is used to attach a scene graph to a renderer.
-
- \internal
- */
-
-
-
-/*!
- \fn QSGRootNode::QSGRootNode()
-
- Creates a new root node.
- */
-
-QSGRootNode::QSGRootNode()
- : QSGNode(RootNodeType)
-{
-}
-
-
-/*!
- Deletes the root node.
-
- When a root node is deleted it removes itself from all of renderers
- that are referencing it.
- */
-
-QSGRootNode::~QSGRootNode()
-{
- while (!m_renderers.isEmpty())
- m_renderers.last()->setRootNode(0);
- destroy(); // Must call destroy() here because markDirty() casts this to QSGRootNode.
-}
-
-
-
-/*!
- Called to notify all renderers that \a node has been marked as dirty
- with \a flags.
- */
-
-void QSGRootNode::notifyNodeChange(QSGNode *node, DirtyFlags flags)
-{
- for (int i=0; i<m_renderers.size(); ++i) {
- m_renderers.at(i)->nodeChanged(node, flags);
- }
-}
-
-
-
-/*!
- \class QSGOpacityNode
- \brief The QSGOpacityNode class is used to change opacity of nodes.
-
- \inmodule QtDeclarative
-
- Opacity applies to its subtree and can be nested. Multiple opacity nodes
- will be accumulated by multiplying their opacity. The accumulation happens
- as part of the rendering.
-
- When nested opacity gets below a certain threshold, the subtree might
- be marked as blocked, causing isSubtreeBlocked() to return true. This
- is done for performance reasons.
-
- */
-
-
-
-/*!
- Constructs an opacity node with a default opacity of 1.
-
- Opacity accumulates downwards in the scene graph so a node with two
- QSGOpacityNode instances above it, both with opacity of 0.5, will have
- effective opacity of 0.25.
-
- The default opacity of nodes is 1.
- */
-QSGOpacityNode::QSGOpacityNode()
- : QSGNode(OpacityNodeType)
- , m_opacity(1)
- , m_combined_opacity(1)
-{
-}
-
-
-
-/*!
- Deletes the opacity node.
- */
-
-QSGOpacityNode::~QSGOpacityNode()
-{
-}
-
-
-
-/*!
- \fn qreal QSGOpacityNode::opacity() const
-
- Returns this opacity node's opacity.
- */
-
-
-
-/*!
- Sets the opacity of this node to \a opacity.
-
- Before rendering the graph, the renderer will do an update pass
- over the subtree to propegate the opacity to its children.
-
- The value will be bounded to the range 0 to 1.
- */
-
-void QSGOpacityNode::setOpacity(qreal opacity)
-{
- opacity = qBound<qreal>(0, opacity, 1);
- if (m_opacity == opacity)
- return;
- m_opacity = opacity;
- markDirty(DirtyOpacity);
-}
-
-
-
-/*!
- \fn qreal QSGOpacityNode::combinedOpacity() const
-
- Returns this node's accumulated opacity.
-
- This vaule is calculated during rendering and only stored
- in the opacity node temporarily.
-
- \internal
- */
-
-
-
-/*!
- Sets the combined opacity of this node to \a opacity.
-
- This function is meant to be called by the node preprocessing
- prior to rendering the tree, so it will not mark the tree as
- dirty.
-
- \internal
- */
-
-void QSGOpacityNode::setCombinedOpacity(qreal opacity)
-{
- m_combined_opacity = opacity;
-}
-
-
-
-/*!
- For performance reasons, we block the subtree when the opacity
- is below a certain threshold.
-
- \internal
- */
-
-bool QSGOpacityNode::isSubtreeBlocked() const
-{
- return QSGNode::isSubtreeBlocked() || m_opacity < 0.001;
-}
-
-
-/*!
- \class QSGNodeVisitor
- \brief The QSGNodeVisitor class is a helper class for traversing the scene graph.
-
- \internal
- */
-
-QSGNodeVisitor::~QSGNodeVisitor()
-{
-
-}
-
-
-void QSGNodeVisitor::visitNode(QSGNode *n)
-{
- switch (n->type()) {
- case QSGNode::TransformNodeType: {
- QSGTransformNode *t = static_cast<QSGTransformNode *>(n);
- enterTransformNode(t);
- visitChildren(t);
- leaveTransformNode(t);
- break; }
- case QSGNode::GeometryNodeType: {
- QSGGeometryNode *g = static_cast<QSGGeometryNode *>(n);
- enterGeometryNode(g);
- visitChildren(g);
- leaveGeometryNode(g);
- break; }
- case QSGNode::ClipNodeType: {
- QSGClipNode *c = static_cast<QSGClipNode *>(n);
- enterClipNode(c);
- visitChildren(c);
- leaveClipNode(c);
- break; }
- case QSGNode::OpacityNodeType: {
- QSGOpacityNode *o = static_cast<QSGOpacityNode *>(n);
- enterOpacityNode(o);
- visitChildren(o);
- leaveOpacityNode(o);
- break; }
- default:
- visitChildren(n);
- break;
- }
-}
-
-void QSGNodeVisitor::visitChildren(QSGNode *n)
-{
- for (QSGNode *c = n->firstChild(); c; c = c->nextSibling())
- visitNode(c);
-}
-
-
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const QSGGeometryNode *n)
-{
- if (!n) {
- d << "QSGGeometryNode(null)";
- return d;
- }
- d << "QSGGeometryNode(" << hex << (void *) n << dec;
-
- const QSGGeometry *g = n->geometry();
-
- if (!g) {
- d << "no geometry";
- } else {
-
- switch (g->drawingMode()) {
- case GL_TRIANGLE_STRIP: d << "strip"; break;
- case GL_TRIANGLE_FAN: d << "fan"; break;
- case GL_TRIANGLES: d << "triangles"; break;
- default: break;
- }
-
- d << g->vertexCount();
-
- if (g->attributeCount() > 0 && g->attributes()->type == GL_FLOAT) {
- float x1 = 1e10, x2 = -1e10, y1=1e10, y2=-1e10;
- int stride = g->sizeOfVertex();
- for (int i = 0; i < g->vertexCount(); ++i) {
- float x = ((float *)((char *)const_cast<QSGGeometry *>(g)->vertexData() + i * stride))[0];
- float y = ((float *)((char *)const_cast<QSGGeometry *>(g)->vertexData() + i * stride))[1];
-
- x1 = qMin(x1, x);
- x2 = qMax(x2, x);
- y1 = qMin(y1, y);
- y2 = qMax(y2, y);
- }
-
- d << "x1=" << x1 << "y1=" << y1 << "x2=" << x2 << "y2=" << y2;
- }
- }
-
- d << "order=" << n->renderOrder();
- if (n->material())
- d << "effect=" << n->material() << "type=" << n->material()->type();
-
-
- d << ")";
-#ifdef QML_RUNTIME_TESTING
- d << n->description;
-#endif
- d << "dirty=" << hex << (int) n->dirtyFlags() << dec;
- return d;
-}
-
-QDebug operator<<(QDebug d, const QSGClipNode *n)
-{
- if (!n) {
- d << "QSGClipNode(null)";
- return d;
- }
- d << "QSGClipNode(" << hex << (void *) n << dec;
-
- if (n->childCount())
- d << "children=" << n->childCount();
-
- d << "is rect?" << (n->isRectangular() ? "yes" : "no");
-
- d << ")";
-#ifdef QML_RUNTIME_TESTING
- d << n->description;
-#endif
- d << "dirty=" << hex << (int) n->dirtyFlags() << dec << (n->isSubtreeBlocked() ? "*BLOCKED*" : "");
- return d;
-}
-
-QDebug operator<<(QDebug d, const QSGTransformNode *n)
-{
- if (!n) {
- d << "QSGTransformNode(null)";
- return d;
- }
- const QMatrix4x4 m = n->matrix();
- d << "QSGTransformNode(";
- d << hex << (void *) n << dec;
- if (m.isIdentity())
- d << "identity";
- else if (m.determinant() == 1 && m(0, 0) == 1 && m(1, 1) == 1 && m(2, 2) == 1)
- d << "translate" << m(0, 3) << m(1, 3) << m(2, 3);
- else
- d << "det=" << n->matrix().determinant();
-#ifdef QML_RUNTIME_TESTING
- d << n->description;
-#endif
- d << "dirty=" << hex << (int) n->dirtyFlags() << dec << (n->isSubtreeBlocked() ? "*BLOCKED*" : "");
- d << ")";
- return d;
-}
-
-QDebug operator<<(QDebug d, const QSGOpacityNode *n)
-{
- if (!n) {
- d << "QSGOpacityNode(null)";
- return d;
- }
- d << "QSGOpacityNode(";
- d << hex << (void *) n << dec;
- d << "opacity=" << n->opacity()
- << "combined=" << n->combinedOpacity()
- << (n->isSubtreeBlocked() ? "*BLOCKED*" : "");
-#ifdef QML_RUNTIME_TESTING
- d << n->description;
-#endif
- d << "dirty=" << hex << (int) n->dirtyFlags() << dec;
- d << ")";
- return d;
-}
-
-
-QDebug operator<<(QDebug d, const QSGRootNode *n)
-{
- if (!n) {
- d << "QSGRootNode(null)";
- return d;
- }
- d << "QSGRootNode" << hex << (void *) n << "dirty=" << (int) n->dirtyFlags() << dec
- << (n->isSubtreeBlocked() ? "*BLOCKED*" : "");
-#ifdef QML_RUNTIME_TESTING
- d << n->description;
-#endif
- d << ")";
- return d;
-}
-
-
-
-QDebug operator<<(QDebug d, const QSGNode *n)
-{
- if (!n) {
- d << "QSGNode(null)";
- return d;
- }
- switch (n->type()) {
- case QSGNode::GeometryNodeType:
- d << static_cast<const QSGGeometryNode *>(n);
- break;
- case QSGNode::TransformNodeType:
- d << static_cast<const QSGTransformNode *>(n);
- break;
- case QSGNode::ClipNodeType:
- d << static_cast<const QSGClipNode *>(n);
- break;
- case QSGNode::RootNodeType:
- d << static_cast<const QSGRootNode *>(n);
- break;
- case QSGNode::OpacityNodeType:
- d << static_cast<const QSGOpacityNode *>(n);
- break;
- default:
- d << "QSGNode(" << hex << (void *) n << dec
- << "dirty=" << hex << (int) n->dirtyFlags()
- << "flags=" << (int) n->flags() << dec
- << (n->isSubtreeBlocked() ? "*BLOCKED*" : "");
-#ifdef QML_RUNTIME_TESTING
- d << n->description;
-#endif
- d << ")";
- break;
- }
- return d;
-}
-
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/coreapi/qsgnode.h b/src/declarative/scenegraph/coreapi/qsgnode.h
deleted file mode 100644
index 58afff4bc7..0000000000
--- a/src/declarative/scenegraph/coreapi/qsgnode.h
+++ /dev/null
@@ -1,348 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef NODE_H
-#define NODE_H
-
-#include "qsggeometry.h"
-#include <QtGui/QMatrix4x4>
-
-#include <float.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-#define QML_RUNTIME_TESTING
-
-class QSGRenderer;
-
-class QSGNode;
-class QSGRootNode;
-class QSGGeometryNode;
-class QSGTransformNode;
-class QSGClipNode;
-
-class Q_DECLARATIVE_EXPORT QSGNode
-{
-public:
- enum NodeType {
- BasicNodeType,
- RootNodeType,
- GeometryNodeType,
- TransformNodeType,
- ClipNodeType,
- OpacityNodeType,
- UserNodeType = 1024
- };
-
- enum DirtyFlag {
- DirtyMatrix = 0x0001,
- DirtyClipList = 0x0002,
- DirtyNodeAdded = 0x0004,
- DirtyNodeRemoved = 0x0008,
- DirtyGeometry = 0x0010,
- DirtyMaterial = 0x0040,
- DirtyOpacity = 0x0080,
- DirtyForceUpdate = 0x0100,
-
- DirtyPropagationMask = DirtyMatrix
- | DirtyClipList
- | DirtyNodeAdded
- | DirtyOpacity
- | DirtyForceUpdate
-
- };
- Q_DECLARE_FLAGS(DirtyFlags, DirtyFlag)
-
- enum Flag {
- // Lower 16 bites reserved for general node
- OwnedByParent = 0x0001,
- UsePreprocess = 0x0002,
- ChildrenDoNotOverlap = 0x0004,
-
- // Upper 16 bits reserved for node subclasses
-
- // QSGBasicGeometryNode
- OwnsGeometry = 0x00010000,
- OwnsMaterial = 0x00020000,
- OwnsOpaqueMaterial = 0x00040000
- };
- Q_DECLARE_FLAGS(Flags, Flag)
-
- QSGNode();
- virtual ~QSGNode();
-
- QSGNode *parent() const { return m_parent; }
-
- void removeChildNode(QSGNode *node);
- void removeAllChildNodes();
- void prependChildNode(QSGNode *node);
- void appendChildNode(QSGNode *node);
- void insertChildNodeBefore(QSGNode *node, QSGNode *before);
- void insertChildNodeAfter(QSGNode *node, QSGNode *after);
-
- int childCount() const;
- QSGNode *childAtIndex(int i) const;
- QSGNode *firstChild() const { return m_firstChild; }
- QSGNode *lastChild() const { return m_lastChild; }
- QSGNode *nextSibling() const { return m_nextSibling; }
- QSGNode* previousSibling() const { return m_previousSibling; }
-
- inline NodeType type() const { return m_type; }
-
- void clearDirty() { m_flags = 0; }
- void markDirty(DirtyFlags flags);
- DirtyFlags dirtyFlags() const { return m_flags; }
-
- virtual bool isSubtreeBlocked() const;
-
- Flags flags() const { return m_nodeFlags; }
- void setFlag(Flag, bool = true);
- void setFlags(Flags, bool = true);
-
- virtual void preprocess() { }
-
-#ifdef QML_RUNTIME_TESTING
- QString description;
-#endif
-
-protected:
- QSGNode(NodeType type);
-
-private:
- friend class QSGRootNode;
-
- void init();
- void destroy();
-
- QSGNode *m_parent;
- NodeType m_type;
- QSGNode *m_firstChild;
- QSGNode *m_lastChild;
- QSGNode *m_nextSibling;
- QSGNode *m_previousSibling;
- int m_subtreeGeometryCount;
-
- Flags m_nodeFlags;
- DirtyFlags m_flags;
-
- void *m_reserved;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QSGNode::DirtyFlags)
-Q_DECLARE_OPERATORS_FOR_FLAGS(QSGNode::Flags)
-
-class Q_DECLARATIVE_EXPORT QSGBasicGeometryNode : public QSGNode
-{
-public:
-// enum UsagePattern {
-// Static,
-// Dynamic,
-// Stream
-// };
-// void setUsagePattern(UsagePattern pattern);
-// UsagePattern usagePattern() const { return m_pattern; }
-
- ~QSGBasicGeometryNode();
-
- void setGeometry(QSGGeometry *geometry);
- const QSGGeometry *geometry() const { return m_geometry; }
- QSGGeometry *geometry() { return m_geometry; }
-
- const QMatrix4x4 *matrix() const { return m_matrix; }
- const QSGClipNode *clipList() const { return m_clip_list; }
-
-protected:
- QSGBasicGeometryNode(NodeType type);
-
-private:
- friend class QSGNodeUpdater;
- QSGGeometry *m_geometry;
-
- int m_reserved_start_index;
- int m_reserved_end_index;
-
- const QMatrix4x4 *m_matrix;
- const QSGClipNode *m_clip_list;
-
-// UsagePattern m_pattern;
-};
-
-class QSGMaterial;
-
-class Q_DECLARATIVE_EXPORT QSGGeometryNode : public QSGBasicGeometryNode
-{
-public:
- QSGGeometryNode();
- ~QSGGeometryNode();
-
- void setMaterial(QSGMaterial *material);
- QSGMaterial *material() const { return m_material; }
-
- void setOpaqueMaterial(QSGMaterial *material);
- QSGMaterial *opaqueMaterial() const { return m_opaque_material; }
-
- QSGMaterial *activeMaterial() const;
-
- void setRenderOrder(int order);
- int renderOrder() const { return m_render_order; }
-
- void setInheritedOpacity(qreal opacity);
- qreal inheritedOpacity() const { return m_opacity; }
-
-private:
- friend class QSGNodeUpdater;
-
- int m_render_order;
- QSGMaterial *m_material;
- QSGMaterial *m_opaque_material;
-
- qreal m_opacity;
-};
-
-class Q_DECLARATIVE_EXPORT QSGClipNode : public QSGBasicGeometryNode
-{
-public:
- QSGClipNode();
- ~QSGClipNode();
-
- void setIsRectangular(bool rectHint);
- bool isRectangular() const { return m_is_rectangular; }
-
- void setClipRect(const QRectF &);
- QRectF clipRect() const { return m_clip_rect; }
-
-private:
- uint m_is_rectangular : 1;
- uint m_reserved : 31;
-
- QRectF m_clip_rect;
-};
-
-
-class Q_DECLARATIVE_EXPORT QSGTransformNode : public QSGNode
-{
-public:
- QSGTransformNode();
- ~QSGTransformNode();
-
- void setMatrix(const QMatrix4x4 &matrix);
- const QMatrix4x4 &matrix() const { return m_matrix; }
-
- void setCombinedMatrix(const QMatrix4x4 &matrix);
- const QMatrix4x4 &combinedMatrix() const { return m_combined_matrix; }
-
-private:
- QMatrix4x4 m_matrix;
- QMatrix4x4 m_combined_matrix;
-};
-
-
-class Q_DECLARATIVE_EXPORT QSGRootNode : public QSGNode
-{
-public:
- QSGRootNode();
- ~QSGRootNode();
-
-private:
- void notifyNodeChange(QSGNode *node, DirtyFlags flags);
-
- friend class QSGRenderer;
- friend class QSGNode;
- friend class QSGGeometryNode;
-
- QList<QSGRenderer *> m_renderers;
-};
-
-
-class Q_DECLARATIVE_EXPORT QSGOpacityNode : public QSGNode
-{
-public:
- QSGOpacityNode();
- ~QSGOpacityNode();
-
- void setOpacity(qreal opacity);
- qreal opacity() const { return m_opacity; }
-
- void setCombinedOpacity(qreal opacity);
- qreal combinedOpacity() const { return m_combined_opacity; }
-
- bool isSubtreeBlocked() const;
-
-private:
- qreal m_opacity;
- qreal m_combined_opacity;
-};
-
-class Q_DECLARATIVE_EXPORT QSGNodeVisitor {
-public:
- virtual ~QSGNodeVisitor();
-
-protected:
- virtual void enterTransformNode(QSGTransformNode *) {}
- virtual void leaveTransformNode(QSGTransformNode *) {}
- virtual void enterClipNode(QSGClipNode *) {}
- virtual void leaveClipNode(QSGClipNode *) {}
- virtual void enterGeometryNode(QSGGeometryNode *) {}
- virtual void leaveGeometryNode(QSGGeometryNode *) {}
- virtual void enterOpacityNode(QSGOpacityNode *) {}
- virtual void leaveOpacityNode(QSGOpacityNode *) {}
- virtual void visitNode(QSGNode *n);
- virtual void visitChildren(QSGNode *n);
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-Q_DECLARATIVE_EXPORT QDebug operator<<(QDebug, const QSGNode *n);
-Q_DECLARATIVE_EXPORT QDebug operator<<(QDebug, const QSGGeometryNode *n);
-Q_DECLARATIVE_EXPORT QDebug operator<<(QDebug, const QSGTransformNode *n);
-Q_DECLARATIVE_EXPORT QDebug operator<<(QDebug, const QSGOpacityNode *n);
-Q_DECLARATIVE_EXPORT QDebug operator<<(QDebug, const QSGRootNode *n);
-
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // NODE_H
diff --git a/src/declarative/scenegraph/coreapi/qsgnodeupdater.cpp b/src/declarative/scenegraph/coreapi/qsgnodeupdater.cpp
deleted file mode 100644
index a7e5b08dc1..0000000000
--- a/src/declarative/scenegraph/coreapi/qsgnodeupdater.cpp
+++ /dev/null
@@ -1,287 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgnodeupdater_p.h"
-
-QT_BEGIN_NAMESPACE
-
-// #define QSG_UPDATER_DEBUG
-
-QSGNodeUpdater::QSGNodeUpdater()
- : m_combined_matrix_stack(64)
- , m_opacity_stack(64)
- , m_current_clip(0)
- , m_force_update(0)
-{
- m_opacity_stack.add(1);
-}
-
-void QSGNodeUpdater::updateStates(QSGNode *n)
-{
- m_current_clip = 0;
- m_force_update = 0;
-
- Q_ASSERT(m_opacity_stack.size() == 1); // The one we added in the constructr...
- Q_ASSERT(m_combined_matrix_stack.isEmpty());
-
- visitNode(n);
-}
-
-/*!
- \fn void QSGNodeUpdater::setToplevelOpacity(qreal opacity)
-
- Sets the toplevel opacity that will be multiplied with the
-
- The default opacity is 1. Any other value will cause artifacts, and is
- primarily useful for debug purposes.
-
- The changing the value during an update pass will have undefined results
- */
-
-/*!
- \fn qreal QSGNodeUpdater::toplevelOpacity() const
-
- Returns the toplevel opacity for the node updater. The default
- value is 1.
- */
-
-
-/*!
- Returns true if \a node is has something that blocks it in the chain from
- \a node to \a root doing a full state update pass.
-
- This function does not process dirty states, simply does a simple traversion
- up to the top.
-
- The function assumes that \a root exists in the parent chain of \a node.
- */
-
-bool QSGNodeUpdater::isNodeBlocked(QSGNode *node, QSGNode *root) const
-{
- qreal opacity = 1;
- while (node != root) {
- if (node->type() == QSGNode::OpacityNodeType) {
- opacity *= static_cast<QSGOpacityNode *>(node)->opacity();
- if (opacity < 0.001)
- return true;
- }
- node = node->parent();
-
- Q_ASSERT_X(node, "QSGNodeUpdater::isNodeBlocked", "node is not in the subtree of root");
- }
-
- return false;
-}
-
-
-void QSGNodeUpdater::enterTransformNode(QSGTransformNode *t)
-{
- if (t->dirtyFlags() & QSGNode::DirtyMatrix)
- ++m_force_update;
-
-#ifdef QSG_UPDATER_DEBUG
- qDebug() << "enter transform:" << t << "force=" << m_force_update;
-#endif
-
- if (!t->matrix().isIdentity()) {
- if (!m_combined_matrix_stack.isEmpty()) {
- t->setCombinedMatrix(*m_combined_matrix_stack.last() * t->matrix());
- } else {
- t->setCombinedMatrix(t->matrix());
- }
- m_combined_matrix_stack.add(&t->combinedMatrix());
- } else {
- if (!m_combined_matrix_stack.isEmpty()) {
- t->setCombinedMatrix(*m_combined_matrix_stack.last());
- } else {
- t->setCombinedMatrix(QMatrix4x4());
- }
- }
-}
-
-
-void QSGNodeUpdater::leaveTransformNode(QSGTransformNode *t)
-{
-#ifdef QSG_UPDATER_DEBUG
- qDebug() << "leave transform:" << t;
-#endif
-
- if (t->dirtyFlags() & QSGNode::DirtyMatrix)
- --m_force_update;
-
- if (!t->matrix().isIdentity()) {
- m_combined_matrix_stack.pop_back();
- }
-
-}
-
-
-void QSGNodeUpdater::enterClipNode(QSGClipNode *c)
-{
-#ifdef QSG_UPDATER_DEBUG
- qDebug() << "enter clip:" << c;
-#endif
-
- if (c->dirtyFlags() & QSGNode::DirtyClipList)
- ++m_force_update;
-
- c->m_matrix = m_combined_matrix_stack.isEmpty() ? 0 : m_combined_matrix_stack.last();
- c->m_clip_list = m_current_clip;
- m_current_clip = c;
-}
-
-
-void QSGNodeUpdater::leaveClipNode(QSGClipNode *c)
-{
-#ifdef QSG_UPDATER_DEBUG
- qDebug() << "leave clip:" << c;
-#endif
-
- if (c->dirtyFlags() & QSGNode::DirtyClipList)
- --m_force_update;
-
- m_current_clip = c->m_clip_list;
-}
-
-
-void QSGNodeUpdater::enterGeometryNode(QSGGeometryNode *g)
-{
-#ifdef QSG_UPDATER_DEBUG
- qDebug() << "enter geometry:" << g;
-#endif
-
- g->m_matrix = m_combined_matrix_stack.isEmpty() ? 0 : m_combined_matrix_stack.last();
- g->m_clip_list = m_current_clip;
- g->setInheritedOpacity(m_opacity_stack.last());
-}
-
-void QSGNodeUpdater::leaveGeometryNode(QSGGeometryNode *g)
-{
-#ifdef QSG_UPDATER_DEBUG
- qDebug() << "leave geometry" << g;
-#else
- Q_UNUSED(g)
-#endif
-}
-
-void QSGNodeUpdater::enterOpacityNode(QSGOpacityNode *o)
-{
- if (o->dirtyFlags() & QSGNode::DirtyOpacity)
- ++m_force_update;
-
- qreal opacity = m_opacity_stack.last() * o->opacity();
- o->setCombinedOpacity(opacity);
- m_opacity_stack.add(opacity);
-
-#ifdef QSG_UPDATER_DEBUG
- qDebug() << "enter opacity" << o;
-#endif
-}
-
-void QSGNodeUpdater::leaveOpacityNode(QSGOpacityNode *o)
-{
-#ifdef QSG_UPDATER_DEBUG
- qDebug() << "leave opacity" << o;
-#endif
- if (o->flags() & QSGNode::DirtyOpacity)
- --m_force_update;
-
- m_opacity_stack.pop_back();
-}
-
-void QSGNodeUpdater::visitChildren(QSGNode *n)
-{
- for (QSGNode *c = n->firstChild(); c; c = c->nextSibling())
- visitNode(c);
-}
-
-void QSGNodeUpdater::visitNode(QSGNode *n)
-{
-#ifdef QSG_UPDATER_DEBUG
- qDebug() << "enter:" << n;
-#endif
-
- if (!n->dirtyFlags() && !m_force_update)
- return;
- if (n->isSubtreeBlocked())
- return;
-
- bool forceUpdate = n->dirtyFlags() & (QSGNode::DirtyNodeAdded | QSGNode::DirtyForceUpdate);
- if (forceUpdate)
- ++m_force_update;
-
- switch (n->type()) {
- case QSGNode::TransformNodeType: {
- QSGTransformNode *t = static_cast<QSGTransformNode *>(n);
- enterTransformNode(t);
- visitChildren(t);
- leaveTransformNode(t);
- break; }
- case QSGNode::GeometryNodeType: {
- QSGGeometryNode *g = static_cast<QSGGeometryNode *>(n);
- enterGeometryNode(g);
- visitChildren(g);
- leaveGeometryNode(g);
- break; }
- case QSGNode::ClipNodeType: {
- QSGClipNode *c = static_cast<QSGClipNode *>(n);
- enterClipNode(c);
- visitChildren(c);
- leaveClipNode(c);
- break; }
- case QSGNode::OpacityNodeType: {
- QSGOpacityNode *o = static_cast<QSGOpacityNode *>(n);
- enterOpacityNode(o);
- visitChildren(o);
- leaveOpacityNode(o);
- break; }
- default:
- visitChildren(n);
- break;
- }
-
- if (forceUpdate)
- --m_force_update;
-
- n->clearDirty();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/coreapi/qsgnodeupdater_p.h b/src/declarative/scenegraph/coreapi/qsgnodeupdater_p.h
deleted file mode 100644
index 25d7c11fa1..0000000000
--- a/src/declarative/scenegraph/coreapi/qsgnodeupdater_p.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef NODEUPDATER_P_H
-#define NODEUPDATER_P_H
-
-#include "qsgnode.h"
-#include <QtGui/private/qdatabuffer_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class Q_DECLARATIVE_EXPORT QSGNodeUpdater
-{
-public:
- QSGNodeUpdater();
-
- virtual void updateStates(QSGNode *n);
- virtual bool isNodeBlocked(QSGNode *n, QSGNode *root) const;
-
- void setToplevelOpacity(qreal alpha) { m_opacity_stack.last() = alpha; }
- qreal toplevelOpacity() const { return m_opacity_stack.last(); }
-
-protected:
- virtual void enterTransformNode(QSGTransformNode *);
- virtual void leaveTransformNode(QSGTransformNode *);
- void enterClipNode(QSGClipNode *c);
- void leaveClipNode(QSGClipNode *c);
- void enterOpacityNode(QSGOpacityNode *o);
- void leaveOpacityNode(QSGOpacityNode *o);
- void enterGeometryNode(QSGGeometryNode *);
- void leaveGeometryNode(QSGGeometryNode *);
-
- void visitNode(QSGNode *n);
- void visitChildren(QSGNode *n);
-
-
- QDataBuffer<const QMatrix4x4 *> m_combined_matrix_stack;
- QDataBuffer<qreal> m_opacity_stack;
- const QSGClipNode *m_current_clip;
-
- int m_force_update;
-
- qreal m_toplevel_alpha;
-};
-
-QT_END_NAMESPACE
-
-#endif // NODEUPDATER_P_H
diff --git a/src/declarative/scenegraph/coreapi/qsgrenderer.cpp b/src/declarative/scenegraph/coreapi/qsgrenderer.cpp
deleted file mode 100644
index b22631afae..0000000000
--- a/src/declarative/scenegraph/coreapi/qsgrenderer.cpp
+++ /dev/null
@@ -1,743 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgrenderer_p.h"
-#include "qsgnode.h"
-#include "qsgmaterial.h"
-#include "qsgnodeupdater_p.h"
-#include "qsggeometry_p.h"
-
-#include <private/qsgadaptationlayer_p.h>
-
-#include <QOpenGLShaderProgram>
-#include <qopenglframebufferobject.h>
-#include <QtGui/qguiapplication.h>
-
-#include <qdatetime.h>
-
-QT_BEGIN_NAMESPACE
-
-//#define RENDERER_DEBUG
-//#define QT_GL_NO_SCISSOR_TEST
-
-
-
-#define QSG_RENDERER_TIMING
-#ifdef QSG_RENDERER_TIMING
-static bool qsg_render_timing = !qgetenv("QML_RENDERER_TIMING").isEmpty();
-static QTime frameTimer;
-static int preprocessTime;
-static int updatePassTime;
-#endif
-
-void QSGBindable::clear(QSGRenderer::ClearMode mode) const
-{
- GLuint bits = 0;
- if (mode & QSGRenderer::ClearColorBuffer) bits |= GL_COLOR_BUFFER_BIT;
- if (mode & QSGRenderer::ClearDepthBuffer) bits |= GL_DEPTH_BUFFER_BIT;
- if (mode & QSGRenderer::ClearStencilBuffer) bits |= GL_STENCIL_BUFFER_BIT;
- glClear(bits);
-}
-
-// Reactivate the color buffer after switching to the stencil.
-void QSGBindable::reactivate() const
-{
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-}
-
-QSGBindableFbo::QSGBindableFbo(QOpenGLFramebufferObject *fbo) : m_fbo(fbo)
-{
-}
-
-
-void QSGBindableFbo::bind() const
-{
- m_fbo->bind();
-}
-
-/*!
- \class QSGRenderer
- \brief The renderer class is the abstract baseclass use for rendering the
- QML scene graph.
-
- The renderer is not tied to any particular surface. It expects a context to
- be current and will render into that surface according to how the device rect,
- viewport rect and projection transformation are set up.
-
- Rendering is a sequence of steps initiated by calling renderScene(). This will
- effectively draw the scene graph starting at the root node. The QSGNode::preprocess()
- function will be called for all the nodes in the graph, followed by an update
- pass which updates all matrices, opacity, clip states and similar in the graph.
- Because the update pass is called after preprocess, it is safe to modify the graph
- during preprocess. To run a custom update pass over the graph, install a custom
- QSGNodeUpdater using setNodeUpdater(). Once all the graphs dirty states are updated,
- the virtual render() function is called.
-
- The render() function is implemented by QSGRenderer subclasses to render the graph
- in the most optimal way for a given hardware.
-
- The renderer can make use of stencil, depth and color buffers in addition to the
- scissor rect.
-
- \internal
- */
-
-
-QSGRenderer::QSGRenderer(QSGContext *context)
- : QObject()
- , m_clear_color(Qt::transparent)
- , m_clear_mode(ClearColorBuffer | ClearDepthBuffer)
- , m_current_opacity(1)
- , m_context(context)
- , m_root_node(0)
- , m_node_updater(0)
- , m_bindable(0)
- , m_changed_emitted(false)
- , m_mirrored(false)
- , m_is_rendering(false)
- , m_vertex_buffer_bound(false)
- , m_index_buffer_bound(false)
-{
- initializeGLFunctions();
-}
-
-
-QSGRenderer::~QSGRenderer()
-{
- setRootNode(0);
- delete m_node_updater;
-}
-
-/*!
- Returns the scene graph context for this renderer.
-
- \internal
- */
-
-QSGContext *QSGRenderer::context()
-{
- return m_context;
-}
-
-
-
-
-/*!
- Returns the node updater that this renderer uses to update states in the
- scene graph.
-
- If no updater is specified a default one is constructed.
- */
-
-QSGNodeUpdater *QSGRenderer::nodeUpdater() const
-{
- if (!m_node_updater)
- const_cast<QSGRenderer *>(this)->m_node_updater = new QSGNodeUpdater();
- return m_node_updater;
-}
-
-
-/*!
- Sets the node updater that this renderer uses to update states in the
- scene graph.
-
- This will delete and override any existing node updater
- */
-void QSGRenderer::setNodeUpdater(QSGNodeUpdater *updater)
-{
- if (m_node_updater)
- delete m_node_updater;
- m_node_updater = updater;
-}
-
-
-void QSGRenderer::setRootNode(QSGRootNode *node)
-{
- if (m_root_node == node)
- return;
- if (m_root_node) {
- m_root_node->m_renderers.removeOne(this);
- nodeChanged(m_root_node, QSGNode::DirtyNodeRemoved);
- }
- m_root_node = node;
- if (m_root_node) {
- Q_ASSERT(!m_root_node->m_renderers.contains(this));
- m_root_node->m_renderers << this;
- nodeChanged(m_root_node, QSGNode::DirtyNodeAdded);
- }
-}
-
-
-void QSGRenderer::renderScene()
-{
- class B : public QSGBindable
- {
- public:
- void bind() const { QOpenGLFramebufferObject::bindDefault(); }
- } b;
- renderScene(b);
-}
-
-void QSGRenderer::renderScene(const QSGBindable &bindable)
-{
- if (!m_root_node)
- return;
-
- m_is_rendering = true;
-
-
-#ifdef QSG_RENDERER_TIMING
- if (qsg_render_timing)
- frameTimer.start();
- int bindTime;
- int renderTime;
-#endif
-
- m_bindable = &bindable;
- preprocess();
-
- bindable.bind();
-#ifdef QSG_RENDERER_TIMING
- if (qsg_render_timing)
- bindTime = frameTimer.elapsed();
-#endif
-
-#ifndef QT_NO_DEBUG
- // Sanity check that attribute registers are disabled
- {
- GLint count;
- glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &count);
- GLint enabled;
- for (int i=0; i<count; ++i) {
- glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &enabled);
- if (enabled) {
- qWarning("QSGRenderer: attribute %d is enabled, this can lead to memory corruption and crashes.", i);
- }
- }
- }
-#endif
-
- render();
-#ifdef QSG_RENDERER_TIMING
- if (qsg_render_timing)
- renderTime = frameTimer.elapsed();
-#endif
-
- glDisable(GL_SCISSOR_TEST);
- m_is_rendering = false;
- m_changed_emitted = false;
- m_bindable = 0;
-
- if (m_vertex_buffer_bound) {
- glBindBuffer(GL_ARRAY_BUFFER, 0);
- m_vertex_buffer_bound = false;
- }
-
- if (m_index_buffer_bound) {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
- m_index_buffer_bound = false;
- }
-
-#ifdef QSG_RENDERER_TIMING
- if (qsg_render_timing) {
- printf(" - Breakdown of frametime: preprocess=%d, updates=%d, binding=%d, render=%d, total=%d\n",
- preprocessTime,
- updatePassTime - preprocessTime,
- bindTime - updatePassTime,
- renderTime - bindTime,
- renderTime);
- }
-#endif
-}
-
-void QSGRenderer::setProjectionMatrixToDeviceRect()
-{
- setProjectionMatrixToRect(m_device_rect);
-}
-
-void QSGRenderer::setProjectionMatrixToRect(const QRectF &rect)
-{
- QMatrix4x4 matrix;
- matrix.ortho(rect.x(),
- rect.x() + rect.width(),
- rect.y() + rect.height(),
- rect.y(),
- qreal(0.01),
- -1);
- setProjectionMatrix(matrix);
-}
-
-void QSGRenderer::setProjectionMatrix(const QMatrix4x4 &matrix)
-{
- m_projection_matrix = matrix;
- // Mirrored relative to the usual Qt coordinate system with origin in the top left corner.
- m_mirrored = matrix(0, 0) * matrix(1, 1) - matrix(0, 1) * matrix(1, 0) > 0;
-}
-
-void QSGRenderer::setClearColor(const QColor &color)
-{
- m_clear_color = color;
-}
-
-/*!
- Updates internal data structures and emits the sceneGraphChanged() signal.
-
- If \a flags contains the QSGNode::DirtyNodeRemoved flag, the node might be
- in the process of being destroyed. It is then not safe to downcast the node
- pointer.
-*/
-
-void QSGRenderer::nodeChanged(QSGNode *node, QSGNode::DirtyFlags flags)
-{
- Q_UNUSED(node);
- Q_UNUSED(flags);
-
- if (flags & QSGNode::DirtyNodeAdded)
- addNodesToPreprocess(node);
- if (flags & QSGNode::DirtyNodeRemoved)
- removeNodesToPreprocess(node);
-
- if (!m_changed_emitted && !m_is_rendering) {
- // Premature overoptimization to avoid excessive signal emissions
- m_changed_emitted = true;
- emit sceneGraphChanged();
- }
-}
-
-void QSGRenderer::materialChanged(QSGGeometryNode *, QSGMaterial *, QSGMaterial *)
-{
-}
-
-void QSGRenderer::preprocess()
-{
- Q_ASSERT(m_root_node);
-
- // We need to take a copy here, in case any of the preprocess calls deletes a node that
- // is in the preprocess list and thus, changes the m_nodes_to_preprocess behind our backs
- // For the default case, when this does not happen, the cost is neglishible.
- QSet<QSGNode *> items = m_nodes_to_preprocess;
-
- for (QSet<QSGNode *>::const_iterator it = items.constBegin();
- it != items.constEnd(); ++it) {
- QSGNode *n = *it;
- if (!nodeUpdater()->isNodeBlocked(n, m_root_node)) {
- n->preprocess();
- }
- }
-
-#ifdef QSG_RENDERER_TIMING
- if (qsg_render_timing)
- preprocessTime = frameTimer.elapsed();
-#endif
-
- nodeUpdater()->setToplevelOpacity(context()->renderAlpha());
- nodeUpdater()->updateStates(m_root_node);
-
-#ifdef QSG_RENDERER_TIMING
- if (qsg_render_timing)
- updatePassTime = frameTimer.elapsed();
-#endif
-
-}
-
-void QSGRenderer::addNodesToPreprocess(QSGNode *node)
-{
- for (QSGNode *c = node->firstChild(); c; c = c->nextSibling())
- addNodesToPreprocess(c);
- if (node->flags() & QSGNode::UsePreprocess)
- m_nodes_to_preprocess.insert(node);
-}
-
-void QSGRenderer::removeNodesToPreprocess(QSGNode *node)
-{
- for (QSGNode *c = node->firstChild(); c; c = c->nextSibling())
- removeNodesToPreprocess(c);
- if (node->flags() & QSGNode::UsePreprocess)
- m_nodes_to_preprocess.remove(node);
-}
-
-
-/*!
- Convenience function to set up the stencil buffer for clipping based on \a clip.
-
- If the clip is a pixel aligned rectangle, this function will use glScissor instead
- of stencil.
- */
-
-QSGRenderer::ClipType QSGRenderer::updateStencilClip(const QSGClipNode *clip)
-{
- if (!clip) {
- glDisable(GL_STENCIL_TEST);
- glDisable(GL_SCISSOR_TEST);
- return NoClip;
- }
-
- bool stencilEnabled = false;
- bool scissorEnabled = false;
-
- glDisable(GL_SCISSOR_TEST);
-
- int clipDepth = 0;
- QRect clipRect;
- while (clip) {
- QMatrix4x4 m = m_current_projection_matrix;
- if (clip->matrix())
- m *= *clip->matrix();
-
- // TODO: Check for multisampling and pixel grid alignment.
- bool isRectangleWithNoPerspective = clip->isRectangular()
- && qFuzzyIsNull(m(3, 0)) && qFuzzyIsNull(m(3, 1));
- bool noRotate = qFuzzyIsNull(m(0, 1)) && qFuzzyIsNull(m(1, 0));
- bool isRotate90 = qFuzzyIsNull(m(0, 0)) && qFuzzyIsNull(m(1, 1));
-
- if (isRectangleWithNoPerspective && (noRotate || isRotate90)) {
- QRectF bbox = clip->clipRect();
- qreal invW = 1 / m(3, 3);
- qreal fx1, fy1, fx2, fy2;
- if (noRotate) {
- fx1 = (bbox.left() * m(0, 0) + m(0, 3)) * invW;
- fy1 = (bbox.bottom() * m(1, 1) + m(1, 3)) * invW;
- fx2 = (bbox.right() * m(0, 0) + m(0, 3)) * invW;
- fy2 = (bbox.top() * m(1, 1) + m(1, 3)) * invW;
- } else {
- Q_ASSERT(isRotate90);
- fx1 = (bbox.bottom() * m(0, 1) + m(0, 3)) * invW;
- fy1 = (bbox.left() * m(1, 0) + m(1, 3)) * invW;
- fx2 = (bbox.top() * m(0, 1) + m(0, 3)) * invW;
- fy2 = (bbox.right() * m(1, 0) + m(1, 3)) * invW;
- }
-
- if (fx1 > fx2)
- qSwap(fx1, fx2);
- if (fy1 > fy2)
- qSwap(fy1, fy2);
-
- GLint ix1 = qRound((fx1 + 1) * m_device_rect.width() * qreal(0.5));
- GLint iy1 = qRound((fy1 + 1) * m_device_rect.height() * qreal(0.5));
- GLint ix2 = qRound((fx2 + 1) * m_device_rect.width() * qreal(0.5));
- GLint iy2 = qRound((fy2 + 1) * m_device_rect.height() * qreal(0.5));
-
- if (!scissorEnabled) {
- clipRect = QRect(ix1, iy1, ix2 - ix1, iy2 - iy1);
- glEnable(GL_SCISSOR_TEST);
- scissorEnabled = true;
- } else {
- clipRect &= QRect(ix1, iy1, ix2 - ix1, iy2 - iy1);
- }
-
- glScissor(clipRect.x(), clipRect.y(), clipRect.width(), clipRect.height());
- } else {
- if (!stencilEnabled) {
- if (!m_clip_program.isLinked()) {
- m_clip_program.addShaderFromSourceCode(QOpenGLShader::Vertex,
- "attribute highp vec4 vCoord; \n"
- "uniform highp mat4 matrix; \n"
- "void main() { \n"
- " gl_Position = matrix * vCoord; \n"
- "}");
- m_clip_program.addShaderFromSourceCode(QOpenGLShader::Fragment,
- "void main() { \n"
- " gl_FragColor = vec4(0.81, 0.83, 0.12, 1.0); \n" // Trolltech green ftw!
- "}");
- m_clip_program.bindAttributeLocation("vCoord", 0);
- m_clip_program.link();
- m_clip_matrix_id = m_clip_program.uniformLocation("matrix");
- }
-
- glStencilMask(0xff); // write mask
- glClearStencil(0);
- glClear(GL_STENCIL_BUFFER_BIT);
- glEnable(GL_STENCIL_TEST);
- glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
- glDepthMask(GL_FALSE);
-
- m_clip_program.bind();
- m_clip_program.enableAttributeArray(0);
-
- stencilEnabled = true;
- }
-
- glStencilFunc(GL_EQUAL, clipDepth, 0xff); // stencil test, ref, test mask
- glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); // stencil fail, z fail, z pass
-
- const QSGGeometry *g = clip->geometry();
- Q_ASSERT(g->attributeCount() > 0);
- const QSGGeometry::Attribute *a = g->attributes();
- glVertexAttribPointer(0, a->tupleSize, a->type, GL_FALSE, g->sizeOfVertex(), g->vertexData());
-
- m_clip_program.setUniformValue(m_clip_matrix_id, m);
- if (g->indexCount()) {
- glDrawElements(g->drawingMode(), g->indexCount(), g->indexType(), g->indexData());
- } else {
- glDrawArrays(g->drawingMode(), 0, g->vertexCount());
- }
-
- ++clipDepth;
- }
-
- clip = clip->clipList();
- }
-
- if (stencilEnabled) {
- m_clip_program.disableAttributeArray(0);
- glStencilFunc(GL_EQUAL, clipDepth, 0xff); // stencil test, ref, test mask
- glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // stencil fail, z fail, z pass
- glStencilMask(0); // write mask
- bindable()->reactivate();
- } else {
- glDisable(GL_STENCIL_TEST);
- }
-
- if (!scissorEnabled)
- glDisable(GL_SCISSOR_TEST);
-
- return stencilEnabled ? StencilClip : ScissorClip;
-}
-
-
-
-static inline int size_of_type(GLenum type)
-{
- static int sizes[] = {
- sizeof(char),
- sizeof(unsigned char),
- sizeof(short),
- sizeof(unsigned short),
- sizeof(int),
- sizeof(unsigned int),
- sizeof(float),
- 2,
- 3,
- 4,
- sizeof(double)
- };
- Q_ASSERT(type >= GL_BYTE && type <= 0x140A); // the value of GL_DOUBLE
- return sizes[type - GL_BYTE];
-}
-
-
-class QSGRendererVBOGeometryData : public QSGGeometryData
-{
-public:
- QSGRendererVBOGeometryData()
- : vertexBuffer(0)
- , indexBuffer(0)
- {
- }
-
- ~QSGRendererVBOGeometryData()
- {
- QOpenGLContext *ctx = QOpenGLContext::currentContext();
- if (!ctx)
- return;
- QOpenGLFunctions *func = ctx->functions();
- if (vertexBuffer)
- func->glDeleteBuffers(1, &vertexBuffer);
- if (indexBuffer)
- func->glDeleteBuffers(1, &indexBuffer);
- }
-
- GLuint vertexBuffer;
- GLuint indexBuffer;
-
- static QSGRendererVBOGeometryData *get(const QSGGeometry *g) {
- QSGRendererVBOGeometryData *gd = static_cast<QSGRendererVBOGeometryData *>(QSGGeometryData::data(g));
- if (!gd) {
- gd = new QSGRendererVBOGeometryData;
- QSGGeometryData::install(g, gd);
- }
- return gd;
- }
-
-};
-
-static inline GLenum qt_drawTypeForPattern(QSGGeometry::DataPattern p)
-{
- Q_ASSERT(p > 0 && p <= 3);
- static GLenum drawTypes[] = { 0,
- GL_STREAM_DRAW,
- GL_DYNAMIC_DRAW,
- GL_STATIC_DRAW
- };
- return drawTypes[p];
-}
-
-
-/*!
- Issues the GL draw call for the geometry \a g using the material \a shader.
-
- The function assumes that attributes have been bound and set up prior
- to making this call.
-
- \internal
- */
-
-void QSGRenderer::draw(const QSGMaterialShader *shader, const QSGGeometry *g)
-{
- // ### remove before final release...
- static bool use_vbo = !QGuiApplication::arguments().contains(QLatin1String("--no-vbo"));
-
- const void *vertexData;
- int vertexByteSize = g->vertexCount() * g->sizeOfVertex();
- if (use_vbo && g->vertexDataPattern() != QSGGeometry::AlwaysUploadPattern && vertexByteSize > 1024) {
-
- // The base pointer for a VBO is 0
- vertexData = 0;
-
- bool updateData = QSGGeometryData::hasDirtyVertexData(g);
- QSGRendererVBOGeometryData *gd = QSGRendererVBOGeometryData::get(g);
- if (!gd->vertexBuffer) {
- glGenBuffers(1, &gd->vertexBuffer);
- updateData = true;
- }
-
- glBindBuffer(GL_ARRAY_BUFFER, gd->vertexBuffer);
- m_vertex_buffer_bound = true;
-
- if (updateData) {
- glBufferData(GL_ARRAY_BUFFER, vertexByteSize, g->vertexData(),
- qt_drawTypeForPattern(g->vertexDataPattern()));
- QSGGeometryData::clearDirtyVertexData(g);
- }
-
- } else {
- if (m_vertex_buffer_bound) {
- glBindBuffer(GL_ARRAY_BUFFER, 0);
- m_vertex_buffer_bound = false;
- }
- vertexData = g->vertexData();
- }
-
- // Bind the vertices to attributes...
- char const *const *attrNames = shader->attributeNames();
- int offset = 0;
- for (int j = 0; attrNames[j]; ++j) {
- if (!*attrNames[j])
- continue;
- Q_ASSERT_X(j < g->attributeCount(), "QSGRenderer::bindGeometry()", "Geometry lacks attribute required by material");
- const QSGGeometry::Attribute &a = g->attributes()[j];
- Q_ASSERT_X(j == a.position, "QSGRenderer::bindGeometry()", "Geometry does not have continuous attribute positions");
-
-#if defined(QT_OPENGL_ES_2)
- GLboolean normalize = a.type != GL_FLOAT;
-#else
- GLboolean normalize = a.type != GL_FLOAT && a.type != GL_DOUBLE;
-#endif
- glVertexAttribPointer(a.position, a.tupleSize, a.type, normalize, g->sizeOfVertex(), (char *) vertexData + offset);
- offset += a.tupleSize * size_of_type(a.type);
- }
-
- // Set up the indices...
- const void *indexData;
- if (use_vbo && g->indexDataPattern() != QSGGeometry::AlwaysUploadPattern && g->indexCount() > 512) {
-
- // Base pointer for a VBO is 0
- indexData = 0;
-
- bool updateData = QSGGeometryData::hasDirtyIndexData(g);
- QSGRendererVBOGeometryData *gd = QSGRendererVBOGeometryData::get(g);
- if (!gd->indexBuffer) {
- glGenBuffers(1, &gd->indexBuffer);
- updateData = true;
- }
-
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gd->indexBuffer);
- m_index_buffer_bound = true;
-
- if (updateData) {
- glBufferData(GL_ELEMENT_ARRAY_BUFFER,
- g->indexCount() * g->sizeOfIndex(),
- g->indexData(),
- qt_drawTypeForPattern(g->indexDataPattern()));
- QSGGeometryData::clearDirtyIndexData(g);
- }
-
- } else {
- if (m_index_buffer_bound) {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
- m_index_buffer_bound = false;
- }
- indexData = g->indexData();
- }
-
-
- // draw the stuff...
- if (g->indexCount()) {
- glDrawElements(g->drawingMode(), g->indexCount(), g->indexType(), indexData);
- } else {
- glDrawArrays(g->drawingMode(), 0, g->vertexCount());
- }
-
- // We leave buffers bound for now... They will be reset by bind on next draw() or
- // set back to 0 if next draw is not using VBOs
-
-}
-
-/*!
- \class QSGNodeDumper
- \brief The QSGNodeDumper class provides a way of dumping a scene grahp to the console.
-
- This class is solely for debugging purposes.
-
- \internal
- */
-
-void QSGNodeDumper::dump(QSGNode *n)
-{
- QSGNodeDumper dump;
- dump.visitNode(n);
-}
-
-void QSGNodeDumper::visitNode(QSGNode *n)
-{
- qDebug() << QString(m_indent * 2, QLatin1Char(' ')) << n;
- QSGNodeVisitor::visitNode(n);
-}
-
-void QSGNodeDumper::visitChildren(QSGNode *n)
-{
- ++m_indent;
- QSGNodeVisitor::visitChildren(n);
- --m_indent;
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/coreapi/qsgrenderer_p.h b/src/declarative/scenegraph/coreapi/qsgrenderer_p.h
deleted file mode 100644
index 05fb9b42fd..0000000000
--- a/src/declarative/scenegraph/coreapi/qsgrenderer_p.h
+++ /dev/null
@@ -1,234 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef RENDERER_H
-#define RENDERER_H
-
-#include <qset.h>
-#include <qhash.h>
-
-#include <qcolor.h>
-#include <qopenglfunctions.h>
-#include <qopenglshaderprogram.h>
-
-#include "qsgnode.h"
-#include "qsgmaterial.h"
-#include "qsgtexture.h"
-
-#include <private/qsgcontext_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGMaterialShader;
-struct QSGMaterialType;
-class QOpenGLFramebufferObject;
-class TextureReference;
-class QSGBindable;
-class QSGNodeUpdater;
-
-class Q_DECLARATIVE_EXPORT QSGRenderer : public QObject, public QOpenGLFunctions
-{
- Q_OBJECT
-public:
- enum ClipType
- {
- NoClip,
- ScissorClip,
- StencilClip
- };
-
- enum ClearModeBit
- {
- ClearColorBuffer = 0x0001,
- ClearDepthBuffer = 0x0002,
- ClearStencilBuffer = 0x0004
- };
- Q_DECLARE_FLAGS(ClearMode, ClearModeBit)
-
- QSGRenderer(QSGContext *context);
- virtual ~QSGRenderer();
-
- void setRootNode(QSGRootNode *node);
- QSGRootNode *rootNode() const { return m_root_node; }
-
- void setDeviceRect(const QRect &rect) { m_device_rect = rect; }
- inline void setDeviceRect(const QSize &size) { setDeviceRect(QRect(QPoint(), size)); }
- QRect deviceRect() const { return m_device_rect; }
-
- void setViewportRect(const QRect &rect) { m_viewport_rect = rect; }
- inline void setViewportRect(const QSize &size) { setViewportRect(QRect(QPoint(), size)); }
- QRect viewportRect() const { return m_viewport_rect; }
-
- // Accessed by QSGMaterialShader::RenderState.
- QMatrix4x4 currentProjectionMatrix() const { return m_current_projection_matrix; }
- QMatrix4x4 currentModelViewMatrix() const { return m_current_model_view_matrix; }
- QMatrix4x4 currentCombinedMatrix() const { return m_current_projection_matrix * m_current_model_view_matrix; }
- qreal currentOpacity() const { return m_current_opacity; }
-
- void setProjectionMatrixToDeviceRect();
- void setProjectionMatrixToRect(const QRectF &rect);
- void setProjectionMatrix(const QMatrix4x4 &matrix);
- QMatrix4x4 projectionMatrix() const { return m_projection_matrix; }
- bool isMirrored() const { return m_mirrored; }
-
- void setClearColor(const QColor &color);
- QColor clearColor() const { return m_clear_color; }
-
- QOpenGLContext *glContext() const { Q_ASSERT(m_context); return m_context->glContext(); }
-
- QSGContext *context();
-
- void renderScene();
- void renderScene(const QSGBindable &bindable);
- virtual void nodeChanged(QSGNode *node, QSGNode::DirtyFlags flags);
- virtual void materialChanged(QSGGeometryNode *node, QSGMaterial *from, QSGMaterial *to);
-
- QSGNodeUpdater *nodeUpdater() const;
- void setNodeUpdater(QSGNodeUpdater *updater);
-
- inline QSGMaterialShader::RenderState state(QSGMaterialShader::RenderState::DirtyStates dirty) const;
-
- void setClearMode(ClearMode mode) { m_clear_mode = mode; }
- ClearMode clearMode() const { return m_clear_mode; }
-
-signals:
- void sceneGraphChanged(); // Add, remove, ChangeFlags changes...
-
-protected:
- void draw(const QSGMaterialShader *material, const QSGGeometry *g);
-
- virtual void render() = 0;
- QSGRenderer::ClipType updateStencilClip(const QSGClipNode *clip);
-
- const QSGBindable *bindable() const { return m_bindable; }
-
- virtual void preprocess();
-
- void addNodesToPreprocess(QSGNode *node);
- void removeNodesToPreprocess(QSGNode *node);
-
-
- QColor m_clear_color;
- ClearMode m_clear_mode;
- QMatrix4x4 m_current_projection_matrix;
- QMatrix4x4 m_current_model_view_matrix;
- qreal m_current_opacity;
-
- QSGContext *m_context;
-
-private:
- QSGRootNode *m_root_node;
- QSGNodeUpdater *m_node_updater;
-
- QRect m_device_rect;
- QRect m_viewport_rect;
-
- QSet<QSGNode *> m_nodes_to_preprocess;
-
- QMatrix4x4 m_projection_matrix;
- QOpenGLShaderProgram m_clip_program;
- int m_clip_matrix_id;
-
- const QSGBindable *m_bindable;
-
- uint m_changed_emitted : 1;
- uint m_mirrored : 1;
- uint m_is_rendering : 1;
-
- uint m_vertex_buffer_bound : 1;
- uint m_index_buffer_bound : 1;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QSGRenderer::ClearMode)
-
-class Q_DECLARATIVE_EXPORT QSGBindable
-{
-public:
- virtual ~QSGBindable() { }
- virtual void bind() const = 0;
- virtual void clear(QSGRenderer::ClearMode mode) const;
- virtual void reactivate() const;
-};
-
-class QSGBindableFbo : public QSGBindable
-{
-public:
- QSGBindableFbo(QOpenGLFramebufferObject *fbo);
- virtual void bind() const;
-private:
- QOpenGLFramebufferObject *m_fbo;
-};
-
-
-
-QSGMaterialShader::RenderState QSGRenderer::state(QSGMaterialShader::RenderState::DirtyStates dirty) const
-{
- QSGMaterialShader::RenderState s;
- s.m_dirty = dirty;
- s.m_data = this;
- return s;
-}
-
-
-class Q_DECLARATIVE_EXPORT QSGNodeDumper : public QSGNodeVisitor {
-
-public:
- static void dump(QSGNode *n);
-
- QSGNodeDumper() : m_indent(0) {}
- void visitNode(QSGNode *n);
- void visitChildren(QSGNode *n);
-
-private:
- int m_indent;
-};
-
-
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // RENDERER_H
diff --git a/src/declarative/scenegraph/qsgadaptationlayer.cpp b/src/declarative/scenegraph/qsgadaptationlayer.cpp
deleted file mode 100644
index 966a24acd3..0000000000
--- a/src/declarative/scenegraph/qsgadaptationlayer.cpp
+++ /dev/null
@@ -1,315 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgadaptationlayer_p.h"
-
-#include <qmath.h>
-#include <private/qsgdistancefieldutil_p.h>
-#include <private/qsgdistancefieldglyphnode_p.h>
-#include <private/qrawfont_p.h>
-#include <QtGui/qguiapplication.h>
-#include <qdir.h>
-
-QT_BEGIN_NAMESPACE
-
-
-QHash<QString, QOpenGLMultiGroupSharedResource> QSGDistanceFieldGlyphCache::m_caches_data;
-
-QSGDistanceFieldGlyphCache::QSGDistanceFieldGlyphCache(QSGDistanceFieldGlyphCacheManager *man, QOpenGLContext *c, const QRawFont &font)
- : ctx(c)
- , m_manager(man)
-{
- Q_ASSERT(font.isValid());
- m_font = font;
-
- m_cacheData = cacheData();
-
- QRawFontPrivate *fontD = QRawFontPrivate::get(m_font);
- m_glyphCount = fontD->fontEngine->glyphCount();
-
- m_cacheData->doubleGlyphResolution = qt_fontHasNarrowOutlines(font) && m_glyphCount < QT_DISTANCEFIELD_HIGHGLYPHCOUNT;
-
- m_referenceFont = m_font;
- m_referenceFont.setPixelSize(QT_DISTANCEFIELD_BASEFONTSIZE(m_cacheData->doubleGlyphResolution));
- Q_ASSERT(m_referenceFont.isValid());
-}
-
-QSGDistanceFieldGlyphCache::~QSGDistanceFieldGlyphCache()
-{
-}
-
-QSGDistanceFieldGlyphCache::GlyphCacheData *QSGDistanceFieldGlyphCache::cacheData()
-{
- QString key = QString::fromLatin1("%1_%2_%3_%4")
- .arg(m_font.familyName())
- .arg(m_font.styleName())
- .arg(m_font.weight())
- .arg(m_font.style());
- return m_caches_data[key].value<QSGDistanceFieldGlyphCache::GlyphCacheData>(ctx);
-}
-
-qreal QSGDistanceFieldGlyphCache::fontScale() const
-{
- return qreal(m_font.pixelSize()) / QT_DISTANCEFIELD_BASEFONTSIZE(m_cacheData->doubleGlyphResolution);
-}
-
-int QSGDistanceFieldGlyphCache::distanceFieldRadius() const
-{
- return QT_DISTANCEFIELD_DEFAULT_RADIUS / QT_DISTANCEFIELD_SCALE(m_cacheData->doubleGlyphResolution);
-}
-
-QSGDistanceFieldGlyphCache::Metrics QSGDistanceFieldGlyphCache::glyphMetrics(glyph_t glyph)
-{
- QHash<glyph_t, Metrics>::iterator metric = m_metrics.find(glyph);
- if (metric == m_metrics.end()) {
- QPainterPath path = m_font.pathForGlyph(glyph);
- QRectF br = path.boundingRect();
-
- Metrics m;
- m.width = br.width();
- m.height = br.height();
- m.baselineX = br.x();
- m.baselineY = -br.y();
-
- metric = m_metrics.insert(glyph, m);
- }
-
- return metric.value();
-}
-
-QSGDistanceFieldGlyphCache::TexCoord QSGDistanceFieldGlyphCache::glyphTexCoord(glyph_t glyph) const
-{
- return m_cacheData->texCoords.value(glyph);
-}
-
-static QSGDistanceFieldGlyphCache::Texture g_emptyTexture;
-
-const QSGDistanceFieldGlyphCache::Texture *QSGDistanceFieldGlyphCache::glyphTexture(glyph_t glyph) const
-{
- QHash<glyph_t, Texture*>::const_iterator it = m_cacheData->glyphTextures.find(glyph);
- if (it == m_cacheData->glyphTextures.constEnd())
- return &g_emptyTexture;
- return it.value();
-}
-
-void QSGDistanceFieldGlyphCache::populate(const QVector<glyph_t> &glyphs)
-{
- QSet<glyph_t> newGlyphs;
- int count = glyphs.count();
- for (int i = 0; i < count; ++i) {
- glyph_t glyphIndex = glyphs.at(i);
- if ((int) glyphIndex >= glyphCount()) {
- qWarning("Warning: distance-field glyph is not available with index %d", glyphIndex);
- continue;
- }
-
- if (m_cacheData->texCoords.contains(glyphIndex) || newGlyphs.contains(glyphIndex))
- continue;
-
- QPainterPath path = m_referenceFont.pathForGlyph(glyphIndex);
- m_cacheData->glyphPaths.insert(glyphIndex, path);
- if (path.isEmpty()) {
- TexCoord c;
- c.width = 0;
- c.height = 0;
- m_cacheData->texCoords.insert(glyphIndex, c);
- continue;
- }
-
- newGlyphs.insert(glyphIndex);
- }
-
- if (newGlyphs.isEmpty())
- return;
-
- QVector<glyph_t> glyphsVec;
- QSet<glyph_t>::const_iterator it = newGlyphs.constBegin();
- while (it != newGlyphs.constEnd()) {
- glyphsVec.append(*it);
- ++it;
- }
- requestGlyphs(glyphsVec);
-}
-
-void QSGDistanceFieldGlyphCache::release(const QVector<glyph_t> &glyphs)
-{
- releaseGlyphs(glyphs);
-}
-
-void QSGDistanceFieldGlyphCache::update()
-{
- if (m_cacheData->pendingGlyphs.isEmpty())
- return;
-
- QHash<glyph_t, QImage> distanceFields;
-
- // ### Remove before final release
- static bool cacheDistanceFields = QGuiApplication::arguments().contains(QLatin1String("--cache-distance-fields"));
-
- QString tmpPath = QString::fromLatin1("%1/.qt/").arg(QDir::tempPath());
- QString keyBase = QString::fromLatin1("%1%2%3_%4_%5_%6.fontblob")
- .arg(tmpPath)
- .arg(m_font.familyName())
- .arg(m_font.styleName())
- .arg(m_font.weight())
- .arg(m_font.style());
-
- if (cacheDistanceFields && !QFile::exists(tmpPath))
- QDir(tmpPath).mkpath(tmpPath);
-
- for (int i = 0; i < m_cacheData->pendingGlyphs.size(); ++i) {
- glyph_t glyphIndex = m_cacheData->pendingGlyphs.at(i);
-
- if (cacheDistanceFields) {
- QString key = keyBase.arg(glyphIndex);
- QFile file(key);
- if (file.open(QFile::ReadOnly)) {
- int fileSize = file.size();
- int dim = sqrt(float(fileSize));
- QByteArray blob = file.readAll();
- QImage df(dim, dim, QImage::Format_Indexed8);
- memcpy(df.bits(), blob.constData(), fileSize);
- distanceFields.insert(glyphIndex, df);
- continue;
- }
- }
-
- QImage distanceField = qt_renderDistanceFieldGlyph(m_font, glyphIndex, m_cacheData->doubleGlyphResolution);
- distanceFields.insert(glyphIndex, distanceField);
-
- if (cacheDistanceFields) {
- QString key = keyBase.arg(glyphIndex);
- QFile file(key);
- file.open(QFile::WriteOnly);
- file.write((const char *) distanceField.constBits(), distanceField.width() * distanceField.height());
- }
- }
-
- m_cacheData->pendingGlyphs.reset();
-
- storeGlyphs(distanceFields);
-}
-
-void QSGDistanceFieldGlyphCache::addGlyphPositions(const QList<GlyphPosition> &glyphs)
-{
- int count = glyphs.count();
- for (int i = 0; i < count; ++i) {
- GlyphPosition glyph = glyphs.at(i);
-
- QPainterPath path = m_cacheData->glyphPaths.value(glyph.glyph);
- QRectF br = path.boundingRect();
- TexCoord c;
- c.xMargin = QT_DISTANCEFIELD_RADIUS(m_cacheData->doubleGlyphResolution) / qreal(QT_DISTANCEFIELD_SCALE(m_cacheData->doubleGlyphResolution));
- c.yMargin = QT_DISTANCEFIELD_RADIUS(m_cacheData->doubleGlyphResolution) / qreal(QT_DISTANCEFIELD_SCALE(m_cacheData->doubleGlyphResolution));
- c.x = glyph.position.x();
- c.y = glyph.position.y();
- c.width = br.width();
- c.height = br.height();
-
- m_cacheData->texCoords.insert(glyph.glyph, c);
- }
-}
-
-void QSGDistanceFieldGlyphCache::addGlyphTextures(const QVector<glyph_t> &glyphs, const Texture &tex)
-{
- int i = m_cacheData->textures.indexOf(tex);
- if (i == -1) {
- m_cacheData->textures.append(tex);
- i = m_cacheData->textures.size() - 1;
- } else {
- m_cacheData->textures[i].size = tex.size;
- }
- Texture *texture = &(m_cacheData->textures[i]);
-
- int count = glyphs.count();
- for (int j = 0; j < count; ++j)
- m_cacheData->glyphTextures.insert(glyphs.at(j), texture);
-
- QLinkedList<QSGDistanceFieldGlyphNode *>::iterator it = m_cacheData->m_registeredNodes.begin();
- while (it != m_cacheData->m_registeredNodes.end()) {
- (*it)->updateGeometry();
- ++it;
- }
-}
-
-void QSGDistanceFieldGlyphCache::markGlyphsToRender(const QVector<glyph_t> &glyphs)
-{
- int count = glyphs.count();
- for (int i = 0; i < count; ++i)
- m_cacheData->pendingGlyphs.add(glyphs.at(i));
-}
-
-void QSGDistanceFieldGlyphCache::removeGlyph(glyph_t glyph)
-{
- m_cacheData->texCoords.remove(glyph);
- m_cacheData->glyphTextures.remove(glyph);
-}
-
-void QSGDistanceFieldGlyphCache::updateTexture(GLuint oldTex, GLuint newTex, const QSize &newTexSize)
-{
- int count = m_cacheData->textures.count();
- for (int i = 0; i < count; ++i) {
- Texture &tex = m_cacheData->textures[i];
- if (tex.textureId == oldTex) {
- tex.textureId = newTex;
- tex.size = newTexSize;
- return;
- }
- }
-}
-
-bool QSGDistanceFieldGlyphCache::containsGlyph(glyph_t glyph) const
-{
- return m_cacheData->texCoords.contains(glyph);
-}
-
-void QSGDistanceFieldGlyphCache::registerGlyphNode(QSGDistanceFieldGlyphNode *node)
-{
- m_cacheData->m_registeredNodes.append(node);
-}
-
-void QSGDistanceFieldGlyphCache::unregisterGlyphNode(QSGDistanceFieldGlyphNode *node)
-{
- m_cacheData->m_registeredNodes.removeOne(node);
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgadaptationlayer_p.h b/src/declarative/scenegraph/qsgadaptationlayer_p.h
deleted file mode 100644
index 82e0c7cf42..0000000000
--- a/src/declarative/scenegraph/qsgadaptationlayer_p.h
+++ /dev/null
@@ -1,257 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ADAPTATIONINTERFACES_H
-#define ADAPTATIONINTERFACES_H
-
-#include "qsgnode.h"
-#include "qsgtexture.h"
-#include <QtCore/qobject.h>
-#include <QtCore/qrect.h>
-#include <QtGui/qbrush.h>
-#include <QtGui/qcolor.h>
-#include <QtCore/qsharedpointer.h>
-#include <QtGui/qglyphrun.h>
-#include <QtCore/qurl.h>
-#include <private/qfontengine_p.h>
-#include <QtGui/private/qdatabuffer_p.h>
-#include <private/qopenglcontext_p.h>
-
-// ### remove
-#include <private/qquicktext_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGNode;
-class QImage;
-class TextureReference;
-class QSGDistanceFieldGlyphCacheManager;
-class QSGDistanceFieldGlyphNode;
-
-// TODO: Rename from XInterface to AbstractX.
-class Q_DECLARATIVE_EXPORT QSGRectangleNode : public QSGGeometryNode
-{
-public:
- virtual void setRect(const QRectF &rect) = 0;
- virtual void setColor(const QColor &color) = 0;
- virtual void setPenColor(const QColor &color) = 0;
- virtual void setPenWidth(qreal width) = 0;
- virtual void setGradientStops(const QGradientStops &stops) = 0;
- virtual void setRadius(qreal radius) = 0;
- virtual void setAligned(bool aligned) = 0;
-
- virtual void update() = 0;
-};
-
-
-class Q_DECLARATIVE_EXPORT QSGImageNode : public QSGGeometryNode
-{
-public:
- virtual void setTargetRect(const QRectF &rect) = 0;
- virtual void setSourceRect(const QRectF &rect) = 0;
- virtual void setTexture(QSGTexture *texture) = 0;
-
- virtual void setMipmapFiltering(QSGTexture::Filtering filtering) = 0;
- virtual void setFiltering(QSGTexture::Filtering filtering) = 0;
- virtual void setHorizontalWrapMode(QSGTexture::WrapMode wrapMode) = 0;
- virtual void setVerticalWrapMode(QSGTexture::WrapMode wrapMode) = 0;
-
- virtual void update() = 0;
-};
-
-
-class Q_DECLARATIVE_EXPORT QSGGlyphNode : public QSGGeometryNode
-{
-public:
- enum AntialiasingMode
- {
- GrayAntialiasing,
- LowQualitySubPixelAntialiasing,
- HighQualitySubPixelAntialiasing
- };
-
- virtual void setGlyphs(const QPointF &position, const QGlyphRun &glyphs) = 0;
- virtual void setColor(const QColor &color) = 0;
- virtual void setStyle(QQuickText::TextStyle style) = 0;
- virtual void setStyleColor(const QColor &color) = 0;
- virtual QPointF baseLine() const = 0;
-
- virtual QRectF boundingRect() const { return m_bounding_rect; }
- virtual void setBoundingRect(const QRectF &bounds) { m_bounding_rect = bounds; }
-
- virtual void setPreferredAntialiasingMode(AntialiasingMode) = 0;
-
- virtual void update() = 0;
-
-protected:
- QRectF m_bounding_rect;
-};
-
-class Q_DECLARATIVE_EXPORT QSGDistanceFieldGlyphCache
-{
-public:
- QSGDistanceFieldGlyphCache(QSGDistanceFieldGlyphCacheManager *man, QOpenGLContext *c, const QRawFont &font);
- virtual ~QSGDistanceFieldGlyphCache();
-
- struct Metrics {
- qreal width;
- qreal height;
- qreal baselineX;
- qreal baselineY;
-
- bool isNull() const { return width == 0 || height == 0; }
- };
-
- struct TexCoord {
- qreal x;
- qreal y;
- qreal width;
- qreal height;
- qreal xMargin;
- qreal yMargin;
-
- TexCoord() : x(0), y(0), width(-1), height(-1), xMargin(0), yMargin(0) { }
-
- bool isNull() const { return width <= 0 || height <= 0; }
- bool isValid() const { return width >= 0 && height >= 0; }
- };
-
- struct Texture {
- GLuint textureId;
- QSize size;
-
- Texture() : textureId(0), size(QSize()) { }
- bool operator == (const Texture &other) const { return textureId == other.textureId; }
- };
-
- const QSGDistanceFieldGlyphCacheManager *manager() const { return m_manager; }
-
- const QRawFont &font() const { return m_font; }
-
- qreal fontScale() const;
- int distanceFieldRadius() const;
- int glyphCount() const { return m_glyphCount; }
- bool doubleGlyphResolution() const { return m_cacheData->doubleGlyphResolution; }
-
- Metrics glyphMetrics(glyph_t glyph);
- TexCoord glyphTexCoord(glyph_t glyph) const;
- const Texture *glyphTexture(glyph_t glyph) const;
-
- void populate(const QVector<glyph_t> &glyphs);
- void release(const QVector<glyph_t> &glyphs);
-
- void update();
-
- void registerGlyphNode(QSGDistanceFieldGlyphNode *node);
- void unregisterGlyphNode(QSGDistanceFieldGlyphNode *node);
-
-protected:
- struct GlyphPosition {
- glyph_t glyph;
- QPointF position;
- };
-
- virtual void requestGlyphs(const QVector<glyph_t> &glyphs) = 0;
- virtual void storeGlyphs(const QHash<glyph_t, QImage> &glyphs) = 0;
- virtual void releaseGlyphs(const QVector<glyph_t> &glyphs) = 0;
-
- void addGlyphPositions(const QList<GlyphPosition> &glyphs);
- void addGlyphTextures(const QVector<glyph_t> &glyphs, const Texture &tex);
- void markGlyphsToRender(const QVector<glyph_t> &glyphs);
- void removeGlyph(glyph_t glyph);
-
- void updateTexture(GLuint oldTex, GLuint newTex, const QSize &newTexSize);
-
- bool containsGlyph(glyph_t glyph) const;
-
- QOpenGLContext *ctx;
-
-private:
- struct GlyphCacheData : public QOpenGLSharedResource {
- QList<Texture> textures;
- QHash<glyph_t, Texture*> glyphTextures;
- QHash<glyph_t, TexCoord> texCoords;
- QDataBuffer<glyph_t> pendingGlyphs;
- QHash<glyph_t, QPainterPath> glyphPaths;
- bool doubleGlyphResolution;
- QLinkedList<QSGDistanceFieldGlyphNode*> m_registeredNodes;
-
- GlyphCacheData(QOpenGLContext *ctx)
- : QOpenGLSharedResource(ctx->shareGroup())
- , pendingGlyphs(64)
- , doubleGlyphResolution(false)
- {}
-
- void invalidateResource()
- {
- textures.clear();
- glyphTextures.clear();
- texCoords.clear();
- }
-
- void freeResource(QOpenGLContext *)
- {
- }
- };
-
- QSGDistanceFieldGlyphCacheManager *m_manager;
-
- QRawFont m_font;
- QRawFont m_referenceFont;
-
- int m_glyphCount;
- QHash<glyph_t, Metrics> m_metrics;
-
- GlyphCacheData *cacheData();
- GlyphCacheData *m_cacheData;
- static QHash<QString, QOpenGLMultiGroupSharedResource> m_caches_data;
-};
-
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/scenegraph/qsgcontext.cpp b/src/declarative/scenegraph/qsgcontext.cpp
deleted file mode 100644
index 1545303d4a..0000000000
--- a/src/declarative/scenegraph/qsgcontext.cpp
+++ /dev/null
@@ -1,512 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <private/qsgcontext_p.h>
-#include <private/qsgrenderer_p.h>
-#include "qsgnode.h"
-
-#include <private/qdeclarativepixmapcache_p.h>
-
-#include <private/qsgdefaultrenderer_p.h>
-
-#include <private/qsgdistancefieldutil_p.h>
-#include <private/qsgdefaultdistancefieldglyphcache_p.h>
-#include <private/qsgdefaultrectanglenode_p.h>
-#include <private/qsgdefaultimagenode_p.h>
-#include <private/qsgdefaultglyphnode_p.h>
-#include <private/qsgdistancefieldglyphnode_p.h>
-
-#include <private/qsgtexture_p.h>
-#include <QGuiApplication>
-#include <QOpenGLContext>
-
-#include <QDeclarativeImageProvider>
-
-#include <private/qobject_p.h>
-#include <qmutex.h>
-
-DEFINE_BOOL_CONFIG_OPTION(qmlFlashMode, QML_FLASH_MODE)
-DEFINE_BOOL_CONFIG_OPTION(qmlTranslucentMode, QML_TRANSLUCENT_MODE)
-DEFINE_BOOL_CONFIG_OPTION(qmlDisableDistanceField, QML_DISABLE_DISTANCEFIELD)
-
-/*
- Comments about this class from Gunnar:
-
- The QSGContext class is right now two things.. The first is the
- adaptation layer and central storage ground for all the things
- in the scene graph, like textures and materials. This part really
- belongs inside the scene graph coreapi.
-
- The other part is the QML adaptation classes, like how to implement
- rectangle nodes. This is not part of the scene graph core API, but
- more part of the QML adaptation of scene graph.
-
- If we ever move the scene graph core API into its own thing, this class
- needs to be split in two. Right now its one because we're lazy when it comes
- to defining plugin interfaces..
-*/
-
-
-QT_BEGIN_NAMESPACE
-
-class QSGContextPrivate : public QObjectPrivate
-{
-public:
- QSGContextPrivate()
- : rootNode(0)
- , renderer(0)
- , gl(0)
- , distanceFieldCacheManager(0)
- , flashMode(qmlFlashMode())
- , distanceFieldDisabled(qmlDisableDistanceField())
- {
- renderAlpha = qmlTranslucentMode() ? 0.5 : 1;
- }
-
- ~QSGContextPrivate()
- {
- }
-
- QSGRootNode *rootNode;
- QSGRenderer *renderer;
-
- QOpenGLContext *gl;
-
- QHash<QSGMaterialType *, QSGMaterialShader *> materials;
- QHash<QDeclarativeTextureFactory *, QSGTexture *> textures;
-
- QSGDistanceFieldGlyphCacheManager *distanceFieldCacheManager;
-
- bool flashMode;
- float renderAlpha;
- bool distanceFieldDisabled;
-};
-
-
-/*!
- \class QSGContext
-
- \brief The QSGContext holds the scene graph entry points for one QML engine.
-
- The context is not ready for use until it has a QOpenGLContext. Once that happens,
- the scene graph population can start.
-
- \internal
- */
-
-QSGContext::QSGContext(QObject *parent) :
- QObject(*(new QSGContextPrivate), parent)
-{
-}
-
-
-QSGContext::~QSGContext()
-{
- Q_D(QSGContext);
- qDeleteAll(d->textures.values());
- d->textures.clear();
- delete d->renderer;
- delete d->rootNode;
- qDeleteAll(d->materials.values());
- delete d->distanceFieldCacheManager;
-}
-
-
-QSGTexture *QSGContext::textureForFactory(QDeclarativeTextureFactory *factory)
-{
- Q_D(QSGContext);
- if (!factory)
- return 0;
-
- QSGTexture *texture = d->textures.value(factory);
- if (!texture) {
- if (QDeclarativeDefaultTextureFactory *dtf = qobject_cast<QDeclarativeDefaultTextureFactory *>(factory))
- texture = createTexture(dtf->image());
- else
- texture = factory->createTexture();
- d->textures.insert(factory, texture);
- connect(factory, SIGNAL(destroyed(QObject *)), this, SLOT(textureFactoryDestroyed(QObject *)));
- }
- return texture;
-}
-
-
-void QSGContext::textureFactoryDestroyed(QObject *o)
-{
- Q_D(QSGContext);
- QDeclarativeTextureFactory *f = static_cast<QDeclarativeTextureFactory *>(o);
-
- // This function will only be called on the scene graph thread, so it is
- // safe to directly delete the texture here.
- delete d->textures.take(f);
-}
-
-
-
-/*!
- Returns the renderer. The renderer instance is created through the adaptation layer.
- */
-QSGRenderer *QSGContext::renderer() const
-{
- Q_D(const QSGContext);
- return d->renderer;
-}
-
-
-/*!
- Returns the root node. The root node instance is only created once the scene graph
- context becomes ready.
- */
-QSGRootNode *QSGContext::rootNode() const
-{
- Q_D(const QSGContext);
- return d->rootNode;
-}
-
-
-QOpenGLContext *QSGContext::glContext() const
-{
- Q_D(const QSGContext);
- return d->gl;
-}
-
-/*!
- Initializes the scene graph context with the GL context \a context. This also
- emits the ready() signal so that the QML graph can start building scene graph nodes.
- */
-void QSGContext::initialize(QOpenGLContext *context)
-{
- Q_D(QSGContext);
-
- Q_ASSERT(!d->gl);
-
- d->gl = context;
-
- d->renderer = createRenderer();
- d->renderer->setClearColor(Qt::white);
-
- d->rootNode = new QSGRootNode();
- d->renderer->setRootNode(d->rootNode);
-
- emit ready();
-}
-
-
-/*!
- Returns if the scene graph context is ready or not, meaning that it has a valid
- GL context.
- */
-bool QSGContext::isReady() const
-{
- Q_D(const QSGContext);
- return d->gl;
-}
-
-
-void QSGContext::renderNextFrame(QOpenGLFramebufferObject *fbo)
-{
- Q_D(QSGContext);
-
- if (fbo) {
- QSGBindableFbo bindable(fbo);
- d->renderer->renderScene(bindable);
- } else {
- d->renderer->renderScene();
- }
-
-}
-
-/*!
- Factory function for scene graph backends of the Rectangle element.
- */
-QSGRectangleNode *QSGContext::createRectangleNode()
-{
- return new QSGDefaultRectangleNode(this);
-}
-
-/*!
- Factory function for scene graph backends of the Image element.
- */
-QSGImageNode *QSGContext::createImageNode()
-{
- return new QSGDefaultImageNode;
-}
-
-/*!
- Factory function for scene graph backends of the distance-field glyph cache.
- */
-QSGDistanceFieldGlyphCache *QSGContext::createDistanceFieldGlyphCache(const QRawFont &font)
-{
- Q_D(QSGContext);
- return new QSGDefaultDistanceFieldGlyphCache(d->distanceFieldCacheManager, glContext(), font);
-}
-
-/*!
- Factory function for scene graph backends of the Text elements;
- */
-QSGGlyphNode *QSGContext::createGlyphNode()
-{
- Q_D(QSGContext);
-
- // ### Do something with these before final release...
- static bool doSubpixel = qApp->arguments().contains(QLatin1String("--text-subpixel-antialiasing"));
- static bool doLowQualSubpixel = qApp->arguments().contains(QLatin1String("--text-subpixel-antialiasing-lowq"));
- static bool doGray = qApp->arguments().contains(QLatin1String("--text-gray-antialiasing"));
-
- if (d->distanceFieldDisabled) {
- return new QSGDefaultGlyphNode;
- } else {
- if (!d->distanceFieldCacheManager) {
- d->distanceFieldCacheManager = new QSGDistanceFieldGlyphCacheManager(this);
- if (doSubpixel)
- d->distanceFieldCacheManager->setDefaultAntialiasingMode(QSGGlyphNode::HighQualitySubPixelAntialiasing);
- else if (doLowQualSubpixel)
- d->distanceFieldCacheManager->setDefaultAntialiasingMode(QSGGlyphNode::LowQualitySubPixelAntialiasing);
- else if (doGray)
- d->distanceFieldCacheManager->setDefaultAntialiasingMode(QSGGlyphNode::GrayAntialiasing);
- }
-
- QSGGlyphNode *node = new QSGDistanceFieldGlyphNode(d->distanceFieldCacheManager);
- return node;
- }
-}
-
-/*!
- Factory function for the scene graph renderers.
-
- The renderers are used for the toplevel renderer and once for every
- QQuickShaderEffectSource used in the QML scene.
- */
-QSGRenderer *QSGContext::createRenderer()
-{
- // ### Do something with this before release...
- static bool doFrontToBack = qApp->arguments().contains(QLatin1String("--opaque-front-to-back"));
- QSGDefaultRenderer *renderer = new QSGDefaultRenderer(this);
- if (doFrontToBack) {
- printf("QSGContext: Sorting opaque nodes front to back...\n");
- renderer->setSortFrontToBackEnabled(true);
- }
- return renderer;
-}
-
-
-
-/*!
- Return true if the image provider supports direct decoding of images,
- straight into textures without going through a QImage first.
-
- If the implementation returns true from this function, the decodeImageToTexture() function
- will be called to read data from a QIODevice, rather than QML decoding
- the image using QImageReader and passing the result to setImage().
-
- \warning This function will be called from outside the GUI and rendering threads
- and must not make use of OpenGL.
- */
-
-bool QSGContext::canDecodeImageToTexture() const
-{
- return true;
-}
-
-
-
-/*!
- Decode the data in \a dev directly to a texture provider of \a requestSize size.
- The size of the decoded data should be written to \a impsize.
-
- If the implementation fails to decode the image data, it should return 0. The
- image data will then be decoded normally.
-
- \warning This function will be called from outside the GUI and renderer threads
- and must not make use of GL calls.
- */
-
-QSGTexture *QSGContext::decodeImageToTexture(QIODevice *dev,
- QSize *size,
- const QSize &requestSize)
-{
- Q_UNUSED(dev);
- Q_UNUSED(size);
- Q_UNUSED(requestSize);
- return 0;
-}
-
-
-
-QSurfaceFormat QSGContext::defaultSurfaceFormat() const
-{
- QSurfaceFormat format;
- format.setDepthBufferSize(24);
- format.setStencilBufferSize(8);
- format.setSamples(16);
- return format;
-}
-
-
-/*!
- Factory function for texture objects.
-
- If \a image is a valid image, the QSGTexture::setImage function
- will be called with \a image as argument.
- */
-
-QSGTexture *QSGContext::createTexture(const QImage &image) const
-{
- QSGPlainTexture *t = new QSGPlainTexture();
- if (!image.isNull())
- t->setImage(image);
- return t;
-}
-
-
-
-/*!
- Returns the minimum supported framebuffer object size.
- */
-
-QSize QSGContext::minimumFBOSize() const
-{
-#ifdef Q_OS_MAC
- return QSize(33, 33);
-#else
- return QSize(1, 1);
-#endif
-}
-
-
-
-/*!
- Returns a material shader for the given material.
- */
-
-QSGMaterialShader *QSGContext::prepareMaterial(QSGMaterial *material)
-{
- Q_D(QSGContext);
- QSGMaterialType *type = material->type();
- QSGMaterialShader *shader = d->materials.value(type);
- if (shader)
- return shader;
-
- shader = material->createShader();
- shader->compile();
- shader->initialize();
- d->materials[type] = shader;
-
- return shader;
-}
-
-
-
-/*!
- Sets whether the scene graph should render with flashing update rectangles or not
- */
-
-void QSGContext::setFlashModeEnabled(bool enabled)
-{
- d_func()->flashMode = enabled;
-}
-
-
-/*!
- Returns true if the scene graph should be rendered with flashing update rectangles
- */
-bool QSGContext::isFlashModeEnabled() const
-{
- return d_func()->flashMode;
-}
-
-
-/*!
- Sets the toplevel opacity for rendering. This value will be multiplied into all
- drawing calls where possible.
-
- The default value is 1. Any other value will cause artifacts and is primarily
- useful for debugging.
- */
-void QSGContext::setRenderAlpha(qreal renderAlpha)
-{
- d_func()->renderAlpha = renderAlpha;
-}
-
-
-/*!
- Returns the toplevel opacity used for rendering.
-
- The default value is 1.
-
- \sa setRenderAlpha()
- */
-qreal QSGContext::renderAlpha() const
-{
- return d_func()->renderAlpha;
-}
-
-
-/*!
- Sets whether or not the scene graph should use the distance field technique to render text
- */
-void QSGContext::setDistanceFieldEnabled(bool enabled)
-{
- d_func()->distanceFieldDisabled = !enabled;
-}
-
-
-/*!
- Returns true if the scene graph uses the distance field technique to render text
- */
-bool QSGContext::isDistanceFieldEnabled() const
-{
- return !d_func()->distanceFieldDisabled;
-}
-
-
-
-/*!
- Creates a new animation driver.
- */
-
-QAnimationDriver *QSGContext::createAnimationDriver(QObject *parent)
-{
- return new QAnimationDriver(parent);
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgcontext_p.h b/src/declarative/scenegraph/qsgcontext_p.h
deleted file mode 100644
index ed1654b8fc..0000000000
--- a/src/declarative/scenegraph/qsgcontext_p.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGCONTEXT_H
-#define QSGCONTEXT_H
-
-#include <QtCore/QObject>
-#include <QtCore/qabstractanimation.h>
-
-#include <QtGui/QImage>
-#include <QtGui/QSurfaceFormat>
-
-#include <private/qrawfont_p.h>
-
-#include "qsgnode.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGContextPrivate;
-class QSGRectangleNode;
-class QSGImageNode;
-class QSGGlyphNode;
-class QSGRenderer;
-class QSGDistanceFieldGlyphCache;
-
-class QSGTexture;
-class QSGMaterial;
-class QSGMaterialShader;
-class QSGEngine;
-
-class QOpenGLContext;
-class QOpenGLFramebufferObject;
-
-class QDeclarativeTextureFactory;
-
-class Q_DECLARATIVE_EXPORT QSGContext : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QSGContext)
-
-public:
- explicit QSGContext(QObject *parent = 0);
- ~QSGContext();
-
- virtual void initialize(QOpenGLContext *context);
-
- QSGRenderer *renderer() const;
-
- void setRootNode(QSGRootNode *node);
- QSGRootNode *rootNode() const;
-
- QOpenGLContext *glContext() const;
-
- bool isReady() const;
-
- QSGMaterialShader *prepareMaterial(QSGMaterial *material);
-
- virtual void renderNextFrame(QOpenGLFramebufferObject *fbo = 0);
-
- virtual QSGDistanceFieldGlyphCache *createDistanceFieldGlyphCache(const QRawFont &font);
-
- virtual QSGRectangleNode *createRectangleNode();
- virtual QSGImageNode *createImageNode();
- virtual QSGGlyphNode *createGlyphNode();
- virtual QSGRenderer *createRenderer();
-
- virtual bool canDecodeImageToTexture() const;
- virtual QSGTexture *decodeImageToTexture(QIODevice *dev,
- QSize *size,
- const QSize &requestSize);
- virtual QSGTexture *createTexture(const QImage &image = QImage()) const;
- virtual QSize minimumFBOSize() const;
-
- virtual QSurfaceFormat defaultSurfaceFormat() const;
-
- QSGTexture *textureForFactory(QDeclarativeTextureFactory *factory);
-
- static QSGContext *createDefaultContext();
-
- void setFlashModeEnabled(bool enabled);
- bool isFlashModeEnabled() const;
-
- void setRenderAlpha(qreal renderAlpha);
- qreal renderAlpha() const;
-
- void setDistanceFieldEnabled(bool enabled);
- bool isDistanceFieldEnabled() const;
-
- virtual QAnimationDriver *createAnimationDriver(QObject *parent);
-
-signals:
- void ready();
-
-public slots:
- void textureFactoryDestroyed(QObject *o);
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSGCONTEXT_H
diff --git a/src/declarative/scenegraph/qsgcontextplugin.cpp b/src/declarative/scenegraph/qsgcontextplugin.cpp
deleted file mode 100644
index 79bcbf9c04..0000000000
--- a/src/declarative/scenegraph/qsgcontextplugin.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgcontextplugin_p.h"
-#include <private/qsgcontext_p.h>
-#include <QtGui/qguiapplication.h>
-#include <QtCore/private/qfactoryloader_p.h>
-#include <QtCore/qlibraryinfo.h>
-
-QT_BEGIN_NAMESPACE
-
-QSGContextPlugin::QSGContextPlugin(QObject *parent)
- : QObject(parent)
-{
-}
-
-QSGContextPlugin::~QSGContextPlugin()
-{
-}
-
-#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
-Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
- (QSGContextFactoryInterface_iid, QLatin1String("/scenegraph")))
-#endif
-
-/*!
- \fn QSGContext *QSGContext::createDefaultContext()
-
- Creates a default scene graph context for the current hardware.
- This may load a device-specific plugin.
-*/
-QSGContext *QSGContext::createDefaultContext()
-{
- const QStringList args = QGuiApplication::arguments();
- QString device;
- for (int index = 0; index < args.count(); ++index) {
- if (args.at(index).startsWith(QLatin1String("--device="))) {
- device = args.at(index).mid(9);
- break;
- }
- }
- if (device.isEmpty())
- device = QString::fromLocal8Bit(qgetenv("QMLSCENE_DEVICE"));
- if (device.isEmpty())
- return new QSGContext();
-
-#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
- if (QSGContextFactoryInterface *factory
- = qobject_cast<QSGContextFactoryInterface*>
- (loader()->instance(device))) {
- QSGContext *context = factory->create(device);
- if (context)
- return context;
- }
-#ifndef QT_NO_DEBUG
- qWarning("Could not create scene graph context for device '%s'"
- " - check that plugins are installed correctly in %s",
- qPrintable(device),
- qPrintable(QLibraryInfo::location(QLibraryInfo::PluginsPath)));
-#endif
-#endif // QT_NO_LIBRARY || QT_NO_SETTINGS
-
- return new QSGContext();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgcontextplugin_p.h b/src/declarative/scenegraph/qsgcontextplugin_p.h
deleted file mode 100644
index 78c4a25372..0000000000
--- a/src/declarative/scenegraph/qsgcontextplugin_p.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGCONTEXTPLUGIN_H
-#define QSGCONTEXTPLUGIN_H
-
-#include <QtCore/qplugin.h>
-#include <QtCore/qfactoryinterface.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGContext;
-
-struct Q_DECLARATIVE_EXPORT QSGContextFactoryInterface : public QFactoryInterface
-{
- virtual QSGContext *create(const QString &key) const = 0;
-};
-
-#define QSGContextFactoryInterface_iid \
- "com.trolltech.Qt.QSGContextFactoryInterface"
-Q_DECLARE_INTERFACE(QSGContextFactoryInterface, QSGContextFactoryInterface_iid)
-
-class Q_DECLARATIVE_EXPORT QSGContextPlugin : public QObject, public QSGContextFactoryInterface
-{
- Q_OBJECT
- Q_INTERFACES(QSGContextFactoryInterface:QFactoryInterface)
-public:
- explicit QSGContextPlugin(QObject *parent = 0);
- virtual ~QSGContextPlugin();
-
- virtual QStringList keys() const = 0;
- virtual QSGContext *create(const QString &key) const = 0;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSGCONTEXTPLUGIN_H
diff --git a/src/declarative/scenegraph/qsgdefaultdistancefieldglyphcache.cpp b/src/declarative/scenegraph/qsgdefaultdistancefieldglyphcache.cpp
deleted file mode 100644
index 3dfa1bd269..0000000000
--- a/src/declarative/scenegraph/qsgdefaultdistancefieldglyphcache.cpp
+++ /dev/null
@@ -1,324 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgdefaultdistancefieldglyphcache_p.h"
-
-#include <private/qsgdistancefieldutil_p.h>
-#include <qopenglfunctions.h>
-
-QT_BEGIN_NAMESPACE
-
-QHash<QString, QOpenGLMultiGroupSharedResource> QSGDefaultDistanceFieldGlyphCache::m_textures_data;
-
-QSGDefaultDistanceFieldGlyphCache::DistanceFieldTextureData *QSGDefaultDistanceFieldGlyphCache::textureData(QOpenGLContext *c)
-{
- QString key = QString::fromLatin1("%1_%2_%3_%4")
- .arg(font().familyName())
- .arg(font().styleName())
- .arg(font().weight())
- .arg(font().style());
- return m_textures_data[key].value<QSGDefaultDistanceFieldGlyphCache::DistanceFieldTextureData>(c);
-}
-
-QSGDefaultDistanceFieldGlyphCache::QSGDefaultDistanceFieldGlyphCache(QSGDistanceFieldGlyphCacheManager *man, QOpenGLContext *c, const QRawFont &font)
- : QSGDistanceFieldGlyphCache(man, c, font)
- , m_maxTextureSize(0)
-{
- m_textureData = textureData(c);
-}
-
-void QSGDefaultDistanceFieldGlyphCache::requestGlyphs(const QVector<glyph_t> &glyphs)
-{
- int count = glyphs.count();
-
- // Avoid useless and costly glyph re-generation
- if (cacheIsFull() && !m_textureData->unusedGlyphs.isEmpty()) {
- for (int i = 0; i < count; ++i) {
- glyph_t glyphIndex = glyphs.at(i);
- if (containsGlyph(glyphIndex) && m_textureData->unusedGlyphs.contains(glyphIndex))
- m_textureData->unusedGlyphs.remove(glyphIndex);
- }
- }
-
- QList<GlyphPosition> glyphPositions;
- QVector<glyph_t> glyphsToRender;
-
- for (int i = 0; i < count; ++i) {
- glyph_t glyphIndex = glyphs.at(i);
-
- if (++m_textureData->glyphRefCount[glyphIndex] == 1)
- m_textureData->unusedGlyphs.remove(glyphIndex);
-
- if (cacheIsFull() && m_textureData->unusedGlyphs.isEmpty())
- continue;
-
- GlyphPosition p;
- p.glyph = glyphIndex;
- p.position = QPointF(m_textureData->currX, m_textureData->currY);
-
- if (!cacheIsFull()) {
- m_textureData->currX += QT_DISTANCEFIELD_TILESIZE(doubleGlyphResolution());
- if (m_textureData->currX >= maxTextureSize()) {
- m_textureData->currX = 0;
- m_textureData->currY += QT_DISTANCEFIELD_TILESIZE(doubleGlyphResolution());
- }
- } else {
- // Recycle glyphs
- if (!m_textureData->unusedGlyphs.isEmpty()) {
- glyph_t unusedGlyph = *m_textureData->unusedGlyphs.constBegin();
- TexCoord unusedCoord = glyphTexCoord(unusedGlyph);
- p.position = QPointF(unusedCoord.x, unusedCoord.y);
- m_textureData->unusedGlyphs.remove(unusedGlyph);
- removeGlyph(unusedGlyph);
- }
- }
-
- if (p.position.y() < maxTextureSize()) {
- glyphPositions.append(p);
- glyphsToRender.append(glyphIndex);
- }
- }
-
- addGlyphPositions(glyphPositions);
- markGlyphsToRender(glyphsToRender);
-}
-
-void QSGDefaultDistanceFieldGlyphCache::storeGlyphs(const QHash<glyph_t, QImage> &glyphs)
-{
- int requiredWidth = maxTextureSize();
- int rows = 128 / (requiredWidth / QT_DISTANCEFIELD_TILESIZE(doubleGlyphResolution())); // Enough rows to fill the latin1 set by default..
- int requiredHeight = qMin(maxTextureSize(),
- qMax(m_textureData->currY + QT_DISTANCEFIELD_TILESIZE(doubleGlyphResolution()),
- QT_DISTANCEFIELD_TILESIZE(doubleGlyphResolution()) * rows));
-
- resizeTexture((requiredWidth), (requiredHeight));
- glBindTexture(GL_TEXTURE_2D, m_textureData->texture);
-
- QVector<glyph_t> glyphTextures;
-
- QHash<glyph_t, QImage>::const_iterator it;
- for (it = glyphs.constBegin(); it != glyphs.constEnd(); ++it) {
- glyph_t glyphIndex = it.key();
- TexCoord c = glyphTexCoord(glyphIndex);
-
- glyphTextures.append(glyphIndex);
-
- QImage glyph = it.value();
-
- if (useWorkaroundBrokenFBOReadback()) {
- uchar *inBits = glyph.scanLine(0);
- uchar *outBits = m_textureData->image.scanLine(int(c.y)) + int(c.x);
- for (int y = 0; y < glyph.height(); ++y) {
- qMemCopy(outBits, inBits, glyph.width());
- inBits += glyph.bytesPerLine();
- outBits += m_textureData->image.bytesPerLine();
- }
- }
-
- glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y, glyph.width(), glyph.height(), GL_ALPHA, GL_UNSIGNED_BYTE, glyph.constBits());
- }
-
- Texture t;
- t.textureId = m_textureData->texture;
- t.size = m_textureData->size;
- addGlyphTextures(glyphTextures, t);
-}
-
-void QSGDefaultDistanceFieldGlyphCache::releaseGlyphs(const QVector<glyph_t> &glyphs)
-{
- int count = glyphs.count();
- for (int i = 0; i < count; ++i) {
- glyph_t glyphIndex = glyphs.at(i);
- if (--m_textureData->glyphRefCount[glyphIndex] == 0 && !glyphTexCoord(glyphIndex).isNull())
- m_textureData->unusedGlyphs.insert(glyphIndex);
- }
-}
-
-void QSGDefaultDistanceFieldGlyphCache::createTexture(int width, int height)
-{
- if (useWorkaroundBrokenFBOReadback() && m_textureData->image.isNull())
- m_textureData->image = QImage(width, height, QImage::Format_Indexed8);
-
- while (glGetError() != GL_NO_ERROR) { }
-
- glGenTextures(1, &m_textureData->texture);
- glBindTexture(GL_TEXTURE_2D, m_textureData->texture);
-
- glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, 0);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
- m_textureData->size = QSize(width, height);
-
- GLuint error = glGetError();
- if (error != GL_NO_ERROR) {
- glBindTexture(GL_TEXTURE_2D, 0);
- glDeleteTextures(1, &m_textureData->texture);
- m_textureData->texture = 0;
- }
-
-}
-
-void QSGDefaultDistanceFieldGlyphCache::resizeTexture(int width, int height)
-{
- int oldWidth = m_textureData->size.width();
- int oldHeight = m_textureData->size.height();
- if (width == oldWidth && height == oldHeight)
- return;
-
- GLuint oldTexture = m_textureData->texture;
- createTexture(width, height);
-
- if (!oldTexture)
- return;
-
- updateTexture(oldTexture, m_textureData->texture, m_textureData->size);
-
- if (useWorkaroundBrokenFBOReadback()) {
- glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, oldWidth, oldHeight, GL_ALPHA, GL_UNSIGNED_BYTE, m_textureData->image.constBits());
- m_textureData->image = m_textureData->image.copy(0, 0, width, height);
- glDeleteTextures(1, &oldTexture);
- return;
- }
-
- if (!m_textureData->blitProgram)
- m_textureData->createBlitProgram();
-
- Q_ASSERT(m_textureData->blitProgram);
-
- if (!m_textureData->fbo)
- ctx->functions()->glGenFramebuffers(1, &m_textureData->fbo);
- ctx->functions()->glBindFramebuffer(GL_FRAMEBUFFER, m_textureData->fbo);
-
- GLuint tmp_texture;
- glGenTextures(1, &tmp_texture);
- glBindTexture(GL_TEXTURE_2D, tmp_texture);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, oldWidth, oldHeight, 0,
- GL_RGBA, GL_UNSIGNED_BYTE, NULL);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glBindTexture(GL_TEXTURE_2D, 0);
- ctx->functions()->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- GL_TEXTURE_2D, tmp_texture, 0);
-
- ctx->functions()->glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, oldTexture);
-
- // save current render states
- GLboolean stencilTestEnabled;
- GLboolean depthTestEnabled;
- GLboolean scissorTestEnabled;
- GLboolean blendEnabled;
- GLint viewport[4];
- GLint oldProgram;
- glGetBooleanv(GL_STENCIL_TEST, &stencilTestEnabled);
- glGetBooleanv(GL_DEPTH_TEST, &depthTestEnabled);
- glGetBooleanv(GL_SCISSOR_TEST, &scissorTestEnabled);
- glGetBooleanv(GL_BLEND, &blendEnabled);
- glGetIntegerv(GL_VIEWPORT, &viewport[0]);
- glGetIntegerv(GL_CURRENT_PROGRAM, &oldProgram);
-
- glDisable(GL_STENCIL_TEST);
- glDisable(GL_DEPTH_TEST);
- glDisable(GL_SCISSOR_TEST);
- glDisable(GL_BLEND);
-
- glViewport(0, 0, oldWidth, oldHeight);
-
- ctx->functions()->glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, m_textureData->blitVertexCoordinateArray);
- ctx->functions()->glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, m_textureData->blitTextureCoordinateArray);
-
- m_textureData->blitProgram->bind();
- m_textureData->blitProgram->enableAttributeArray(int(QT_VERTEX_COORDS_ATTR));
- m_textureData->blitProgram->enableAttributeArray(int(QT_TEXTURE_COORDS_ATTR));
- m_textureData->blitProgram->disableAttributeArray(int(QT_OPACITY_ATTR));
- m_textureData->blitProgram->setUniformValue("imageTexture", GLuint(0));
-
- glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
-
- glBindTexture(GL_TEXTURE_2D, m_textureData->texture);
-
- glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, oldWidth, oldHeight);
-
- ctx->functions()->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- GL_RENDERBUFFER, 0);
- glDeleteTextures(1, &tmp_texture);
- glDeleteTextures(1, &oldTexture);
-
- ctx->functions()->glBindFramebuffer(GL_FRAMEBUFFER, 0);
-
- // restore render states
- if (stencilTestEnabled)
- glEnable(GL_STENCIL_TEST);
- if (depthTestEnabled)
- glEnable(GL_DEPTH_TEST);
- if (scissorTestEnabled)
- glEnable(GL_SCISSOR_TEST);
- if (blendEnabled)
- glEnable(GL_BLEND);
- glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
- ctx->functions()->glUseProgram(oldProgram);
-}
-
-bool QSGDefaultDistanceFieldGlyphCache::useWorkaroundBrokenFBOReadback() const
-{
- static bool set = false;
- static bool useWorkaround = false;
- if (!set) {
- QOpenGLContextPrivate *ctx_p = static_cast<QOpenGLContextPrivate *>(QOpenGLContextPrivate::get(ctx));
- useWorkaround = ctx_p->workaround_brokenFBOReadBack;
- set = true;
- }
- return useWorkaround;
-}
-
-int QSGDefaultDistanceFieldGlyphCache::maxTextureSize() const
-{
- if (!m_maxTextureSize)
- glGetIntegerv(GL_MAX_TEXTURE_SIZE, &m_maxTextureSize);
- return m_maxTextureSize;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgdefaultdistancefieldglyphcache_p.h b/src/declarative/scenegraph/qsgdefaultdistancefieldglyphcache_p.h
deleted file mode 100644
index 28860912c8..0000000000
--- a/src/declarative/scenegraph/qsgdefaultdistancefieldglyphcache_p.h
+++ /dev/null
@@ -1,165 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGDEFAULTDISTANCEFIELDGLYPHCACHE_H
-#define QSGDEFAULTDISTANCEFIELDGLYPHCACHE_H
-
-#include <QtGui/qopenglfunctions.h>
-#include <private/qsgadaptationlayer_p.h>
-#include <qopenglshaderprogram.h>
-#include <QtGui/private/qopenglengineshadersource_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class Q_DECLARATIVE_EXPORT QSGDefaultDistanceFieldGlyphCache : public QSGDistanceFieldGlyphCache
-{
-public:
- QSGDefaultDistanceFieldGlyphCache(QSGDistanceFieldGlyphCacheManager *man, QOpenGLContext *c, const QRawFont &font);
-
- void requestGlyphs(const QVector<glyph_t> &glyphs);
- void storeGlyphs(const QHash<glyph_t, QImage> &glyphs);
- void releaseGlyphs(const QVector<glyph_t> &glyphs);
-
- bool cacheIsFull() const { return m_textureData->currY >= maxTextureSize(); }
- bool useWorkaroundBrokenFBOReadback() const;
- int maxTextureSize() const;
-
-private:
- void createTexture(int width, int height);
- void resizeTexture(int width, int height);
-
- mutable int m_maxTextureSize;
-
- struct DistanceFieldTextureData : public QOpenGLSharedResource {
- GLuint texture;
- GLuint fbo;
- QSize size;
- QHash<glyph_t, quint32> glyphRefCount;
- QSet<glyph_t> unusedGlyphs;
- int currX;
- int currY;
- QImage image;
-
- QOpenGLShaderProgram *blitProgram;
- GLfloat blitVertexCoordinateArray[8];
- GLfloat blitTextureCoordinateArray[8];
-
- DistanceFieldTextureData(QOpenGLContext *ctx)
- : QOpenGLSharedResource(ctx->shareGroup())
- , texture(0)
- , fbo(0)
- , currX(0)
- , currY(0)
- , blitProgram(0)
- {
- blitVertexCoordinateArray[0] = -1.0f;
- blitVertexCoordinateArray[1] = -1.0f;
- blitVertexCoordinateArray[2] = 1.0f;
- blitVertexCoordinateArray[3] = -1.0f;
- blitVertexCoordinateArray[4] = 1.0f;
- blitVertexCoordinateArray[5] = 1.0f;
- blitVertexCoordinateArray[6] = -1.0f;
- blitVertexCoordinateArray[7] = 1.0f;
-
- blitTextureCoordinateArray[0] = 0.0f;
- blitTextureCoordinateArray[1] = 0.0f;
- blitTextureCoordinateArray[2] = 1.0f;
- blitTextureCoordinateArray[3] = 0.0f;
- blitTextureCoordinateArray[4] = 1.0f;
- blitTextureCoordinateArray[5] = 1.0f;
- blitTextureCoordinateArray[6] = 0.0f;
- blitTextureCoordinateArray[7] = 1.0f;
- }
-
- void invalidateResource()
- {
- texture = 0;
- fbo = 0;
- size = QSize();
- delete blitProgram;
- blitProgram = 0;
- }
-
- void freeResource(QOpenGLContext *ctx)
- {
- glDeleteTextures(1, &texture);
- ctx->functions()->glDeleteFramebuffers(1, &fbo);
- delete blitProgram;
- blitProgram = 0;
- }
-
- void createBlitProgram()
- {
- blitProgram = new QOpenGLShaderProgram;
- {
- QString source;
- source.append(QLatin1String(qopenglslMainWithTexCoordsVertexShader));
- source.append(QLatin1String(qopenglslUntransformedPositionVertexShader));
-
- QOpenGLShader *vertexShader = new QOpenGLShader(QOpenGLShader::Vertex, blitProgram);
- vertexShader->compileSourceCode(source);
-
- blitProgram->addShader(vertexShader);
- }
- {
- QString source;
- source.append(QLatin1String(qopenglslMainFragmentShader));
- source.append(QLatin1String(qopenglslImageSrcFragmentShader));
-
- QOpenGLShader *fragmentShader = new QOpenGLShader(QOpenGLShader::Fragment, blitProgram);
- fragmentShader->compileSourceCode(source);
-
- blitProgram->addShader(fragmentShader);
- }
- blitProgram->bindAttributeLocation("vertexCoordsArray", QT_VERTEX_COORDS_ATTR);
- blitProgram->bindAttributeLocation("textureCoordArray", QT_TEXTURE_COORDS_ATTR);
- blitProgram->link();
- }
- };
-
- DistanceFieldTextureData *textureData(QOpenGLContext *c);
- DistanceFieldTextureData *m_textureData;
- static QHash<QString, QOpenGLMultiGroupSharedResource> m_textures_data;
-};
-
-QT_END_NAMESPACE
-
-#endif // QSGDEFAULTDISTANCEFIELDGLYPHCACHE_H
diff --git a/src/declarative/scenegraph/qsgdefaultglyphnode.cpp b/src/declarative/scenegraph/qsgdefaultglyphnode.cpp
deleted file mode 100644
index f41fbe486a..0000000000
--- a/src/declarative/scenegraph/qsgdefaultglyphnode.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgdefaultglyphnode_p.h"
-#include "qsgdefaultglyphnode_p_p.h"
-
-#include <qopenglshaderprogram.h>
-#include <private/qfont_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QSGDefaultGlyphNode::QSGDefaultGlyphNode()
- : m_material(0)
- , m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 0)
-{
- m_geometry.setDrawingMode(GL_TRIANGLES);
- setGeometry(&m_geometry);
-}
-
-QSGDefaultGlyphNode::~QSGDefaultGlyphNode()
-{
- delete m_material;
-}
-
-void QSGDefaultGlyphNode::setColor(const QColor &color)
-{
- m_color = color;
- if (m_material != 0) {
- m_material->setColor(color);
- markDirty(DirtyMaterial);
- }
-}
-
-void QSGDefaultGlyphNode::setGlyphs(const QPointF &position, const QGlyphRun &glyphs)
-{
- if (m_material != 0)
- delete m_material;
-
- QRawFont font = glyphs.rawFont();
- m_material = new QSGTextMaskMaterial(font);
- m_material->setColor(m_color);
-
- QRectF boundingRect;
- m_material->populate(position, glyphs.glyphIndexes(), glyphs.positions(), geometry(),
- &boundingRect, &m_baseLine);
-
- setMaterial(m_material);
- setBoundingRect(boundingRect);
-
- markDirty(DirtyGeometry);
-
-#ifdef QML_RUNTIME_TESTING
- description = QLatin1String("glyphs");
-#endif
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgdefaultglyphnode_p.cpp b/src/declarative/scenegraph/qsgdefaultglyphnode_p.cpp
deleted file mode 100644
index 3476ab1665..0000000000
--- a/src/declarative/scenegraph/qsgdefaultglyphnode_p.cpp
+++ /dev/null
@@ -1,306 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgdefaultglyphnode_p_p.h"
-
-#include <qopenglshaderprogram.h>
-
-#include <QtGui/private/qopengltextureglyphcache_p.h>
-#include <private/qfontengine_p.h>
-#include <private/qopenglextensions_p.h>
-
-#include <private/qsgtexture_p.h>
-
-#include <private/qrawfont_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QSGTextMaskMaterialData : public QSGMaterialShader
-{
-public:
- QSGTextMaskMaterialData();
-
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
- virtual char const *const *attributeNames() const;
-private:
- virtual void initialize();
- virtual const char *vertexShader() const;
- virtual const char *fragmentShader() const;
-
- int m_matrix_id;
- int m_color_id;
- int m_textureScale_id;
-};
-
-const char *QSGTextMaskMaterialData::vertexShader() const {
- return
- "uniform highp mat4 matrix; \n"
- "uniform highp vec2 textureScale; \n"
- "attribute highp vec4 vCoord; \n"
- "attribute highp vec2 tCoord; \n"
- "varying highp vec2 sampleCoord; \n"
- "void main() { \n"
- " sampleCoord = tCoord * textureScale; \n"
- " gl_Position = matrix * vCoord; \n"
- "}";
-}
-
-const char *QSGTextMaskMaterialData::fragmentShader() const {
- return
- "varying highp vec2 sampleCoord; \n"
- "uniform sampler2D texture; \n"
- "uniform lowp vec4 color; \n"
- "void main() { \n"
- " gl_FragColor = color * texture2D(texture, sampleCoord).a; \n"
- "}";
-}
-
-char const *const *QSGTextMaskMaterialData::attributeNames() const
-{
- static char const *const attr[] = { "vCoord", "tCoord", 0 };
- return attr;
-}
-
-QSGTextMaskMaterialData::QSGTextMaskMaterialData()
-{
-}
-
-void QSGTextMaskMaterialData::initialize()
-{
- m_matrix_id = program()->uniformLocation("matrix");
- m_color_id = program()->uniformLocation("color");
- m_textureScale_id = program()->uniformLocation("textureScale");
-}
-
-void QSGTextMaskMaterialData::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
-{
- Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type());
- QSGTextMaskMaterial *material = static_cast<QSGTextMaskMaterial *>(newEffect);
- QSGTextMaskMaterial *oldMaterial = static_cast<QSGTextMaskMaterial *>(oldEffect);
-
- if (oldMaterial == 0 || material->color() != oldMaterial->color() || state.isOpacityDirty()) {
- QVector4D color(material->color().redF(), material->color().greenF(),
- material->color().blueF(), material->color().alphaF());
- color *= state.opacity();
- program()->setUniformValue(m_color_id, color);
- }
-
- bool updated = material->ensureUpToDate();
- Q_ASSERT(material->texture());
-
- Q_ASSERT(oldMaterial == 0 || oldMaterial->texture());
- if (updated
- || oldMaterial == 0
- || oldMaterial->texture()->textureId() != material->texture()->textureId()) {
- program()->setUniformValue(m_textureScale_id, QVector2D(1.0 / material->cacheTextureWidth(),
- 1.0 / material->cacheTextureHeight()));
- glBindTexture(GL_TEXTURE_2D, material->texture()->textureId());
-
- // Set the mag/min filters to be linear. We only need to do this when the texture
- // has been recreated.
- if (updated) {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- }
- }
-
- if (state.isMatrixDirty())
- program()->setUniformValue(m_matrix_id, state.combinedMatrix());
-}
-
-QSGTextMaskMaterial::QSGTextMaskMaterial(const QRawFont &font)
- : m_texture(0), m_glyphCache(), m_font(font)
-{
- init();
-}
-
-QSGTextMaskMaterial::~QSGTextMaskMaterial()
-{
-}
-
-void QSGTextMaskMaterial::init()
-{
- Q_ASSERT(m_font.isValid());
-
- QFontEngineGlyphCache::Type type = QFontEngineGlyphCache::Raster_A8;
- setFlag(Blending, true);
-
- QOpenGLContext *ctx = const_cast<QOpenGLContext *>(QOpenGLContext::currentContext());
- Q_ASSERT(ctx != 0);
-
- QRawFontPrivate *fontD = QRawFontPrivate::get(m_font);
- if (fontD->fontEngine != 0) {
- m_glyphCache = fontD->fontEngine->glyphCache(ctx, type, QTransform());
- if (!m_glyphCache || m_glyphCache->cacheType() != type) {
- m_glyphCache = new QOpenGLTextureGlyphCache(type, QTransform());
- fontD->fontEngine->setGlyphCache(ctx, m_glyphCache.data());
- }
- }
-}
-
-void QSGTextMaskMaterial::populate(const QPointF &p,
- const QVector<quint32> &glyphIndexes,
- const QVector<QPointF> &glyphPositions,
- QSGGeometry *geometry,
- QRectF *boundingRect,
- QPointF *baseLine)
-{
- Q_ASSERT(m_font.isValid());
- QVector<QFixedPoint> fixedPointPositions;
- for (int i=0; i<glyphPositions.size(); ++i)
- fixedPointPositions.append(QFixedPoint::fromPointF(glyphPositions.at(i)));
-
- QTextureGlyphCache *cache = glyphCache();
-
- QRawFontPrivate *fontD = QRawFontPrivate::get(m_font);
- cache->populate(fontD->fontEngine, glyphIndexes.size(), glyphIndexes.constData(),
- fixedPointPositions.data());
- cache->fillInPendingGlyphs();
-
- int margin = cache->glyphMargin();
-
- Q_ASSERT(geometry->indexType() == GL_UNSIGNED_SHORT);
- geometry->allocate(glyphIndexes.size() * 4, glyphIndexes.size() * 6);
- QVector4D *vp = (QVector4D *)geometry->vertexDataAsTexturedPoint2D();
- Q_ASSERT(geometry->sizeOfVertex() == sizeof(QVector4D));
- ushort *ip = geometry->indexDataAsUShort();
-
- QPointF position(p.x(), p.y() - m_font.ascent());
- bool supportsSubPixelPositions = fontD->fontEngine->supportsSubPixelPositions();
- for (int i=0; i<glyphIndexes.size(); ++i) {
- QFixed subPixelPosition;
- if (supportsSubPixelPositions)
- subPixelPosition = fontD->fontEngine->subPixelPositionForX(QFixed::fromReal(glyphPositions.at(i).x()));
-
- QTextureGlyphCache::GlyphAndSubPixelPosition glyph(glyphIndexes.at(i), subPixelPosition);
- const QTextureGlyphCache::Coord &c = cache->coords.value(glyph);
-
- QPointF glyphPosition = glyphPositions.at(i) + position;
- int x = qRound(glyphPosition.x()) + c.baseLineX - margin;
- int y = qRound(glyphPosition.y()) - c.baseLineY - margin;
-
- *boundingRect |= QRectF(x + margin, y + margin, c.w, c.h);
-
- float cx1 = x;
- float cx2 = x + c.w;
- float cy1 = y;
- float cy2 = y + c.h;
-
- float tx1 = c.x;
- float tx2 = (c.x + c.w);
- float ty1 = c.y;
- float ty2 = (c.y + c.h);
-
- if (baseLine->isNull())
- *baseLine = glyphPosition;
-
- vp[4 * i + 0] = QVector4D(cx1, cy1, tx1, ty1);
- vp[4 * i + 1] = QVector4D(cx2, cy1, tx2, ty1);
- vp[4 * i + 2] = QVector4D(cx1, cy2, tx1, ty2);
- vp[4 * i + 3] = QVector4D(cx2, cy2, tx2, ty2);
-
- int o = i * 4;
- ip[6 * i + 0] = o + 0;
- ip[6 * i + 1] = o + 2;
- ip[6 * i + 2] = o + 3;
- ip[6 * i + 3] = o + 3;
- ip[6 * i + 4] = o + 1;
- ip[6 * i + 5] = o + 0;
- }
-}
-
-QSGMaterialType *QSGTextMaskMaterial::type() const
-{
- static QSGMaterialType type;
- return &type;
-}
-
-QOpenGLTextureGlyphCache *QSGTextMaskMaterial::glyphCache() const
-{
- return static_cast<QOpenGLTextureGlyphCache*>(m_glyphCache.data());
-}
-
-QSGMaterialShader *QSGTextMaskMaterial::createShader() const
-{
- return new QSGTextMaskMaterialData;
-}
-
-int QSGTextMaskMaterial::compare(const QSGMaterial *o) const
-{
- Q_ASSERT(o && type() == o->type());
- const QSGTextMaskMaterial *other = static_cast<const QSGTextMaskMaterial *>(o);
- if (m_glyphCache != other->m_glyphCache)
- return m_glyphCache - other->m_glyphCache;
- QRgb c1 = m_color.rgba();
- QRgb c2 = other->m_color.rgba();
- return int(c2 < c1) - int(c1 < c2);
-}
-
-bool QSGTextMaskMaterial::ensureUpToDate()
-{
- QSize glyphCacheSize(glyphCache()->width(), glyphCache()->height());
- if (glyphCacheSize != m_size) {
- if (m_texture)
- delete m_texture;
- m_texture = new QSGPlainTexture();
- m_texture->setTextureId(glyphCache()->texture());
- m_texture->setTextureSize(QSize(glyphCache()->width(), glyphCache()->height()));
- m_texture->setOwnsTexture(false);
-
- m_size = glyphCacheSize;
-
- return true;
- } else {
- return false;
- }
-}
-
-int QSGTextMaskMaterial::cacheTextureWidth() const
-{
- return glyphCache()->width();
-}
-
-int QSGTextMaskMaterial::cacheTextureHeight() const
-{
- return glyphCache()->height();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgdefaultglyphnode_p.h b/src/declarative/scenegraph/qsgdefaultglyphnode_p.h
deleted file mode 100644
index f9d163c425..0000000000
--- a/src/declarative/scenegraph/qsgdefaultglyphnode_p.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DEFAULT_GLYPHNODE_H
-#define DEFAULT_GLYPHNODE_H
-
-#include <private/qsgadaptationlayer_p.h>
-#include <qsgnode.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QGlyphs;
-class QSGTextMaskMaterial;
-class QSGDefaultGlyphNode: public QSGGlyphNode
-{
-public:
- QSGDefaultGlyphNode();
- ~QSGDefaultGlyphNode();
-
- virtual QPointF baseLine() const { return m_baseLine; }
- virtual void setGlyphs(const QPointF &position, const QGlyphRun &glyphs);
- virtual void setColor(const QColor &color);
-
- virtual void setPreferredAntialiasingMode(AntialiasingMode) { }
- virtual void setStyle(QQuickText::TextStyle) { }
- virtual void setStyleColor(const QColor &) { }
-
- virtual void update() { }
-
-private:
- QGlyphRun m_glyphs;
- QPointF m_position;
- QColor m_color;
-
- QPointF m_baseLine;
- QSGTextMaskMaterial *m_material;
-
- QSGGeometry m_geometry;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // DEFAULT_GLYPHNODE_H
diff --git a/src/declarative/scenegraph/qsgdefaultglyphnode_p_p.h b/src/declarative/scenegraph/qsgdefaultglyphnode_p_p.h
deleted file mode 100644
index d22bc33fea..0000000000
--- a/src/declarative/scenegraph/qsgdefaultglyphnode_p_p.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TEXTMASKMATERIAL_H
-#define TEXTMASKMATERIAL_H
-
-#include <qcolor.h>
-#include <qsgmaterial.h>
-#include <qsgtexture.h>
-#include <qsggeometry.h>
-#include <qshareddata.h>
-#include <private/qsgtexture_p.h>
-#include <qrawfont.h>
-
-QT_BEGIN_NAMESPACE
-
-class QFontEngineGlyphCache;
-class QOpenGLTextureGlyphCache;
-class QFontEngine;
-class Geometry;
-class QSGTextMaskMaterial: public QSGMaterial
-{
-public:
- QSGTextMaskMaterial(const QRawFont &font);
- ~QSGTextMaskMaterial();
-
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
- virtual int compare(const QSGMaterial *other) const;
-
- void setColor(const QColor &color) { m_color = color; }
- const QColor &color() const { return m_color; }
-
- QSGTexture *texture() const { return m_texture; }
-
- int cacheTextureWidth() const;
- int cacheTextureHeight() const;
-
- bool ensureUpToDate();
-
- QOpenGLTextureGlyphCache *glyphCache() const;
- void populate(const QPointF &position,
- const QVector<quint32> &glyphIndexes, const QVector<QPointF> &glyphPositions,
- QSGGeometry *geometry, QRectF *boundingRect, QPointF *baseLine);
-
-private:
- void init();
-
- QSGPlainTexture *m_texture;
- QExplicitlySharedDataPointer<QFontEngineGlyphCache> m_glyphCache;
- QRawFont m_font;
- QColor m_color;
- QSize m_size;
-};
-
-QT_END_NAMESPACE
-
-#endif // TEXTMASKMATERIAL_H
diff --git a/src/declarative/scenegraph/qsgdefaultimagenode.cpp b/src/declarative/scenegraph/qsgdefaultimagenode.cpp
deleted file mode 100644
index f30a7e2675..0000000000
--- a/src/declarative/scenegraph/qsgdefaultimagenode.cpp
+++ /dev/null
@@ -1,293 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgdefaultimagenode_p.h"
-
-#include <private/qsgtextureprovider_p.h>
-
-#include <QtCore/qvarlengtharray.h>
-#include <QtCore/qmath.h>
-#include <QtGui/qopenglfunctions.h>
-
-QT_BEGIN_NAMESPACE
-
-QSGDefaultImageNode::QSGDefaultImageNode()
- : m_sourceRect(0, 0, 1, 1)
- , m_dirtyGeometry(false)
- , m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
-{
- setMaterial(&m_materialO);
- setOpaqueMaterial(&m_material);
- setGeometry(&m_geometry);
-
-#ifdef QML_RUNTIME_TESTING
- description = QLatin1String("image");
-#endif
-}
-
-void QSGDefaultImageNode::setTargetRect(const QRectF &rect)
-{
- if (rect == m_targetRect)
- return;
- m_targetRect = rect;
- m_dirtyGeometry = true;
-}
-
-void QSGDefaultImageNode::setSourceRect(const QRectF &rect)
-{
- if (rect == m_sourceRect)
- return;
- m_sourceRect = rect;
- m_dirtyGeometry = true;
-}
-
-
-void QSGDefaultImageNode::setFiltering(QSGTexture::Filtering filtering)
-{
- if (m_material.filtering() == filtering)
- return;
-
- m_material.setFiltering(filtering);
- m_materialO.setFiltering(filtering);
- markDirty(DirtyMaterial);
-}
-
-
-void QSGDefaultImageNode::setMipmapFiltering(QSGTexture::Filtering filtering)
-{
- if (m_material.mipmapFiltering() == filtering)
- return;
-
- m_material.setMipmapFiltering(filtering);
- m_materialO.setMipmapFiltering(filtering);
- markDirty(DirtyMaterial);
-}
-
-void QSGDefaultImageNode::setVerticalWrapMode(QSGTexture::WrapMode wrapMode)
-{
- if (m_material.verticalWrapMode() == wrapMode)
- return;
-
- m_material.setVerticalWrapMode(wrapMode);
- m_materialO.setVerticalWrapMode(wrapMode);
- markDirty(DirtyMaterial);
-}
-
-void QSGDefaultImageNode::setHorizontalWrapMode(QSGTexture::WrapMode wrapMode)
-{
- if (m_material.horizontalWrapMode() == wrapMode)
- return;
-
- m_material.setHorizontalWrapMode(wrapMode);
- m_materialO.setHorizontalWrapMode(wrapMode);
- markDirty(DirtyMaterial);
-}
-
-
-void QSGDefaultImageNode::setTexture(QSGTexture *texture)
-{
- if (texture == m_material.texture())
- return;
-
- m_material.setTexture(texture);
- m_materialO.setTexture(texture);
- // Texture cleanup
-// if (!texture.isNull())
-// m_material.setBlending(texture->hasAlphaChannel());
- markDirty(DirtyMaterial);
-
- // Because the texture can be a different part of the atlas, we need to update it...
- m_dirtyGeometry = true;
-}
-
-void QSGDefaultImageNode::update()
-{
- if (m_dirtyGeometry)
- updateGeometry();
-}
-
-void QSGDefaultImageNode::preprocess()
-{
- bool doDirty = false;
- QSGDynamicTexture *t = qobject_cast<QSGDynamicTexture *>(m_material.texture());
- if (t) {
- doDirty = t->updateTexture();
- updateGeometry();
- }
-// ### texture cleanup
-// bool alpha = m_material.blending();
-// if (!m_material->texture().isNull() && alpha != m_material.texture()->hasAlphaChannel()) {
-// m_material.setBlending(!alpha);
-// doDirty = true;
-// }
-
- if (doDirty)
- markDirty(DirtyMaterial);
-}
-
-inline static bool isPowerOfTwo(int x)
-{
- // Assumption: x >= 1
- return x == (x & -x);
-}
-
-namespace {
- struct X { float x, tx; };
- struct Y { float y, ty; };
-}
-
-void QSGDefaultImageNode::updateGeometry()
-{
- const QSGTexture *t = m_material.texture();
- if (!t) {
- m_geometry.allocate(4);
- m_geometry.setDrawingMode(GL_TRIANGLE_STRIP);
- QSGGeometry::updateTexturedRectGeometry(&m_geometry, QRectF(), QRectF());
- } else {
- QRectF textureRect = t->textureSubRect();
-
- bool isSubRect = textureRect != QRectF(0, 0, 1, 1);
- const int ceilRight = qCeil(m_sourceRect.right());
- const int floorLeft = qFloor(m_sourceRect.left());
- const int ceilBottom = qCeil(m_sourceRect.bottom());
- const int floorTop = qFloor(m_sourceRect.top());
- const int hCells = ceilRight - floorLeft;
- const int vCells = ceilBottom - floorTop;
- bool isRepeating = hCells > 1 || vCells > 1;
-
-#ifdef QT_OPENGL_ES_2
- QOpenGLContext *ctx = QOpenGLContext::currentContext();
- bool npotSupported = ctx->functions()->hasOpenGLFeature(QOpenGLFunctions::NPOTTextures);
-
- QSize size = t->textureSize();
- bool isNpot = !isPowerOfTwo(size.width()) || !isPowerOfTwo(size.height());
-
- if (isRepeating && (isSubRect || (isNpot && !npotSupported))) {
-#else
- if (isRepeating && isSubRect) {
-#endif
- m_geometry.allocate(hCells * vCells * 4, hCells * vCells * 6);
- m_geometry.setDrawingMode(GL_TRIANGLES);
- QVarLengthArray<X, 32> xData(2 * hCells);
- QVarLengthArray<Y, 32> yData(2 * vCells);
- X *xs = xData.data();
- Y *ys = yData.data();
-
- xs->x = m_targetRect.left();
- xs->tx = textureRect.x() + (m_sourceRect.left() - floorLeft) * textureRect.width();
- ++xs;
- ys->y = m_targetRect.top();
- ys->ty = textureRect.y() + (m_sourceRect.top() - floorTop) * textureRect.height();
- ++ys;
-
- float a, b;
- b = m_targetRect.width() / m_sourceRect.width();
- a = m_targetRect.x() - m_sourceRect.x() * b;
-
- float tex_x1 = textureRect.x();
- float tex_x2 = textureRect.right();
- float tex_y1 = textureRect.y();
- float tex_y2 = textureRect.bottom();
- for (int i = floorLeft + 1; i <= ceilRight - 1; ++i) {
- xs[0].x = xs[1].x = a + b * i;
- xs[0].tx = tex_x2;
- xs[1].tx = tex_x1;
- xs += 2;
- }
- b = m_targetRect.height() / m_sourceRect.height();
- a = m_targetRect.y() - m_sourceRect.y() * b;
- for (int i = floorTop + 1; i <= ceilBottom - 1; ++i) {
- ys[0].y = ys[1].y = a + b * i;
- ys[0].ty = tex_y2;
- ys[1].ty = tex_y1;
- ys += 2;
- }
-
- xs->x = m_targetRect.right();
- xs->tx = textureRect.x() + (m_sourceRect.right() - ceilRight + 1) * textureRect.width();
-
- ys->y = m_targetRect.bottom();
- ys->ty = textureRect.y() + (m_sourceRect.bottom() - ceilBottom + 1) * textureRect.height();
-
- QSGGeometry::TexturedPoint2D *vertices = m_geometry.vertexDataAsTexturedPoint2D();
- ys = yData.data();
- for (int j = 0; j < vCells; ++j, ys += 2) {
- xs = xData.data();
- for (int i = 0; i < hCells; ++i, xs += 2) {
- vertices[0].x = vertices[2].x = xs[0].x;
- vertices[0].tx = vertices[2].tx = xs[0].tx;
- vertices[1].x = vertices[3].x = xs[1].x;
- vertices[1].tx = vertices[3].tx = xs[1].tx;
-
- vertices[0].y = vertices[1].y = ys[0].y;
- vertices[0].ty = vertices[1].ty = ys[0].ty;
- vertices[2].y = vertices[3].y = ys[1].y;
- vertices[2].ty = vertices[3].ty = ys[1].ty;
-
- vertices += 4;
- }
- }
-
- quint16 *indices = m_geometry.indexDataAsUShort();
- for (int i = 0; i < 4 * vCells * hCells; i += 4) {
- *indices++ = i;
- *indices++ = i + 2;
- *indices++ = i + 3;
- *indices++ = i + 3;
- *indices++ = i + 1;
- *indices++ = i;
- }
- } else {
- QRectF sr(textureRect.x() + m_sourceRect.x() * textureRect.width(),
- textureRect.y() + m_sourceRect.y() * textureRect.height(),
- m_sourceRect.width() * textureRect.width(),
- m_sourceRect.height() * textureRect.height());
-
- m_geometry.allocate(4);
- m_geometry.setDrawingMode(GL_TRIANGLE_STRIP);
- QSGGeometry::updateTexturedRectGeometry(&m_geometry, m_targetRect, sr);
- }
- }
- markDirty(DirtyGeometry);
- m_dirtyGeometry = false;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgdefaultimagenode_p.h b/src/declarative/scenegraph/qsgdefaultimagenode_p.h
deleted file mode 100644
index db11cd9181..0000000000
--- a/src/declarative/scenegraph/qsgdefaultimagenode_p.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef DEFAULT_PIXMAPNODE_H
-#define DEFAULT_PIXMAPNODE_H
-
-#include <private/qsgadaptationlayer_p.h>
-
-#include "qsgtexturematerial.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGDefaultImageNode : public QSGImageNode
-{
-public:
- QSGDefaultImageNode();
- virtual void setTargetRect(const QRectF &rect);
- virtual void setSourceRect(const QRectF &rect);
- virtual void setTexture(QSGTexture *t);
- virtual void update();
-
- virtual void setMipmapFiltering(QSGTexture::Filtering filtering);
- virtual void setFiltering(QSGTexture::Filtering filtering);
- virtual void setHorizontalWrapMode(QSGTexture::WrapMode wrapMode);
- virtual void setVerticalWrapMode(QSGTexture::WrapMode wrapMode);
-
- virtual void preprocess();
-
-private:
- void updateGeometry();
-
- QRectF m_targetRect;
- QRectF m_sourceRect;
-
- QSGOpaqueTextureMaterial m_material;
- QSGTextureMaterial m_materialO;
-
- uint m_dirtyGeometry : 1;
-
- QSGGeometry m_geometry;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/scenegraph/qsgdefaultrectanglenode.cpp b/src/declarative/scenegraph/qsgdefaultrectanglenode.cpp
deleted file mode 100644
index 4753b6021e..0000000000
--- a/src/declarative/scenegraph/qsgdefaultrectanglenode.cpp
+++ /dev/null
@@ -1,548 +0,0 @@
-
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-
-#include "qsgdefaultrectanglenode_p.h"
-
-#include <qsgvertexcolormaterial.h>
-#include "qsgtexturematerial.h"
-
-#include <private/qsgcontext_p.h>
-
-#include <QtCore/qmath.h>
-#include <QtCore/qvarlengtharray.h>
-
-QT_BEGIN_NAMESPACE
-
-QSGDefaultRectangleNode::QSGDefaultRectangleNode(QSGContext *context)
- : m_border(0)
- , m_radius(0)
- , m_pen_width(0)
- , m_aligned(true)
- , m_gradient_is_opaque(true)
- , m_dirty_geometry(false)
- , m_default_geometry(QSGGeometry::defaultAttributes_Point2D(), 4)
- , m_context(context)
-{
- setGeometry(&m_default_geometry);
- setMaterial(&m_fill_material);
- m_border_material.setColor(QColor(0, 0, 0));
-
- m_material_type = TypeFlat;
-
-#ifdef QML_RUNTIME_TESTING
- description = QLatin1String("rectangle");
-#endif
-}
-
-QSGDefaultRectangleNode::~QSGDefaultRectangleNode()
-{
- if (m_material_type == TypeVertexGradient)
- delete material();
- delete m_border;
-}
-
-QSGGeometryNode *QSGDefaultRectangleNode::border()
-{
- if (!m_border) {
- m_border = new QSGGeometryNode;
- m_border->setMaterial(&m_border_material);
- QSGGeometry *geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 0);
- m_border->setGeometry(geometry);
- m_border->setFlag(QSGNode::OwnsGeometry);
- }
- return m_border;
-}
-
-void QSGDefaultRectangleNode::setRect(const QRectF &rect)
-{
- if (rect == m_rect)
- return;
- m_rect = rect;
- m_dirty_geometry = true;
-}
-
-void QSGDefaultRectangleNode::setColor(const QColor &color)
-{
- if (color == m_fill_material.color())
- return;
- m_fill_material.setColor(color);
- if (m_gradient_stops.isEmpty()) {
- Q_ASSERT(m_material_type == TypeFlat);
- markDirty(DirtyMaterial);
- }
-}
-
-void QSGDefaultRectangleNode::setPenColor(const QColor &color)
-{
- if (color == m_border_material.color())
- return;
- m_border_material.setColor(color);
- if (m_border)
- m_border->markDirty(DirtyMaterial);
-}
-
-void QSGDefaultRectangleNode::setPenWidth(qreal width)
-{
- if (width == m_pen_width)
- return;
- m_pen_width = width;
- if (m_pen_width <= 0 && m_border && m_border->parent())
- removeChildNode(m_border);
- else if (m_pen_width > 0 && !border()->parent())
- appendChildNode(m_border);
- m_dirty_geometry = true;
-}
-
-
-void QSGDefaultRectangleNode::setGradientStops(const QGradientStops &stops)
-{
- if (stops.constData() == m_gradient_stops.constData())
- return;
-
- m_gradient_stops = stops;
-
- m_gradient_is_opaque = true;
- for (int i = 0; i < stops.size(); ++i)
- m_gradient_is_opaque &= stops.at(i).second.alpha() == 0xff;
-
- if (stops.isEmpty()) {
- // No gradient specified, use flat color.
- if (m_material_type != TypeFlat) {
- delete material();
-
- setMaterial(&m_fill_material);
- m_material_type = TypeFlat;
-
- setGeometry(&m_default_geometry);
- setFlag(OwnsGeometry, false);
- }
- } else {
- if (m_material_type == TypeFlat) {
- QSGVertexColorMaterial *material = new QSGVertexColorMaterial;
- setMaterial(material);
- m_material_type = TypeVertexGradient;
- QSGGeometry *g = new QSGGeometry(QSGGeometry::defaultAttributes_ColoredPoint2D(), 0);
- setGeometry(g);
- setFlag(OwnsGeometry);
- }
- static_cast<QSGVertexColorMaterial *>(material())->setFlag(QSGMaterial::Blending, !m_gradient_is_opaque);
- }
-
- m_dirty_geometry = true;
-}
-
-void QSGDefaultRectangleNode::setRadius(qreal radius)
-{
- if (radius == m_radius)
- return;
- m_radius = radius;
- m_dirty_geometry = true;
-}
-
-void QSGDefaultRectangleNode::setAligned(bool aligned)
-{
- if (aligned == m_aligned)
- return;
- m_aligned = aligned;
- m_dirty_geometry = true;
-}
-
-void QSGDefaultRectangleNode::update()
-{
- if (m_dirty_geometry) {
- updateGeometry();
- m_dirty_geometry = false;
- }
-}
-
-struct Color4ub
-{
- unsigned char r, g, b, a;
-};
-
-Color4ub operator *(Color4ub c, float t) { c.a *= t; c.r *= t; c.g *= t; c.b *= t; return c; }
-Color4ub operator +(Color4ub a, Color4ub b) { a.a += b.a; a.r += b.r; a.g += b.g; a.b += b.b; return a; }
-
-static inline Color4ub colorToColor4ub(const QColor &c)
-{
- Color4ub color = { uchar(c.redF() * c.alphaF() * 255),
- uchar(c.greenF() * c.alphaF() * 255),
- uchar(c.blueF() * c.alphaF() * 255),
- uchar(c.alphaF() * 255)
- };
- return color;
-}
-
-struct Vertex
-{
- QVector2D position;
-};
-
-struct ColorVertex
-{
- QVector2D position;
- Color4ub color;
-};
-
-void QSGDefaultRectangleNode::updateGeometry()
-{
- qreal penWidth = m_aligned ? qreal(qRound(m_pen_width)) : m_pen_width;
-
- // fast path for the simple case...
- if ((penWidth == 0 || m_border_material.color().alpha() == 0)
- && m_radius == 0
- && m_material_type == TypeFlat) {
- QSGGeometry::updateRectGeometry(&m_default_geometry, m_rect);
- return;
- }
-
- QSGGeometry *fill = geometry();
-
- // Check that the vertex type matches the material.
- Q_ASSERT(m_material_type != TypeFlat || fill->sizeOfVertex() == sizeof(Vertex));
- Q_ASSERT(m_material_type != TypeVertexGradient || fill->sizeOfVertex() == sizeof(ColorVertex));
-
- QSGGeometry *borderGeometry = 0;
- if (m_border) {
- borderGeometry = m_border->geometry();
- Q_ASSERT(borderGeometry->sizeOfVertex() == sizeof(Vertex));
- }
-
- int fillVertexCount = 0;
-
- // Preallocate arrays for a rectangle with 18 segments per corner and 3 gradient stops.
- uchar *fillVertices = 0;
- Vertex *borderVertices = 0;
-
- Color4ub fillColor = colorToColor4ub(m_fill_material.color());
- const QGradientStops &stops = m_gradient_stops;
-
- if (m_radius > 0) {
- // Rounded corners.
-
- // Radius should never exceeds half of the width or half of the height
- qreal radius = qMin(qMin(m_rect.width() * qreal(0.5), m_rect.height() * qreal(0.5)), m_radius);
- QRectF innerRect = m_rect;
- innerRect.adjust(radius, radius, -radius, -radius);
- if (m_aligned && (int(penWidth) & 1)) {
- // Pen width is odd, so add the offset as documented.
- innerRect.moveLeft(innerRect.left() + qreal(0.5));
- innerRect.moveTop(innerRect.top() + qreal(0.5));
- }
-
- qreal innerRadius = radius - penWidth * qreal(0.5);
- qreal outerRadius = radius + penWidth * qreal(0.5);
-
- // Number of segments per corner, approximately one per 3 pixels.
- int segments = qBound(3, qCeil(outerRadius * (M_PI / 6)), 18);
-
- /*
-
- --+-__
- | segment
- | _+
- --+-__ _- \
- -+ segment
- --------+ \ <- gradient line
- +-----+
- | |
-
- */
-
- int nextGradientStop = 0;
- qreal gradientPos = (radius - innerRadius) / (innerRect.height() + 2 * radius);
- while (nextGradientStop < stops.size() && stops.at(nextGradientStop).first <= gradientPos)
- ++nextGradientStop;
- int lastGradientStop = stops.size() - 1;
- qreal lastGradientPos = (innerRect.height() + radius + innerRadius) / (innerRect.height() + 2 * radius);
- while (lastGradientStop >= nextGradientStop && stops.at(lastGradientStop).first >= lastGradientPos)
- --lastGradientStop;
-
- int borderVertexHead = 0;
- int borderVertexTail = 0;
- if (penWidth) {
- // The reason I add extra vertices where the gradient lines intersect the border is
- // to avoid pixel sized gaps between the fill and the border caused by floating point
- // inaccuracies.
- borderGeometry->allocate((segments + 1) * 2 * 4 + (lastGradientStop - nextGradientStop + 1) * 4 + 2);
- borderVertexHead = borderVertexTail = (borderGeometry->vertexCount() >> 1) - 1;
- borderVertices = (Vertex *)borderGeometry->vertexData();
- }
-
- fill->allocate((segments + 1) * 4 + (lastGradientStop - nextGradientStop + 1) * 2);
- fillVertices = (uchar *)fill->vertexData();
-
- qreal py = 0; // previous inner y-coordinate.
- qreal plx = 0; // previous inner left x-coordinate.
- qreal prx = 0; // previous inner right x-coordinate.
-
- qreal angle = qreal(0.5) * M_PI / qreal(segments);
- qreal cosStep = qFastCos(angle);
- qreal sinStep = qFastSin(angle);
-
- for (int part = 0; part < 2; ++part) {
- qreal c = 1 - part;
- qreal s = part;
- for (int i = 0; i <= segments; ++i) {
- qreal y, lx, rx;
- if (innerRadius > 0) {
- y = (part ? innerRect.bottom() : innerRect.top()) - innerRadius * c; // current inner y-coordinate.
- lx = innerRect.left() - innerRadius * s; // current inner left x-coordinate.
- rx = innerRect.right() + innerRadius * s; // current inner right x-coordinate.
- gradientPos = ((part ? innerRect.height() : 0) + radius - innerRadius * c) / (innerRect.height() + 2 * radius);
- } else {
- y = (part ? innerRect.bottom() + innerRadius : innerRect.top() - innerRadius); // current inner y-coordinate.
- lx = innerRect.left() - innerRadius; // current inner left x-coordinate.
- rx = innerRect.right() + innerRadius; // current inner right x-coordinate.
- gradientPos = ((part ? innerRect.height() + innerRadius : -innerRadius) + radius) / (innerRect.height() + 2 * radius);
- }
- qreal Y = (part ? innerRect.bottom() : innerRect.top()) - outerRadius * c; // current outer y-coordinate.
- qreal lX = innerRect.left() - outerRadius * s; // current outer left x-coordinate.
- qreal rX = innerRect.right() + outerRadius * s; // current outer right x-coordinate.
-
- while (nextGradientStop <= lastGradientStop && stops.at(nextGradientStop).first <= gradientPos) {
- // Insert vertices at gradient stops.
- qreal gy = (innerRect.top() - radius) + stops.at(nextGradientStop).first * (innerRect.height() + 2 * radius);
- Q_ASSERT(fillVertexCount >= 2);
- qreal t = (gy - py) / (y - py);
- qreal glx = plx * (1 - t) + t * lx;
- qreal grx = prx * (1 - t) + t * rx;
-
- if (penWidth) {
- const Vertex &first = borderVertices[borderVertexHead];
- borderVertices[--borderVertexHead].position = QVector2D(glx, gy);
- borderVertices[--borderVertexHead] = first;
-
- const Vertex &last = borderVertices[borderVertexTail - 2];
- borderVertices[borderVertexTail++] = last;
- borderVertices[borderVertexTail++].position = QVector2D(grx, gy);
- }
-
- ColorVertex *vertices = (ColorVertex *)fillVertices;
-
- fillColor = colorToColor4ub(stops.at(nextGradientStop).second);
- vertices[fillVertexCount].position = QVector2D(grx, gy);
- vertices[fillVertexCount].color = fillColor;
- ++fillVertexCount;
- vertices[fillVertexCount].position = QVector2D(glx, gy);
- vertices[fillVertexCount].color = fillColor;
- ++fillVertexCount;
-
- ++nextGradientStop;
- }
-
- if (penWidth) {
- borderVertices[--borderVertexHead].position = QVector2D(lx, y);
- borderVertices[--borderVertexHead].position = QVector2D(lX, Y);
- borderVertices[borderVertexTail++].position = QVector2D(rX, Y);
- borderVertices[borderVertexTail++].position = QVector2D(rx, y);
- }
-
- if (stops.isEmpty()) {
- Q_ASSERT(m_material_type == TypeFlat);
- Vertex *vertices = (Vertex *)fillVertices;
- vertices[fillVertexCount++].position = QVector2D(rx, y);
- vertices[fillVertexCount++].position = QVector2D(lx, y);
- } else {
- if (nextGradientStop == 0) {
- fillColor = colorToColor4ub(stops.at(0).second);
- } else if (nextGradientStop == stops.size()) {
- fillColor = colorToColor4ub(stops.last().second);
- } else {
- const QGradientStop &prev = stops.at(nextGradientStop - 1);
- const QGradientStop &next = stops.at(nextGradientStop);
- qreal t = (gradientPos - prev.first) / (next.first - prev.first);
- fillColor = (colorToColor4ub(prev.second) * (1 - t) + colorToColor4ub(next.second) * t);
- }
-
- ColorVertex *vertices = (ColorVertex *)fillVertices;
- vertices[fillVertexCount].position = QVector2D(rx, y);
- vertices[fillVertexCount].color = fillColor;
- ++fillVertexCount;
- vertices[fillVertexCount].position = QVector2D(lx, y);
- vertices[fillVertexCount].color = fillColor;
- ++fillVertexCount;
- }
- py = y;
- plx = lx;
- prx = rx;
-
- // Rotate
- qreal tmp = c;
- c = c * cosStep - s * sinStep;
- s = s * cosStep + tmp * sinStep;
- }
- }
-
- if (penWidth) {
- // Close border.
- const Vertex &first = borderVertices[borderVertexHead];
- const Vertex &second = borderVertices[borderVertexHead + 1];
- borderVertices[borderVertexTail++] = first;
- borderVertices[borderVertexTail++] = second;
-
- Q_ASSERT(borderVertexHead == 0 && borderVertexTail == borderGeometry->vertexCount());
- }
- Q_ASSERT(fillVertexCount == fill->vertexCount());
-
- } else {
-
- // Straight corners.
- QRectF innerRect = m_rect;
- QRectF outerRect = m_rect;
-
- qreal halfPenWidth = 0;
- if (penWidth) {
- if (m_aligned && (int(penWidth) & 1)) {
- // Pen width is odd, so add the offset as documented.
- innerRect.moveLeft(innerRect.left() + qreal(0.5));
- innerRect.moveTop(innerRect.top() + qreal(0.5));
- outerRect = innerRect;
- }
- halfPenWidth = penWidth * qreal(0.5);
- innerRect.adjust(halfPenWidth, halfPenWidth, -halfPenWidth, -halfPenWidth);
- outerRect.adjust(-halfPenWidth, -halfPenWidth, halfPenWidth, halfPenWidth);
- }
-
- int nextGradientStop = 0;
- qreal gradientPos = halfPenWidth / m_rect.height();
- while (nextGradientStop < stops.size() && stops.at(nextGradientStop).first <= gradientPos)
- ++nextGradientStop;
- int lastGradientStop = stops.size() - 1;
- qreal lastGradientPos = (m_rect.height() - halfPenWidth) / m_rect.height();
- while (lastGradientStop >= nextGradientStop && stops.at(lastGradientStop).first >= lastGradientPos)
- --lastGradientStop;
-
- int borderVertexCount = 0;
- if (penWidth) {
- borderGeometry->allocate((1 + lastGradientStop - nextGradientStop) * 4 + 10);
- borderVertices = (Vertex *)borderGeometry->vertexData();
- }
- fill->allocate((3 + lastGradientStop - nextGradientStop) * 2);
- fillVertices = (uchar *)fill->vertexData();
-
- QVarLengthArray<qreal, 16> ys(3 + lastGradientStop - nextGradientStop);
- int yCount = 0;
-
- for (int part = 0; part < 2; ++part) {
- qreal y = (part ? innerRect.bottom() : innerRect.top());
- gradientPos = (y - innerRect.top() + halfPenWidth) / m_rect.height();
-
- while (nextGradientStop <= lastGradientStop && stops.at(nextGradientStop).first <= gradientPos) {
- // Insert vertices at gradient stops.
- qreal gy = (innerRect.top() - halfPenWidth) + stops.at(nextGradientStop).first * m_rect.height();
- Q_ASSERT(fillVertexCount >= 2);
-
- ColorVertex *vertices = (ColorVertex *)fillVertices;
-
- fillColor = colorToColor4ub(stops.at(nextGradientStop).second);
- vertices[fillVertexCount].position = QVector2D(innerRect.right(), gy);
- vertices[fillVertexCount].color = fillColor;
- ++fillVertexCount;
- vertices[fillVertexCount].position = QVector2D(innerRect.left(), gy);
- vertices[fillVertexCount].color = fillColor;
- ++fillVertexCount;
-
- ys[yCount++] = gy;
-
- ++nextGradientStop;
- }
-
- if (stops.isEmpty()) {
- Q_ASSERT(m_material_type == TypeFlat);
- Vertex *vertices = (Vertex *)fillVertices;
- vertices[fillVertexCount++].position = QVector2D(innerRect.right(), y);
- vertices[fillVertexCount++].position = QVector2D(innerRect.left(), y);
- } else {
- if (nextGradientStop == 0) {
- fillColor = colorToColor4ub(stops.at(0).second);
- } else if (nextGradientStop == stops.size()) {
- fillColor = colorToColor4ub(stops.last().second);
- } else {
- const QGradientStop &prev = stops.at(nextGradientStop - 1);
- const QGradientStop &next = stops.at(nextGradientStop);
- qreal t = (gradientPos - prev.first) / (next.first - prev.first);
- fillColor = (colorToColor4ub(prev.second) * (1 - t) + colorToColor4ub(next.second) * t);
- }
-
- ColorVertex *vertices = (ColorVertex *)fillVertices;
- vertices[fillVertexCount].position = QVector2D(innerRect.right(), y);
- vertices[fillVertexCount].color = fillColor;
- ++fillVertexCount;
- vertices[fillVertexCount].position = QVector2D(innerRect.left(), y);
- vertices[fillVertexCount].color = fillColor;
- ++fillVertexCount;
- }
-
- ys[yCount++] = y;
- }
-
- if (penWidth) {
- borderVertices[borderVertexCount++].position = QVector2D(outerRect.right(), outerRect.top());
- borderVertices[borderVertexCount++].position = QVector2D(innerRect.right(), ys[0]);
- for (int i = 1; i < fillVertexCount / 2; ++i) {
- borderVertices[borderVertexCount++].position = QVector2D(outerRect.right(), outerRect.bottom());
- borderVertices[borderVertexCount++].position = QVector2D(innerRect.right(), ys[i]);
- }
-
- borderVertices[borderVertexCount++].position = QVector2D(outerRect.left(), outerRect.bottom());
- borderVertices[borderVertexCount++].position = QVector2D(innerRect.left(), ys[fillVertexCount / 2 - 1]);
- for (int i = fillVertexCount / 2 - 2; i >= 0; --i) {
- borderVertices[borderVertexCount++].position = QVector2D(outerRect.left(), outerRect.top());
- borderVertices[borderVertexCount++].position = QVector2D(innerRect.left(), ys[i]);
- }
-
- borderVertices[borderVertexCount++].position = QVector2D(outerRect.right(), outerRect.top());
- borderVertices[borderVertexCount++].position = QVector2D(innerRect.right(), innerRect.top());
-
- Q_ASSERT(borderVertexCount == borderGeometry->vertexCount());
- }
- Q_ASSERT(fillVertexCount == fill->vertexCount());
- }
-
- markDirty(DirtyGeometry);
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgdefaultrectanglenode_p.h b/src/declarative/scenegraph/qsgdefaultrectanglenode_p.h
deleted file mode 100644
index 6a197136cf..0000000000
--- a/src/declarative/scenegraph/qsgdefaultrectanglenode_p.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef DEFAULT_RECTANGLENODE_H
-#define DEFAULT_RECTANGLENODE_H
-
-#include <private/qsgadaptationlayer_p.h>
-
-#include "qsgflatcolormaterial.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGMaterial;
-class QSGContext;
-
-class QSGDefaultRectangleNode : public QSGRectangleNode
-{
-public:
- QSGDefaultRectangleNode(QSGContext *context);
- ~QSGDefaultRectangleNode();
-
- virtual void setRect(const QRectF &rect);
- virtual void setColor(const QColor &color);
- virtual void setPenColor(const QColor &color);
- virtual void setPenWidth(qreal width);
- virtual void setGradientStops(const QGradientStops &stops);
- virtual void setRadius(qreal radius);
- virtual void setAligned(bool aligned);
- virtual void update();
-
-private:
- enum {
- TypeFlat,
- TypeVertexGradient
- };
- QSGGeometryNode *border();
-
- void updateGeometry();
- void updateGradientTexture();
-
- QSGGeometryNode *m_border;
- QSGFlatColorMaterial m_border_material;
- QSGFlatColorMaterial m_fill_material;
-
- QRectF m_rect;
- QGradientStops m_gradient_stops;
- qreal m_radius;
- qreal m_pen_width;
-
- uint m_aligned : 1;
- uint m_gradient_is_opaque : 1;
- uint m_dirty_geometry : 1;
-
- uint m_material_type : 2; // Only goes up to 3
-
- QSGGeometry m_default_geometry;
-
- QSGContext *m_context;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/scenegraph/qsgdistancefieldglyphnode.cpp b/src/declarative/scenegraph/qsgdistancefieldglyphnode.cpp
deleted file mode 100644
index e4a39e484b..0000000000
--- a/src/declarative/scenegraph/qsgdistancefieldglyphnode.cpp
+++ /dev/null
@@ -1,316 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgdistancefieldglyphnode_p.h"
-#include "qsgdistancefieldglyphnode_p_p.h"
-#include <private/qsgdistancefieldutil_p.h>
-#include <private/qsgcontext_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QSGDistanceFieldGlyphNode::QSGDistanceFieldGlyphNode(QSGDistanceFieldGlyphCacheManager *cacheManager)
- : m_material(0)
- , m_glyph_cacheManager(cacheManager)
- , m_glyph_cache(0)
- , m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 0)
- , m_style(QQuickText::Normal)
- , m_antialiasingMode(GrayAntialiasing)
- , m_dirtyGeometry(false)
- , m_dirtyMaterial(false)
-{
- m_geometry.setDrawingMode(GL_TRIANGLES);
- setGeometry(&m_geometry);
- setPreferredAntialiasingMode(cacheManager->defaultAntialiasingMode());
-#ifdef QML_RUNTIME_TESTING
- description = QLatin1String("glyphs");
-#endif
-}
-
-QSGDistanceFieldGlyphNode::~QSGDistanceFieldGlyphNode()
-{
- delete m_material;
- if (m_glyph_cache) {
- m_glyph_cache->release(m_glyphs.glyphIndexes());
- m_glyph_cache->unregisterGlyphNode(this);
- }
-}
-
-void QSGDistanceFieldGlyphNode::setColor(const QColor &color)
-{
- m_color = color;
- if (m_material != 0) {
- m_material->setColor(color);
- markDirty(DirtyMaterial);
- }
-}
-
-void QSGDistanceFieldGlyphNode::setPreferredAntialiasingMode(AntialiasingMode mode)
-{
- if (mode == m_antialiasingMode)
- return;
- m_antialiasingMode = mode;
- m_dirtyMaterial = true;
-}
-
-void QSGDistanceFieldGlyphNode::setGlyphs(const QPointF &position, const QGlyphRun &glyphs)
-{
- QRawFont font = glyphs.rawFont();
- m_position = QPointF(position.x(), position.y() - font.ascent());
- m_glyphs = glyphs;
-
- QSGDistanceFieldGlyphCache *oldCache = m_glyph_cache;
- m_glyph_cache = m_glyph_cacheManager->cache(m_glyphs.rawFont());
- if (m_glyph_cache != oldCache) {
- if (oldCache)
- oldCache->unregisterGlyphNode(this);
- m_glyph_cache->registerGlyphNode(this);
- }
- m_glyph_cache->populate(glyphs.glyphIndexes());
-
- const QVector<quint32> &glyphIndexes = m_glyphs.glyphIndexes();
- const QVector<QPointF> &glyphPositions = m_glyphs.positions();
- for (int i = 0; i < glyphIndexes.size(); ++i) {
- GlyphInfo g;
- g.glyphIndex = glyphIndexes.at(i);
- g.position = glyphPositions.at(i);
- m_glyphsToAdd.append(g);
- }
-
- m_dirtyGeometry = true;
- m_dirtyMaterial = true;
-}
-
-void QSGDistanceFieldGlyphNode::setStyle(QQuickText::TextStyle style)
-{
- if (m_style == style)
- return;
- m_style = style;
- m_dirtyMaterial = true;
-}
-
-void QSGDistanceFieldGlyphNode::setStyleColor(const QColor &color)
-{
- if (m_styleColor == color)
- return;
- m_styleColor = color;
- m_dirtyMaterial = true;
-}
-
-void QSGDistanceFieldGlyphNode::update()
-{
- if (m_dirtyMaterial)
- updateMaterial();
- if (m_dirtyGeometry)
- updateGeometry();
-}
-
-void QSGDistanceFieldGlyphNode::updateGeometry()
-{
- Q_ASSERT(m_glyph_cache);
-
- if (m_glyphsToAdd.isEmpty())
- return;
-
- QSGGeometry *g = geometry();
-
- Q_ASSERT(g->indexType() == GL_UNSIGNED_SHORT);
-
- int oldVertexCount = g->vertexCount();
- int oldIndexCount = g->indexCount();
-
- QVector<QSGGeometry::TexturedPoint2D> vp;
- vp.reserve(m_glyphsToAdd.size() * 4);
- QVector<ushort> ip;
- ip.reserve(m_glyphsToAdd.size() * 6);
-
- QPointF margins(2, 2);
- QPointF texMargins = margins / m_glyph_cache->fontScale();
-
- const QSGDistanceFieldGlyphCache::Texture *textureToUse = 0;
-
- QLinkedList<GlyphInfo>::iterator it = m_glyphsToAdd.begin();
- while (it != m_glyphsToAdd.end()) {
- quint32 glyphIndex = it->glyphIndex;
- QSGDistanceFieldGlyphCache::TexCoord c = m_glyph_cache->glyphTexCoord(glyphIndex);
-
- if (c.isNull()) {
- if (!c.isValid())
- ++it;
- else
- it = m_glyphsToAdd.erase(it);
- continue;
- }
-
- const QSGDistanceFieldGlyphCache::Texture *texture = m_glyph_cache->glyphTexture(glyphIndex);
- if (!texture->textureId) {
- ++it;
- continue;
- }
-
- QSGDistanceFieldGlyphCache::Metrics metrics = m_glyph_cache->glyphMetrics(glyphIndex);
-
- if (!textureToUse)
- textureToUse = texture;
-
- metrics.width += margins.x() * 2;
- metrics.height += margins.y() * 2;
- metrics.baselineX -= margins.x();
- metrics.baselineY += margins.y();
- c.xMargin -= texMargins.x();
- c.yMargin -= texMargins.y();
- c.width += texMargins.x() * 2;
- c.height += texMargins.y() * 2;
-
- const QPointF &glyphPosition = it->position;
- qreal x = glyphPosition.x() + metrics.baselineX + m_position.x();
- qreal y = glyphPosition.y() - metrics.baselineY + m_position.y();
-
- m_boundingRect |= QRectF(x, y, metrics.width, metrics.height);
-
- float cx1 = x;
- float cx2 = x + metrics.width;
- float cy1 = y;
- float cy2 = y + metrics.height;
-
- float tx1 = c.x + c.xMargin;
- float tx2 = tx1 + c.width;
- float ty1 = c.y + c.yMargin;
- float ty2 = ty1 + c.height;
-
- if (m_baseLine.isNull())
- m_baseLine = glyphPosition;
-
- int i = vp.size();
-
- QSGGeometry::TexturedPoint2D v1;
- v1.set(cx1, cy1, tx1, ty1);
- QSGGeometry::TexturedPoint2D v2;
- v2.set(cx2, cy1, tx2, ty1);
- QSGGeometry::TexturedPoint2D v3;
- v3.set(cx1, cy2, tx1, ty2);
- QSGGeometry::TexturedPoint2D v4;
- v4.set(cx2, cy2, tx2, ty2);
- vp.append(v1);
- vp.append(v2);
- vp.append(v3);
- vp.append(v4);
-
- int o = i + oldVertexCount;
- ip.append(o + 0);
- ip.append(o + 2);
- ip.append(o + 3);
- ip.append(o + 3);
- ip.append(o + 1);
- ip.append(o + 0);
-
- it = m_glyphsToAdd.erase(it);
- }
-
- if (vp.isEmpty())
- return;
-
- void *data = 0;
- if (oldVertexCount && oldIndexCount) {
- int byteSize = oldVertexCount * sizeof(QSGGeometry::TexturedPoint2D)
- + oldIndexCount * sizeof(quint16);
- data = qMalloc(byteSize);
- memcpy(data, g->vertexData(), byteSize);
- }
-
- g->allocate(oldVertexCount + vp.size(), oldIndexCount + ip.size());
-
- if (data) {
- memcpy(g->vertexData(), data, oldVertexCount * sizeof(QSGGeometry::TexturedPoint2D));
- memcpy(g->indexData(), ((char *) data) + oldVertexCount * sizeof(QSGGeometry::TexturedPoint2D),
- oldIndexCount * sizeof(quint16));
- qFree(data);
- }
-
- memcpy(g->vertexDataAsTexturedPoint2D() + oldVertexCount, vp.constData(), vp.size() * sizeof(QSGGeometry::TexturedPoint2D));
- memcpy(g->indexDataAsUShort() + oldIndexCount, ip.constData(), ip.size() * sizeof(quint16));
-
- setBoundingRect(m_boundingRect);
- markDirty(DirtyGeometry);
- m_dirtyGeometry = false;
-
- m_material->setTexture(textureToUse);
-}
-
-void QSGDistanceFieldGlyphNode::updateMaterial()
-{
- delete m_material;
-
- if (m_style == QQuickText::Normal) {
- switch (m_antialiasingMode) {
- case HighQualitySubPixelAntialiasing:
- m_material = new QSGHiQSubPixelDistanceFieldTextMaterial;
- break;
- case LowQualitySubPixelAntialiasing:
- m_material = new QSGLoQSubPixelDistanceFieldTextMaterial;
- break;
- case GrayAntialiasing:
- default:
- m_material = new QSGDistanceFieldTextMaterial;
- break;
- }
- } else {
- QSGDistanceFieldStyledTextMaterial *material;
- if (m_style == QQuickText::Outline) {
- material = new QSGDistanceFieldOutlineTextMaterial;
- } else {
- QSGDistanceFieldShiftedStyleTextMaterial *sMaterial = new QSGDistanceFieldShiftedStyleTextMaterial;
- if (m_style == QQuickText::Raised)
- sMaterial->setShift(QPointF(0.0, 1.0));
- else
- sMaterial->setShift(QPointF(0.0, -1.0));
- material = sMaterial;
- }
- material->setStyleColor(m_styleColor);
- m_material = material;
- }
-
- m_material->setGlyphCache(m_glyph_cache);
- m_material->setColor(m_color);
- setMaterial(m_material);
- m_dirtyMaterial = false;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgdistancefieldglyphnode_p.cpp b/src/declarative/scenegraph/qsgdistancefieldglyphnode_p.cpp
deleted file mode 100644
index a506e23cc1..0000000000
--- a/src/declarative/scenegraph/qsgdistancefieldglyphnode_p.cpp
+++ /dev/null
@@ -1,725 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgdistancefieldglyphnode_p_p.h"
-#include <private/qsgdistancefieldutil_p.h>
-#include <private/qsgtexture_p.h>
-#include <QtGui/qopenglfunctions.h>
-#include <qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-class QSGDistanceFieldTextMaterialShader : public QSGMaterialShader
-{
-public:
- QSGDistanceFieldTextMaterialShader();
-
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
- virtual char const *const *attributeNames() const;
-
-protected:
- virtual void initialize();
- virtual const char *vertexShader() const;
- virtual const char *fragmentShader() const;
-
- void updateAlphaRange(ThresholdFunc thresholdFunc, AntialiasingSpreadFunc spreadFunc);
-
- float m_fontScale;
- float m_matrixScale;
-
- int m_matrix_id;
- int m_textureScale_id;
- int m_alphaMin_id;
- int m_alphaMax_id;
- int m_color_id;
-};
-
-const char *QSGDistanceFieldTextMaterialShader::vertexShader() const {
- return
- "uniform highp mat4 matrix; \n"
- "uniform highp vec2 textureScale; \n"
- "attribute highp vec4 vCoord; \n"
- "attribute highp vec2 tCoord; \n"
- "varying highp vec2 sampleCoord; \n"
- "void main() { \n"
- " sampleCoord = tCoord * textureScale; \n"
- " gl_Position = matrix * vCoord; \n"
- "}";
-}
-
-const char *QSGDistanceFieldTextMaterialShader::fragmentShader() const {
- return
- "varying highp vec2 sampleCoord; \n"
- "uniform sampler2D texture; \n"
- "uniform lowp vec4 color; \n"
- "uniform highp float alphaMin; \n"
- "uniform highp float alphaMax; \n"
- "void main() { \n"
- " gl_FragColor = color * smoothstep(alphaMin, \n"
- " alphaMax, \n"
- " texture2D(texture, sampleCoord).a); \n"
- "}";
-}
-
-char const *const *QSGDistanceFieldTextMaterialShader::attributeNames() const {
- static char const *const attr[] = { "vCoord", "tCoord", 0 };
- return attr;
-}
-
-QSGDistanceFieldTextMaterialShader::QSGDistanceFieldTextMaterialShader()
- : m_fontScale(1.0)
- , m_matrixScale(1.0)
-{
-}
-
-void QSGDistanceFieldTextMaterialShader::updateAlphaRange(ThresholdFunc thresholdFunc, AntialiasingSpreadFunc spreadFunc)
-{
- float combinedScale = m_fontScale * m_matrixScale;
- float base = thresholdFunc(combinedScale);
- float range = spreadFunc(combinedScale);
-
- float alphaMin = qMax(0.0f, base - range);
- float alphaMax = qMin(base + range, 1.0f);
- program()->setUniformValue(m_alphaMin_id, GLfloat(alphaMin));
- program()->setUniformValue(m_alphaMax_id, GLfloat(alphaMax));
-}
-
-void QSGDistanceFieldTextMaterialShader::initialize()
-{
- QSGMaterialShader::initialize();
- m_matrix_id = program()->uniformLocation("matrix");
- m_textureScale_id = program()->uniformLocation("textureScale");
- m_color_id = program()->uniformLocation("color");
- m_alphaMin_id = program()->uniformLocation("alphaMin");
- m_alphaMax_id = program()->uniformLocation("alphaMax");
-}
-
-void QSGDistanceFieldTextMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
-{
- Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type());
- QSGDistanceFieldTextMaterial *material = static_cast<QSGDistanceFieldTextMaterial *>(newEffect);
- QSGDistanceFieldTextMaterial *oldMaterial = static_cast<QSGDistanceFieldTextMaterial *>(oldEffect);
-
- bool updated = material->updateCache();
-
- if (oldMaterial == 0
- || material->color() != oldMaterial->color()
- || state.isOpacityDirty()) {
- QVector4D color(material->color().redF(), material->color().greenF(),
- material->color().blueF(), material->color().alphaF());
- color *= state.opacity();
- program()->setUniformValue(m_color_id, color);
- }
-
- bool updateRange = false;
- if (oldMaterial == 0
- || material->glyphCache()->fontScale() != oldMaterial->glyphCache()->fontScale()) {
- m_fontScale = material->glyphCache()->fontScale();
- updateRange = true;
- }
- if (state.isMatrixDirty()) {
- program()->setUniformValue(m_matrix_id, state.combinedMatrix());
- m_matrixScale = qSqrt(qAbs(state.modelViewMatrix().determinant()));
- updateRange = true;
- }
- if (updateRange) {
- updateAlphaRange(material->glyphCache()->manager()->thresholdFunc(),
- material->glyphCache()->manager()->antialiasingSpreadFunc());
- }
-
- Q_ASSERT(material->glyphCache());
-
- if (updated
- || oldMaterial == 0
- || oldMaterial->texture()->textureId != material->texture()->textureId) {
- program()->setUniformValue(m_textureScale_id, QVector2D(1.0 / material->textureSize().width(),
- 1.0 / material->textureSize().height()));
- glBindTexture(GL_TEXTURE_2D, material->texture()->textureId);
-
- if (updated) {
- // Set the mag/min filters to be linear. We only need to do this when the texture
- // has been recreated.
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- }
- }
-}
-
-QSGDistanceFieldTextMaterial::QSGDistanceFieldTextMaterial()
- : m_glyph_cache(0)
- , m_texture(0)
-{
- setFlag(Blending, true);
-}
-
-QSGDistanceFieldTextMaterial::~QSGDistanceFieldTextMaterial()
-{
-}
-
-QSGMaterialType *QSGDistanceFieldTextMaterial::type() const
-{
- static QSGMaterialType type;
- return &type;
-}
-
-QSGMaterialShader *QSGDistanceFieldTextMaterial::createShader() const
-{
- return new QSGDistanceFieldTextMaterialShader;
-}
-
-bool QSGDistanceFieldTextMaterial::updateCache()
-{
- m_glyph_cache->update();
- if (!m_texture)
- m_texture = m_glyph_cache->glyphTexture(-1); // invalid texture
- QSize glyphCacheSize = m_texture->size;
- if (glyphCacheSize != m_size) {
- m_size = glyphCacheSize;
-
- return true;
- } else {
- return false;
- }
-}
-
-int QSGDistanceFieldTextMaterial::compare(const QSGMaterial *o) const
-{
- Q_ASSERT(o && type() == o->type());
- const QSGDistanceFieldTextMaterial *other = static_cast<const QSGDistanceFieldTextMaterial *>(o);
- if (m_glyph_cache != other->m_glyph_cache)
- return m_glyph_cache - other->m_glyph_cache;
- if (m_glyph_cache->fontScale() != other->m_glyph_cache->fontScale()) {
- qreal s1 = m_glyph_cache->fontScale();
- qreal s2 = other->m_glyph_cache->fontScale();
- return int(s2 < s1) - int(s1 < s2);
- }
- QRgb c1 = m_color.rgba();
- QRgb c2 = other->m_color.rgba();
- return int(c2 < c1) - int(c1 < c2);
-}
-
-
-class DistanceFieldStyledTextMaterialShader : public QSGDistanceFieldTextMaterialShader
-{
-public:
- DistanceFieldStyledTextMaterialShader();
-
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
-
-protected:
- virtual void initialize();
- virtual const char *fragmentShader() const = 0;
-
- int m_styleColor_id;
-};
-
-DistanceFieldStyledTextMaterialShader::DistanceFieldStyledTextMaterialShader()
- : QSGDistanceFieldTextMaterialShader()
-{
-}
-
-void DistanceFieldStyledTextMaterialShader::initialize()
-{
- QSGDistanceFieldTextMaterialShader::initialize();
- m_styleColor_id = program()->uniformLocation("styleColor");
-}
-
-void DistanceFieldStyledTextMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
-{
- QSGDistanceFieldTextMaterialShader::updateState(state, newEffect, oldEffect);
-
- QSGDistanceFieldStyledTextMaterial *material = static_cast<QSGDistanceFieldStyledTextMaterial *>(newEffect);
- QSGDistanceFieldStyledTextMaterial *oldMaterial = static_cast<QSGDistanceFieldStyledTextMaterial *>(oldEffect);
-
- if (oldMaterial == 0
- || material->styleColor() != oldMaterial->styleColor()
- || (state.isOpacityDirty())) {
- QVector4D color(material->styleColor().redF(), material->styleColor().greenF(),
- material->styleColor().blueF(), material->styleColor().alphaF());
- color *= state.opacity();
- program()->setUniformValue(m_styleColor_id, color);
- }
-}
-
-QSGDistanceFieldStyledTextMaterial::QSGDistanceFieldStyledTextMaterial()
- : QSGDistanceFieldTextMaterial()
-{
-}
-
-QSGDistanceFieldStyledTextMaterial::~QSGDistanceFieldStyledTextMaterial()
-{
-}
-
-int QSGDistanceFieldStyledTextMaterial::compare(const QSGMaterial *o) const
-{
- Q_ASSERT(o && type() == o->type());
- const QSGDistanceFieldStyledTextMaterial *other = static_cast<const QSGDistanceFieldStyledTextMaterial *>(o);
- if (m_styleColor != other->m_styleColor) {
- QRgb c1 = m_styleColor.rgba();
- QRgb c2 = other->m_styleColor.rgba();
- return int(c2 < c1) - int(c1 < c2);
- }
- return QSGDistanceFieldTextMaterial::compare(o);
-}
-
-
-class DistanceFieldOutlineTextMaterialShader : public DistanceFieldStyledTextMaterialShader
-{
-public:
- DistanceFieldOutlineTextMaterialShader();
-
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
-
-protected:
- virtual void initialize();
- virtual const char *fragmentShader() const;
-
- void updateOutlineAlphaRange(int dfRadius);
-
- int m_outlineAlphaMax0_id;
- int m_outlineAlphaMax1_id;
-};
-
-const char *DistanceFieldOutlineTextMaterialShader::fragmentShader() const {
- return
- "varying highp vec2 sampleCoord; \n"
- "uniform sampler2D texture; \n"
- "uniform lowp vec4 color; \n"
- "uniform lowp vec4 styleColor; \n"
- "uniform highp float alphaMin; \n"
- "uniform highp float alphaMax; \n"
- "uniform highp float outlineAlphaMax0; \n"
- "uniform highp float outlineAlphaMax1; \n"
- "void main() { \n"
- " mediump float d = texture2D(texture, sampleCoord).a; \n"
- " gl_FragColor = mix(styleColor, color, smoothstep(alphaMin, alphaMax, d)) \n"
- " * smoothstep(outlineAlphaMax0, outlineAlphaMax1, d); \n"
- "}";
-}
-
-DistanceFieldOutlineTextMaterialShader::DistanceFieldOutlineTextMaterialShader()
- : DistanceFieldStyledTextMaterialShader()
-{
-}
-
-void DistanceFieldOutlineTextMaterialShader::initialize()
-{
- DistanceFieldStyledTextMaterialShader::initialize();
- m_outlineAlphaMax0_id = program()->uniformLocation("outlineAlphaMax0");
- m_outlineAlphaMax1_id = program()->uniformLocation("outlineAlphaMax1");
-}
-
-void DistanceFieldOutlineTextMaterialShader::updateOutlineAlphaRange(int dfRadius)
-{
- qreal outlineLimit = qMax(qreal(0.2), qreal(0.5 - 0.5 / dfRadius / m_fontScale));
-
- qreal combinedScale = m_fontScale * m_matrixScale;
- qreal alphaMin = qMax(0.0, 0.5 - 0.07 / combinedScale);
- qreal styleAlphaMin0 = qMax(0.0, outlineLimit - 0.07 / combinedScale);
- qreal styleAlphaMin1 = qMin(qreal(outlineLimit + 0.07 / combinedScale), alphaMin);
- program()->setUniformValue(m_outlineAlphaMax0_id, GLfloat(styleAlphaMin0));
- program()->setUniformValue(m_outlineAlphaMax1_id, GLfloat(styleAlphaMin1));
-}
-
-void DistanceFieldOutlineTextMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
-{
- DistanceFieldStyledTextMaterialShader::updateState(state, newEffect, oldEffect);
-
- QSGDistanceFieldOutlineTextMaterial *material = static_cast<QSGDistanceFieldOutlineTextMaterial *>(newEffect);
- QSGDistanceFieldOutlineTextMaterial *oldMaterial = static_cast<QSGDistanceFieldOutlineTextMaterial *>(oldEffect);
-
- if (oldMaterial == 0
- || material->glyphCache()->fontScale() != oldMaterial->glyphCache()->fontScale()
- || state.isMatrixDirty())
- updateOutlineAlphaRange(material->glyphCache()->distanceFieldRadius());
-}
-
-
-QSGDistanceFieldOutlineTextMaterial::QSGDistanceFieldOutlineTextMaterial()
- : QSGDistanceFieldStyledTextMaterial()
-{
-}
-
-QSGDistanceFieldOutlineTextMaterial::~QSGDistanceFieldOutlineTextMaterial()
-{
-}
-
-QSGMaterialType *QSGDistanceFieldOutlineTextMaterial::type() const
-{
- static QSGMaterialType type;
- return &type;
-}
-
-QSGMaterialShader *QSGDistanceFieldOutlineTextMaterial::createShader() const
-{
- return new DistanceFieldOutlineTextMaterialShader;
-}
-
-
-class DistanceFieldShiftedStyleTextMaterialShader : public DistanceFieldStyledTextMaterialShader
-{
-public:
- DistanceFieldShiftedStyleTextMaterialShader();
-
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
-
-protected:
- virtual void initialize();
- virtual const char *vertexShader() const;
- virtual const char *fragmentShader() const;
-
- void updateShift(const QSGDistanceFieldGlyphCache *cache, const QPointF& shift);
-
- int m_shift_id;
-};
-
-DistanceFieldShiftedStyleTextMaterialShader::DistanceFieldShiftedStyleTextMaterialShader()
- : DistanceFieldStyledTextMaterialShader()
-{
-}
-
-void DistanceFieldShiftedStyleTextMaterialShader::initialize()
-{
- DistanceFieldStyledTextMaterialShader::initialize();
- m_shift_id = program()->uniformLocation("shift");
-}
-
-void DistanceFieldShiftedStyleTextMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
-{
- DistanceFieldStyledTextMaterialShader::updateState(state, newEffect, oldEffect);
-
- QSGDistanceFieldShiftedStyleTextMaterial *material = static_cast<QSGDistanceFieldShiftedStyleTextMaterial *>(newEffect);
- QSGDistanceFieldShiftedStyleTextMaterial *oldMaterial = static_cast<QSGDistanceFieldShiftedStyleTextMaterial *>(oldEffect);
-
- if (oldMaterial == 0
- || oldMaterial->glyphCache()->fontScale() != material->glyphCache()->fontScale()
- || oldMaterial->shift() != material->shift()
- || oldMaterial->textureSize() != material->textureSize()) {
- updateShift(material->glyphCache(), material->shift());
- }
-}
-
-void DistanceFieldShiftedStyleTextMaterialShader::updateShift(const QSGDistanceFieldGlyphCache *cache, const QPointF &shift)
-{
- QPointF texel(1.0 / cache->fontScale() * shift.x(),
- 1.0 / cache->fontScale() * shift.y());
- program()->setUniformValue(m_shift_id, texel);
-}
-
-const char *DistanceFieldShiftedStyleTextMaterialShader::vertexShader() const
-{
- return
- "uniform highp mat4 matrix; \n"
- "uniform highp vec2 textureScale; \n"
- "attribute highp vec4 vCoord; \n"
- "attribute highp vec2 tCoord; \n"
- "uniform highp vec2 shift; \n"
- "varying highp vec2 sampleCoord; \n"
- "varying highp vec2 shiftedSampleCoord; \n"
- "void main() { \n"
- " sampleCoord = tCoord * textureScale; \n"
- " shiftedSampleCoord = (tCoord - shift) * textureScale; \n"
- " gl_Position = matrix * vCoord; \n"
- "}";
-}
-
-const char *DistanceFieldShiftedStyleTextMaterialShader::fragmentShader() const {
- return
- "varying highp vec2 sampleCoord; \n"
- "varying highp vec2 shiftedSampleCoord; \n"
- "uniform sampler2D texture; \n"
- "uniform lowp vec4 color; \n"
- "uniform lowp vec4 styleColor; \n"
- "uniform highp float alphaMin; \n"
- "uniform highp float alphaMax; \n"
- "void main() { \n"
- " highp float a = smoothstep(alphaMin, alphaMax, texture2D(texture, sampleCoord).a);\n"
- " highp vec4 shifted = styleColor * smoothstep(alphaMin, \n"
- " alphaMax, \n"
- " texture2D(texture, shiftedSampleCoord).a); \n"
- " gl_FragColor = mix(shifted, color, a); \n"
- "}";
-}
-
-QSGDistanceFieldShiftedStyleTextMaterial::QSGDistanceFieldShiftedStyleTextMaterial()
- : QSGDistanceFieldStyledTextMaterial()
-{
-}
-
-QSGDistanceFieldShiftedStyleTextMaterial::~QSGDistanceFieldShiftedStyleTextMaterial()
-{
-}
-
-QSGMaterialType *QSGDistanceFieldShiftedStyleTextMaterial::type() const
-{
- static QSGMaterialType type;
- return &type;
-}
-
-QSGMaterialShader *QSGDistanceFieldShiftedStyleTextMaterial::createShader() const
-{
- return new DistanceFieldShiftedStyleTextMaterialShader;
-}
-
-
-class QSGHiQSubPixelDistanceFieldTextMaterialShader : public QSGDistanceFieldTextMaterialShader
-{
-public:
- virtual void initialize();
- virtual void activate();
- virtual void deactivate();
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
-
-protected:
- virtual const char *vertexShader() const;
- virtual const char *fragmentShader() const;
-
-private:
- int m_fontScale_id;
- int m_vecDelta_id;
-};
-
-const char *QSGHiQSubPixelDistanceFieldTextMaterialShader::vertexShader() const {
- return
- "uniform highp mat4 matrix; \n"
- "uniform highp vec2 textureScale; \n"
- "uniform highp float fontScale; \n"
- "uniform highp vec4 vecDelta; \n"
- "attribute highp vec4 vCoord; \n"
- "attribute highp vec2 tCoord; \n"
- "varying highp vec2 sampleCoord; \n"
- "varying highp vec3 sampleFarLeft; \n"
- "varying highp vec3 sampleNearLeft; \n"
- "varying highp vec3 sampleNearRight; \n"
- "varying highp vec3 sampleFarRight; \n"
- "void main() { \n"
- " sampleCoord = tCoord * textureScale; \n"
- " gl_Position = matrix * vCoord; \n"
- // Calculate neighbour pixel position in item space.
- " highp vec3 wDelta = gl_Position.w * vecDelta.xyw; \n"
- " highp vec3 farLeft = vCoord.xyw - 0.667 * wDelta; \n"
- " highp vec3 nearLeft = vCoord.xyw - 0.333 * wDelta; \n"
- " highp vec3 nearRight = vCoord.xyw + 0.333 * wDelta; \n"
- " highp vec3 farRight = vCoord.xyw + 0.667 * wDelta; \n"
- // Calculate neighbour texture coordinate.
- " highp vec2 scale = textureScale / fontScale; \n"
- " highp vec2 base = sampleCoord - scale * vCoord.xy; \n"
- " sampleFarLeft = vec3(base * farLeft.z + scale * farLeft.xy, farLeft.z); \n"
- " sampleNearLeft = vec3(base * nearLeft.z + scale * nearLeft.xy, nearLeft.z); \n"
- " sampleNearRight = vec3(base * nearRight.z + scale * nearRight.xy, nearRight.z); \n"
- " sampleFarRight = vec3(base * farRight.z + scale * farRight.xy, farRight.z); \n"
- "}";
-}
-
-const char *QSGHiQSubPixelDistanceFieldTextMaterialShader::fragmentShader() const {
- return
- "varying highp vec2 sampleCoord; \n"
- "varying highp vec3 sampleFarLeft; \n"
- "varying highp vec3 sampleNearLeft; \n"
- "varying highp vec3 sampleNearRight; \n"
- "varying highp vec3 sampleFarRight; \n"
- "uniform sampler2D texture; \n"
- "uniform lowp vec4 color; \n"
- "uniform highp float alphaMin; \n"
- "uniform highp float alphaMax; \n"
- "void main() { \n"
- " highp vec4 n; \n"
- " n.x = texture2DProj(texture, sampleFarLeft).a; \n"
- " n.y = texture2DProj(texture, sampleNearLeft).a; \n"
- " highp float c = texture2D(texture, sampleCoord).a; \n"
- " n.z = texture2DProj(texture, sampleNearRight).a; \n"
- " n.w = texture2DProj(texture, sampleFarRight).a; \n"
-#if 0
- // Blurrier, faster.
- " n = smoothstep(alphaMin, alphaMax, n); \n"
- " c = smoothstep(alphaMin, alphaMax, c); \n"
-#else
- // Sharper, slower.
- " highp vec2 d = min(abs(n.yw - n.xz) * 2., 0.67); \n"
- " highp vec2 lo = mix(vec2(alphaMin), vec2(0.5), d); \n"
- " highp vec2 hi = mix(vec2(alphaMax), vec2(0.5), d); \n"
- " n = smoothstep(lo.xxyy, hi.xxyy, n); \n"
- " c = smoothstep(lo.x + lo.y, hi.x + hi.y, 2. * c); \n"
-#endif
- " gl_FragColor = vec4(0.333 * (n.xyz + n.yzw + c), c) * color.w; \n"
- "}";
-}
-
-//const char *QSGHiQSubPixelDistanceFieldTextMaterialShader::fragmentShader() const {
-// return
-// "#extension GL_OES_standard_derivatives: enable \n"
-// "varying highp vec2 sampleCoord; \n"
-// "uniform sampler2D texture; \n"
-// "uniform lowp vec4 color; \n"
-// "uniform highp float alphaMin; \n"
-// "uniform highp float alphaMax; \n"
-// "void main() { \n"
-// " highp vec2 delta = dFdx(sampleCoord); \n"
-// " highp vec4 n; \n"
-// " n.x = texture2D(texture, sampleCoord - 0.667 * delta).a; \n"
-// " n.y = texture2D(texture, sampleCoord - 0.333 * delta).a; \n"
-// " highp float c = texture2D(texture, sampleCoord).a; \n"
-// " n.z = texture2D(texture, sampleCoord + 0.333 * delta).a; \n"
-// " n.w = texture2D(texture, sampleCoord + 0.667 * delta).a; \n"
-// " n = smoothstep(alphaMin, alphaMax, n); \n"
-// " c = smoothstep(alphaMin, alphaMax, c); \n"
-// " gl_FragColor = vec4(0.333 * (n.xyz + n.yzw + c), c) * color.w; \n"
-// "}";
-//}
-
-void QSGHiQSubPixelDistanceFieldTextMaterialShader::initialize()
-{
- QSGDistanceFieldTextMaterialShader::initialize();
- m_fontScale_id = program()->uniformLocation("fontScale");
- m_vecDelta_id = program()->uniformLocation("vecDelta");
-}
-
-void QSGHiQSubPixelDistanceFieldTextMaterialShader::activate()
-{
- QSGDistanceFieldTextMaterialShader::activate();
- glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
-}
-
-void QSGHiQSubPixelDistanceFieldTextMaterialShader::deactivate()
-{
- QSGDistanceFieldTextMaterialShader::deactivate();
- glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
-}
-
-void QSGHiQSubPixelDistanceFieldTextMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
-{
- Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type());
- QSGDistanceFieldTextMaterial *material = static_cast<QSGDistanceFieldTextMaterial *>(newEffect);
- QSGDistanceFieldTextMaterial *oldMaterial = static_cast<QSGDistanceFieldTextMaterial *>(oldEffect);
-
- if (oldMaterial == 0 || material->color() != oldMaterial->color()) {
- QColor c = material->color();
- state.context()->functions()->glBlendColor(c.redF(), c.greenF(), c.blueF(), 1.0f);
- }
-
- if (oldMaterial == 0 || material->glyphCache()->fontScale() != oldMaterial->glyphCache()->fontScale())
- program()->setUniformValue(m_fontScale_id, GLfloat(material->glyphCache()->fontScale()));
-
- if (oldMaterial == 0 || state.isMatrixDirty()) {
- int viewportWidth = state.viewportRect().width();
- QMatrix4x4 mat = state.combinedMatrix().inverted();
- program()->setUniformValue(m_vecDelta_id, mat.column(0) * (qreal(2) / viewportWidth));
- }
-
- QSGDistanceFieldTextMaterialShader::updateState(state, newEffect, oldEffect);
-}
-
-QSGMaterialType *QSGHiQSubPixelDistanceFieldTextMaterial::type() const
-{
- static QSGMaterialType type;
- return &type;
-}
-
-QSGMaterialShader *QSGHiQSubPixelDistanceFieldTextMaterial::createShader() const
-{
- return new QSGHiQSubPixelDistanceFieldTextMaterialShader;
-}
-
-
-class QSGLoQSubPixelDistanceFieldTextMaterialShader : public QSGHiQSubPixelDistanceFieldTextMaterialShader
-{
-protected:
- virtual const char *vertexShader() const;
- virtual const char *fragmentShader() const;
-};
-
-const char *QSGLoQSubPixelDistanceFieldTextMaterialShader::vertexShader() const {
- return
- "uniform highp mat4 matrix; \n"
- "uniform highp vec2 textureScale; \n"
- "uniform highp float fontScale; \n"
- "uniform highp vec4 vecDelta; \n"
- "attribute highp vec4 vCoord; \n"
- "attribute highp vec2 tCoord; \n"
- "varying highp vec3 sampleNearLeft; \n"
- "varying highp vec3 sampleNearRight; \n"
- "void main() { \n"
- " highp vec2 sampleCoord = tCoord * textureScale; \n"
- " gl_Position = matrix * vCoord; \n"
- // Calculate neighbour pixel position in item space.
- " highp vec3 wDelta = gl_Position.w * vecDelta.xyw; \n"
- " highp vec3 nearLeft = vCoord.xyw - 0.25 * wDelta; \n"
- " highp vec3 nearRight = vCoord.xyw + 0.25 * wDelta; \n"
- // Calculate neighbour texture coordinate.
- " highp vec2 scale = textureScale / fontScale; \n"
- " highp vec2 base = sampleCoord - scale * vCoord.xy; \n"
- " sampleNearLeft = vec3(base * nearLeft.z + scale * nearLeft.xy, nearLeft.z); \n"
- " sampleNearRight = vec3(base * nearRight.z + scale * nearRight.xy, nearRight.z); \n"
- "}";
-}
-
-const char *QSGLoQSubPixelDistanceFieldTextMaterialShader::fragmentShader() const {
- return
- "varying highp vec3 sampleNearLeft; \n"
- "varying highp vec3 sampleNearRight; \n"
- "uniform sampler2D texture; \n"
- "uniform lowp vec4 color; \n"
- "uniform highp float alphaMin; \n"
- "uniform highp float alphaMax; \n"
- "void main() { \n"
- " highp vec2 n; \n"
- " n.x = texture2DProj(texture, sampleNearLeft).a; \n"
- " n.y = texture2DProj(texture, sampleNearRight).a; \n"
- " n = smoothstep(alphaMin, alphaMax, n); \n"
- " highp float c = 0.5 * (n.x + n.y); \n"
- " gl_FragColor = vec4(n.x, c, n.y, c) * color.w; \n"
- "}";
-}
-
-QSGMaterialType *QSGLoQSubPixelDistanceFieldTextMaterial::type() const
-{
- static QSGMaterialType type;
- return &type;
-}
-
-QSGMaterialShader *QSGLoQSubPixelDistanceFieldTextMaterial::createShader() const
-{
- return new QSGLoQSubPixelDistanceFieldTextMaterialShader;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgdistancefieldglyphnode_p.h b/src/declarative/scenegraph/qsgdistancefieldglyphnode_p.h
deleted file mode 100644
index f4877b0a1d..0000000000
--- a/src/declarative/scenegraph/qsgdistancefieldglyphnode_p.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DISTANCEFIELD_GLYPHNODE_H
-#define DISTANCEFIELD_GLYPHNODE_H
-
-#include <private/qsgadaptationlayer_p.h>
-#include "qsgtexture.h"
-
-#include <private/qquicktext_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGDistanceFieldGlyphCacheManager;
-class QSGDistanceFieldTextMaterial;
-class QSGDistanceFieldGlyphNode: public QSGGlyphNode
-{
-public:
- QSGDistanceFieldGlyphNode(QSGDistanceFieldGlyphCacheManager *cacheManager);
- ~QSGDistanceFieldGlyphNode();
-
- virtual QPointF baseLine() const { return m_baseLine; }
- virtual void setGlyphs(const QPointF &position, const QGlyphRun &glyphs);
- virtual void setColor(const QColor &color);
-
- virtual void setPreferredAntialiasingMode(AntialiasingMode mode);
-
- virtual void setStyle(QQuickText::TextStyle style);
- virtual void setStyleColor(const QColor &color);
-
- virtual void update();
-
- void updateGeometry();
-
-private:
- void updateMaterial();
-
- QColor m_color;
- QPointF m_baseLine;
- QSGDistanceFieldTextMaterial *m_material;
- QPointF m_position;
- QGlyphRun m_glyphs;
- QSGDistanceFieldGlyphCacheManager *m_glyph_cacheManager;
- QSGDistanceFieldGlyphCache *m_glyph_cache;
- QSGGeometry m_geometry;
- QQuickText::TextStyle m_style;
- QColor m_styleColor;
- AntialiasingMode m_antialiasingMode;
- QRectF m_boundingRect;
-
- struct GlyphInfo {
- quint32 glyphIndex;
- QPointF position;
- };
- QLinkedList<GlyphInfo> m_glyphsToAdd;
-
- uint m_dirtyGeometry: 1;
- uint m_dirtyMaterial: 1;
-};
-
-QT_END_HEADER
-
-QT_END_NAMESPACE
-
-#endif // DISTANCEFIELD_GLYPHNODE_H
diff --git a/src/declarative/scenegraph/qsgdistancefieldglyphnode_p_p.h b/src/declarative/scenegraph/qsgdistancefieldglyphnode_p_p.h
deleted file mode 100644
index c8c73bfac0..0000000000
--- a/src/declarative/scenegraph/qsgdistancefieldglyphnode_p_p.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DISTANCEFIELDTEXTMATERIAL_H
-#define DISTANCEFIELDTEXTMATERIAL_H
-
-#include <qsgmaterial.h>
-#include "qsgdistancefieldglyphnode_p.h"
-#include "qsgadaptationlayer_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QSGDistanceFieldTextMaterial: public QSGMaterial
-{
-public:
- QSGDistanceFieldTextMaterial();
- ~QSGDistanceFieldTextMaterial();
-
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
- virtual int compare(const QSGMaterial *other) const;
-
- void setColor(const QColor &color) { m_color = color; }
- const QColor &color() const { return m_color; }
-
- void setGlyphCache(QSGDistanceFieldGlyphCache *a) { m_glyph_cache = a; }
- QSGDistanceFieldGlyphCache *glyphCache() const { return m_glyph_cache; }
-
- void setTexture(const QSGDistanceFieldGlyphCache::Texture * tex) { m_texture = tex; }
- const QSGDistanceFieldGlyphCache::Texture * texture() const { return m_texture; }
-
- QSize textureSize() const { return m_size; }
-
- bool updateCache();
-
-protected:
- QSize m_size;
- QColor m_color;
- QSGDistanceFieldGlyphCache *m_glyph_cache;
- const QSGDistanceFieldGlyphCache::Texture *m_texture;
-};
-
-class QSGDistanceFieldStyledTextMaterial : public QSGDistanceFieldTextMaterial
-{
-public:
- QSGDistanceFieldStyledTextMaterial();
- ~QSGDistanceFieldStyledTextMaterial();
-
- virtual QSGMaterialType *type() const = 0;
- virtual QSGMaterialShader *createShader() const = 0;
- virtual int compare(const QSGMaterial *other) const;
-
- void setStyleColor(const QColor &color) { m_styleColor = color; }
- const QColor &styleColor() const { return m_styleColor; }
-
-protected:
- QColor m_styleColor;
-};
-
-class QSGDistanceFieldOutlineTextMaterial : public QSGDistanceFieldStyledTextMaterial
-{
-public:
- QSGDistanceFieldOutlineTextMaterial();
- ~QSGDistanceFieldOutlineTextMaterial();
-
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
-};
-
-class QSGDistanceFieldShiftedStyleTextMaterial : public QSGDistanceFieldStyledTextMaterial
-{
-public:
- QSGDistanceFieldShiftedStyleTextMaterial();
- ~QSGDistanceFieldShiftedStyleTextMaterial();
-
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
-
- void setShift(const QPointF &shift) { m_shift = shift; }
- const QPointF &shift() const { return m_shift; }
-
-protected:
- QPointF m_shift;
-};
-
-class QSGHiQSubPixelDistanceFieldTextMaterial : public QSGDistanceFieldTextMaterial
-{
-public:
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
-};
-
-class QSGLoQSubPixelDistanceFieldTextMaterial : public QSGDistanceFieldTextMaterial
-{
-public:
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
-};
-
-QT_END_NAMESPACE
-
-#endif // DISTANCEFIELDTEXTMATERIAL_H
diff --git a/src/declarative/scenegraph/qsgflashnode.cpp b/src/declarative/scenegraph/qsgflashnode.cpp
deleted file mode 100644
index 9546e91ee1..0000000000
--- a/src/declarative/scenegraph/qsgflashnode.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgflashnode_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QSGFlashNode::QSGFlashNode()
- : m_counter(1)
-{
- setFlag(UsePreprocess);
- setColor(QColor(rand()%56 + 200, rand()%56 + 200, rand()%156 + 100)); // A random, mostly yellow, color
-}
-
-void QSGFlashNode::preprocess()
-{
- if (m_counter) {
- --m_counter;
- } else {
- delete this;
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgflashnode_p.h b/src/declarative/scenegraph/qsgflashnode_p.h
deleted file mode 100644
index 0967fa8901..0000000000
--- a/src/declarative/scenegraph/qsgflashnode_p.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGFLASHNODE_H
-#define QSGFLASHNODE_H
-
-#include <QSGSimpleRectNode>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGFlashNode : public QSGSimpleRectNode
-{
-public:
- QSGFlashNode();
-
- void preprocess();
-
-private:
- int m_counter;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSGFLASHNODE_H
-
diff --git a/src/declarative/scenegraph/qsgpathsimplifier.cpp b/src/declarative/scenegraph/qsgpathsimplifier.cpp
deleted file mode 100644
index 9e851bf434..0000000000
--- a/src/declarative/scenegraph/qsgpathsimplifier.cpp
+++ /dev/null
@@ -1,1673 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgpathsimplifier_p.h"
-
-#include <QtCore/qvarlengtharray.h>
-#include <QtCore/qglobal.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qalgorithms.h>
-
-#include <math.h>
-
-#include <private/qopengl_p.h>
-#include <private/qrbtree_p.h>
-
-QT_BEGIN_NAMESPACE
-
-#define Q_FIXED_POINT_SCALE 256
-#define Q_TRIANGULATE_END_OF_POLYGON quint32(-1)
-
-
-namespace {
-
-//============================================================================//
-// QPoint //
-//============================================================================//
-
-inline bool operator < (const QPoint &a, const QPoint &b)
-{
- return a.y() < b.y() || (a.y() == b.y() && a.x() < b.x());
-}
-
-inline bool operator > (const QPoint &a, const QPoint &b)
-{
- return b < a;
-}
-
-inline bool operator <= (const QPoint &a, const QPoint &b)
-{
- return !(a > b);
-}
-
-inline bool operator >= (const QPoint &a, const QPoint &b)
-{
- return !(a < b);
-}
-
-inline int cross(const QPoint &u, const QPoint &v)
-{
- return u.x() * v.y() - u.y() * v.x();
-}
-
-inline int dot(const QPoint &u, const QPoint &v)
-{
- return u.x() * v.x() + u.y() * v.y();
-}
-
-//============================================================================//
-// Fraction //
-//============================================================================//
-
-// Fraction must be in the range [0, 1)
-struct Fraction
-{
- bool isValid() const { return denominator != 0; }
-
- // numerator and denominator must not have common denominators.
- unsigned int numerator, denominator;
-};
-
-inline unsigned int gcd(unsigned int x, unsigned int y)
-{
- while (y != 0) {
- unsigned int z = y;
- y = x % y;
- x = z;
- }
- return x;
-}
-
-// Fraction must be in the range [0, 1)
-// Assume input is valid.
-Fraction fraction(unsigned int n, unsigned int d) {
- Fraction result;
- if (n == 0) {
- result.numerator = 0;
- result.denominator = 1;
- } else {
- unsigned int g = gcd(n, d);
- result.numerator = n / g;
- result.denominator = d / g;
- }
- return result;
-}
-
-//============================================================================//
-// Rational //
-//============================================================================//
-
-struct Rational
-{
- bool isValid() const { return fraction.isValid(); }
- int integer;
- Fraction fraction;
-};
-
-//============================================================================//
-// IntersectionPoint //
-//============================================================================//
-
-struct IntersectionPoint
-{
- bool isValid() const { return x.fraction.isValid() && y.fraction.isValid(); }
- QPoint round() const;
- bool isAccurate() const { return x.fraction.numerator == 0 && y.fraction.numerator == 0; }
-
- Rational x; // 8:8 signed, 32/32
- Rational y; // 8:8 signed, 32/32
-};
-
-QPoint IntersectionPoint::round() const
-{
- QPoint result(x.integer, y.integer);
- if (2 * x.fraction.numerator >= x.fraction.denominator)
- ++result.rx();
- if (2 * y.fraction.numerator >= y.fraction.denominator)
- ++result.ry();
- return result;
-}
-
-// Return positive value if 'p' is to the right of the line 'v1'->'v2', negative if left of the
-// line and zero if exactly on the line.
-// The returned value is the z-component of the qCross product between 'v2-v1' and 'p-v1',
-// which is twice the signed area of the triangle 'p'->'v1'->'v2' (positive for CW order).
-inline int pointDistanceFromLine(const QPoint &p, const QPoint &v1, const QPoint &v2)
-{
- return cross(v2 - v1, p - v1);
-}
-
-IntersectionPoint intersectionPoint(const QPoint &u1, const QPoint &u2,
- const QPoint &v1, const QPoint &v2)
-{
- IntersectionPoint result = {{0, {0, 0}}, {0, {0, 0}}};
-
- QPoint u = u2 - u1;
- QPoint v = v2 - v1;
- int d1 = cross(u, v1 - u1);
- int d2 = cross(u, v2 - u1);
- int det = d2 - d1;
- int d3 = cross(v, u1 - v1);
- int d4 = d3 - det; //qCross(v, u2 - v1);
-
- // Check that the math is correct.
- Q_ASSERT(d4 == cross(v, u2 - v1));
-
- // The intersection point can be expressed as:
- // v1 - v * d1/det
- // v2 - v * d2/det
- // u1 + u * d3/det
- // u2 + u * d4/det
-
- // I'm only interested in lines that are crossing, so ignore parallel lines even if they overlap.
- if (det == 0)
- return result;
-
- if (det < 0) {
- det = -det;
- d1 = -d1;
- d2 = -d2;
- d3 = -d3;
- d4 = -d4;
- }
-
- // I'm only interested in lines intersecting at their interior, not at their end points.
- // The lines intersect at their interior if and only if 'd1 < 0', 'd2 > 0', 'd3 < 0' and 'd4 > 0'.
- if (d1 >= 0 || d2 <= 0 || d3 <= 0 || d4 >= 0)
- return result;
-
- // Calculate the intersection point as follows:
- // v1 - v * d1/det | v1 <= v2 (component-wise)
- // v2 - v * d2/det | v2 < v1 (component-wise)
-
- // Assuming 16 bits per vector component.
- if (v.x() >= 0) {
- result.x.integer = v1.x() + int(qint64(-v.x()) * d1 / det);
- result.x.fraction = fraction((unsigned int)(qint64(-v.x()) * d1 % det), (unsigned int)det);
- } else {
- result.x.integer = v2.x() + int(qint64(-v.x()) * d2 / det);
- result.x.fraction = fraction((unsigned int)(qint64(-v.x()) * d2 % det), (unsigned int)det);
- }
-
- if (v.y() >= 0) {
- result.y.integer = v1.y() + int(qint64(-v.y()) * d1 / det);
- result.y.fraction = fraction((unsigned int)(qint64(-v.y()) * d1 % det), (unsigned int)det);
- } else {
- result.y.integer = v2.y() + int(qint64(-v.y()) * d2 / det);
- result.y.fraction = fraction((unsigned int)(qint64(-v.y()) * d2 % det), (unsigned int)det);
- }
-
- Q_ASSERT(result.x.fraction.isValid());
- Q_ASSERT(result.y.fraction.isValid());
- return result;
-}
-
-//============================================================================//
-// PathSimplifier //
-//============================================================================//
-
-class PathSimplifier
-{
-public:
- PathSimplifier(const QVectorPath &path, QDataBuffer<QPoint> &vertices,
- QDataBuffer<quint32> &indices, const QTransform &matrix);
-
-private:
- struct Element;
-
- class BoundingVolumeHierarchy
- {
- public:
- struct Node
- {
- enum Type
- {
- Leaf,
- Split
- };
- Type type;
- QPoint minimum;
- QPoint maximum;
- union {
- Element *element; // type == Leaf
- Node *left; // type == Split
- };
- Node *right;
- };
-
- BoundingVolumeHierarchy();
- ~BoundingVolumeHierarchy();
- void allocate(int nodeCount);
- void free();
- Node *newNode();
-
- Node *root;
- private:
- void freeNode(Node *n);
-
- Node *nodeBlock;
- int blockSize;
- int firstFree;
- };
-
- struct Element
- {
- enum Degree
- {
- Line = 1,
- Quadratic = 2,
- Cubic = 3
- };
-
- quint32 &upperIndex() { return indices[pointingUp ? degree : 0]; }
- quint32 &lowerIndex() { return indices[pointingUp ? 0 : degree]; }
- quint32 upperIndex() const { return indices[pointingUp ? degree : 0]; }
- quint32 lowerIndex() const { return indices[pointingUp ? 0 : degree]; }
- void flip();
-
- QPoint middle;
- quint32 indices[4]; // index to points
- Element *next, *previous; // used in connectElements()
- int winding; // used in connectElements()
- union {
- QRBTree<Element *>::Node *edgeNode; // used in connectElements()
- BoundingVolumeHierarchy::Node *bvhNode;
- };
- Degree degree : 8;
- uint processed : 1; // initially false, true when the element has been checked for intersections.
- uint pointingUp : 1; // used in connectElements()
- uint originallyPointingUp : 1; // used in connectElements()
- };
-
- class ElementAllocator
- {
- public:
- ElementAllocator();
- ~ElementAllocator();
- void allocate(int count);
- Element *newElement();
- private:
- struct ElementBlock
- {
- ElementBlock *next;
- int blockSize;
- int firstFree;
- Element elements[1];
- } *blocks;
- };
-
- struct Event
- {
- enum Type { Upper, Lower };
- bool operator < (const Event &other) const;
-
- QPoint point;
- Type type;
- Element *element;
- };
-
- typedef QRBTree<Element *>::Node RBNode;
- typedef BoundingVolumeHierarchy::Node BVHNode;
-
- void initElements(const QVectorPath &path, const QTransform &matrix);
- void removeIntersections();
- void connectElements();
- void fillIndices();
- BVHNode *buildTree(Element **elements, int elementCount);
- bool intersectNodes(QDataBuffer<Element *> &elements, BVHNode *elementNode, BVHNode *treeNode);
- bool equalElements(const Element *e1, const Element *e2);
- bool splitLineAt(QDataBuffer<Element *> &elements, BVHNode *node, quint32 pointIndex, bool processAgain);
- void appendSeparatingAxes(QVarLengthArray<QPoint, 12> &axes, Element *element);
- QPair<int, int> calculateSeparatingAxisRange(const QPoint &axis, Element *element);
- void splitCurve(QDataBuffer<Element *> &elements, BVHNode *node);
- bool setElementToQuadratic(Element *element, quint32 pointIndex1, const QPoint &ctrl, quint32 pointIndex2);
- bool setElementToCubic(Element *element, quint32 pointIndex1, const QPoint &ctrl1, const QPoint &ctrl2, quint32 pointIndex2);
- void setElementToCubicAndSimplify(Element *element, quint32 pointIndex1, const QPoint &ctrl1, const QPoint &ctrl2, quint32 pointIndex2);
- RBNode *findElementLeftOf(const Element *element, const QPair<RBNode *, RBNode *> &bounds);
- bool elementIsLeftOf(const Element *left, const Element *right);
- QPair<RBNode *, RBNode *> outerBounds(const QPoint &point);
- static bool flattenQuadratic(const QPoint &u, const QPoint &v, const QPoint &w);
- static bool flattenCubic(const QPoint &u, const QPoint &v, const QPoint &w, const QPoint &q);
- static bool splitQuadratic(const QPoint &u, const QPoint &v, const QPoint &w, QPoint *result);
- static bool splitCubic(const QPoint &u, const QPoint &v, const QPoint &w, const QPoint &q, QPoint *result);
- void subDivQuadratic(const QPoint &u, const QPoint &v, const QPoint &w);
- void subDivCubic(const QPoint &u, const QPoint &v, const QPoint &w, const QPoint &q);
- static void sortEvents(Event *events, int count);
-
- ElementAllocator m_elementAllocator;
- QDataBuffer<Element *> m_elements;
- QDataBuffer<QPoint> *m_points;
- BoundingVolumeHierarchy m_bvh;
- QDataBuffer<quint32> *m_indices;
- QRBTree<Element *> m_elementList;
- uint m_hints;
-};
-
-inline PathSimplifier::BoundingVolumeHierarchy::BoundingVolumeHierarchy()
- : root(0)
- , nodeBlock(0)
- , blockSize(0)
- , firstFree(0)
-{
-}
-
-inline PathSimplifier::BoundingVolumeHierarchy::~BoundingVolumeHierarchy()
-{
- free();
-}
-
-inline void PathSimplifier::BoundingVolumeHierarchy::allocate(int nodeCount)
-{
- Q_ASSERT(nodeBlock == 0);
- Q_ASSERT(firstFree == 0);
- nodeBlock = new Node[blockSize = nodeCount];
-}
-
-inline void PathSimplifier::BoundingVolumeHierarchy::free()
-{
- freeNode(root);
- delete[] nodeBlock;
- nodeBlock = 0;
- firstFree = blockSize = 0;
- root = 0;
-}
-
-inline PathSimplifier::BVHNode *PathSimplifier::BoundingVolumeHierarchy::newNode()
-{
- if (firstFree < blockSize)
- return &nodeBlock[firstFree++];
- return new Node;
-}
-
-inline void PathSimplifier::BoundingVolumeHierarchy::freeNode(Node *n)
-{
- if (!n)
- return;
- Q_ASSERT(n->type == Node::Split || n->type == Node::Leaf);
- if (n->type == Node::Split) {
- freeNode(n->left);
- freeNode(n->right);
- }
- if (!(n >= nodeBlock && n < nodeBlock + blockSize))
- delete n;
-}
-
-inline PathSimplifier::ElementAllocator::ElementAllocator()
- : blocks(0)
-{
-}
-
-inline PathSimplifier::ElementAllocator::~ElementAllocator()
-{
- while (blocks) {
- ElementBlock *block = blocks;
- blocks = blocks->next;
- qFree(block);
- }
-}
-
-inline void PathSimplifier::ElementAllocator::allocate(int count)
-{
- Q_ASSERT(blocks == 0);
- Q_ASSERT(count > 0);
- blocks = (ElementBlock *)qMalloc(sizeof(ElementBlock) + (count - 1) * sizeof(Element));
- blocks->blockSize = count;
- blocks->next = 0;
- blocks->firstFree = 0;
-}
-
-inline PathSimplifier::Element *PathSimplifier::ElementAllocator::newElement()
-{
- Q_ASSERT(blocks);
- if (blocks->firstFree < blocks->blockSize)
- return &blocks->elements[blocks->firstFree++];
- ElementBlock *oldBlock = blocks;
- blocks = (ElementBlock *)qMalloc(sizeof(ElementBlock) + (oldBlock->blockSize - 1) * sizeof(Element));
- blocks->blockSize = oldBlock->blockSize;
- blocks->next = oldBlock;
- blocks->firstFree = 0;
- return &blocks->elements[blocks->firstFree++];
-}
-
-
-inline bool PathSimplifier::Event::operator < (const Event &other) const
-{
- if (point == other.point)
- return type < other.type;
- return other.point < point;
-}
-
-inline void PathSimplifier::Element::flip()
-{
- for (int i = 0; i < (degree + 1) >> 1; ++i) {
- Q_ASSERT(degree >= Line && degree <= Cubic);
- Q_ASSERT(i >= 0 && i < degree);
- qSwap(indices[i], indices[degree - i]);
- }
- pointingUp = !pointingUp;
- Q_ASSERT(next == 0 && previous == 0);
-}
-
-PathSimplifier::PathSimplifier(const QVectorPath &path, QDataBuffer<QPoint> &vertices,
- QDataBuffer<quint32> &indices, const QTransform &matrix)
- : m_elements(0)
- , m_points(&vertices)
- , m_indices(&indices)
-{
- m_points->reset();
- m_indices->reset();
- initElements(path, matrix);
- if (!m_elements.isEmpty()) {
- removeIntersections();
- connectElements();
- fillIndices();
- }
-}
-
-void PathSimplifier::initElements(const QVectorPath &path, const QTransform &matrix)
-{
- m_hints = path.hints();
- int pathElementCount = path.elementCount();
- if (pathElementCount == 0)
- return;
- m_elements.reserve(2 * pathElementCount);
- m_elementAllocator.allocate(2 * pathElementCount);
- m_points->reserve(2 * pathElementCount);
- const QPainterPath::ElementType *e = path.elements();
- const qreal *p = path.points();
- if (e) {
- qreal x, y;
- quint32 moveToIndex = 0;
- quint32 previousIndex = 0;
- for (int i = 0; i < pathElementCount; ++i, ++e, p += 2) {
- switch (*e) {
- case QPainterPath::MoveToElement:
- {
- if (!m_points->isEmpty()) {
- const QPoint &from = m_points->at(previousIndex);
- const QPoint &to = m_points->at(moveToIndex);
- if (from != to) {
- Element *element = m_elementAllocator.newElement();
- element->degree = Element::Line;
- element->indices[0] = previousIndex;
- element->indices[1] = moveToIndex;
- element->middle.rx() = (from.x() + to.x()) >> 1;
- element->middle.ry() = (from.y() + to.y()) >> 1;
- m_elements.add(element);
- }
- }
- previousIndex = moveToIndex = m_points->size();
- matrix.map(p[0], p[1], &x, &y);
- QPoint to(qRound(x * Q_FIXED_POINT_SCALE), qRound(y * Q_FIXED_POINT_SCALE));
- m_points->add(to);
- }
- break;
- case QPainterPath::LineToElement:
- Q_ASSERT(!m_points->isEmpty());
- {
- matrix.map(p[0], p[1], &x, &y);
- QPoint to(qRound(x * Q_FIXED_POINT_SCALE), qRound(y * Q_FIXED_POINT_SCALE));
- const QPoint &from = m_points->last();
- if (to != from) {
- Element *element = m_elementAllocator.newElement();
- element->degree = Element::Line;
- element->indices[0] = previousIndex;
- element->indices[1] = quint32(m_points->size());
- element->middle.rx() = (from.x() + to.x()) >> 1;
- element->middle.ry() = (from.y() + to.y()) >> 1;
- m_elements.add(element);
- previousIndex = m_points->size();
- m_points->add(to);
- }
- }
- break;
- case QPainterPath::CurveToElement:
- Q_ASSERT(i + 2 < pathElementCount);
- Q_ASSERT(!m_points->isEmpty());
- Q_ASSERT(e[1] == QPainterPath::CurveToDataElement);
- Q_ASSERT(e[2] == QPainterPath::CurveToDataElement);
- {
- quint32 startPointIndex = previousIndex;
- matrix.map(p[4], p[5], &x, &y);
- QPoint end(qRound(x * Q_FIXED_POINT_SCALE), qRound(y * Q_FIXED_POINT_SCALE));
- previousIndex = m_points->size();
- m_points->add(end);
-
- // See if this cubic bezier is really quadratic.
- qreal x1 = p[-2] + qreal(1.5) * (p[0] - p[-2]);
- qreal y1 = p[-1] + qreal(1.5) * (p[1] - p[-1]);
- qreal x2 = p[4] + qreal(1.5) * (p[2] - p[4]);
- qreal y2 = p[5] + qreal(1.5) * (p[3] - p[5]);
-
- Element *element = m_elementAllocator.newElement();
- if (qAbs(x1 - x2) < qreal(1e-3) && qAbs(y1 - y2) < qreal(1e-3)) {
- // The bezier curve is quadratic.
- matrix.map(x1, y1, &x, &y);
- QPoint ctrl(qRound(x * Q_FIXED_POINT_SCALE),
- qRound(y * Q_FIXED_POINT_SCALE));
- setElementToQuadratic(element, startPointIndex, ctrl, previousIndex);
- } else {
- // The bezier curve is cubic.
- matrix.map(p[0], p[1], &x, &y);
- QPoint ctrl1(qRound(x * Q_FIXED_POINT_SCALE),
- qRound(y * Q_FIXED_POINT_SCALE));
- matrix.map(p[2], p[3], &x, &y);
- QPoint ctrl2(qRound(x * Q_FIXED_POINT_SCALE),
- qRound(y * Q_FIXED_POINT_SCALE));
- setElementToCubicAndSimplify(element, startPointIndex, ctrl1, ctrl2,
- previousIndex);
- }
- m_elements.add(element);
- }
- i += 2;
- e += 2;
- p += 4;
-
- break;
- default:
- Q_ASSERT_X(0, "QSGPathSimplifier::initialize", "Unexpected element type.");
- break;
- }
- }
- if (!m_points->isEmpty()) {
- const QPoint &from = m_points->at(previousIndex);
- const QPoint &to = m_points->at(moveToIndex);
- if (from != to) {
- Element *element = m_elementAllocator.newElement();
- element->degree = Element::Line;
- element->indices[0] = previousIndex;
- element->indices[1] = moveToIndex;
- element->middle.rx() = (from.x() + to.x()) >> 1;
- element->middle.ry() = (from.y() + to.y()) >> 1;
- m_elements.add(element);
- }
- }
- } else {
- qreal x, y;
-
- for (int i = 0; i < pathElementCount; ++i, p += 2) {
- matrix.map(p[0], p[1], &x, &y);
- QPoint to(qRound(x * Q_FIXED_POINT_SCALE), qRound(y * Q_FIXED_POINT_SCALE));
- if (to != m_points->last())
- m_points->add(to);
- }
-
- while (!m_points->isEmpty() && m_points->last() == m_points->first())
- m_points->pop_back();
-
- if (m_points->isEmpty())
- return;
-
- quint32 prev = quint32(m_points->size() - 1);
- for (int i = 0; i < m_points->size(); ++i) {
- QPoint &to = m_points->at(i);
- QPoint &from = m_points->at(prev);
- Element *element = m_elementAllocator.newElement();
- element->degree = Element::Line;
- element->indices[0] = prev;
- element->indices[1] = quint32(i);
- element->middle.rx() = (from.x() + to.x()) >> 1;
- element->middle.ry() = (from.y() + to.y()) >> 1;
- m_elements.add(element);
- prev = i;
- }
- }
-
- for (int i = 0; i < m_elements.size(); ++i)
- m_elements.at(i)->processed = false;
-}
-
-void PathSimplifier::removeIntersections()
-{
- Q_ASSERT(!m_elements.isEmpty());
- QDataBuffer<Element *> elements(m_elements.size());
- for (int i = 0; i < m_elements.size(); ++i)
- elements.add(m_elements.at(i));
- m_bvh.allocate(2 * m_elements.size());
- m_bvh.root = buildTree(elements.data(), elements.size());
-
- elements.reset();
- for (int i = 0; i < m_elements.size(); ++i)
- elements.add(m_elements.at(i));
-
- while (!elements.isEmpty()) {
- Element *element = elements.last();
- elements.pop_back();
- BVHNode *node = element->bvhNode;
- Q_ASSERT(node->type == BVHNode::Leaf);
- Q_ASSERT(node->element == element);
- if (!element->processed) {
- if (!intersectNodes(elements, node, m_bvh.root))
- element->processed = true;
- }
- }
-
- m_bvh.free(); // The bounding volume hierarchy is not needed anymore.
-}
-
-void PathSimplifier::connectElements()
-{
- Q_ASSERT(!m_elements.isEmpty());
- QDataBuffer<Event> events(m_elements.size() * 2);
- for (int i = 0; i < m_elements.size(); ++i) {
- Element *element = m_elements.at(i);
- element->next = element->previous = 0;
- element->winding = 0;
- element->edgeNode = 0;
- const QPoint &u = m_points->at(element->indices[0]);
- const QPoint &v = m_points->at(element->indices[element->degree]);
- if (u != v) {
- element->pointingUp = element->originallyPointingUp = v < u;
-
- Event event;
- event.element = element;
- event.point = u;
- event.type = element->pointingUp ? Event::Lower : Event::Upper;
- events.add(event);
- event.point = v;
- event.type = element->pointingUp ? Event::Upper : Event::Lower;
- events.add(event);
- }
- }
- QVarLengthArray<Element *, 8> orderedElements;
- if (!events.isEmpty())
- sortEvents(events.data(), events.size());
- while (!events.isEmpty()) {
- const Event *event = &events.last();
- QPoint eventPoint = event->point;
-
- // Find all elements passing through the event point.
- QPair<RBNode *, RBNode *> bounds = outerBounds(eventPoint);
-
- // Special case: single element above and single element below event point.
- int eventCount = events.size();
- if (event->type == Event::Lower && eventCount > 2) {
- QPair<RBNode *, RBNode *> range;
- range.first = bounds.first ? m_elementList.next(bounds.first)
- : m_elementList.front(m_elementList.root);
- range.second = bounds.second ? m_elementList.previous(bounds.second)
- : m_elementList.back(m_elementList.root);
-
- const Event *event2 = &events.at(eventCount - 2);
- const Event *event3 = &events.at(eventCount - 3);
- Q_ASSERT(event2->point == eventPoint); // There are always at least two events at a point.
- if (range.first == range.second && event2->type == Event::Upper && event3->point != eventPoint) {
- Element *element = event->element;
- Element *element2 = event2->element;
- element->edgeNode->data = event2->element;
- element2->edgeNode = element->edgeNode;
- element->edgeNode = 0;
-
- events.pop_back();
- events.pop_back();
-
- if (element2->pointingUp != element->pointingUp)
- element2->flip();
- element2->winding = element->winding;
- int winding = element->winding;
- if (element->originallyPointingUp)
- ++winding;
- if (winding == 0 || winding == 1) {
- if (element->pointingUp) {
- element->previous = event2->element;
- element2->next = event->element;
- } else {
- element->next = event2->element;
- element2->previous = event->element;
- }
- }
- continue;
- }
- }
- orderedElements.clear();
-
- // First, find the ones above the event point.
- if (m_elementList.root) {
- RBNode *current = bounds.first ? m_elementList.next(bounds.first)
- : m_elementList.front(m_elementList.root);
- while (current != bounds.second) {
- Element *element = current->data;
- Q_ASSERT(element->edgeNode == current);
- int winding = element->winding;
- if (element->originallyPointingUp)
- ++winding;
- const QPoint &lower = m_points->at(element->lowerIndex());
- if (lower == eventPoint) {
- if (winding == 0 || winding == 1)
- orderedElements.append(current->data);
- } else {
- // The element is passing through 'event.point'.
- Q_ASSERT(m_points->at(element->upperIndex()) != eventPoint);
- Q_ASSERT(element->degree == Element::Line);
- // Split the line.
- Element *eventElement = event->element;
- int indexIndex = (event->type == Event::Upper) == eventElement->pointingUp
- ? eventElement->degree : 0;
- quint32 pointIndex = eventElement->indices[indexIndex];
- Q_ASSERT(eventPoint == m_points->at(pointIndex));
-
- Element *upperElement = m_elementAllocator.newElement();
- *upperElement = *element;
- upperElement->lowerIndex() = element->upperIndex() = pointIndex;
- upperElement->edgeNode = 0;
- element->next = element->previous = 0;
- if (upperElement->next)
- upperElement->next->previous = upperElement;
- else if (upperElement->previous)
- upperElement->previous->next = upperElement;
- if (element->pointingUp != element->originallyPointingUp)
- element->flip();
- if (winding == 0 || winding == 1)
- orderedElements.append(upperElement);
- m_elements.add(upperElement);
- }
- current = m_elementList.next(current);
- }
- }
- while (!events.isEmpty() && events.last().point == eventPoint) {
- event = &events.last();
- if (event->type == Event::Upper) {
- Q_ASSERT(event->point == m_points->at(event->element->upperIndex()));
- RBNode *left = findElementLeftOf(event->element, bounds);
- RBNode *node = m_elementList.newNode();
- node->data = event->element;
- Q_ASSERT(event->element->edgeNode == 0);
- event->element->edgeNode = node;
- m_elementList.attachAfter(left, node);
- } else {
- Q_ASSERT(event->type == Event::Lower);
- Q_ASSERT(event->point == m_points->at(event->element->lowerIndex()));
- Element *element = event->element;
- Q_ASSERT(element->edgeNode);
- m_elementList.deleteNode(element->edgeNode);
- Q_ASSERT(element->edgeNode == 0);
- }
- events.pop_back();
- }
-
- if (m_elementList.root) {
- RBNode *current = bounds.first ? m_elementList.next(bounds.first)
- : m_elementList.front(m_elementList.root);
- int winding = bounds.first ? bounds.first->data->winding : 0;
-
- // Calculate winding numbers and flip elements if necessary.
- while (current != bounds.second) {
- Element *element = current->data;
- Q_ASSERT(element->edgeNode == current);
- int ccw = winding & 1;
- Q_ASSERT(element->pointingUp == element->originallyPointingUp);
- if (element->originallyPointingUp) {
- --winding;
- } else {
- ++winding;
- ccw ^= 1;
- }
- element->winding = winding;
- if (ccw == 0)
- element->flip();
- current = m_elementList.next(current);
- }
-
- // Pick elements with correct winding number.
- current = bounds.second ? m_elementList.previous(bounds.second)
- : m_elementList.back(m_elementList.root);
- while (current != bounds.first) {
- Element *element = current->data;
- Q_ASSERT(element->edgeNode == current);
- Q_ASSERT(m_points->at(element->upperIndex()) == eventPoint);
- int winding = element->winding;
- if (element->originallyPointingUp)
- ++winding;
- if (winding == 0 || winding == 1)
- orderedElements.append(current->data);
- current = m_elementList.previous(current);
- }
- }
-
- if (!orderedElements.isEmpty()) {
- Q_ASSERT((orderedElements.size() & 1) == 0);
- int i = 0;
- Element *firstElement = orderedElements.at(0);
- if (m_points->at(firstElement->indices[0]) != eventPoint) {
- orderedElements.append(firstElement);
- i = 1;
- }
- for (; i < orderedElements.size(); i += 2) {
- Q_ASSERT(i + 1 < orderedElements.size());
- Element *next = orderedElements.at(i);
- Element *previous = orderedElements.at(i + 1);
- Q_ASSERT(next->previous == 0);
- Q_ASSERT(previous->next == 0);
- next->previous = previous;
- previous->next = next;
- }
- }
- }
-#ifndef QT_NO_DEBUG
- for (int i = 0; i < m_elements.size(); ++i) {
- const Element *element = m_elements.at(i);
- Q_ASSERT(element->next == 0 || element->next->previous == element);
- Q_ASSERT(element->previous == 0 || element->previous->next == element);
- Q_ASSERT((element->next == 0) == (element->previous == 0));
- }
-#endif
-}
-
-void PathSimplifier::fillIndices()
-{
- for (int i = 0; i < m_elements.size(); ++i)
- m_elements.at(i)->processed = false;
- for (int i = 0; i < m_elements.size(); ++i) {
- Element *element = m_elements.at(i);
- if (element->processed || element->next == 0)
- continue;
- do {
- m_indices->add(element->indices[0]);
- switch (element->degree) {
- case Element::Quadratic:
- {
- QPoint pts[] = {
- m_points->at(element->indices[0]),
- m_points->at(element->indices[1]),
- m_points->at(element->indices[2])
- };
- subDivQuadratic(pts[0], pts[1], pts[2]);
- }
- break;
- case Element::Cubic:
- {
- QPoint pts[] = {
- m_points->at(element->indices[0]),
- m_points->at(element->indices[1]),
- m_points->at(element->indices[2]),
- m_points->at(element->indices[3])
- };
- subDivCubic(pts[0], pts[1], pts[2], pts[3]);
- }
- break;
- default:
- break;
- }
- Q_ASSERT(element->next);
- element->processed = true;
- element = element->next;
- } while (element != m_elements.at(i));
- m_indices->add(Q_TRIANGULATE_END_OF_POLYGON);
- }
-}
-
-PathSimplifier::BVHNode *PathSimplifier::buildTree(Element **elements, int elementCount)
-{
- Q_ASSERT(elementCount > 0);
- BVHNode *node = m_bvh.newNode();
- if (elementCount == 1) {
- Element *element = *elements;
- element->bvhNode = node;
- node->type = BVHNode::Leaf;
- node->element = element;
- node->minimum = node->maximum = m_points->at(element->indices[0]);
- for (int i = 1; i <= element->degree; ++i) {
- const QPoint &p = m_points->at(element->indices[i]);
- node->minimum.rx() = qMin(node->minimum.x(), p.x());
- node->minimum.ry() = qMin(node->minimum.y(), p.y());
- node->maximum.rx() = qMax(node->maximum.x(), p.x());
- node->maximum.ry() = qMax(node->maximum.y(), p.y());
- }
- return node;
- }
-
- node->type = BVHNode::Split;
-
- QPoint minimum, maximum;
- minimum = maximum = elements[0]->middle;
-
- for (int i = 1; i < elementCount; ++i) {
- const QPoint &p = elements[i]->middle;
- minimum.rx() = qMin(minimum.x(), p.x());
- minimum.ry() = qMin(minimum.y(), p.y());
- maximum.rx() = qMax(maximum.x(), p.x());
- maximum.ry() = qMax(maximum.y(), p.y());
- }
-
- int comp, pivot;
- if (maximum.x() - minimum.x() > maximum.y() - minimum.y()) {
- comp = 0;
- pivot = (maximum.x() + minimum.x()) >> 1;
- } else {
- comp = 1;
- pivot = (maximum.y() + minimum.y()) >> 1;
- }
-
- int lo = 0;
- int hi = elementCount - 1;
- while (lo < hi) {
- while (lo < hi && (&elements[lo]->middle.rx())[comp] <= pivot)
- ++lo;
- while (lo < hi && (&elements[hi]->middle.rx())[comp] > pivot)
- --hi;
- if (lo < hi)
- qSwap(elements[lo], elements[hi]);
- }
-
- if (lo == elementCount) {
- // All points are the same.
- Q_ASSERT(minimum.x() == maximum.x() && minimum.y() == maximum.y());
- lo = elementCount >> 1;
- }
-
- node->left = buildTree(elements, lo);
- node->right = buildTree(elements + lo, elementCount - lo);
-
- const BVHNode *left = node->left;
- const BVHNode *right = node->right;
- node->minimum.rx() = qMin(left->minimum.x(), right->minimum.x());
- node->minimum.ry() = qMin(left->minimum.y(), right->minimum.y());
- node->maximum.rx() = qMax(left->maximum.x(), right->maximum.x());
- node->maximum.ry() = qMax(left->maximum.y(), right->maximum.y());
-
- return node;
-}
-
-bool PathSimplifier::intersectNodes(QDataBuffer<Element *> &elements, BVHNode *elementNode,
- BVHNode *treeNode)
-{
- if (elementNode->minimum.x() >= treeNode->maximum.x()
- || elementNode->minimum.y() >= treeNode->maximum.y()
- || elementNode->maximum.x() <= treeNode->minimum.x()
- || elementNode->maximum.y() <= treeNode->minimum.y())
- {
- return false;
- }
-
- Q_ASSERT(elementNode->type == BVHNode::Leaf);
- Element *element = elementNode->element;
- Q_ASSERT(!element->processed);
-
- if (treeNode->type == BVHNode::Leaf) {
- Element *nodeElement = treeNode->element;
- if (!nodeElement->processed)
- return false;
-
- if (treeNode->element == elementNode->element)
- return false;
-
- if (equalElements(treeNode->element, elementNode->element))
- return false; // element doesn't split itself.
-
- if (element->degree == Element::Line && nodeElement->degree == Element::Line) {
- const QPoint &u1 = m_points->at(element->indices[0]);
- const QPoint &u2 = m_points->at(element->indices[1]);
- const QPoint &v1 = m_points->at(nodeElement->indices[0]);
- const QPoint &v2 = m_points->at(nodeElement->indices[1]);
- IntersectionPoint intersection = intersectionPoint(u1, u2, v1, v2);
- if (!intersection.isValid())
- return false;
-
- Q_ASSERT(intersection.x.integer >= qMin(u1.x(), u2.x()));
- Q_ASSERT(intersection.y.integer >= qMin(u1.y(), u2.y()));
- Q_ASSERT(intersection.x.integer >= qMin(v1.x(), v2.x()));
- Q_ASSERT(intersection.y.integer >= qMin(v1.y(), v2.y()));
-
- Q_ASSERT(intersection.x.integer <= qMax(u1.x(), u2.x()));
- Q_ASSERT(intersection.y.integer <= qMax(u1.y(), u2.y()));
- Q_ASSERT(intersection.x.integer <= qMax(v1.x(), v2.x()));
- Q_ASSERT(intersection.y.integer <= qMax(v1.y(), v2.y()));
-
- m_points->add(intersection.round());
- splitLineAt(elements, treeNode, m_points->size() - 1, !intersection.isAccurate());
- return splitLineAt(elements, elementNode, m_points->size() - 1, false);
- } else {
- QVarLengthArray<QPoint, 12> axes;
- appendSeparatingAxes(axes, elementNode->element);
- appendSeparatingAxes(axes, treeNode->element);
- for (int i = 0; i < axes.size(); ++i) {
- QPair<int, int> range1 = calculateSeparatingAxisRange(axes.at(i), elementNode->element);
- QPair<int, int> range2 = calculateSeparatingAxisRange(axes.at(i), treeNode->element);
- if (range1.first >= range2.second || range1.second <= range2.first) {
- return false; // Separating axis found.
- }
- }
- // Bounding areas overlap.
- if (nodeElement->degree > Element::Line)
- splitCurve(elements, treeNode);
- if (element->degree > Element::Line) {
- splitCurve(elements, elementNode);
- } else {
- // The element was not split, so it can be processed further.
- if (intersectNodes(elements, elementNode, treeNode->left))
- return true;
- if (intersectNodes(elements, elementNode, treeNode->right))
- return true;
- return false;
- }
- return true;
- }
- } else {
- if (intersectNodes(elements, elementNode, treeNode->left))
- return true;
- if (intersectNodes(elements, elementNode, treeNode->right))
- return true;
- return false;
- }
-}
-
-bool PathSimplifier::equalElements(const Element *e1, const Element *e2)
-{
- Q_ASSERT(e1 != e2);
- if (e1->degree != e2->degree)
- return false;
-
- // Possibly equal and in the same direction.
- bool equalSame = true;
- for (int i = 0; i <= e1->degree; ++i)
- equalSame &= m_points->at(e1->indices[i]) == m_points->at(e2->indices[i]);
-
- // Possibly equal and in opposite directions.
- bool equalOpposite = true;
- for (int i = 0; i <= e1->degree; ++i)
- equalOpposite &= m_points->at(e1->indices[e1->degree - i]) == m_points->at(e2->indices[i]);
-
- return equalSame || equalOpposite;
-}
-
-bool PathSimplifier::splitLineAt(QDataBuffer<Element *> &elements, BVHNode *node,
- quint32 pointIndex, bool processAgain)
-{
- Q_ASSERT(node->type == BVHNode::Leaf);
- Element *element = node->element;
- Q_ASSERT(element->degree == Element::Line);
- const QPoint &u = m_points->at(element->indices[0]);
- const QPoint &v = m_points->at(element->indices[1]);
- const QPoint &p = m_points->at(pointIndex);
- if (u == p || v == p)
- return false; // No split needed.
-
- if (processAgain)
- element->processed = false; // Needs to be processed again.
-
- Element *first = node->element;
- Element *second = m_elementAllocator.newElement();
- *second = *first;
- first->indices[1] = second->indices[0] = pointIndex;
- first->middle.rx() = (u.x() + p.x()) >> 1;
- first->middle.ry() = (u.y() + p.y()) >> 1;
- second->middle.rx() = (v.x() + p.x()) >> 1;
- second->middle.ry() = (v.y() + p.y()) >> 1;
- m_elements.add(second);
-
- BVHNode *left = m_bvh.newNode();
- BVHNode *right = m_bvh.newNode();
- left->type = right->type = BVHNode::Leaf;
- left->element = first;
- right->element = second;
- left->minimum = right->minimum = node->minimum;
- left->maximum = right->maximum = node->maximum;
- if (u.x() < v.x())
- left->maximum.rx() = right->minimum.rx() = p.x();
- else
- left->minimum.rx() = right->maximum.rx() = p.x();
- if (u.y() < v.y())
- left->maximum.ry() = right->minimum.ry() = p.y();
- else
- left->minimum.ry() = right->maximum.ry() = p.y();
- left->element->bvhNode = left;
- right->element->bvhNode = right;
-
- node->type = BVHNode::Split;
- node->left = left;
- node->right = right;
-
- if (!first->processed) {
- elements.add(left->element);
- elements.add(right->element);
- }
- return true;
-}
-
-void PathSimplifier::appendSeparatingAxes(QVarLengthArray<QPoint, 12> &axes, Element *element)
-{
- switch (element->degree) {
- case Element::Cubic:
- {
- const QPoint &u = m_points->at(element->indices[0]);
- const QPoint &v = m_points->at(element->indices[1]);
- const QPoint &w = m_points->at(element->indices[2]);
- const QPoint &q = m_points->at(element->indices[3]);
- QPoint ns[] = {
- QPoint(u.y() - v.y(), v.x() - u.x()),
- QPoint(v.y() - w.y(), w.x() - v.x()),
- QPoint(w.y() - q.y(), q.x() - w.x()),
- QPoint(q.y() - u.y(), u.x() - q.x()),
- QPoint(u.y() - w.y(), w.x() - u.x()),
- QPoint(v.y() - q.y(), q.x() - v.x())
- };
- for (int i = 0; i < 6; ++i) {
- if (ns[i].x() || ns[i].y())
- axes.append(ns[i]);
- }
- }
- break;
- case Element::Quadratic:
- {
- const QPoint &u = m_points->at(element->indices[0]);
- const QPoint &v = m_points->at(element->indices[1]);
- const QPoint &w = m_points->at(element->indices[2]);
- QPoint ns[] = {
- QPoint(u.y() - v.y(), v.x() - u.x()),
- QPoint(v.y() - w.y(), w.x() - v.x()),
- QPoint(w.y() - u.y(), u.x() - w.x())
- };
- for (int i = 0; i < 3; ++i) {
- if (ns[i].x() || ns[i].y())
- axes.append(ns[i]);
- }
- }
- break;
- case Element::Line:
- {
- const QPoint &u = m_points->at(element->indices[0]);
- const QPoint &v = m_points->at(element->indices[1]);
- QPoint n(u.y() - v.y(), v.x() - u.x());
- if (n.x() || n.y())
- axes.append(n);
- }
- break;
- default:
- Q_ASSERT_X(0, "QSGPathSimplifier::appendSeparatingAxes", "Unexpected element type.");
- break;
- }
-}
-
-QPair<int, int> PathSimplifier::calculateSeparatingAxisRange(const QPoint &axis, Element *element)
-{
- QPair<int, int> range(0x7fffffff, -0x7fffffff);
- for (int i = 0; i <= element->degree; ++i) {
- const QPoint &p = m_points->at(element->indices[i]);
- int dist = dot(axis, p);
- range.first = qMin(range.first, dist);
- range.second = qMax(range.second, dist);
- }
- return range;
-}
-
-void PathSimplifier::splitCurve(QDataBuffer<Element *> &elements, BVHNode *node)
-{
- Q_ASSERT(node->type == BVHNode::Leaf);
-
- Element *first = node->element;
- Element *second = m_elementAllocator.newElement();
- *second = *first;
- m_elements.add(second);
- Q_ASSERT(first->degree > Element::Line);
-
- bool accurate = true;
- const QPoint &u = m_points->at(first->indices[0]);
- const QPoint &v = m_points->at(first->indices[1]);
- const QPoint &w = m_points->at(first->indices[2]);
-
- if (first->degree == Element::Quadratic) {
- QPoint pts[3];
- accurate = splitQuadratic(u, v, w, pts);
- int pointIndex = m_points->size();
- m_points->add(pts[1]);
- accurate &= setElementToQuadratic(first, first->indices[0], pts[0], pointIndex);
- accurate &= setElementToQuadratic(second, pointIndex, pts[2], second->indices[2]);
- } else {
- Q_ASSERT(first->degree == Element::Cubic);
- const QPoint &q = m_points->at(first->indices[3]);
- QPoint pts[5];
- accurate = splitCubic(u, v, w, q, pts);
- int pointIndex = m_points->size();
- m_points->add(pts[2]);
- accurate &= setElementToCubic(first, first->indices[0], pts[0], pts[1], pointIndex);
- accurate &= setElementToCubic(second, pointIndex, pts[3], pts[4], second->indices[3]);
- }
-
- if (!accurate)
- first->processed = second->processed = false; // Needs to be processed again.
-
- BVHNode *left = m_bvh.newNode();
- BVHNode *right = m_bvh.newNode();
- left->type = right->type = BVHNode::Leaf;
- left->element = first;
- right->element = second;
-
- left->minimum.rx() = left->minimum.ry() = right->minimum.rx() = right->minimum.ry() = INT_MAX;
- left->maximum.rx() = left->maximum.ry() = right->maximum.rx() = right->maximum.ry() = INT_MIN;
-
- for (int i = 0; i <= first->degree; ++i) {
- QPoint &p = m_points->at(first->indices[i]);
- left->minimum.rx() = qMin(left->minimum.x(), p.x());
- left->minimum.ry() = qMin(left->minimum.y(), p.y());
- left->maximum.rx() = qMax(left->maximum.x(), p.x());
- left->maximum.ry() = qMax(left->maximum.y(), p.y());
- }
- for (int i = 0; i <= second->degree; ++i) {
- QPoint &p = m_points->at(second->indices[i]);
- right->minimum.rx() = qMin(right->minimum.x(), p.x());
- right->minimum.ry() = qMin(right->minimum.y(), p.y());
- right->maximum.rx() = qMax(right->maximum.x(), p.x());
- right->maximum.ry() = qMax(right->maximum.y(), p.y());
- }
- left->element->bvhNode = left;
- right->element->bvhNode = right;
-
- node->type = BVHNode::Split;
- node->left = left;
- node->right = right;
-
- if (!first->processed) {
- elements.add(left->element);
- elements.add(right->element);
- }
-}
-
-bool PathSimplifier::setElementToQuadratic(Element *element, quint32 pointIndex1,
- const QPoint &ctrl, quint32 pointIndex2)
-{
- const QPoint &p1 = m_points->at(pointIndex1);
- const QPoint &p2 = m_points->at(pointIndex2);
- if (flattenQuadratic(p1, ctrl, p2)) {
- // Insert line.
- element->degree = Element::Line;
- element->indices[0] = pointIndex1;
- element->indices[1] = pointIndex2;
- element->middle.rx() = (p1.x() + p2.x()) >> 1;
- element->middle.ry() = (p1.y() + p2.y()) >> 1;
- return false;
- } else {
- // Insert bezier.
- element->degree = Element::Quadratic;
- element->indices[0] = pointIndex1;
- element->indices[1] = m_points->size();
- element->indices[2] = pointIndex2;
- element->middle.rx() = (p1.x() + ctrl.x() + p2.x()) / 3;
- element->middle.ry() = (p1.y() + ctrl.y() + p2.y()) / 3;
- m_points->add(ctrl);
- return true;
- }
-}
-
-bool PathSimplifier::setElementToCubic(Element *element, quint32 pointIndex1, const QPoint &v,
- const QPoint &w, quint32 pointIndex2)
-{
- const QPoint &u = m_points->at(pointIndex1);
- const QPoint &q = m_points->at(pointIndex2);
- if (flattenCubic(u, v, w, q)) {
- // Insert line.
- element->degree = Element::Line;
- element->indices[0] = pointIndex1;
- element->indices[1] = pointIndex2;
- element->middle.rx() = (u.x() + q.x()) >> 1;
- element->middle.ry() = (u.y() + q.y()) >> 1;
- return false;
- } else {
- // Insert bezier.
- element->degree = Element::Cubic;
- element->indices[0] = pointIndex1;
- element->indices[1] = m_points->size();
- element->indices[2] = m_points->size() + 1;
- element->indices[3] = pointIndex2;
- element->middle.rx() = (u.x() + v.x() + w.x() + q.x()) >> 2;
- element->middle.ry() = (u.y() + v.y() + w.y() + q.y()) >> 2;
- m_points->add(v);
- m_points->add(w);
- return true;
- }
-}
-
-void PathSimplifier::setElementToCubicAndSimplify(Element *element, quint32 pointIndex1,
- const QPoint &v, const QPoint &w,
- quint32 pointIndex2)
-{
- const QPoint &u = m_points->at(pointIndex1);
- const QPoint &q = m_points->at(pointIndex2);
- if (flattenCubic(u, v, w, q)) {
- // Insert line.
- element->degree = Element::Line;
- element->indices[0] = pointIndex1;
- element->indices[1] = pointIndex2;
- element->middle.rx() = (u.x() + q.x()) >> 1;
- element->middle.ry() = (u.y() + q.y()) >> 1;
- return;
- }
-
- bool intersecting = (u == q) || intersectionPoint(u, v, w, q).isValid();
- if (!intersecting) {
- // Insert bezier.
- element->degree = Element::Cubic;
- element->indices[0] = pointIndex1;
- element->indices[1] = m_points->size();
- element->indices[2] = m_points->size() + 1;
- element->indices[3] = pointIndex2;
- element->middle.rx() = (u.x() + v.x() + w.x() + q.x()) >> 2;
- element->middle.ry() = (u.y() + v.y() + w.y() + q.y()) >> 2;
- m_points->add(v);
- m_points->add(w);
- return;
- }
-
- QPoint pts[5];
- splitCubic(u, v, w, q, pts);
- int pointIndex = m_points->size();
- m_points->add(pts[2]);
- Element *element2 = m_elementAllocator.newElement();
- m_elements.add(element2);
- setElementToCubicAndSimplify(element, pointIndex1, pts[0], pts[1], pointIndex);
- setElementToCubicAndSimplify(element2, pointIndex, pts[3], pts[4], pointIndex2);
-}
-
-PathSimplifier::RBNode *PathSimplifier::findElementLeftOf(const Element *element,
- const QPair<RBNode *, RBNode *> &bounds)
-{
- if (!m_elementList.root)
- return 0;
- RBNode *current = bounds.first;
- Q_ASSERT(!current || !elementIsLeftOf(element, current->data));
- if (!current)
- current = m_elementList.front(m_elementList.root);
- Q_ASSERT(current);
- RBNode *result = 0;
- while (current != bounds.second && !elementIsLeftOf(element, current->data)) {
- result = current;
- current = m_elementList.next(current);
- }
- return result;
-}
-
-bool PathSimplifier::elementIsLeftOf(const Element *left, const Element *right)
-{
- const QPoint &leftU = m_points->at(left->upperIndex());
- const QPoint &leftL = m_points->at(left->lowerIndex());
- const QPoint &rightU = m_points->at(right->upperIndex());
- const QPoint &rightL = m_points->at(right->lowerIndex());
- Q_ASSERT(leftL >= rightU && rightL >= leftU);
- if (leftU.x() < qMin(rightL.x(), rightU.x()))
- return true;
- if (leftU.x() > qMax(rightL.x(), rightU.x()))
- return false;
- int d = pointDistanceFromLine(leftU, rightL, rightU);
- // d < 0: left, d > 0: right, d == 0: on top
- if (d == 0) {
- d = pointDistanceFromLine(leftL, rightL, rightU);
- if (d == 0) {
- if (right->degree > Element::Line) {
- d = pointDistanceFromLine(leftL, rightL, m_points->at(right->indices[1]));
- if (d == 0)
- d = pointDistanceFromLine(leftL, rightL, m_points->at(right->indices[2]));
- } else if (left->degree > Element::Line) {
- d = pointDistanceFromLine(m_points->at(left->indices[1]), rightL, rightU);
- if (d == 0)
- d = pointDistanceFromLine(m_points->at(left->indices[2]), rightL, rightU);
- }
- }
- }
- return d < 0;
-}
-
-QPair<PathSimplifier::RBNode *, PathSimplifier::RBNode *> PathSimplifier::outerBounds(const QPoint &point)
-{
- RBNode *current = m_elementList.root;
- QPair<RBNode *, RBNode *> result(0, 0);
-
- while (current) {
- const Element *element = current->data;
- Q_ASSERT(element->edgeNode == current);
- const QPoint &v1 = m_points->at(element->lowerIndex());
- const QPoint &v2 = m_points->at(element->upperIndex());
- Q_ASSERT(point >= v2 && point <= v1);
- if (point == v1 || point == v2)
- break;
- int d = pointDistanceFromLine(point, v1, v2);
- if (d == 0) {
- if (element->degree == Element::Line)
- break;
- d = pointDistanceFromLine(point, v1, m_points->at(element->indices[1]));
- if (d == 0)
- d = pointDistanceFromLine(point, v1, m_points->at(element->indices[2]));
- Q_ASSERT(d != 0);
- }
- if (d < 0) {
- result.second = current;
- current = current->left;
- } else {
- result.first = current;
- current = current->right;
- }
- }
-
- if (!current)
- return result;
-
- RBNode *mid = current;
-
- current = mid->left;
- while (current) {
- const Element *element = current->data;
- Q_ASSERT(element->edgeNode == current);
- const QPoint &v1 = m_points->at(element->lowerIndex());
- const QPoint &v2 = m_points->at(element->upperIndex());
- Q_ASSERT(point >= v2 && point <= v1);
- bool equal = (point == v1 || point == v2);
- if (!equal) {
- int d = pointDistanceFromLine(point, v1, v2);
- Q_ASSERT(d >= 0);
- equal = (d == 0 && element->degree == Element::Line);
- }
- if (equal) {
- current = current->left;
- } else {
- result.first = current;
- current = current->right;
- }
- }
-
- current = mid->right;
- while (current) {
- const Element *element = current->data;
- Q_ASSERT(element->edgeNode == current);
- const QPoint &v1 = m_points->at(element->lowerIndex());
- const QPoint &v2 = m_points->at(element->upperIndex());
- Q_ASSERT(point >= v2 && point <= v1);
- bool equal = (point == v1 || point == v2);
- if (!equal) {
- int d = pointDistanceFromLine(point, v1, v2);
- Q_ASSERT(d <= 0);
- equal = (d == 0 && element->degree == Element::Line);
- }
- if (equal) {
- current = current->right;
- } else {
- result.second = current;
- current = current->left;
- }
- }
-
- return result;
-}
-
-inline bool PathSimplifier::flattenQuadratic(const QPoint &u, const QPoint &v, const QPoint &w)
-{
- QPoint deltas[2] = { v - u, w - v };
- int d = qAbs(cross(deltas[0], deltas[1]));
- int l = qAbs(deltas[0].x()) + qAbs(deltas[0].y()) + qAbs(deltas[1].x()) + qAbs(deltas[1].y());
- return d < (Q_FIXED_POINT_SCALE * Q_FIXED_POINT_SCALE * 3 / 2) || l <= Q_FIXED_POINT_SCALE * 2;
-}
-
-inline bool PathSimplifier::flattenCubic(const QPoint &u, const QPoint &v,
- const QPoint &w, const QPoint &q)
-{
- QPoint deltas[] = { v - u, w - v, q - w, q - u };
- int d = qAbs(cross(deltas[0], deltas[1])) + qAbs(cross(deltas[1], deltas[2]))
- + qAbs(cross(deltas[0], deltas[3])) + qAbs(cross(deltas[3], deltas[2]));
- int l = qAbs(deltas[0].x()) + qAbs(deltas[0].y()) + qAbs(deltas[1].x()) + qAbs(deltas[1].y())
- + qAbs(deltas[2].x()) + qAbs(deltas[2].y());
- return d < (Q_FIXED_POINT_SCALE * Q_FIXED_POINT_SCALE * 3) || l <= Q_FIXED_POINT_SCALE * 2;
-}
-
-inline bool PathSimplifier::splitQuadratic(const QPoint &u, const QPoint &v,
- const QPoint &w, QPoint *result)
-{
- result[0] = u + v;
- result[2] = v + w;
- result[1] = result[0] + result[2];
- bool accurate = ((result[0].x() | result[0].y() | result[2].x() | result[2].y()) & 1) == 0
- && ((result[1].x() | result[1].y()) & 3) == 0;
- result[0].rx() >>= 1;
- result[0].ry() >>= 1;
- result[1].rx() >>= 2;
- result[1].ry() >>= 2;
- result[2].rx() >>= 1;
- result[2].ry() >>= 1;
- return accurate;
-}
-
-inline bool PathSimplifier::splitCubic(const QPoint &u, const QPoint &v,
- const QPoint &w, const QPoint &q, QPoint *result)
-{
- result[0] = u + v;
- result[2] = v + w;
- result[4] = w + q;
- result[1] = result[0] + result[2];
- result[3] = result[2] + result[4];
- result[2] = result[1] + result[3];
- bool accurate = ((result[0].x() | result[0].y() | result[4].x() | result[4].y()) & 1) == 0
- && ((result[1].x() | result[1].y() | result[3].x() | result[3].y()) & 3) == 0
- && ((result[2].x() | result[2].y()) & 7) == 0;
- result[0].rx() >>= 1;
- result[0].ry() >>= 1;
- result[1].rx() >>= 2;
- result[1].ry() >>= 2;
- result[2].rx() >>= 3;
- result[2].ry() >>= 3;
- result[3].rx() >>= 2;
- result[3].ry() >>= 2;
- result[4].rx() >>= 1;
- result[4].ry() >>= 1;
- return accurate;
-}
-
-inline void PathSimplifier::subDivQuadratic(const QPoint &u, const QPoint &v, const QPoint &w)
-{
- if (flattenQuadratic(u, v, w))
- return;
- QPoint pts[3];
- splitQuadratic(u, v, w, pts);
- subDivQuadratic(u, pts[0], pts[1]);
- m_indices->add(m_points->size());
- m_points->add(pts[1]);
- subDivQuadratic(pts[1], pts[2], w);
-}
-
-inline void PathSimplifier::subDivCubic(const QPoint &u, const QPoint &v,
- const QPoint &w, const QPoint &q)
-{
- if (flattenCubic(u, v, w, q))
- return;
- QPoint pts[5];
- splitCubic(u, v, w, q, pts);
- subDivCubic(u, pts[0], pts[1], pts[2]);
- m_indices->add(m_points->size());
- m_points->add(pts[2]);
- subDivCubic(pts[2], pts[3], pts[4], q);
-}
-
-void PathSimplifier::sortEvents(Event *events, int count)
-{
- // Bucket sort + insertion sort.
- Q_ASSERT(count > 0);
- QDataBuffer<Event> buffer(count);
- buffer.resize(count);
- QScopedArrayPointer<int> bins(new int[count]);
- int counts[0x101];
- memset(counts, 0, sizeof(counts));
-
- int minimum, maximum;
- minimum = maximum = events[0].point.y();
- for (int i = 1; i < count; ++i) {
- minimum = qMin(minimum, events[i].point.y());
- maximum = qMax(maximum, events[i].point.y());
- }
-
- for (int i = 0; i < count; ++i) {
- bins[i] = ((maximum - events[i].point.y()) << 8) / (maximum - minimum + 1);
- Q_ASSERT(bins[i] >= 0 && bins[i] < 0x100);
- ++counts[bins[i]];
- }
-
- for (int i = 1; i < 0x100; ++i)
- counts[i] += counts[i - 1];
- counts[0x100] = counts[0xff];
- Q_ASSERT(counts[0x100] == count);
-
- for (int i = 0; i < count; ++i)
- buffer.at(--counts[bins[i]]) = events[i];
-
- int j = 0;
- for (int i = 0; i < 0x100; ++i) {
- for (; j < counts[i + 1]; ++j) {
- int k = j;
- while (k > 0 && (buffer.at(j) < events[k - 1])) {
- events[k] = events[k - 1];
- --k;
- }
- events[k] = buffer.at(j);
- }
- }
-}
-
-} // end anonymous namespace
-
-
-void qSimplifyPath(const QVectorPath &path, QDataBuffer<QPoint> &vertices,
- QDataBuffer<quint32> &indices, const QTransform &matrix)
-{
- PathSimplifier(path, vertices, indices, matrix);
-}
-
-void qSimplifyPath(const QPainterPath &path, QDataBuffer<QPoint> &vertices,
- QDataBuffer<quint32> &indices, const QTransform &matrix)
-{
- qSimplifyPath(qtVectorPathForPath(path), vertices, indices, matrix);
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/qsgpathsimplifier_p.h b/src/declarative/scenegraph/qsgpathsimplifier_p.h
deleted file mode 100644
index 0639c4f622..0000000000
--- a/src/declarative/scenegraph/qsgpathsimplifier_p.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGPATHSIMPLIFIER_P_H
-#define QSGPATHSIMPLIFIER_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 <QtGui/qpainterpath.h>
-#include <QtGui/private/qdatabuffer_p.h>
-#include <QtGui/private/qvectorpath_p.h>
-
-QT_BEGIN_NAMESPACE
-
-// The returned vertices are in 8:8 fixed point format. The path is assumed to be in the range (-128, 128)x(-128, 128).
-void qSimplifyPath(const QVectorPath &path, QDataBuffer<QPoint> &vertices, QDataBuffer<quint32> &indices, const QTransform &matrix = QTransform());
-void qSimplifyPath(const QPainterPath &path, QDataBuffer<QPoint> &vertices, QDataBuffer<quint32> &indices, const QTransform &matrix = QTransform());
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/declarative/scenegraph/scenegraph.pri b/src/declarative/scenegraph/scenegraph.pri
deleted file mode 100644
index 0adc20502d..0000000000
--- a/src/declarative/scenegraph/scenegraph.pri
+++ /dev/null
@@ -1,86 +0,0 @@
-!contains(QT_CONFIG, egl):DEFINES += QT_NO_EGL
-
-# Core API
-HEADERS += \
- $$PWD/coreapi/qsgdefaultrenderer_p.h \
- $$PWD/coreapi/qsggeometry.h \
- $$PWD/coreapi/qsgmaterial.h \
- $$PWD/coreapi/qsgnode.h \
- $$PWD/coreapi/qsgnodeupdater_p.h \
- $$PWD/coreapi/qsgrenderer_p.h \
- $$PWD/coreapi/qsggeometry_p.h
-
-SOURCES += \
- $$PWD/coreapi/qsgdefaultrenderer.cpp \
- $$PWD/coreapi/qsggeometry.cpp \
- $$PWD/coreapi/qsgmaterial.cpp \
- $$PWD/coreapi/qsgnode.cpp \
- $$PWD/coreapi/qsgnodeupdater.cpp \
- $$PWD/coreapi/qsgrenderer.cpp
-
-
-# Util API
-HEADERS += \
- $$PWD/util/qsgareaallocator_p.h \
- $$PWD/util/qsgengine.h \
- $$PWD/util/qsgflatcolormaterial.h \
- $$PWD/util/qsgsimplematerial.h \
- $$PWD/util/qsgsimplerectnode.h \
- $$PWD/util/qsgsimpletexturenode.h \
- $$PWD/util/qsgtexturematerial.h \
- $$PWD/util/qsgtexturematerial_p.h \
- $$PWD/util/qsgvertexcolormaterial.h \
- $$PWD/util/qsgtexture.h \
- $$PWD/util/qsgtexture_p.h \
- $$PWD/util/qsgtextureprovider_p.h \
- $$PWD/util/qsgpainternode_p.h \
- $$PWD/util/qsgdistancefieldutil_p.h
-
-SOURCES += \
- $$PWD/util/qsgareaallocator.cpp \
- $$PWD/util/qsgengine.cpp \
- $$PWD/util/qsgflatcolormaterial.cpp \
- $$PWD/util/qsgsimplerectnode.cpp \
- $$PWD/util/qsgsimpletexturenode.cpp \
- $$PWD/util/qsgtexturematerial.cpp \
- $$PWD/util/qsgvertexcolormaterial.cpp \
- $$PWD/util/qsgtexture.cpp \
- $$PWD/util/qsgtextureprovider.cpp \
- $$PWD/util/qsgpainternode.cpp \
- $$PWD/util/qsgdistancefieldutil.cpp
-
-
-# QML / Adaptations API
-HEADERS += \
- $$PWD/qsgadaptationlayer_p.h \
- $$PWD/qsgcontext_p.h \
- $$PWD/qsgcontextplugin_p.h \
- $$PWD/qsgdefaultglyphnode_p.h \
- $$PWD/qsgdefaultdistancefieldglyphcache_p.h \
- $$PWD/qsgdistancefieldglyphnode_p.h \
- $$PWD/qsgdistancefieldglyphnode_p_p.h \
- $$PWD/qsgdefaultglyphnode_p_p.h \
- $$PWD/qsgdefaultimagenode_p.h \
- $$PWD/qsgdefaultrectanglenode_p.h \
- $$PWD/qsgflashnode_p.h \
- $$PWD/qsgpathsimplifier_p.h
-
-SOURCES += \
- $$PWD/qsgadaptationlayer.cpp \
- $$PWD/qsgcontext.cpp \
- $$PWD/qsgcontextplugin.cpp \
- $$PWD/qsgdefaultglyphnode.cpp \
- $$PWD/qsgdefaultglyphnode_p.cpp \
- $$PWD/qsgdefaultdistancefieldglyphcache.cpp \
- $$PWD/qsgdistancefieldglyphnode.cpp \
- $$PWD/qsgdistancefieldglyphnode_p.cpp \
- $$PWD/qsgdefaultimagenode.cpp \
- $$PWD/qsgdefaultrectanglenode.cpp \
- $$PWD/qsgflashnode.cpp \
- $$PWD/qsgpathsimplifier.cpp
-
-
-
-
-
-
diff --git a/src/declarative/scenegraph/util/qsgareaallocator.cpp b/src/declarative/scenegraph/util/qsgareaallocator.cpp
deleted file mode 100644
index c5171f1c93..0000000000
--- a/src/declarative/scenegraph/util/qsgareaallocator.cpp
+++ /dev/null
@@ -1,290 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgareaallocator_p.h"
-
-#include <QtCore/qglobal.h>
-#include <QtCore/qrect.h>
-#include <QtCore/qpoint.h>
-
-QT_BEGIN_NAMESPACE
-
-namespace
-{
- enum SplitType
- {
- VerticalSplit,
- HorizontalSplit
- };
-
- static const int maxMargin = 2;
-}
-
-struct QSGAreaAllocatorNode
-{
- QSGAreaAllocatorNode(QSGAreaAllocatorNode *parent);
- ~QSGAreaAllocatorNode();
- inline bool isLeaf();
-
- QSGAreaAllocatorNode *parent;
- QSGAreaAllocatorNode *left;
- QSGAreaAllocatorNode *right;
- int split; // only valid for inner nodes.
- SplitType splitType;
- bool isOccupied; // only valid for leaf nodes.
-};
-
-QSGAreaAllocatorNode::QSGAreaAllocatorNode(QSGAreaAllocatorNode *parent)
- : parent(parent)
- , left(0)
- , right(0)
- , isOccupied(false)
-{
-}
-
-QSGAreaAllocatorNode::~QSGAreaAllocatorNode()
-{
- delete left;
- delete right;
-}
-
-bool QSGAreaAllocatorNode::isLeaf()
-{
- Q_ASSERT((left != 0) == (right != 0));
- return !left;
-}
-
-
-QSGAreaAllocator::QSGAreaAllocator(const QSize &size) : m_size(size)
-{
- m_root = new QSGAreaAllocatorNode(0);
-}
-
-QSGAreaAllocator::~QSGAreaAllocator()
-{
- delete m_root;
-}
-
-QRect QSGAreaAllocator::allocate(const QSize &size)
-{
- QPoint point;
- bool result = allocateInNode(size, point, QRect(QPoint(0, 0), m_size), m_root);
- return result ? QRect(point, size) : QRect();
-}
-
-bool QSGAreaAllocator::deallocate(const QRect &rect)
-{
- return deallocateInNode(rect.topLeft(), m_root);
-}
-
-bool QSGAreaAllocator::allocateInNode(const QSize &size, QPoint &result, const QRect &currentRect, QSGAreaAllocatorNode *node)
-{
- if (size.width() > currentRect.width() || size.height() > currentRect.height())
- return false;
-
- if (node->isLeaf()) {
- if (node->isOccupied)
- return false;
- if (size.width() + maxMargin >= currentRect.width() && size.height() + maxMargin >= currentRect.height()) {
- //Snug fit, occupy entire rectangle.
- node->isOccupied = true;
- result = currentRect.topLeft();
- return true;
- }
- // TODO: Reuse nodes.
- // Split node.
- node->left = new QSGAreaAllocatorNode(node);
- node->right = new QSGAreaAllocatorNode(node);
- QRect splitRect = currentRect;
- if ((currentRect.width() - size.width()) * currentRect.height() < (currentRect.height() - size.height()) * currentRect.width()) {
- node->splitType = HorizontalSplit;
- node->split = currentRect.top() + size.height();
- splitRect.setHeight(size.height());
- } else {
- node->splitType = VerticalSplit;
- node->split = currentRect.left() + size.width();
- splitRect.setWidth(size.width());
- }
- return allocateInNode(size, result, splitRect, node->left);
- } else {
- // TODO: avoid unnecessary recursion.
- // has been split.
- QRect leftRect = currentRect;
- QRect rightRect = currentRect;
- if (node->splitType == HorizontalSplit) {
- leftRect.setHeight(node->split - leftRect.top());
- rightRect.setTop(node->split);
- } else {
- leftRect.setWidth(node->split - leftRect.left());
- rightRect.setLeft(node->split);
- }
- if (allocateInNode(size, result, leftRect, node->left))
- return true;
- if (allocateInNode(size, result, rightRect, node->right))
- return true;
- return false;
- }
-}
-
-bool QSGAreaAllocator::deallocateInNode(const QPoint &pos, QSGAreaAllocatorNode *node)
-{
- while (!node->isLeaf()) {
- // has been split.
- int cmp = node->splitType == HorizontalSplit ? pos.y() : pos.x();
- node = cmp < node->split ? node->left : node->right;
- }
- if (!node->isOccupied)
- return false;
- node->isOccupied = false;
- mergeNodeWithNeighbors(node);
- return true;
-}
-
-void QSGAreaAllocator::mergeNodeWithNeighbors(QSGAreaAllocatorNode *node)
-{
- bool done = false;
- QSGAreaAllocatorNode *parent = 0;
- QSGAreaAllocatorNode *current = 0;
- QSGAreaAllocatorNode *sibling;
- while (!done) {
- Q_ASSERT(node->isLeaf());
- Q_ASSERT(!node->isOccupied);
- if (node->parent == 0)
- return; // No neighbours.
-
- SplitType splitType = SplitType(node->parent->splitType);
- done = true;
-
- /* Special case. Might be faster than going through the general code path.
- // Merge with sibling.
- parent = node->parent;
- sibling = (node == parent->left ? parent->right : parent->left);
- if (sibling->isLeaf() && !sibling->isOccupied) {
- Q_ASSERT(!sibling->right);
- node = parent;
- parent->isOccupied = false;
- delete parent->left;
- delete parent->right;
- parent->left = parent->right = 0;
- done = false;
- continue;
- }
- */
-
- // Merge with left neighbour.
- current = node;
- parent = current->parent;
- while (parent && current == parent->left && parent->splitType == splitType) {
- current = parent;
- parent = parent->parent;
- }
-
- if (parent && parent->splitType == splitType) {
- Q_ASSERT(current == parent->right);
- Q_ASSERT(parent->left);
-
- QSGAreaAllocatorNode *neighbor = parent->left;
- while (neighbor->right && neighbor->splitType == splitType)
- neighbor = neighbor->right;
-
- if (neighbor->isLeaf() && neighbor->parent->splitType == splitType && !neighbor->isOccupied) {
- // Left neighbour can be merged.
- parent->split = neighbor->parent->split;
-
- parent = neighbor->parent;
- sibling = neighbor == parent->left ? parent->right : parent->left;
- QSGAreaAllocatorNode **nodeRef = &m_root;
- if (parent->parent) {
- if (parent == parent->parent->left)
- nodeRef = &parent->parent->left;
- else
- nodeRef = &parent->parent->right;
- }
- sibling->parent = parent->parent;
- *nodeRef = sibling;
- parent->left = parent->right = 0;
- delete parent;
- delete neighbor;
- done = false;
- }
- }
-
- // Merge with right neighbour.
- current = node;
- parent = current->parent;
- while (parent && current == parent->right && parent->splitType == splitType) {
- current = parent;
- parent = parent->parent;
- }
-
- if (parent && parent->splitType == splitType) {
- Q_ASSERT(current == parent->left);
- Q_ASSERT(parent->right);
-
- QSGAreaAllocatorNode *neighbor = parent->right;
- while (neighbor->left && neighbor->splitType == splitType)
- neighbor = neighbor->left;
-
- if (neighbor->isLeaf() && neighbor->parent->splitType == splitType && !neighbor->isOccupied) {
- // Right neighbour can be merged.
- parent->split = neighbor->parent->split;
-
- parent = neighbor->parent;
- sibling = neighbor == parent->left ? parent->right : parent->left;
- QSGAreaAllocatorNode **nodeRef = &m_root;
- if (parent->parent) {
- if (parent == parent->parent->left)
- nodeRef = &parent->parent->left;
- else
- nodeRef = &parent->parent->right;
- }
- sibling->parent = parent->parent;
- *nodeRef = sibling;
- parent->left = parent->right = 0;
- delete parent;
- delete neighbor;
- done = false;
- }
- }
- } // end while(!done)
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgareaallocator_p.h b/src/declarative/scenegraph/util/qsgareaallocator_p.h
deleted file mode 100644
index fd79d4c67a..0000000000
--- a/src/declarative/scenegraph/util/qsgareaallocator_p.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef AREAALLOCATOR_H
-#define AREAALLOCATOR_H
-
-#include <QtCore/qsize.h>
-
-QT_BEGIN_NAMESPACE
-
-class QRect;
-class QPoint;
-struct QSGAreaAllocatorNode;
-class Q_DECLARATIVE_EXPORT QSGAreaAllocator
-{
-public:
- QSGAreaAllocator(const QSize &size);
- ~QSGAreaAllocator();
-
- QRect allocate(const QSize &size);
- bool deallocate(const QRect &rect);
- bool isEmpty() const { return m_root == 0; }
- QSize size() const { return m_size; }
-private:
- bool allocateInNode(const QSize &size, QPoint &result, const QRect &currentRect, QSGAreaAllocatorNode *node);
- bool deallocateInNode(const QPoint &pos, QSGAreaAllocatorNode *node);
- void mergeNodeWithNeighbors(QSGAreaAllocatorNode *node);
-
- QSGAreaAllocatorNode *m_root;
- QSize m_size;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/declarative/scenegraph/util/qsgdistancefieldutil.cpp b/src/declarative/scenegraph/util/qsgdistancefieldutil.cpp
deleted file mode 100644
index 3429162d6b..0000000000
--- a/src/declarative/scenegraph/util/qsgdistancefieldutil.cpp
+++ /dev/null
@@ -1,805 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgdistancefieldutil_p.h"
-
-#include <qmath.h>
-#include <private/qsgpathsimplifier_p.h>
-#include <private/qsgadaptationlayer_p.h>
-#include <QtGui/private/qopenglengineshadersource_p.h>
-#include <private/qsgcontext_p.h>
-
-QT_BEGIN_NAMESPACE
-
-static float defaultThresholdFunc(float glyphScale)
-{
- static float base = qgetenv("QT_DF_BASE").isEmpty() ? 0.5f : qgetenv("QT_DF_BASE").toFloat();
- static float baseDev = qgetenv("QT_DF_BASEDEVIATION").isEmpty() ? 0.065f : qgetenv("QT_DF_BASEDEVIATION").toFloat();
- static float devScaleMin = qgetenv("QT_DF_SCALEFORMAXDEV").isEmpty() ? 0.15f : qgetenv("QT_DF_SCALEFORMAXDEV").toFloat();
- static float devScaleMax = qgetenv("QT_DF_SCALEFORNODEV").isEmpty() ? 0.3f : qgetenv("QT_DF_SCALEFORNODEV").toFloat();
- return base - ((qBound(devScaleMin, glyphScale, devScaleMax) - devScaleMin) / (devScaleMax - devScaleMin) * -baseDev + baseDev);
-}
-
-static float defaultAntialiasingSpreadFunc(float glyphScale)
-{
- static float range = qgetenv("QT_DF_RANGE").isEmpty() ? 0.06f : qgetenv("QT_DF_RANGE").toFloat();
- return range / glyphScale;
-}
-
-namespace
-{
- enum FillHDir
- {
- LeftToRight,
- RightToLeft
- };
-
- enum FillVDir
- {
- TopDown,
- BottomUp
- };
-
- enum FillClip
- {
- NoClip,
- Clip
- };
-}
-
-template <FillClip clip, FillHDir dir>
-inline void fillLine(qint32 *, int, int, int, qint32, qint32)
-{
-}
-
-template <>
-inline void fillLine<Clip, LeftToRight>(qint32 *line, int width, int lx, int rx, qint32 d, qint32 dd)
-{
- int fromX = qMax(0, lx >> 8);
- int toX = qMin(width, rx >> 8);
- int x = toX - fromX;
- if (x <= 0)
- return;
- qint32 val = d + (((fromX << 8) + 0xff - lx) * dd >> 8);
- line += fromX;
- do {
- *line = abs(val) < abs(*line) ? val : *line;
- val += dd;
- ++line;
- } while (--x);
-}
-
-template <>
-inline void fillLine<Clip, RightToLeft>(qint32 *line, int width, int lx, int rx, qint32 d, qint32 dd)
-{
- int fromX = qMax(0, lx >> 8);
- int toX = qMin(width, rx >> 8);
- int x = toX - fromX;
- if (x <= 0)
- return;
- qint32 val = d + (((toX << 8) + 0xff - rx) * dd >> 8);
- line += toX;
- do {
- val -= dd;
- --line;
- *line = abs(val) < abs(*line) ? val : *line;
- } while (--x);
-}
-
-template <>
-inline void fillLine<NoClip, LeftToRight>(qint32 *line, int, int lx, int rx, qint32 d, qint32 dd)
-{
- int fromX = lx >> 8;
- int toX = rx >> 8;
- int x = toX - fromX;
- if (x <= 0)
- return;
- qint32 val = d + ((~lx & 0xff) * dd >> 8);
- line += fromX;
- do {
- *line = abs(val) < abs(*line) ? val : *line;
- val += dd;
- ++line;
- } while (--x);
-}
-
-template <>
-inline void fillLine<NoClip, RightToLeft>(qint32 *line, int, int lx, int rx, qint32 d, qint32 dd)
-{
- int fromX = lx >> 8;
- int toX = rx >> 8;
- int x = toX - fromX;
- if (x <= 0)
- return;
- qint32 val = d + ((~rx & 0xff) * dd >> 8);
- line += toX;
- do {
- val -= dd;
- --line;
- *line = abs(val) < abs(*line) ? val : *line;
- } while (--x);
-}
-
-template <FillClip clip, FillVDir vDir, FillHDir hDir>
-inline void fillLines(qint32 *bits, int width, int height, int upperY, int lowerY,
- int &lx, int ldx, int &rx, int rdx, qint32 &d, qint32 ddy, qint32 ddx)
-{
- Q_UNUSED(height);
- Q_ASSERT(upperY < lowerY);
- int y = lowerY - upperY;
- if (vDir == TopDown) {
- qint32 *line = bits + upperY * width;
- do {
- fillLine<clip, hDir>(line, width, lx, rx, d, ddx);
- lx += ldx;
- d += ddy;
- rx += rdx;
- line += width;
- } while (--y);
- } else {
- qint32 *line = bits + lowerY * width;
- do {
- lx -= ldx;
- d -= ddy;
- rx -= rdx;
- line -= width;
- fillLine<clip, hDir>(line, width, lx, rx, d, ddx);
- } while (--y);
- }
-}
-
-template <FillClip clip>
-void drawTriangle(qint32 *bits, int width, int height, const QPoint *center,
- const QPoint *v1, const QPoint *v2, qint32 value)
-{
- const int y1 = clip == Clip ? qBound(0, v1->y() >> 8, height) : v1->y() >> 8;
- const int y2 = clip == Clip ? qBound(0, v2->y() >> 8, height) : v2->y() >> 8;
- const int yC = clip == Clip ? qBound(0, center->y() >> 8, height) : center->y() >> 8;
-
- const int v1Frac = clip == Clip ? (y1 << 8) + 0xff - v1->y() : ~v2->y() & 0xff;
- const int v2Frac = clip == Clip ? (y2 << 8) + 0xff - v2->y() : ~v1->y() & 0xff;
- const int centerFrac = clip == Clip ? (yC << 8) + 0xff - center->y() : ~center->y() & 0xff;
-
- int dx1 = 0, x1 = 0, dx2 = 0, x2 = 0;
- qint32 dd1, d1, dd2, d2;
- if (v1->y() != center->y()) {
- dx1 = ((v1->x() - center->x()) << 8) / (v1->y() - center->y());
- x1 = center->x() + centerFrac * (v1->x() - center->x()) / (v1->y() - center->y());
- }
- if (v2->y() != center->y()) {
- dx2 = ((v2->x() - center->x()) << 8) / (v2->y() - center->y());
- x2 = center->x() + centerFrac * (v2->x() - center->x()) / (v2->y() - center->y());
- }
-
- const qint32 div = (v2->x() - center->x()) * (v1->y() - center->y())
- - (v2->y() - center->y()) * (v1->x() - center->x());
- const qint32 dd = div ? qint32((qint64(value * (v1->y() - v2->y())) << 8) / div) : 0;
-
- if (y2 < yC) {
- if (y1 < yC) {
- // Center at the bottom.
- if (y2 < y1) {
- // y2 < y1 < yC
- // Long right edge.
- d1 = centerFrac * value / (v1->y() - center->y());
- dd1 = ((value << 8) / (v1->y() - center->y()));
- fillLines<clip, BottomUp, LeftToRight>(bits, width, height, y1, yC, x1, dx1,
- x2, dx2, d1, dd1, dd);
- dx1 = ((v1->x() - v2->x()) << 8) / (v1->y() - v2->y());
- x1 = v1->x() + v1Frac * (v1->x() - v2->x()) / (v1->y() - v2->y());
- fillLines<clip, BottomUp, LeftToRight>(bits, width, height, y2, y1, x1, dx1,
- x2, dx2, value, 0, dd);
- } else {
- // y1 <= y2 < yC
- // Long left edge.
- d2 = centerFrac * value / (v2->y() - center->y());
- dd2 = ((value << 8) / (v2->y() - center->y()));
- fillLines<clip, BottomUp, RightToLeft>(bits, width, height, y2, yC, x1, dx1,
- x2, dx2, d2, dd2, dd);
- if (y1 != y2) {
- dx2 = ((v1->x() - v2->x()) << 8) / (v1->y() - v2->y());
- x2 = v2->x() + v2Frac * (v1->x() - v2->x()) / (v1->y() - v2->y());
- fillLines<clip, BottomUp, RightToLeft>(bits, width, height, y1, y2, x1, dx1,
- x2, dx2, value, 0, dd);
- }
- }
- } else {
- // y2 < yC <= y1
- // Center to the right.
- int dx = ((v1->x() - v2->x()) << 8) / (v1->y() - v2->y());
- int xUp, xDn;
- xUp = xDn = v2->x() + (clip == Clip ? (yC << 8) + 0xff - v2->y()
- : (center->y() | 0xff) - v2->y())
- * (v1->x() - v2->x()) / (v1->y() - v2->y());
- fillLines<clip, BottomUp, LeftToRight>(bits, width, height, y2, yC, xUp, dx,
- x2, dx2, value, 0, dd);
- if (yC != y1)
- fillLines<clip, TopDown, LeftToRight>(bits, width, height, yC, y1, xDn, dx,
- x1, dx1, value, 0, dd);
- }
- } else {
- if (y1 < yC) {
- // y1 < yC <= y2
- // Center to the left.
- int dx = ((v1->x() - v2->x()) << 8) / (v1->y() - v2->y());
- int xUp, xDn;
- xUp = xDn = v1->x() + (clip == Clip ? (yC << 8) + 0xff - v1->y()
- : (center->y() | 0xff) - v1->y())
- * (v1->x() - v2->x()) / (v1->y() - v2->y());
- fillLines<clip, BottomUp, RightToLeft>(bits, width, height, y1, yC, x1, dx1,
- xUp, dx, value, 0, dd);
- if (yC != y2)
- fillLines<clip, TopDown, RightToLeft>(bits, width, height, yC, y2, x2, dx2,
- xDn, dx, value, 0, dd);
- } else {
- // Center at the top.
- if (y2 < y1) {
- // yC <= y2 < y1
- // Long right edge.
- if (yC != y2) {
- d2 = centerFrac * value / (v2->y() - center->y());
- dd2 = ((value << 8) / (v2->y() - center->y()));
- fillLines<clip, TopDown, LeftToRight>(bits, width, height, yC, y2, x2, dx2,
- x1, dx1, d2, dd2, dd);
- }
- dx2 = ((v1->x() - v2->x()) << 8) / (v1->y() - v2->y());
- x2 = v2->x() + v2Frac * (v1->x() - v2->x()) / (v1->y() - v2->y());
- fillLines<clip, TopDown, LeftToRight>(bits, width, height, y2, y1, x2, dx2,
- x1, dx1, value, 0, dd);
- } else {
- // Long left edge.
- // yC <= y1 <= y2
- if (yC != y1) {
- d1 = centerFrac * value / (v1->y() - center->y());
- dd1 = ((value << 8) / (v1->y() - center->y()));
- fillLines<clip, TopDown, RightToLeft>(bits, width, height, yC, y1, x2, dx2,
- x1, dx1, d1, dd1, dd);
- }
- if (y1 != y2) {
- dx1 = ((v1->x() - v2->x()) << 8) / (v1->y() - v2->y());
- x1 = v1->x() + v1Frac * (v1->x() - v2->x()) / (v1->y() - v2->y());
- fillLines<clip, TopDown, RightToLeft>(bits, width, height, y1, y2, x2, dx2,
- x1, dx1, value, 0, dd);
- }
- }
- }
- }
-}
-
-template <FillClip clip>
-void drawRectangle(qint32 *bits, int width, int height,
- const QPoint *int1, const QPoint *center1, const QPoint *ext1,
- const QPoint *int2, const QPoint *center2, const QPoint *ext2,
- qint32 extValue)
-{
- if (center1->y() > center2->y()) {
- qSwap(center1, center2);
- qSwap(int1, ext2);
- qSwap(ext1, int2);
- extValue = -extValue;
- }
-
- Q_ASSERT(ext1->x() - center1->x() == center1->x() - int1->x());
- Q_ASSERT(ext1->y() - center1->y() == center1->y() - int1->y());
- Q_ASSERT(ext2->x() - center2->x() == center2->x() - int2->x());
- Q_ASSERT(ext2->y() - center2->y() == center2->y() - int2->y());
-
- const int yc1 = clip == Clip ? qBound(0, center1->y() >> 8, height) : center1->y() >> 8;
- const int yc2 = clip == Clip ? qBound(0, center2->y() >> 8, height) : center2->y() >> 8;
- const int yi1 = clip == Clip ? qBound(0, int1->y() >> 8, height) : int1->y() >> 8;
- const int yi2 = clip == Clip ? qBound(0, int2->y() >> 8, height) : int2->y() >> 8;
- const int ye1 = clip == Clip ? qBound(0, ext1->y() >> 8, height) : ext1->y() >> 8;
- const int ye2 = clip == Clip ? qBound(0, ext2->y() >> 8, height) : ext2->y() >> 8;
-
- const int center1Frac = clip == Clip ? (yc1 << 8) + 0xff - center1->y() : ~center1->y() & 0xff;
- const int center2Frac = clip == Clip ? (yc2 << 8) + 0xff - center2->y() : ~center2->y() & 0xff;
- const int int1Frac = clip == Clip ? (yi1 << 8) + 0xff - int1->y() : ~int1->y() & 0xff;
- const int ext1Frac = clip == Clip ? (ye1 << 8) + 0xff - ext1->y() : ~ext1->y() & 0xff;
-
- int dxC = 0, dxE = 0; // cap slope, edge slope
- qint32 ddC = 0;
- if (ext1->y() != int1->y()) {
- dxC = ((ext1->x() - int1->x()) << 8) / (ext1->y() - int1->y());
- ddC = (extValue << 9) / (ext1->y() - int1->y());
- }
- if (ext1->y() != ext2->y())
- dxE = ((ext1->x() - ext2->x()) << 8) / (ext1->y() - ext2->y());
-
- const qint32 div = (ext1->x() - int1->x()) * (ext2->y() - int1->y())
- - (ext1->y() - int1->y()) * (ext2->x() - int1->x());
- const qint32 dd = div ? qint32((qint64(extValue * (ext2->y() - ext1->y())) << 9) / div) : 0;
-
- int xe1, xe2, xc1, xc2;
- qint32 d;
-
- qint32 intValue = -extValue;
-
- if (center2->x() < center1->x()) {
- // Leaning to the right. '/'
- if (int1->y() < ext2->y()) {
- // Mostly vertical.
- Q_ASSERT(ext1->y() != ext2->y());
- xe1 = ext1->x() + ext1Frac * (ext1->x() - ext2->x()) / (ext1->y() - ext2->y());
- xe2 = int1->x() + int1Frac * (ext1->x() - ext2->x()) / (ext1->y() - ext2->y());
- if (ye1 != yi1) {
- xc2 = center1->x() + center1Frac * (ext1->x() - int1->x()) / (ext1->y() - int1->y());
- xc2 += (ye1 - yc1) * dxC;
- fillLines<clip, TopDown, LeftToRight>(bits, width, height, ye1, yi1, xe1, dxE,
- xc2, dxC, extValue, 0, dd);
- }
- if (yi1 != ye2)
- fillLines<clip, TopDown, LeftToRight>(bits, width, height, yi1, ye2, xe1, dxE,
- xe2, dxE, extValue, 0, dd);
- if (ye2 != yi2) {
- xc1 = center2->x() + center2Frac * (ext1->x() - int1->x()) / (ext1->y() - int1->y());
- xc1 += (ye2 - yc2) * dxC;
- fillLines<clip, TopDown, RightToLeft>(bits, width, height, ye2, yi2, xc1, dxC,
- xe2, dxE, intValue, 0, dd);
- }
- } else {
- // Mostly horizontal.
- Q_ASSERT(ext1->y() != int1->y());
- xc1 = center2->x() + center2Frac * (ext1->x() - int1->x()) / (ext1->y() - int1->y());
- xc2 = center1->x() + center1Frac * (ext1->x() - int1->x()) / (ext1->y() - int1->y());
- xc1 += (ye2 - yc2) * dxC;
- xc2 += (ye1 - yc1) * dxC;
- if (ye1 != ye2) {
- xe1 = ext1->x() + ext1Frac * (ext1->x() - ext2->x()) / (ext1->y() - ext2->y());
- fillLines<clip, TopDown, LeftToRight>(bits, width, height, ye1, ye2, xe1, dxE,
- xc2, dxC, extValue, 0, dd);
- }
- if (ye2 != yi1) {
- d = (clip == Clip ? (ye2 << 8) + 0xff - center2->y()
- : (ext2->y() | 0xff) - center2->y())
- * 2 * extValue / (ext1->y() - int1->y());
- fillLines<clip, TopDown, LeftToRight>(bits, width, height, ye2, yi1, xc1, dxC,
- xc2, dxC, d, ddC, dd);
- }
- if (yi1 != yi2) {
- xe2 = int1->x() + int1Frac * (ext1->x() - ext2->x()) / (ext1->y() - ext2->y());
- fillLines<clip, TopDown, RightToLeft>(bits, width, height, yi1, yi2, xc1, dxC,
- xe2, dxE, intValue, 0, dd);
- }
- }
- } else {
- // Leaning to the left. '\'
- if (ext1->y() < int2->y()) {
- // Mostly vertical.
- Q_ASSERT(ext1->y() != ext2->y());
- xe1 = ext1->x() + ext1Frac * (ext1->x() - ext2->x()) / (ext1->y() - ext2->y());
- xe2 = int1->x() + int1Frac * (ext1->x() - ext2->x()) / (ext1->y() - ext2->y());
- if (yi1 != ye1) {
- xc1 = center1->x() + center1Frac * (ext1->x() - int1->x()) / (ext1->y() - int1->y());
- xc1 += (yi1 - yc1) * dxC;
- fillLines<clip, TopDown, RightToLeft>(bits, width, height, yi1, ye1, xc1, dxC,
- xe2, dxE, intValue, 0, dd);
- }
- if (ye1 != yi2)
- fillLines<clip, TopDown, RightToLeft>(bits, width, height, ye1, yi2, xe1, dxE,
- xe2, dxE, intValue, 0, dd);
- if (yi2 != ye2) {
- xc2 = center2->x() + center2Frac * (ext1->x() - int1->x()) / (ext1->y() - int1->y());
- xc2 += (yi2 - yc2) * dxC;
- fillLines<clip, TopDown, LeftToRight>(bits, width, height, yi2, ye2, xe1, dxE,
- xc2, dxC, extValue, 0, dd);
- }
- } else {
- // Mostly horizontal.
- Q_ASSERT(ext1->y() != int1->y());
- xc1 = center1->x() + center1Frac * (ext1->x() - int1->x()) / (ext1->y() - int1->y());
- xc2 = center2->x() + center2Frac * (ext1->x() - int1->x()) / (ext1->y() - int1->y());
- xc1 += (yi1 - yc1) * dxC;
- xc2 += (yi2 - yc2) * dxC;
- if (yi1 != yi2) {
- xe2 = int1->x() + int1Frac * (ext1->x() - ext2->x()) / (ext1->y() - ext2->y());
- fillLines<clip, TopDown, RightToLeft>(bits, width, height, yi1, yi2, xc1, dxC,
- xe2, dxE, intValue, 0, dd);
- }
- if (yi2 != ye1) {
- d = (clip == Clip ? (yi2 << 8) + 0xff - center2->y()
- : (int2->y() | 0xff) - center2->y())
- * 2 * extValue / (ext1->y() - int1->y());
- fillLines<clip, TopDown, RightToLeft>(bits, width, height, yi2, ye1, xc1, dxC,
- xc2, dxC, d, ddC, dd);
- }
- if (ye1 != ye2) {
- xe1 = ext1->x() + ext1Frac * (ext1->x() - ext2->x()) / (ext1->y() - ext2->y());
- fillLines<clip, TopDown, LeftToRight>(bits, width, height, ye1, ye2, xe1, dxE,
- xc2, dxC, extValue, 0, dd);
- }
- }
- }
-}
-
-static void drawPolygons(qint32 *bits, int width, int height, const QPoint *vertices,
- const quint32 *indices, int indexCount, qint32 value)
-{
- Q_ASSERT(indexCount != 0);
- Q_ASSERT(height <= 128);
- QVarLengthArray<quint8, 16> scans[128];
- int first = 0;
- for (int i = 1; i < indexCount; ++i) {
- quint32 idx1 = indices[i - 1];
- quint32 idx2 = indices[i];
- Q_ASSERT(idx1 != quint32(-1));
- if (idx2 == quint32(-1)) {
- idx2 = indices[first];
- Q_ASSERT(idx2 != quint32(-1));
- first = ++i;
- }
- const QPoint *v1 = &vertices[idx1];
- const QPoint *v2 = &vertices[idx2];
- if (v2->y() < v1->y())
- qSwap(v1, v2);
- int fromY = qMax(0, v1->y() >> 8);
- int toY = qMin(height, v2->y() >> 8);
- if (fromY >= toY)
- continue;
- int dx = ((v2->x() - v1->x()) << 8) / (v2->y() - v1->y());
- int x = v1->x() + ((fromY << 8) + 0xff - v1->y()) * (v2->x() - v1->x()) / (v2->y() - v1->y());
- for (int y = fromY; y < toY; ++y) {
- quint32 c = quint32(x >> 8);
- if (c < quint32(width))
- scans[y].append(quint8(c));
- x += dx;
- }
- }
- for (int i = 0; i < height; ++i) {
- quint8 *scanline = scans[i].data();
- int size = scans[i].size();
- for (int j = 1; j < size; ++j) {
- int k = j;
- quint8 value = scanline[k];
- for (; k != 0 && value < scanline[k - 1]; --k)
- scanline[k] = scanline[k - 1];
- scanline[k] = value;
- }
- qint32 *line = bits + i * width;
- int j = 0;
- for (; j + 1 < size; j += 2) {
- for (quint8 x = scanline[j]; x < scanline[j + 1]; ++x)
- line[x] = value;
- }
- if (j < size) {
- for (int x = scanline[j]; x < width; ++x)
- line[x] = value;
- }
- }
-}
-
-static QImage makeDistanceField(int imgSize, const QPainterPath &path, int dfScale, int offs)
-{
- QImage image(imgSize, imgSize, QImage::Format_Indexed8);
-
- if (path.isEmpty()) {
- image.fill(0);
- return image;
- }
-
- QTransform transform;
- transform.translate(offs, offs);
- transform.scale(qreal(1) / dfScale, qreal(1) / dfScale);
-
- QDataBuffer<quint32> pathIndices(0);
- QDataBuffer<QPoint> pathVertices(0);
- qSimplifyPath(path, pathVertices, pathIndices, transform);
-
- const qint32 interiorColor = -0x7f80; // 8:8 signed format, -127.5
- const qint32 exteriorColor = 0x7f80; // 8:8 signed format, 127.5
-
- QScopedArrayPointer<qint32> bits(new qint32[imgSize * imgSize]);
- for (int i = 0; i < imgSize * imgSize; ++i)
- bits[i] = exteriorColor;
-
- const qreal angleStep = qreal(15 * 3.141592653589793238 / 180);
- const QPoint rotation(qRound(cos(angleStep) * 0x4000),
- qRound(sin(angleStep) * 0x4000)); // 2:14 signed
-
- const quint32 *indices = pathIndices.data();
- QVarLengthArray<QPoint> normals;
- QVarLengthArray<QPoint> vertices;
- QVarLengthArray<bool> isConvex;
- QVarLengthArray<bool> needsClipping;
-
- drawPolygons(bits.data(), imgSize, imgSize, pathVertices.data(), indices, pathIndices.size(),
- interiorColor);
-
- int index = 0;
-
- while (index < pathIndices.size()) {
- normals.clear();
- vertices.clear();
- needsClipping.clear();
-
- // Find end of polygon.
- int end = index;
- while (indices[end] != quint32(-1))
- ++end;
-
- // Calculate vertex normals.
- for (int next = index, prev = end - 1; next < end; prev = next++) {
- quint32 fromVertexIndex = indices[prev];
- quint32 toVertexIndex = indices[next];
-
- const QPoint &from = pathVertices.at(fromVertexIndex);
- const QPoint &to = pathVertices.at(toVertexIndex);
-
- QPoint n(to.y() - from.y(), from.x() - to.x());
- if (n.x() == 0 && n.y() == 0)
- continue;
- int scale = qRound((offs << 16) / sqrt(qreal(n.x() * n.x() + n.y() * n.y()))); // 8:16
- n.rx() = n.x() * scale >> 8;
- n.ry() = n.y() * scale >> 8;
- normals.append(n);
- QPoint v(to.x() + 0x7f, to.y() + 0x7f);
- vertices.append(v);
- needsClipping.append((to.x() < offs << 8) || (to.x() >= (imgSize - offs) << 8)
- || (to.y() < offs << 8) || (to.y() >= (imgSize - offs) << 8));
- }
-
- isConvex.resize(normals.count());
- for (int next = 0, prev = normals.count() - 1; next < normals.count(); prev = next++) {
- isConvex[prev] = normals.at(prev).x() * normals.at(next).y()
- - normals.at(prev).y() * normals.at(next).x() < 0;
- }
-
- // Draw quads.
- for (int next = 0, prev = normals.count() - 1; next < normals.count(); prev = next++) {
- QPoint n = normals.at(next);
- QPoint intPrev = vertices.at(prev);
- QPoint extPrev = vertices.at(prev);
- QPoint intNext = vertices.at(next);
- QPoint extNext = vertices.at(next);
-
- extPrev.rx() -= n.x();
- extPrev.ry() -= n.y();
- intPrev.rx() += n.x();
- intPrev.ry() += n.y();
- extNext.rx() -= n.x();
- extNext.ry() -= n.y();
- intNext.rx() += n.x();
- intNext.ry() += n.y();
-
- if (needsClipping[prev] || needsClipping[next]) {
- drawRectangle<Clip>(bits.data(), imgSize, imgSize,
- &intPrev, &vertices.at(prev), &extPrev,
- &intNext, &vertices.at(next), &extNext,
- exteriorColor);
- } else {
- drawRectangle<NoClip>(bits.data(), imgSize, imgSize,
- &intPrev, &vertices.at(prev), &extPrev,
- &intNext, &vertices.at(next), &extNext,
- exteriorColor);
- }
-
- if (isConvex.at(prev)) {
- QPoint p = extPrev;
- if (needsClipping[prev]) {
- for (;;) {
- QPoint rn((n.x() * rotation.x() - n.y() * rotation.y()) >> 14,
- (n.y() * rotation.x() + n.x() * rotation.y()) >> 14);
- n = rn;
- if (n.x() * normals.at(prev).y() - n.y() * normals.at(prev).x() <= 0) {
- p.rx() = vertices.at(prev).x() - normals.at(prev).x();
- p.ry() = vertices.at(prev).y() - normals.at(prev).y();
- drawTriangle<Clip>(bits.data(), imgSize, imgSize, &vertices.at(prev),
- &extPrev, &p, exteriorColor);
- break;
- }
-
- p.rx() = vertices.at(prev).x() - n.x();
- p.ry() = vertices.at(prev).y() - n.y();
- drawTriangle<Clip>(bits.data(), imgSize, imgSize, &vertices.at(prev),
- &extPrev, &p, exteriorColor);
- extPrev = p;
- }
- } else {
- for (;;) {
- QPoint rn((n.x() * rotation.x() - n.y() * rotation.y()) >> 14,
- (n.y() * rotation.x() + n.x() * rotation.y()) >> 14);
- n = rn;
- if (n.x() * normals.at(prev).y() - n.y() * normals.at(prev).x() <= 0) {
- p.rx() = vertices.at(prev).x() - normals.at(prev).x();
- p.ry() = vertices.at(prev).y() - normals.at(prev).y();
- drawTriangle<NoClip>(bits.data(), imgSize, imgSize, &vertices.at(prev),
- &extPrev, &p, exteriorColor);
- break;
- }
-
- p.rx() = vertices.at(prev).x() - n.x();
- p.ry() = vertices.at(prev).y() - n.y();
- drawTriangle<NoClip>(bits.data(), imgSize, imgSize, &vertices.at(prev),
- &extPrev, &p, exteriorColor);
- extPrev = p;
- }
- }
- } else {
- QPoint p = intPrev;
- if (needsClipping[prev]) {
- for (;;) {
- QPoint rn((n.x() * rotation.x() + n.y() * rotation.y()) >> 14,
- (n.y() * rotation.x() - n.x() * rotation.y()) >> 14);
- n = rn;
- if (n.x() * normals.at(prev).y() - n.y() * normals.at(prev).x() >= 0) {
- p.rx() = vertices.at(prev).x() + normals.at(prev).x();
- p.ry() = vertices.at(prev).y() + normals.at(prev).y();
- drawTriangle<Clip>(bits.data(), imgSize, imgSize, &vertices.at(prev),
- &p, &intPrev, interiorColor);
- break;
- }
-
- p.rx() = vertices.at(prev).x() + n.x();
- p.ry() = vertices.at(prev).y() + n.y();
- drawTriangle<Clip>(bits.data(), imgSize, imgSize, &vertices.at(prev),
- &p, &intPrev, interiorColor);
- intPrev = p;
- }
- } else {
- for (;;) {
- QPoint rn((n.x() * rotation.x() + n.y() * rotation.y()) >> 14,
- (n.y() * rotation.x() - n.x() * rotation.y()) >> 14);
- n = rn;
- if (n.x() * normals.at(prev).y() - n.y() * normals.at(prev).x() >= 0) {
- p.rx() = vertices.at(prev).x() + normals.at(prev).x();
- p.ry() = vertices.at(prev).y() + normals.at(prev).y();
- drawTriangle<NoClip>(bits.data(), imgSize, imgSize, &vertices.at(prev),
- &p, &intPrev, interiorColor);
- break;
- }
-
- p.rx() = vertices.at(prev).x() + n.x();
- p.ry() = vertices.at(prev).y() + n.y();
- drawTriangle<NoClip>(bits.data(), imgSize, imgSize, &vertices.at(prev),
- &p, &intPrev, interiorColor);
- intPrev = p;
- }
- }
- }
- }
-
- index = end + 1;
- }
-
- const qint32 *inLine = bits.data();
- uchar *outLine = image.bits();
- int padding = image.bytesPerLine() - image.width();
- for (int y = 0; y < imgSize; ++y) {
- for (int x = 0; x < imgSize; ++x, ++inLine, ++outLine)
- *outLine = uchar((0x7f80 - *inLine) >> 8);
- outLine += padding;
- }
-
- return image;
-}
-
-bool qt_fontHasNarrowOutlines(const QRawFont &f)
-{
- QRawFont font = f;
- font.setPixelSize(QT_DISTANCEFIELD_DEFAULT_BASEFONTSIZE);
- Q_ASSERT(font.isValid());
-
- QVector<quint32> glyphIndices = font.glyphIndexesForString(QLatin1String("O"));
- if (glyphIndices.size() < 1)
- return false;
-
- QImage im = font.alphaMapForGlyph(glyphIndices.at(0), QRawFont::PixelAntialiasing);
- if (im.isNull())
- return false;
-
- int minHThick = 999;
- int minVThick = 999;
-
- int thick = 0;
- bool in = false;
- int y = (im.height() + 1) / 2;
- for (int x = 0; x < im.width(); ++x) {
- int a = qAlpha(im.pixel(x, y));
- if (a > 127) {
- in = true;
- ++thick;
- } else if (in) {
- in = false;
- minHThick = qMin(minHThick, thick);
- thick = 0;
- }
- }
-
- thick = 0;
- in = false;
- int x = (im.width() + 1) / 2;
- for (int y = 0; y < im.height(); ++y) {
- int a = qAlpha(im.pixel(x, y));
- if (a > 127) {
- in = true;
- ++thick;
- } else if (in) {
- in = false;
- minVThick = qMin(minVThick, thick);
- thick = 0;
- }
- }
-
- return minHThick == 1 || minVThick == 1;
-}
-
-QImage qt_renderDistanceFieldGlyph(const QRawFont &font, glyph_t glyph, bool doubleResolution)
-{
- QRawFont renderFont = font;
- renderFont.setPixelSize(QT_DISTANCEFIELD_BASEFONTSIZE(doubleResolution) * QT_DISTANCEFIELD_SCALE(doubleResolution));
-
- QPainterPath path = renderFont.pathForGlyph(glyph);
- path.translate(-path.boundingRect().topLeft());
- path.setFillRule(Qt::WindingFill);
-
- QImage im = makeDistanceField(QT_DISTANCEFIELD_TILESIZE(doubleResolution),
- path,
- QT_DISTANCEFIELD_SCALE(doubleResolution),
- QT_DISTANCEFIELD_RADIUS(doubleResolution) / QT_DISTANCEFIELD_SCALE(doubleResolution));
- return im;
-}
-
-QSGDistanceFieldGlyphCacheManager::QSGDistanceFieldGlyphCacheManager(QSGContext *c)
- : sgCtx(c)
- , m_threshold_func(defaultThresholdFunc)
- , m_antialiasingSpread_func(defaultAntialiasingSpreadFunc)
-{
-#ifndef QT_OPENGL_ES
- m_defaultAntialiasingMode = QSGGlyphNode::HighQualitySubPixelAntialiasing;
-#else
- m_defaultAntialiasingMode = QSGGlyphNode::GrayAntialiasing;
-#endif
-}
-
-QSGDistanceFieldGlyphCacheManager::~QSGDistanceFieldGlyphCacheManager()
-{
- qDeleteAll(m_caches.values());
-}
-
-QSGDistanceFieldGlyphCache *QSGDistanceFieldGlyphCacheManager::cache(const QRawFont &font)
-{
- QRawFontPrivate *fontD = QRawFontPrivate::get(font);
- QHash<QFontEngine *, QSGDistanceFieldGlyphCache *>::iterator cache = m_caches.find(fontD->fontEngine);
- if (cache == m_caches.end())
- cache = m_caches.insert(fontD->fontEngine, sgCtx->createDistanceFieldGlyphCache(font));
- return cache.value();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgdistancefieldutil_p.h b/src/declarative/scenegraph/util/qsgdistancefieldutil_p.h
deleted file mode 100644
index 93dffab76e..0000000000
--- a/src/declarative/scenegraph/util/qsgdistancefieldutil_p.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGDISTANCEFIELDUTIL_H
-#define QSGDISTANCEFIELDUTIL_H
-
-#include <qrawfont.h>
-#include <private/qfontengine_p.h>
-#include <private/qsgadaptationlayer_p.h>
-
-QT_BEGIN_NAMESPACE
-
-#define QT_DISTANCEFIELD_DEFAULT_BASEFONTSIZE 54
-#define QT_DISTANCEFIELD_DEFAULT_TILESIZE 64
-#define QT_DISTANCEFIELD_DEFAULT_SCALE 16
-#define QT_DISTANCEFIELD_DEFAULT_RADIUS 80
-#define QT_DISTANCEFIELD_HIGHGLYPHCOUNT 2000
-
-#define QT_DISTANCEFIELD_BASEFONTSIZE(NarrowOutlineFont) \
- (NarrowOutlineFont ? QT_DISTANCEFIELD_DEFAULT_BASEFONTSIZE * 2 : \
- QT_DISTANCEFIELD_DEFAULT_BASEFONTSIZE)
-#define QT_DISTANCEFIELD_TILESIZE(NarrowOutlineFont) \
- (NarrowOutlineFont ? QT_DISTANCEFIELD_DEFAULT_TILESIZE * 2 : \
- QT_DISTANCEFIELD_DEFAULT_TILESIZE)
-#define QT_DISTANCEFIELD_SCALE(NarrowOutlineFont) \
- (NarrowOutlineFont ? QT_DISTANCEFIELD_DEFAULT_SCALE / 2 : \
- QT_DISTANCEFIELD_DEFAULT_SCALE)
-#define QT_DISTANCEFIELD_RADIUS(NarrowOutlineFont) \
- (NarrowOutlineFont ? QT_DISTANCEFIELD_DEFAULT_RADIUS / 2 : \
- QT_DISTANCEFIELD_DEFAULT_RADIUS)
-
-
-typedef float (*ThresholdFunc)(float glyphScale);
-typedef float (*AntialiasingSpreadFunc)(float glyphScale);
-
-bool qt_fontHasNarrowOutlines(const QRawFont &f);
-QImage qt_renderDistanceFieldGlyph(const QRawFont &font, glyph_t glyph, bool doubleResolution);
-
-
-class QOpenGLShaderProgram;
-class QSGDistanceFieldGlyphCache;
-class QSGContext;
-
-class Q_DECLARATIVE_EXPORT QSGDistanceFieldGlyphCacheManager
-{
-public:
- QSGDistanceFieldGlyphCacheManager(QSGContext *c);
- ~QSGDistanceFieldGlyphCacheManager();
-
- QSGDistanceFieldGlyphCache *cache(const QRawFont &font);
-
- QSGGlyphNode::AntialiasingMode defaultAntialiasingMode() const { return m_defaultAntialiasingMode; }
- void setDefaultAntialiasingMode(QSGGlyphNode::AntialiasingMode mode) { m_defaultAntialiasingMode = mode; }
-
- ThresholdFunc thresholdFunc() const { return m_threshold_func; }
- void setThresholdFunc(ThresholdFunc func) { m_threshold_func = func; }
-
- AntialiasingSpreadFunc antialiasingSpreadFunc() const { return m_antialiasingSpread_func; }
- void setAntialiasingSpreadFunc(AntialiasingSpreadFunc func) { m_antialiasingSpread_func = func; }
-
-private:
- QHash<QFontEngine *, QSGDistanceFieldGlyphCache *> m_caches;
-
- QSGContext *sgCtx;
-
- QSGGlyphNode::AntialiasingMode m_defaultAntialiasingMode;
- ThresholdFunc m_threshold_func;
- AntialiasingSpreadFunc m_antialiasingSpread_func;
-};
-
-QT_END_NAMESPACE
-
-#endif // QSGDISTANCEFIELDUTIL_H
diff --git a/src/declarative/scenegraph/util/qsgengine.cpp b/src/declarative/scenegraph/util/qsgengine.cpp
deleted file mode 100644
index 88eeebc472..0000000000
--- a/src/declarative/scenegraph/util/qsgengine.cpp
+++ /dev/null
@@ -1,115 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgengine.h"
-
-#include <qquickcanvas.h>
-
-#include <private/qobject_p.h>
-#include <QtGui/QColor>
-
-QT_BEGIN_NAMESPACE
-
-class QSGEnginePrivate : public QObjectPrivate
-{
-public:
- QSGEnginePrivate()
- : canvas(0)
- {
- }
-
- QQuickCanvas *canvas;
-};
-
-/*!
- \class QSGEngine
- \deprecated
- */
-
-QSGEngine::QSGEngine(QObject *parent) :
- QObject(*(new QSGEnginePrivate), parent)
-{
-}
-
-
-QSGEngine::~QSGEngine()
-{
-}
-
-
-void QSGEngine::setCanvas(QQuickCanvas *canvas)
-{
- d_func()->canvas = canvas;
- connect(canvas, SIGNAL(afterRendering()), this, SIGNAL(afterRendering()));
- connect(canvas, SIGNAL(beforeRendering()), this, SIGNAL(beforeRendering()));
-}
-
-void QSGEngine::setClearBeforeRendering(bool enabled)
-{
- d_func()->canvas->setClearBeforeRendering(enabled);
-}
-
-bool QSGEngine::clearBeforeRendering() const
-{
- return d_func()->canvas->clearBeforeRendering();
-}
-
-QSGTexture *QSGEngine::createTextureFromImage(const QImage &image) const
-{
- return d_func()->canvas->createTextureFromImage(image);
-}
-
-QSGTexture *QSGEngine::createTextureFromId(uint id, const QSize &size, TextureOptions options) const
-{
- return d_func()->canvas->createTextureFromId(id, size, QQuickCanvas::CreateTextureOptions((int) options));
-}
-
-void QSGEngine::setClearColor(const QColor &color)
-{
- d_func()->canvas->setClearColor(color);
-}
-
-QColor QSGEngine::clearColor() const
-{
- return d_func()->canvas->clearColor();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgengine.h b/src/declarative/scenegraph/util/qsgengine.h
deleted file mode 100644
index 0cbbcddfec..0000000000
--- a/src/declarative/scenegraph/util/qsgengine.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGENGINE_H
-#define QSGENGINE_H
-
-#include <QObject>
-
-#include <qsgtexture.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGEnginePrivate;
-
-class QQuickCanvas;
-
-class Q_DECLARATIVE_EXPORT QSGEngine : public QObject
-{
- Q_OBJECT
-
- Q_DECLARE_PRIVATE(QSGEngine)
-
-public:
-
- enum TextureOption {
- TextureHasAlphaChannel = 0x0001,
- TextureHasMipmaps = 0x0002,
- TextureOwnsGLTexture = 0x0004
- };
- Q_DECLARE_FLAGS(TextureOptions, TextureOption)
-
- QSGTexture *createTextureFromImage(const QImage &image) const;
- QSGTexture *createTextureFromId(uint id, const QSize &size, TextureOptions options = TextureOption(0)) const;
-
- void setClearBeforeRendering(bool enabled);
- bool clearBeforeRendering() const;
-
- void setClearColor(const QColor &color);
- QColor clearColor() const;
-
-Q_SIGNALS:
- void beforeRendering();
- void afterRendering();
-
-private:
- QSGEngine(QObject *parent = 0);
- ~QSGEngine();
-
- friend class QSGContext;
- friend class QSGContextPrivate;
- friend class QQuickCanvasPrivate;
- void setCanvas(QQuickCanvas *canvas);
-
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSGENGINE_H
diff --git a/src/declarative/scenegraph/util/qsgflatcolormaterial.cpp b/src/declarative/scenegraph/util/qsgflatcolormaterial.cpp
deleted file mode 100644
index ee73616e4f..0000000000
--- a/src/declarative/scenegraph/util/qsgflatcolormaterial.cpp
+++ /dev/null
@@ -1,202 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgflatcolormaterial.h"
-
-#include <qopenglshaderprogram.h>
-
-QT_BEGIN_NAMESPACE
-
-class FlatColorMaterialShader : public QSGMaterialShader
-{
-public:
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
- virtual char const *const *attributeNames() const;
-
- static QSGMaterialType type;
-
-private:
- virtual void initialize();
- virtual const char *vertexShader() const;
- virtual const char *fragmentShader() const;
-
- int m_matrix_id;
- int m_color_id;
-};
-
-QSGMaterialType FlatColorMaterialShader::type;
-
-void FlatColorMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
-{
- Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type());
-
- QSGFlatColorMaterial *oldMaterial = static_cast<QSGFlatColorMaterial *>(oldEffect);
- QSGFlatColorMaterial *newMaterial = static_cast<QSGFlatColorMaterial *>(newEffect);
-
- const QColor &c = newMaterial->color();
-
- if (oldMaterial == 0 || c != oldMaterial->color() || state.isOpacityDirty()) {
- float opacity = state.opacity();
- QVector4D v(c.redF() * c.alphaF() * opacity,
- c.greenF() * c.alphaF() * opacity,
- c.blueF() * c.alphaF() * opacity,
- c.alphaF() * opacity);
- program()->setUniformValue(m_color_id, v);
- }
-
- if (state.isMatrixDirty())
- program()->setUniformValue(m_matrix_id, state.combinedMatrix());
-}
-
-char const *const *FlatColorMaterialShader::attributeNames() const
-{
- static char const *const attr[] = { "vCoord", 0 };
- return attr;
-}
-
-void FlatColorMaterialShader::initialize()
-{
- m_matrix_id = program()->uniformLocation("matrix");
- m_color_id = program()->uniformLocation("color");
-}
-
-const char *FlatColorMaterialShader::vertexShader() const {
- return
- "attribute highp vec4 vCoord; \n"
- "uniform highp mat4 matrix; \n"
- "void main() { \n"
- " gl_Position = matrix * vCoord; \n"
- "}";
-}
-
-const char *FlatColorMaterialShader::fragmentShader() const {
- return
- "uniform lowp vec4 color; \n"
- "void main() { \n"
- " gl_FragColor = color; \n"
- "}";
-}
-
-
-
-/*!
- \class QSGFlatColorMaterial
- \brief The QSGFlatColorMaterial class provides a convenient way of rendering
- solid colored geometry in the scene graph.
-
- \inmodule QtDeclarative
-
- The flat color material will fill every pixel in a geometry using
- a solid color. The color can contain transparency.
-
- The geometry to be rendered with a flat color material requires
- vertices in attribute location 0 in the QSGGeometry object to render
- correctly. The QSGGeometry::defaultAttributes_Point2D() returns an attribute
- set compatible with this material.
-
- The flat color material respects both current opacity and current matrix
- when updating it's rendering state.
- */
-
-
-/*!
- Constructs a new flat color material.
-
- The default color is white.
- */
-
-QSGFlatColorMaterial::QSGFlatColorMaterial() : m_color(QColor(255, 255, 255))
-{
-}
-
-
-
-/*!
- \fn QColor QSGFlatColorMaterial::color() const
-
- Returns this flat color material's color.
-
- The default color is white.
- */
-
-
-
-/*!
- Sets this flat color material's color to \a color.
- */
-
-void QSGFlatColorMaterial::setColor(const QColor &color)
-{
- m_color = color;
- setFlag(Blending, m_color.alpha() != 0xff);
-}
-
-
-
-/*!
- \internal
- */
-
-QSGMaterialType *QSGFlatColorMaterial::type() const
-{
- return &FlatColorMaterialShader::type;
-}
-
-
-
-/*!
- \internal
- */
-
-QSGMaterialShader *QSGFlatColorMaterial::createShader() const
-{
- return new FlatColorMaterialShader;
-}
-
-
-int QSGFlatColorMaterial::compare(const QSGMaterial *other) const
-{
- const QSGFlatColorMaterial *flat = static_cast<const QSGFlatColorMaterial *>(other);
- return m_color.rgba() - flat->color().rgba();
-
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgflatcolormaterial.h b/src/declarative/scenegraph/util/qsgflatcolormaterial.h
deleted file mode 100644
index f6345b6483..0000000000
--- a/src/declarative/scenegraph/util/qsgflatcolormaterial.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef FLATCOLORMATERIAL_H
-#define FLATCOLORMATERIAL_H
-
-#include <qsgmaterial.h>
-#include <qcolor.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class Q_DECLARATIVE_EXPORT QSGFlatColorMaterial : public QSGMaterial
-{
-public:
- QSGFlatColorMaterial();
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
-
- void setColor(const QColor &color);
- const QColor &color() const { return m_color; }
-
- int compare(const QSGMaterial *other) const;
-
-private:
- QColor m_color;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // FLATCOLORMATERIAL_H
diff --git a/src/declarative/scenegraph/util/qsgpainternode.cpp b/src/declarative/scenegraph/util/qsgpainternode.cpp
deleted file mode 100644
index f3e5202241..0000000000
--- a/src/declarative/scenegraph/util/qsgpainternode.cpp
+++ /dev/null
@@ -1,464 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgpainternode_p.h"
-
-#include <private/qquickpainteditem_p.h>
-
-#include <private/qsgcontext_p.h>
-#include <private/qopenglextensions_p.h>
-#include <qopenglframebufferobject.h>
-#include <qopenglfunctions.h>
-#include <qopenglpaintdevice.h>
-#include <qmath.h>
-#include <qpainter.h>
-
-QT_BEGIN_NAMESPACE
-
-#define QT_MINIMUM_DYNAMIC_FBO_SIZE 64
-
-static inline int qt_next_power_of_two(int v)
-{
- v--;
- v |= v >> 1;
- v |= v >> 2;
- v |= v >> 4;
- v |= v >> 8;
- v |= v >> 16;
- ++v;
- return v;
-}
-
-QSGPainterTexture::QSGPainterTexture()
- : QSGPlainTexture()
-{
-
-}
-
-void QSGPainterTexture::bind()
-{
- if (m_dirty_rect.isNull()) {
- QSGPlainTexture::bind();
- return;
- }
-
- bool oldMipmapsGenerated = m_mipmaps_generated;
- m_mipmaps_generated = true;
- QSGPlainTexture::bind();
- m_mipmaps_generated = oldMipmapsGenerated;
-
- QImage subImage = m_image.copy(m_dirty_rect);
-
- int w = m_dirty_rect.width();
- int h = m_dirty_rect.height();
-
-#ifdef QT_OPENGL_ES
- glTexSubImage2D(GL_TEXTURE_2D, 0, m_dirty_rect.x(), m_dirty_rect.y(), w, h,
- GL_RGBA, GL_UNSIGNED_BYTE, subImage.constBits());
-#else
- glTexSubImage2D(GL_TEXTURE_2D, 0, m_dirty_rect.x(), m_dirty_rect.y(), w, h,
- GL_BGRA, GL_UNSIGNED_BYTE, subImage.constBits());
-#endif
-
- if (m_has_mipmaps && !m_mipmaps_generated) {
- QOpenGLContext *ctx = QOpenGLContext::currentContext();
- ctx->functions()->glGenerateMipmap(GL_TEXTURE_2D);
- m_mipmaps_generated = true;
- }
-
- m_dirty_texture = false;
- m_dirty_bind_options = false;
-
- m_dirty_rect = QRect();
-}
-
-QSGPainterNode::QSGPainterNode(QQuickPaintedItem *item)
- : QSGGeometryNode()
- , m_preferredRenderTarget(QQuickPaintedItem::Image)
- , m_actualRenderTarget(QQuickPaintedItem::Image)
- , m_item(item)
- , m_fbo(0)
- , m_multisampledFbo(0)
- , m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
- , m_texture(0)
- , m_gl_device(0)
- , m_size(1, 1)
- , m_dirtyContents(false)
- , m_opaquePainting(false)
- , m_linear_filtering(false)
- , m_mipmapping(false)
- , m_smoothPainting(false)
- , m_extensionsChecked(false)
- , m_multisamplingSupported(false)
- , m_fastFBOResizing(false)
- , m_fillColor(Qt::transparent)
- , m_contentsScale(1.0)
- , m_dirtyGeometry(false)
- , m_dirtyRenderTarget(false)
- , m_dirtyTexture(false)
-{
- m_context = static_cast<QQuickPaintedItemPrivate *>(QObjectPrivate::get(item))->sceneGraphContext();
-
- setMaterial(&m_materialO);
- setOpaqueMaterial(&m_material);
- setGeometry(&m_geometry);
-}
-
-QSGPainterNode::~QSGPainterNode()
-{
- delete m_texture;
- delete m_fbo;
- delete m_multisampledFbo;
- delete m_gl_device;
-}
-
-void QSGPainterNode::paint()
-{
- QRect dirtyRect = m_dirtyRect.isNull() ? QRect(0, 0, m_size.width(), m_size.height()) : m_dirtyRect;
-
- QPainter painter;
- if (m_actualRenderTarget == QQuickPaintedItem::Image)
- painter.begin(&m_image);
- else {
- if (!m_gl_device) {
- m_gl_device = new QOpenGLPaintDevice(m_fboSize);
- m_gl_device->setPaintFlipped(true);
- }
-
- if (m_multisampledFbo)
- m_multisampledFbo->bind();
- else
- m_fbo->bind();
-
- painter.begin(m_gl_device);
- }
-
- if (m_smoothPainting) {
- painter.setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing
- | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
- }
-
- painter.scale(m_contentsScale, m_contentsScale);
-
- QRect sclip(qFloor(dirtyRect.x()/m_contentsScale),
- qFloor(dirtyRect.y()/m_contentsScale),
- qCeil(dirtyRect.width()/m_contentsScale+dirtyRect.x()/m_contentsScale-qFloor(dirtyRect.x()/m_contentsScale)),
- qCeil(dirtyRect.height()/m_contentsScale+dirtyRect.y()/m_contentsScale-qFloor(dirtyRect.y()/m_contentsScale)));
-
- if (!m_dirtyRect.isNull())
- painter.setClipRect(sclip);
-
- painter.setCompositionMode(QPainter::CompositionMode_Source);
- painter.fillRect(sclip, m_fillColor);
- painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
-
- m_item->paint(&painter);
- painter.end();
-
- if (m_actualRenderTarget == QQuickPaintedItem::Image) {
- m_texture->setImage(m_image);
- m_texture->setDirtyRect(dirtyRect);
- } else if (m_multisampledFbo) {
- QOpenGLFramebufferObject::blitFramebuffer(m_fbo, dirtyRect, m_multisampledFbo, dirtyRect);
- }
-
- if (m_multisampledFbo)
- m_multisampledFbo->release();
- else if (m_fbo)
- m_fbo->release();
-
- m_dirtyRect = QRect();
-}
-
-void QSGPainterNode::update()
-{
- if (m_dirtyRenderTarget)
- updateRenderTarget();
- if (m_dirtyGeometry)
- updateGeometry();
- if (m_dirtyTexture)
- updateTexture();
-
- if (m_dirtyContents)
- paint();
-
- m_dirtyGeometry = false;
- m_dirtyRenderTarget = false;
- m_dirtyTexture = false;
- m_dirtyContents = false;
-}
-
-void QSGPainterNode::updateTexture()
-{
- m_texture->setHasMipmaps(m_mipmapping);
- m_texture->setHasAlphaChannel(!m_opaquePainting);
- m_material.setTexture(m_texture);
- m_materialO.setTexture(m_texture);
-
- markDirty(DirtyMaterial);
-}
-
-void QSGPainterNode::updateGeometry()
-{
- QRectF source;
- if (m_actualRenderTarget == QQuickPaintedItem::Image)
- source = QRectF(0, 0, 1, 1);
- else
- source = QRectF(0, 0, qreal(m_size.width()) / m_fboSize.width(), qreal(m_size.height()) / m_fboSize.height());
- QRectF dest(0, 0, m_size.width(), m_size.height());
- if (m_actualRenderTarget == QQuickPaintedItem::InvertedYFramebufferObject)
- dest = QRectF(QPointF(0, m_size.height()), QPointF(m_size.width(), 0));
- QSGGeometry::updateTexturedRectGeometry(&m_geometry,
- dest,
- source);
- markDirty(DirtyGeometry);
-}
-
-void QSGPainterNode::updateRenderTarget()
-{
- if (!m_extensionsChecked) {
- QList<QByteArray> extensions = QByteArray((const char *)glGetString(GL_EXTENSIONS)).split(' ');
- m_multisamplingSupported = extensions.contains("GL_EXT_framebuffer_multisample")
- && extensions.contains("GL_EXT_framebuffer_blit");
- m_extensionsChecked = true;
- }
-
- m_dirtyContents = true;
-
- QQuickPaintedItem::RenderTarget oldTarget = m_actualRenderTarget;
- if (m_preferredRenderTarget == QQuickPaintedItem::Image) {
- m_actualRenderTarget = QQuickPaintedItem::Image;
- } else {
- if (!m_multisamplingSupported && m_smoothPainting)
- m_actualRenderTarget = QQuickPaintedItem::Image;
- else
- m_actualRenderTarget = m_preferredRenderTarget;
- }
- if (oldTarget != m_actualRenderTarget) {
- m_image = QImage();
- delete m_fbo;
- delete m_multisampledFbo;
- m_fbo = m_multisampledFbo = 0;
- }
-
- if (m_actualRenderTarget == QQuickPaintedItem::FramebufferObject ||
- m_actualRenderTarget == QQuickPaintedItem::InvertedYFramebufferObject) {
- const QOpenGLContext *ctx = m_context->glContext();
- if (m_fbo && !m_dirtyGeometry && (!ctx->format().samples() || !m_multisamplingSupported))
- return;
-
- if (m_fboSize.isEmpty())
- updateFBOSize();
-
- delete m_fbo;
- delete m_multisampledFbo;
- m_fbo = m_multisampledFbo = 0;
-
- if (m_smoothPainting && ctx->format().samples() && m_multisamplingSupported) {
- {
- QOpenGLFramebufferObjectFormat format;
- format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
- format.setSamples(8);
- m_multisampledFbo = new QOpenGLFramebufferObject(m_fboSize, format);
- }
- {
- QOpenGLFramebufferObjectFormat format;
- format.setAttachment(QOpenGLFramebufferObject::NoAttachment);
- m_fbo = new QOpenGLFramebufferObject(m_fboSize, format);
- }
- } else {
- QOpenGLFramebufferObjectFormat format;
- format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
- m_fbo = new QOpenGLFramebufferObject(m_fboSize, format);
- }
- } else {
- if (!m_image.isNull() && !m_dirtyGeometry)
- return;
-
- m_image = QImage(m_size, QImage::Format_ARGB32_Premultiplied);
- m_image.fill(Qt::transparent);
- }
-
- QSGPainterTexture *texture = new QSGPainterTexture;
- if (m_actualRenderTarget == QQuickPaintedItem::Image) {
- texture->setOwnsTexture(true);
- texture->setTextureSize(m_size);
- } else {
- texture->setTextureId(m_fbo->texture());
- texture->setOwnsTexture(false);
- texture->setTextureSize(m_fboSize);
- }
-
- if (m_texture)
- delete m_texture;
-
- texture->setTextureSize(m_size);
- m_texture = texture;
-}
-
-void QSGPainterNode::updateFBOSize()
-{
- int fboWidth;
- int fboHeight;
- if (m_fastFBOResizing) {
- fboWidth = qMax(QT_MINIMUM_DYNAMIC_FBO_SIZE, qt_next_power_of_two(m_size.width()));
- fboHeight = qMax(QT_MINIMUM_DYNAMIC_FBO_SIZE, qt_next_power_of_two(m_size.height()));
- } else {
- QSize minimumFBOSize = m_context->minimumFBOSize();
- fboWidth = qMax(minimumFBOSize.width(), m_size.width());
- fboHeight = qMax(minimumFBOSize.height(), m_size.height());
- }
-
- m_fboSize = QSize(fboWidth, fboHeight);
-}
-
-void QSGPainterNode::setPreferredRenderTarget(QQuickPaintedItem::RenderTarget target)
-{
- if (m_preferredRenderTarget == target)
- return;
-
- m_preferredRenderTarget = target;
-
- m_dirtyRenderTarget = true;
- m_dirtyGeometry = true;
- m_dirtyTexture = true;
-}
-
-void QSGPainterNode::setSize(const QSize &size)
-{
- if (size == m_size)
- return;
-
- m_size = size;
- updateFBOSize();
-
- if (m_fbo)
- m_dirtyRenderTarget = m_fbo->size() != m_fboSize || m_dirtyRenderTarget;
- else
- m_dirtyRenderTarget = true;
- m_dirtyGeometry = true;
- m_dirtyTexture = true;
-}
-
-void QSGPainterNode::setDirty(const QRect &dirtyRect)
-{
- m_dirtyContents = true;
- m_dirtyRect = dirtyRect;
-
- if (m_mipmapping)
- m_dirtyTexture = true;
-
- markDirty(DirtyMaterial);
-}
-
-void QSGPainterNode::setOpaquePainting(bool opaque)
-{
- if (opaque == m_opaquePainting)
- return;
-
- m_opaquePainting = opaque;
- m_dirtyTexture = true;
-}
-
-void QSGPainterNode::setLinearFiltering(bool linearFiltering)
-{
- if (linearFiltering == m_linear_filtering)
- return;
-
- m_linear_filtering = linearFiltering;
-
- m_material.setFiltering(linearFiltering ? QSGTexture::Linear : QSGTexture::Nearest);
- m_materialO.setFiltering(linearFiltering ? QSGTexture::Linear : QSGTexture::Nearest);
- markDirty(DirtyMaterial);
-}
-
-void QSGPainterNode::setMipmapping(bool mipmapping)
-{
- if (mipmapping == m_mipmapping)
- return;
-
- m_mipmapping = mipmapping;
- m_material.setMipmapFiltering(mipmapping ? QSGTexture::Linear : QSGTexture::None);
- m_materialO.setMipmapFiltering(mipmapping ? QSGTexture::Linear : QSGTexture::None);
- m_dirtyTexture = true;
-}
-
-void QSGPainterNode::setSmoothPainting(bool s)
-{
- if (s == m_smoothPainting)
- return;
-
- m_smoothPainting = s;
- m_dirtyRenderTarget = true;
-}
-
-void QSGPainterNode::setFillColor(const QColor &c)
-{
- if (c == m_fillColor)
- return;
-
- m_fillColor = c;
- markDirty(DirtyMaterial);
-}
-
-void QSGPainterNode::setContentsScale(qreal s)
-{
- if (s == m_contentsScale)
- return;
-
- m_contentsScale = s;
- markDirty(DirtyMaterial);
-}
-
-void QSGPainterNode::setFastFBOResizing(bool dynamic)
-{
- m_fastFBOResizing = dynamic;
-}
-
-QImage QSGPainterNode::toImage() const
-{
- if (m_actualRenderTarget == QQuickPaintedItem::Image)
- return m_image;
- else
- return m_fbo->toImage();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgpainternode_p.h b/src/declarative/scenegraph/util/qsgpainternode_p.h
deleted file mode 100644
index 8e95107efc..0000000000
--- a/src/declarative/scenegraph/util/qsgpainternode_p.h
+++ /dev/null
@@ -1,160 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGPAINTERNODE_P_H
-#define QSGPAINTERNODE_P_H
-
-#include "qsgnode.h"
-#include "qsgtexturematerial.h"
-#include "qsgtexture_p.h"
-
-#include <qquickpainteditem.h>
-
-#include <QtGui/qcolor.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QOpenGLFramebufferObject;
-class QOpenGLPaintDevice;
-
-class Q_DECLARATIVE_EXPORT QSGPainterTexture : public QSGPlainTexture
-{
-public:
- QSGPainterTexture();
-
- void setDirtyRect(const QRect &rect) { m_dirty_rect = rect; }
-
- void bind();
-
-private:
- QRect m_dirty_rect;
-};
-
-class Q_DECLARATIVE_EXPORT QSGPainterNode : public QSGGeometryNode
-{
-public:
- QSGPainterNode(QQuickPaintedItem *item);
- virtual ~QSGPainterNode();
-
- void setPreferredRenderTarget(QQuickPaintedItem::RenderTarget target);
-
- void setSize(const QSize &size);
- QSize size() const { return m_size; }
-
- void setDirty(const QRect &dirtyRect = QRect());
-
- void setOpaquePainting(bool opaque);
- bool opaquePainting() const { return m_opaquePainting; }
-
- void setLinearFiltering(bool linearFiltering);
- bool linearFiltering() const { return m_linear_filtering; }
-
- void setMipmapping(bool mipmapping);
- bool mipmapping() const { return m_mipmapping; }
-
- void setSmoothPainting(bool s);
- bool smoothPainting() const { return m_smoothPainting; }
-
- void setFillColor(const QColor &c);
- QColor fillColor() const { return m_fillColor; }
-
- void setContentsScale(qreal s);
- qreal contentsScale() const { return m_contentsScale; }
-
- void setFastFBOResizing(bool dynamic);
- bool fastFBOResizing() const { return m_fastFBOResizing; }
-
- QImage toImage() const;
- void update();
-
- void paint();
-
-private:
- void updateTexture();
- void updateGeometry();
- void updateRenderTarget();
- void updateFBOSize();
-
- QSGContext *m_context;
-
- QQuickPaintedItem::RenderTarget m_preferredRenderTarget;
- QQuickPaintedItem::RenderTarget m_actualRenderTarget;
-
- QQuickPaintedItem *m_item;
-
- QOpenGLFramebufferObject *m_fbo;
- QOpenGLFramebufferObject *m_multisampledFbo;
- QImage m_image;
-
- QSGOpaqueTextureMaterial m_material;
- QSGTextureMaterial m_materialO;
- QSGGeometry m_geometry;
- QSGPainterTexture *m_texture;
- QOpenGLPaintDevice *m_gl_device;
-
- QSize m_size;
- QSize m_fboSize;
- bool m_dirtyContents;
- QRect m_dirtyRect;
- bool m_opaquePainting;
- bool m_linear_filtering;
- bool m_mipmapping;
- bool m_smoothPainting;
- bool m_extensionsChecked;
- bool m_multisamplingSupported;
- bool m_fastFBOResizing;
- QColor m_fillColor;
- qreal m_contentsScale;
-
- bool m_dirtyGeometry;
- bool m_dirtyRenderTarget;
- bool m_dirtyTexture;
-};
-
-QT_END_HEADER
-
-QT_END_NAMESPACE
-
-#endif // QSGPAINTERNODE_P_H
diff --git a/src/declarative/scenegraph/util/qsgsimplematerial.h b/src/declarative/scenegraph/util/qsgsimplematerial.h
deleted file mode 100644
index b9e453abec..0000000000
--- a/src/declarative/scenegraph/util/qsgsimplematerial.h
+++ /dev/null
@@ -1,222 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGSIMPLEMATERIAL_H
-#define QSGSIMPLEMATERIAL_H
-
-#include <qsgmaterial.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-template <typename State>
-class QSGSimpleMaterialShader : public QSGMaterialShader
-{
-public:
- void initialize() {
- QSGMaterialShader::initialize();
-
- m_id_matrix = program()->uniformLocation(uniformMatrixName());
- if (m_id_matrix < 0) {
- qFatal("QSGSimpleMaterialShader does not implement 'uniform highp mat4 %s;' in its vertex shader",
- uniformMatrixName());
- }
-
- const char *opacity = uniformOpacityName();
- if (opacity) {
- m_id_opacity = program()->uniformLocation(uniformOpacityName());
- if (m_id_opacity < 0) {
- qFatal("QSGSimpleMaterialShader does not implement 'uniform lowp float %s' in its fragment shader",
- uniformOpacityName());
- }
- } else {
- m_id_opacity = -1;
- }
-
- resolveUniforms();
- }
-
- const char *uniformMatrixName() const { return "qt_Matrix"; }
- const char *uniformOpacityName() const { return "qt_Opacity"; }
-
- void updateState(const RenderState &state, QSGMaterial *newMaterial, QSGMaterial *oldMaterial);
-
- virtual void updateState(const State *newState, const State *oldState) = 0;
-
- virtual void resolveUniforms() {}
-
- virtual QList<QByteArray> attributes() const = 0;
-
- char const *const *attributeNames() const
- {
- if (m_attribute_pointers.size())
- return m_attribute_pointers.constData();
-
- QList<QByteArray> names = attributes();
-
- // Calculate the total number of bytes needed, so we don't get rellocs and
- // bad pointers while copying over the individual names.
- // Add an extra byte pr entry for the '\0' char.
- int total = 0;
- for (int i=0; i<names.size(); ++i)
- total += names.at(i).size() + 1;
- m_attribute_name_data.reserve(total);
-
- // Copy over the names
- for (int i=0; i<names.size(); ++i) {
- m_attribute_pointers << m_attribute_name_data.constData() + m_attribute_name_data.size();
- m_attribute_name_data.append(names.at(i));
- m_attribute_name_data.append('\0');
- }
-
- // Append the "null" terminator
- m_attribute_pointers << 0;
-
- return m_attribute_pointers.constData();
- }
-
-private:
- int m_id_matrix;
- int m_id_opacity;
-
- mutable QByteArray m_attribute_name_data;
- mutable QVector<const char *> m_attribute_pointers;
-};
-
-#define QSG_DECLARE_SIMPLE_SHADER(Shader, State) \
-static QSGMaterialShader *createShader() \
-{ \
- return new Shader; \
-} \
-public: \
-static QSGSimpleMaterial<State> *createMaterial() \
-{ \
- return new QSGSimpleMaterial<State>(createShader); \
-}
-
-
-typedef QSGMaterialShader *(*PtrShaderCreateFunc)();
-
-
-template <typename State>
-class QSGSimpleMaterial : public QSGMaterial
-{
-
-public:
- QSGSimpleMaterial(const State &state, PtrShaderCreateFunc func)
- : m_state(state)
- , m_func(func)
- {
- }
-
- QSGSimpleMaterial(PtrShaderCreateFunc func)
- : m_func(func)
- {
- }
-
- QSGMaterialShader *createShader() const { return m_func(); }
- QSGMaterialType *type() const { return &m_type; }
-
- State *state() { return &m_state; }
- const State *state() const { return &m_state; }
-
-private:
- static QSGMaterialType m_type;
- State m_state;
- PtrShaderCreateFunc m_func;
-};
-
-#define QSG_DECLARE_SIMPLE_COMPARABLE_SHADER(Shader, State) \
-static QSGMaterialShader *createShader() \
-{ \
- return new Shader; \
-} \
-public: \
-static QSGSimpleMaterialComparableMaterial<State> *createMaterial() \
-{ \
- return new QSGSimpleMaterialComparableMaterial<State>(createShader); \
-}
-
-template <typename State>
-class QSGSimpleMaterialComparableMaterial : public QSGSimpleMaterial<State>
-{
-
-public:
- QSGSimpleMaterialComparableMaterial(const State &state, PtrShaderCreateFunc func)
- : QSGSimpleMaterial<State>(state, func) {}
-
- QSGSimpleMaterialComparableMaterial(PtrShaderCreateFunc func)
- : QSGSimpleMaterial<State>(func) {}
-
- int compare(const QSGMaterial *other) const {
- return QSGSimpleMaterialComparableMaterial<State>::state()->compare(static_cast<const QSGSimpleMaterialComparableMaterial<State> *>(other)->state());
- }
-};
-
-
-template <typename State>
-QSGMaterialType QSGSimpleMaterial<State>::m_type;
-
-
-template <typename State>
-Q_INLINE_TEMPLATE void QSGSimpleMaterialShader<State>::updateState(const RenderState &state, QSGMaterial *newMaterial, QSGMaterial *oldMaterial)
-{
- if (state.isMatrixDirty())
- program()->setUniformValue(m_id_matrix, state.combinedMatrix());
- if (state.isOpacityDirty() && m_id_opacity >= 0)
- program()->setUniformValue(m_id_opacity, state.opacity());
-
- State *ns = static_cast<QSGSimpleMaterial<State> *>(newMaterial)->state();
- State *old = 0;
- if (oldMaterial)
- old = static_cast<QSGSimpleMaterial<State> *>(oldMaterial)->state();
- updateState(ns, old);
-}
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-
-#endif
diff --git a/src/declarative/scenegraph/util/qsgsimplerectnode.cpp b/src/declarative/scenegraph/util/qsgsimplerectnode.cpp
deleted file mode 100644
index c3dc5354ca..0000000000
--- a/src/declarative/scenegraph/util/qsgsimplerectnode.cpp
+++ /dev/null
@@ -1,132 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgsimplerectnode.h"
-#include "qsgflatcolormaterial.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QSGSimpleRectNode
-
- \brief The QSGSimpleRectNode class is a convenience class for drawing
- solid filled rectangles using scenegraph.
-
- */
-
-
-
-/*!
- Constructs a QSGSimpleRectNode instance which is spanning \a rect with
- the color \a color.
- */
-QSGSimpleRectNode::QSGSimpleRectNode(const QRectF &rect, const QColor &color)
- : m_geometry(QSGGeometry::defaultAttributes_Point2D(), 4)
-{
- QSGGeometry::updateRectGeometry(&m_geometry, rect);
- m_material.setColor(color);
- setMaterial(&m_material);
- setGeometry(&m_geometry);
-}
-
-
-
-/*!
- Constructs a QSGSimpleRectNode instance with an empty rectangle and
- white color.
- */
-QSGSimpleRectNode::QSGSimpleRectNode()
- : m_geometry(QSGGeometry::defaultAttributes_Point2D(), 4)
-{
- QSGGeometry::updateRectGeometry(&m_geometry, QRectF());
- setMaterial(&m_material);
- setGeometry(&m_geometry);
-}
-
-
-
-/*!
- Sets the rectangle of this rect node to \a rect.
- */
-void QSGSimpleRectNode::setRect(const QRectF &rect)
-{
- QSGGeometry::updateRectGeometry(&m_geometry, rect);
- markDirty(QSGNode::DirtyGeometry);
-}
-
-
-
-/*!
- Returns the rectangle that this rect node covers.
- */
-QRectF QSGSimpleRectNode::rect() const
-{
- const QSGGeometry::Point2D *pts = m_geometry.vertexDataAsPoint2D();
- return QRectF(pts[0].x,
- pts[0].y,
- pts[3].x - pts[0].x,
- pts[3].y - pts[0].y);
-}
-
-
-/*!
- Sets the color of this rectangle to \a color. The default
- color will be white.
- */
-void QSGSimpleRectNode::setColor(const QColor &color)
-{
- if (color != m_material.color()) {
- m_material.setColor(color);
- markDirty(QSGNode::DirtyMaterial);
- }
-}
-
-
-
-/*!
- Returns the color of this rectangle.
- */
-QColor QSGSimpleRectNode::color() const
-{
- return m_material.color();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgsimplerectnode.h b/src/declarative/scenegraph/util/qsgsimplerectnode.h
deleted file mode 100644
index c06db07f93..0000000000
--- a/src/declarative/scenegraph/util/qsgsimplerectnode.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SOLIDRECTNODE_H
-#define SOLIDRECTNODE_H
-
-#include "qsgnode.h"
-#include "qsgflatcolormaterial.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class Q_DECLARATIVE_EXPORT QSGSimpleRectNode : public QSGGeometryNode
-{
-public:
- QSGSimpleRectNode(const QRectF &rect, const QColor &color);
- QSGSimpleRectNode();
-
- void setRect(const QRectF &rect);
- inline void setRect(qreal x, qreal y, qreal w, qreal h) { setRect(QRectF(x, y, w, h)); }
- QRectF rect() const;
-
- void setColor(const QColor &color);
- QColor color() const;
-
-private:
- QSGFlatColorMaterial m_material;
- QSGGeometry m_geometry;
- void *reserved;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // SOLIDRECTNODE_H
diff --git a/src/declarative/scenegraph/util/qsgsimpletexturenode.cpp b/src/declarative/scenegraph/util/qsgsimpletexturenode.cpp
deleted file mode 100644
index a0d6616371..0000000000
--- a/src/declarative/scenegraph/util/qsgsimpletexturenode.cpp
+++ /dev/null
@@ -1,154 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qsgsimpletexturenode.h"
-
-QT_BEGIN_NAMESPACE
-
-static void qsgsimpletexturenode_update(QSGGeometry *g,
- QSGTexture *texture,
- const QRectF &rect)
-{
- if (!texture)
- return;
-
- QSize ts = texture->textureSize();
- QRectF sourceRect(0, 0, ts.width(), ts.height());
- QSGGeometry::updateTexturedRectGeometry(g, rect, texture->convertToNormalizedSourceRect(sourceRect));
-}
-
-/*!
- \class QSGSimpleTextureNode
- \brief The QSGSimpleTextureNode class is provided for convenience to easily draw
- textured content using the QML scene graph.
-
- \inmodule QtDeclarative
-
- \warning The simple texture node class must have a texture before being
- added to the scene graph to be rendered.
-*/
-
-/*!
- Constructs a new simple texture node
- */
-QSGSimpleTextureNode::QSGSimpleTextureNode()
- : m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
-{
- setGeometry(&m_geometry);
- setMaterial(&m_material);
- setOpaqueMaterial(&m_opaque_material);
-}
-
-/*!
- Sets the filtering to be used for this texture node to \a filtering.
-
- For smooth scaling, use QSGTexture::Linear; for normal scaling, use
- QSGTexture::Nearest.
- */
-void QSGSimpleTextureNode::setFiltering(QSGTexture::Filtering filtering)
-{
- if (m_material.filtering() == filtering)
- return;
-
- m_material.setFiltering(filtering);
- m_opaque_material.setFiltering(filtering);
- markDirty(DirtyMaterial);
-}
-
-
-/*!
- Returns the filtering currently set on this texture node
- */
-QSGTexture::Filtering QSGSimpleTextureNode::filtering() const
-{
- return m_material.filtering();
-}
-
-
-/*!
- Sets the target rect of this texture node to \a r
- */
-void QSGSimpleTextureNode::setRect(const QRectF &r)
-{
- if (m_rect == r)
- return;
- m_rect = r;
- qsgsimpletexturenode_update(&m_geometry, texture(), m_rect);
- markDirty(DirtyGeometry);
-}
-
-
-/*!
- Returns the target rect of this texture node.
- */
-QRectF QSGSimpleTextureNode::rect() const
-{
- return m_rect;
-}
-
-/*!
- Sets the texture of this texture node to \a texture.
-
- \warning A texture node must have a texture before being added
- to the scenegraph to be rendered.
- */
-void QSGSimpleTextureNode::setTexture(QSGTexture *texture)
-{
- if (m_material.texture() == texture)
- return;
- m_material.setTexture(texture);
- m_opaque_material.setTexture(texture);
- qsgsimpletexturenode_update(&m_geometry, texture, m_rect);
- markDirty(DirtyMaterial);
-}
-
-
-
-/*!
- Returns the texture for this texture node
- */
-QSGTexture *QSGSimpleTextureNode::texture() const
-{
- return m_material.texture();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgsimpletexturenode.h b/src/declarative/scenegraph/util/qsgsimpletexturenode.h
deleted file mode 100644
index db58c30b5f..0000000000
--- a/src/declarative/scenegraph/util/qsgsimpletexturenode.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGSIMPLETEXTURENODE_H
-#define QSGSIMPLETEXTURENODE_H
-
-#include "qsgnode.h"
-#include "qsggeometry.h"
-#include "qsgtexturematerial.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class Q_DECLARATIVE_EXPORT QSGSimpleTextureNode : public QSGGeometryNode
-{
-public:
- QSGSimpleTextureNode();
-
- void setRect(const QRectF &rect);
- inline void setRect(qreal x, qreal y, qreal w, qreal h) { setRect(QRectF(x, y, w, h)); }
- QRectF rect() const;
-
- void setTexture(QSGTexture *texture);
- QSGTexture *texture() const;
-
- void setFiltering(QSGTexture::Filtering filtering);
- QSGTexture::Filtering filtering() const;
-
-private:
- QSGGeometry m_geometry;
- QSGOpaqueTextureMaterial m_opaque_material;
- QSGTextureMaterial m_material;
-
- QRectF m_rect;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSGSIMPLETEXTURENODE_H
diff --git a/src/declarative/scenegraph/util/qsgtexture.cpp b/src/declarative/scenegraph/util/qsgtexture.cpp
deleted file mode 100644
index e2219e54f5..0000000000
--- a/src/declarative/scenegraph/util/qsgtexture.cpp
+++ /dev/null
@@ -1,541 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#define GL_GLEXT_PROTOTYPES
-
-#include <private/qsgtexture_p.h>
-#include <qopenglfunctions.h>
-#include <private/qsgcontext_p.h>
-#include <qthread.h>
-#include <private/qdeclarativedebugtrace_p.h>
-
-#if !defined(QT_NO_DEBUG) && (defined(Q_OS_LINUX) || defined(Q_OS_MAC))
-#include <execinfo.h>
-#include <QHash>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-inline static bool isPowerOfTwo(int x)
-{
- // Assumption: x >= 1
- return x == (x & -x);
-}
-
-QSGTexturePrivate::QSGTexturePrivate()
- : wrapChanged(false)
- , filteringChanged(false)
- , horizontalWrap(QSGTexture::ClampToEdge)
- , verticalWrap(QSGTexture::ClampToEdge)
- , mipmapMode(QSGTexture::None)
- , filterMode(QSGTexture::Nearest)
-{
-}
-
-#ifndef QT_NO_DEBUG
-
-static int qt_debug_texture_count = 0;
-
-#if defined(Q_OS_LINUX) || defined (Q_OS_MAC)
-DEFINE_BOOL_CONFIG_OPTION(qmlDebugLeakBacktrace, QML_DEBUG_LEAK_BACKTRACE)
-
-#define BACKTRACE_SIZE 20
-class SGTextureTraceItem
-{
-public:
- void *backTrace[BACKTRACE_SIZE];
- size_t backTraceSize;
-};
-
-static QHash<QSGTexture*, SGTextureTraceItem*> qt_debug_allocated_textures;
-#endif
-
-inline static void qt_debug_print_texture_count()
-{
- qDebug("Number of leaked textures: %i", qt_debug_texture_count);
- qt_debug_texture_count = -1;
-
-#if defined(Q_OS_LINUX) || defined (Q_OS_MAC)
- if (qmlDebugLeakBacktrace()) {
- while (!qt_debug_allocated_textures.isEmpty()) {
- QHash<QSGTexture*, SGTextureTraceItem*>::Iterator it = qt_debug_allocated_textures.begin();
- QSGTexture* texture = it.key();
- SGTextureTraceItem* item = it.value();
-
- qt_debug_allocated_textures.erase(it);
-
- qDebug() << "------";
- qDebug() << "Leaked" << texture << "backtrace:";
-
- char** symbols = backtrace_symbols(item->backTrace, item->backTraceSize);
-
- if (symbols) {
- for (int i=0; i<(int) item->backTraceSize; i++)
- qDebug("Backtrace <%02d>: %s", i, symbols[i]);
- free(symbols);
- }
-
- qDebug() << "------";
-
- delete item;
- }
- }
-#endif
-}
-
-inline static void qt_debug_add_texture(QSGTexture* texture)
-{
-#if defined(Q_OS_LINUX) || defined (Q_OS_MAC)
- if (qmlDebugLeakBacktrace()) {
- SGTextureTraceItem* item = new SGTextureTraceItem;
- item->backTraceSize = backtrace(item->backTrace, BACKTRACE_SIZE);
- qt_debug_allocated_textures.insert(texture, item);
- }
-#else
- Q_UNUSED(texture);
-#endif // Q_OS_LINUX
-
- ++qt_debug_texture_count;
-
- static bool atexit_registered = false;
- if (!atexit_registered) {
- atexit(qt_debug_print_texture_count);
- atexit_registered = true;
- }
-}
-
-static void qt_debug_remove_texture(QSGTexture* texture)
-{
-#if defined(Q_OS_LINUX) || defined (Q_OS_MAC)
- if (qmlDebugLeakBacktrace()) {
- SGTextureTraceItem* item = qt_debug_allocated_textures.value(texture, 0);
- if (item) {
- qt_debug_allocated_textures.remove(texture);
- delete item;
- }
- }
-#else
- Q_UNUSED(texture)
-#endif
-
- --qt_debug_texture_count;
-
- if (qt_debug_texture_count < 0)
- qDebug("Material destroyed after qt_debug_print_texture_count() was called.");
-}
-
-#endif // QT_NO_DEBUG
-
-
-QSGTexture::QSGTexture()
- : QObject(*(new QSGTexturePrivate))
-{
-#ifndef QT_NO_DEBUG
- qt_debug_add_texture(this);
-#endif
-}
-
-QSGTexture::~QSGTexture()
-{
-#ifndef QT_NO_DEBUG
- qt_debug_remove_texture(this);
-#endif
-}
-
-
-/*!
- \fn void QSGTexture::bind()
-
- Call this function to bind this texture to the current texture
- target.
-
- Binding a texture may also include uploading the texture data from
- a previously set QImage.
-
- \warning This function can only be called from the rendering thread.
- */
-
-/*!
- This function returns a copy of the current texture which is removed
- from its atlas.
-
- The current texture remains unchanged, so texture coordinates do not
- need to be updated.
-
- Removing a texture from an atlas is primarily useful when passing
- it to a shader that operates on the texture coordinates 0-1 instead
- of the texture subrect inside the atlas.
-
- If the texture is not part of a texture atlas, this function returns 0.
-
- Implementations of this function are recommended to return the same instance
- for multiple calls to limit memory usage.
-
- \warning This function can only be called from the rendering thread.
- */
-
-QSGTexture *QSGTexture::removedFromAtlas() const
-{
- Q_ASSERT_X(!isAtlasTexture(), "QSGTexture::removedFromAtlas()", "Called on a non-atlas texture");
- return 0;
-}
-
-/*!
- Returns weither this texture is part of an atlas or not.
-
- The default implementation returns false.
- */
-bool QSGTexture::isAtlasTexture() const
-{
- return false;
-}
-
-/*!
- \fn int QSGTexture::textureId() const
-
- Returns the OpenGL texture id for this texture.
-
- The default value is 0, indicating that it is an invalid texture id.
-
- The function should at all times return the correct texture id.
-
- \warning This function can only be called from the rendering thread.
- */
-
-
-
-/*!
- Returns the rectangle inside textureSize() that this texture
- represents in normalized coordinates.
-
- The default implementation returns a rect at position (0, 0) with
- width and height of 1.
- */
-QRectF QSGTexture::textureSubRect() const
-{
- return QRectF(0, 0, 1, 1);
-}
-
-/*!
- \fn bool QSGTexture::hasMipmaps() const
-
- Returns true if the texture data contains mipmap levels.
- */
-
-
-/*!
- Sets the mipmap sampling mode to be used for the upcoming bind() call to \a filter.
-
- Setting the mipmap filtering has no effect it the texture does not have mipmaps.
-
- \sa hasMipmaps()
- */
-void QSGTexture::setMipmapFiltering(Filtering filter)
-{
- Q_D(QSGTexture);
- if (d->mipmapMode != (uint) filter) {
- d->mipmapMode = filter;
- d->filteringChanged = true;
- }
-}
-
-/*!
- Returns whether mipmapping should be used when sampling from this texture.
- */
-QSGTexture::Filtering QSGTexture::mipmapFiltering() const
-{
- return (QSGTexture::Filtering) d_func()->mipmapMode;
-}
-
-
-/*!
- Sets the sampling mode to be used for the upcoming bind() call to \a filter.
- */
-void QSGTexture::setFiltering(QSGTexture::Filtering filter)
-{
- Q_D(QSGTexture);
- if (d->filterMode != (uint) filter) {
- d->filterMode = filter;
- d->filteringChanged = true;
- }
-}
-
-QSGTexture::Filtering QSGTexture::filtering() const
-{
- return (QSGTexture::Filtering) d_func()->filterMode;
-}
-
-
-
-/*!
- Sets the horizontal wrap mode to be used for the upcoming bind() call to \a hwrap
- */
-
-void QSGTexture::setHorizontalWrapMode(WrapMode hwrap)
-{
- Q_D(QSGTexture);
- if ((uint) hwrap != d->horizontalWrap) {
- d->horizontalWrap = hwrap;
- d->wrapChanged = true;
- }
-}
-
-QSGTexture::WrapMode QSGTexture::horizontalWrapMode() const
-{
- return (QSGTexture::WrapMode) d_func()->horizontalWrap;
-}
-
-
-
-void QSGTexture::setVerticalWrapMode(WrapMode vwrap)
-{
- Q_D(QSGTexture);
- if ((uint) vwrap != d->verticalWrap) {
- d->verticalWrap = vwrap;
- d->wrapChanged = true;
- }
-}
-
-QSGTexture::WrapMode QSGTexture::verticalWrapMode() const
-{
- return (QSGTexture::WrapMode) d_func()->verticalWrap;
-}
-
-
-/*!
- Update the texture state to match the filtering, mipmap and wrap options
- currently set.
-
- If \a force is true, all properties will be updated regardless of weither
- they have changed or not.
- */
-void QSGTexture::updateBindOptions(bool force)
-{
- Q_D(QSGTexture);
- if (force || d->filteringChanged) {
- bool linear = d->filterMode == Linear;
- GLint minFilter = linear ? GL_LINEAR : GL_NEAREST;
- GLint magFilter = linear ? GL_LINEAR : GL_NEAREST;
-
- if (hasMipmaps()) {
- if (d->mipmapMode == Nearest)
- minFilter = linear ? GL_LINEAR_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_NEAREST;
- else if (d->mipmapMode == Linear)
- minFilter = linear ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_LINEAR;
- }
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
- d->filteringChanged = false;
- }
-
- if (force || d->wrapChanged) {
-#if !defined(QT_NO_DEBUG) && defined(QT_OPENGL_ES_2)
- if (d->horizontalWrap == Repeat || d->verticalWrap == Repeat) {
- bool npotSupported = QOpenGLFunctions(QOpenGLContext::currentContext()).hasOpenGLFeature(QOpenGLFunctions::NPOTTextures);
- QSize size = textureSize();
- bool isNpot = !isPowerOfTwo(size.width()) || !isPowerOfTwo(size.height());
- if (!npotSupported && isNpot)
- qWarning("Scene Graph: This system does not support the REPEAT wrap mode for non-power-of-two textures.");
- }
-#endif
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, d->horizontalWrap == Repeat ? GL_REPEAT : GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, d->verticalWrap == Repeat ? GL_REPEAT : GL_CLAMP_TO_EDGE);
- d->wrapChanged = false;
- }
-}
-
-QSGPlainTexture::QSGPlainTexture()
- : QSGTexture()
- , m_texture_id(0)
- , m_has_alpha(false)
- , m_has_mipmaps(false)
- , m_dirty_bind_options(false)
- , m_owns_texture(true)
- , m_mipmaps_generated(false)
-{
-}
-
-
-QSGPlainTexture::~QSGPlainTexture()
-{
- if (m_texture_id && m_owns_texture)
- glDeleteTextures(1, &m_texture_id);
-}
-
-#ifdef QT_OPENGL_ES
-static void swizzleBGRAToRGBA(QImage *image)
-{
- const int width = image->width();
- const int height = image->height();
- for (int i = 0; i < height; ++i) {
- uint *p = (uint *) image->scanLine(i);
- for (int x = 0; x < width; ++x)
- p[x] = ((p[x] << 16) & 0xff0000) | ((p[x] >> 16) & 0xff) | (p[x] & 0xff00ff00);
- }
-}
-#endif
-
-void QSGPlainTexture::setImage(const QImage &image)
-{
- m_image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
-#ifdef QT_OPENGL_ES
- swizzleBGRAToRGBA(&m_image);
-#endif
-
- m_texture_size = image.size();
- m_has_alpha = image.hasAlphaChannel();
- m_dirty_texture = true;
- m_dirty_bind_options = true;
- }
-
-int QSGPlainTexture::textureId() const
-{
- if (m_dirty_texture) {
- if (m_image.isNull()) {
- // The actual texture and id will be updated/deleted in a later bind()
- // or ~QSGPlainTexture so just keep it minimal here.
- return 0;
- } else {
- // Generate a texture id for use later and return it.
- glGenTextures(1, &const_cast<QSGPlainTexture *>(this)->m_texture_id);
- return m_texture_id;
- }
- }
- return m_texture_id;
-}
-
-void QSGPlainTexture::setTextureId(int id)
-{
- if (m_texture_id && m_owns_texture)
- glDeleteTextures(1, &m_texture_id);
-
- m_texture_id = id;
- m_dirty_texture = false;
- m_dirty_bind_options = true;
- m_image = QImage();
- m_mipmaps_generated = false;
-}
-
-void QSGPlainTexture::setHasMipmaps(bool mm)
-{
- m_has_mipmaps = mm;
- m_mipmaps_generated = false;
-}
-
-
-void QSGPlainTexture::bind()
-{
- if (!m_dirty_texture) {
- glBindTexture(GL_TEXTURE_2D, m_texture_id);
- if (m_has_mipmaps && !m_mipmaps_generated) {
- QOpenGLContext *ctx = QOpenGLContext::currentContext();
- ctx->functions()->glGenerateMipmap(GL_TEXTURE_2D);
- m_mipmaps_generated = true;
- }
- updateBindOptions(m_dirty_bind_options);
- m_dirty_bind_options = false;
- return;
- }
-
- m_dirty_texture = false;
-
-
- if (m_image.isNull()) {
- if (m_texture_id && m_owns_texture)
- glDeleteTextures(1, &m_texture_id);
- m_texture_id = 0;
- m_texture_size = QSize();
- m_has_mipmaps = false;
- m_has_alpha = false;
- return;
- }
-
- if (m_texture_id == 0)
- glGenTextures(1, &m_texture_id);
- glBindTexture(GL_TEXTURE_2D, m_texture_id);
-
- // ### TODO: check for out-of-memory situations...
- int w = m_image.width();
- int h = m_image.height();
-
-#ifdef QT_OPENGL_ES
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_image.constBits());
-#else
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, m_image.constBits());
-#endif
-
- if (m_has_mipmaps) {
- QOpenGLContext *ctx = QOpenGLContext::currentContext();
- ctx->functions()->glGenerateMipmap(GL_TEXTURE_2D);
- m_mipmaps_generated = true;
- }
-
- m_texture_size = QSize(w, h);
- m_texture_rect = QRectF(0, 0, 1, 1);
-
- updateBindOptions(m_dirty_bind_options);
- m_dirty_bind_options = false;
-}
-
-
-/*!
- \class QSGDynamicTexture
- \brief The QSGDynamicTexture class serves as a baseclass for dynamically changing textures,
- such as content that is rendered to FBO's.
-
- To update the content of the texture, call updateTexture() explicitly. Simply calling bind()
- will not update the texture.
- */
-
-
-/*!
- \fn bool QSGDynamicTexture::updateTexture()
-
- Call this function to explicitely update the dynamic texture. Calling bind() will bind
- the content that was previously updated.
-
- The function returns true if the texture was changed as a resul of the update; otherwise
- returns false.
- */
-
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgtexture.h b/src/declarative/scenegraph/util/qsgtexture.h
deleted file mode 100644
index 1a49fb941e..0000000000
--- a/src/declarative/scenegraph/util/qsgtexture.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGTEXTURE_H
-#define QSGTEXTURE_H
-
-#include <QObject>
-#include <QImage>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QSGTexturePrivate;
-class Q_DECLARATIVE_EXPORT QSGTexture : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QSGTexture)
-
-public:
- QSGTexture();
- ~QSGTexture();
-
- enum WrapMode {
- Repeat,
- ClampToEdge
- };
-
- enum Filtering {
- None,
- Nearest,
- Linear
- };
-
- virtual int textureId() const = 0;
- virtual QSize textureSize() const = 0;
- virtual bool hasAlphaChannel() const = 0;
- virtual bool hasMipmaps() const = 0;
-
- virtual QRectF textureSubRect() const;
-
- virtual bool isAtlasTexture() const;
-
- virtual QSGTexture *removedFromAtlas() const;
-
- virtual void bind() = 0;
- void updateBindOptions(bool force = false);
-
- void setMipmapFiltering(Filtering filter);
- QSGTexture::Filtering mipmapFiltering() const;
-
- void setFiltering(Filtering filter);
- QSGTexture::Filtering filtering() const;
-
- void setHorizontalWrapMode(WrapMode hwrap);
- QSGTexture::WrapMode horizontalWrapMode() const;
-
- void setVerticalWrapMode(WrapMode vwrap);
- QSGTexture::WrapMode verticalWrapMode() const;
-
- inline QRectF convertToNormalizedSourceRect(const QRectF &rect) const;
-
-protected:
- QSGTexture(QSGTexturePrivate &dd);
-};
-
-QRectF QSGTexture::convertToNormalizedSourceRect(const QRectF &rect) const
-{
- QSize s = textureSize();
- QRectF r = textureSubRect();
-
- qreal sx = r.width() / s.width();
- qreal sy = r.height() / s.height();
-
- return QRectF(r.x() + rect.x() * sx,
- r.y() + rect.y() * sy,
- rect.width() * sx,
- rect.height() * sy);
-}
-
-
-class Q_DECLARATIVE_EXPORT QSGDynamicTexture : public QSGTexture
-{
- Q_OBJECT
-public:
- virtual bool updateTexture() = 0;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/scenegraph/util/qsgtexture_p.h b/src/declarative/scenegraph/util/qsgtexture_p.h
deleted file mode 100644
index f14508fd25..0000000000
--- a/src/declarative/scenegraph/util/qsgtexture_p.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGTEXTURE_P_H
-#define QSGTEXTURE_P_H
-
-#include <private/qobject_p.h>
-
-#include <QtGui/qopengl.h>
-
-#include "qsgtexture.h"
-#include <private/qsgcontext_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QSGTexturePrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QSGTexture);
-public:
- QSGTexturePrivate();
-
- uint wrapChanged : 1;
- uint filteringChanged : 1;
-
- uint horizontalWrap : 1;
- uint verticalWrap : 1;
- uint mipmapMode : 2;
- uint filterMode : 2;
-};
-
-class Q_DECLARATIVE_EXPORT QSGPlainTexture : public QSGTexture
-{
- Q_OBJECT
-public:
- QSGPlainTexture();
- virtual ~QSGPlainTexture();
-
- void setOwnsTexture(bool owns) { m_owns_texture = owns; }
- bool ownsTexture() const { return m_owns_texture; }
-
- void setTextureId(int id);
- int textureId() const;
- void setTextureSize(const QSize &size) { m_texture_size = size; }
- QSize textureSize() const { return m_texture_size; }
-
- void setHasAlphaChannel(bool alpha) { m_has_alpha = alpha; }
- bool hasAlphaChannel() const { return m_has_alpha; }
-
- void setHasMipmaps(bool mm);
- bool hasMipmaps() const { return m_has_mipmaps; }
-
- void setImage(const QImage &image);
- const QImage &image() { return m_image; }
-
- virtual void bind();
-
- static QSGPlainTexture *fromImage(const QImage &image) {
- QSGPlainTexture *t = new QSGPlainTexture();
- t->setImage(image);
- return t;
- }
-
-protected:
- QImage m_image;
-
- GLuint m_texture_id;
- QSize m_texture_size;
- QRectF m_texture_rect;
-
- uint m_has_alpha : 1;
- uint m_has_mipmaps : 1;
- uint m_dirty_texture : 1;
- uint m_dirty_bind_options : 1;
- uint m_owns_texture : 1;
- uint m_mipmaps_generated : 1;
-};
-
-QT_END_NAMESPACE
-
-#endif // QSGTEXTURE_P_H
diff --git a/src/declarative/scenegraph/util/qsgtexturematerial.cpp b/src/declarative/scenegraph/util/qsgtexturematerial.cpp
deleted file mode 100644
index 0bee81993c..0000000000
--- a/src/declarative/scenegraph/util/qsgtexturematerial.cpp
+++ /dev/null
@@ -1,410 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgtexturematerial_p.h"
-
-#include <QtGui/qopenglshaderprogram.h>
-#include <QtGui/qopenglfunctions.h>
-
-QT_BEGIN_NAMESPACE
-
-inline static bool isPowerOfTwo(int x)
-{
- // Assumption: x >= 1
- return x == (x & -x);
-}
-
-const char qt_scenegraph_texture_material_vertex_code[] =
- "uniform highp mat4 qt_Matrix; \n"
- "attribute highp vec4 qt_VertexPosition; \n"
- "attribute highp vec2 qt_VertexTexCoord; \n"
- "varying highp vec2 qt_TexCoord; \n"
- "void main() { \n"
- " qt_TexCoord = qt_VertexTexCoord; \n"
- " gl_Position = qt_Matrix * qt_VertexPosition; \n"
- "}";
-
-const char qt_scenegraph_texture_material_fragment[] =
- "varying highp vec2 qt_TexCoord; \n"
- "uniform sampler2D qt_Texture; \n"
- "void main() { \n"
- " gl_FragColor = texture2D(qt_Texture, qt_TexCoord);\n"
- "}";
-
-
-const char *QSGOpaqueTextureMaterialShader::vertexShader() const
-{
- return qt_scenegraph_texture_material_vertex_code;
-}
-
-const char *QSGOpaqueTextureMaterialShader::fragmentShader() const
-{
- return qt_scenegraph_texture_material_fragment;
-}
-
-QSGMaterialType QSGOpaqueTextureMaterialShader::type;
-
-char const *const *QSGOpaqueTextureMaterialShader::attributeNames() const
-{
- static char const *const attr[] = { "qt_VertexPosition", "qt_VertexTexCoord", 0 };
- return attr;
-}
-
-void QSGOpaqueTextureMaterialShader::initialize()
-{
- m_matrix_id = program()->uniformLocation("qt_Matrix");
-}
-
-void QSGOpaqueTextureMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
-{
- Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type());
- QSGOpaqueTextureMaterial *tx = static_cast<QSGOpaqueTextureMaterial *>(newEffect);
- QSGOpaqueTextureMaterial *oldTx = static_cast<QSGOpaqueTextureMaterial *>(oldEffect);
-
- QSGTexture *t = tx->texture();
-
- t->setFiltering(tx->filtering());
-#ifdef QT_OPENGL_ES_2
- bool npotSupported = QOpenGLFunctions(const_cast<QOpenGLContext *>(state.context())).hasOpenGLFeature(QOpenGLFunctions::NPOTTextures);
- QSize size = t->textureSize();
- bool isNpot = !isPowerOfTwo(size.width()) || !isPowerOfTwo(size.height());
- if (!npotSupported && isNpot) {
- t->setHorizontalWrapMode(QSGTexture::ClampToEdge);
- t->setVerticalWrapMode(QSGTexture::ClampToEdge);
- } else
-#endif
- {
- t->setHorizontalWrapMode(tx->horizontalWrapMode());
- t->setVerticalWrapMode(tx->verticalWrapMode());
- }
- t->setMipmapFiltering(tx->mipmapFiltering());
-
- if (oldTx == 0 || oldTx->texture()->textureId() != t->textureId())
- t->bind();
- else
- t->updateBindOptions();
-
- if (state.isMatrixDirty())
- program()->setUniformValue(m_matrix_id, state.combinedMatrix());
-}
-
-
-/*!
- \class QSGOpaqueTextureMaterial
- \brief The QSGOpaqueTextureMaterial class provides a convenient way of
- rendering textured geometry in the scene graph.
-
- The opaque textured material will fill every pixel in a geometry with
- the supplied texture. The material does not respect the opacity of the
- QSGMaterialShader::RenderState, so opacity nodes in the parent chain
- of nodes using this material, have no effect.
-
- The geometry to be rendered with an opaque texture material requires
- vertices in attribute location 0 and texture coordinates in attribute
- location 1. The texture coordinate is a 2-dimensional floating-point
- tuple. The QSGGeometry::defaultAttributes_TexturedPoint2D returns an
- attribute set compatible with this material.
-
- The texture to be rendered is can be set using setTexture(). How the
- texure should be rendered can be specified using setMipmapFiltering(),
- setFiltering(), setHorizontalWrapMode() and setVerticalWrapMode().
- The rendering state is set on the texture instance just before it
- is bound.
-
- The opaque textured material respects the current matrix and the alpha
- channel of the texture. It will disregard the accumulated opacity in
- the scenegraph.
-
- A texture material must have a texture set before it is used as
- a material in the scene graph.
- */
-
-
-
-/*!
- Creates a new QSGOpaqueTextureMaterial.
-
- The default mipmap filtering and filtering mode is set to
- QSGTexture::Nearest. The default wrap modes is set to
- QSGTexture::ClampToEdge.
-
- */
-QSGOpaqueTextureMaterial::QSGOpaqueTextureMaterial()
- : m_texture(0)
- , m_filtering(QSGTexture::Nearest)
- , m_mipmap_filtering(QSGTexture::Nearest)
- , m_horizontal_wrap(QSGTexture::ClampToEdge)
- , m_vertical_wrap(QSGTexture::ClampToEdge)
-{
-}
-
-
-/*!
- \internal
- */
-QSGMaterialType *QSGOpaqueTextureMaterial::type() const
-{
- return &QSGOpaqueTextureMaterialShader::type;
-}
-
-/*!
- \internal
- */
-QSGMaterialShader *QSGOpaqueTextureMaterial::createShader() const
-{
- return new QSGOpaqueTextureMaterialShader;
-}
-
-
-
-/*!
- \fn QSGTexture *QSGOpaqueTextureMaterial::texture() const
-
- Returns this texture material's texture.
- */
-
-
-
-/*!
- Sets the texture of this material to \a texture.
-
- The material does not take ownership over the texture.
- */
-
-void QSGOpaqueTextureMaterial::setTexture(QSGTexture *texture)
-{
- m_texture = texture;
- setFlag(Blending, m_texture ? m_texture->hasAlphaChannel() : false);
-}
-
-
-
-/*!
- \fn void QSGOpaqueTextureMaterial::setMipmapFiltering(QSGTexture::Filtering filtering)
-
- Sets the mipmap mode to \a filtering.
-
- The mipmap filtering mode is set on the texture instance just before the
- texture is bound for rendering.
-
- If the texture does not have mipmapping support, enabling mipmapping has no
- effect.
- */
-
-
-
-/*!
- \fn QSGTexture::Filtering QSGOpaqueTextureMaterial::mipmapFiltering() const
-
- Returns this material's mipmap filtering mode.
-
- The default mipmap mode is QSGTexture::Nearest.
- */
-
-
-
-/*!
- \fn void QSGOpaqueTextureMaterial::setFiltering(QSGTexture::Filtering filtering)
-
- Sets the filtering to \a filtering.
-
- The filtering mode is set on the texture instance just before the texture
- is bound for rendering.
- */
-
-
-
-/*!
- \fn QSGTexture::Filtering filtering() const
-
- Returns this material's filtering mode.
-
- The default filtering is QSGTexture::Nearest.
- */
-
-
-
-/*!
- \fn void setHorizontalWrapMode(QSGTexture::WrapMode mode)
-
- Sets the horizontal wrap mode to \a mode.
-
- The horizontal wrap mode is set on the texture instance just before the texture
- is bound for rendering.
- */
-
-
-
- /*!
- \fn QSGTexture::WrapMode horizontalWrapMode() const
-
- Returns this material's horizontal wrap mode.
-
- The default horizontal wrap mode is QSGTexutre::ClampToEdge
- */
-
-
-
-/*!
- \fn void setVerticalWrapMode(QSGTexture::WrapMode mode)
-
- Sets the vertical wrap mode to \a mode.
-
- The vertical wrap mode is set on the texture instance just before the texture
- is bound for rendering.
- */
-
-
-
- /*!
- \fn QSGTexture::WrapMode verticalWrapMode() const
-
- Returns this material's vertical wrap mode.
-
- The default vertical wrap mode is QSGTexutre::ClampToEdge
- */
-
-
-
-/*!
- \internal
- */
-
-int QSGOpaqueTextureMaterial::compare(const QSGMaterial *o) const
-{
- Q_ASSERT(o && type() == o->type());
- const QSGOpaqueTextureMaterial *other = static_cast<const QSGOpaqueTextureMaterial *>(o);
- if (int diff = m_texture->textureId() - other->texture()->textureId())
- return diff;
- return int(m_filtering) - int(other->m_filtering);
-}
-
-
-
-/*!
- \class QSGTextureMaterial
- \brief The QSGTextureMaterial class provides a convenient way of
- rendering textured geometry in the scene graph.
-
- The textured material will fill every pixel in a geometry with
- the supplied texture.
-
- The geometry to be rendered with a texture material requires
- vertices in attribute location 0 and texture coordinates in attribute
- location 1. The texture coordinate is a 2-dimensional floating-point
- tuple. The QSGGeometry::defaultAttributes_TexturedPoint2D returns an
- attribute set compatible with this material.
-
- The texture to be rendered is set using setTexture(). How the
- texure should be rendered can be specified using setMipmapFiltering(),
- setFiltering(), setHorizontalWrapMode() and setVerticalWrapMode().
- The rendering state is set on the texture instance just before it
- is bound.
-
- The textured material respects the current matrix and the alpha
- channel of the texture. It will also respect the accumulated opacity
- in the scenegraph.
-
- A texture material must have a texture set before it is used as
- a material in the scene graph.
- */
-
-static const char qt_scenegraph_texture_material_opacity_fragment[] =
- "varying highp vec2 qt_TexCoord; \n"
- "uniform sampler2D qt_Texture; \n"
- "uniform lowp float opacity; \n"
- "void main() { \n"
- " gl_FragColor = texture2D(qt_Texture, qt_TexCoord) * opacity; \n"
- "}";
-
-class QSGTextureMaterialShader : public QSGOpaqueTextureMaterialShader
-{
-public:
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
- virtual void initialize();
-
- static QSGMaterialType type;
-
-protected:
- virtual const char *fragmentShader() const { return qt_scenegraph_texture_material_opacity_fragment; }
-
- int m_opacity_id;
-};
-QSGMaterialType QSGTextureMaterialShader::type;
-
-
-
-/*!
- \internal
- */
-
-QSGMaterialType *QSGTextureMaterial::type() const
-{
- return &QSGTextureMaterialShader::type;
-}
-
-
-
-/*!
- \internal
- */
-
-QSGMaterialShader *QSGTextureMaterial::createShader() const
-{
- return new QSGTextureMaterialShader;
-}
-
-void QSGTextureMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
-{
- Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type());
- if (state.isOpacityDirty())
- program()->setUniformValue(m_opacity_id, state.opacity());
-
- QSGOpaqueTextureMaterialShader::updateState(state, newEffect, oldEffect);
-}
-
-void QSGTextureMaterialShader::initialize()
-{
- QSGOpaqueTextureMaterialShader::initialize();
- m_opacity_id = program()->uniformLocation("opacity");
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgtexturematerial.h b/src/declarative/scenegraph/util/qsgtexturematerial.h
deleted file mode 100644
index be6ba7a8ab..0000000000
--- a/src/declarative/scenegraph/util/qsgtexturematerial.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TEXTUREMATERIAL_H
-#define TEXTUREMATERIAL_H
-
-#include "qsgmaterial.h"
-#include <qsgtexture.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class Q_DECLARATIVE_EXPORT QSGOpaqueTextureMaterial : public QSGMaterial
-{
-public:
- QSGOpaqueTextureMaterial();
-
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
- virtual int compare(const QSGMaterial *other) const;
-
- void setTexture(QSGTexture *texture);
- QSGTexture *texture() const { return m_texture; }
-
- void setMipmapFiltering(QSGTexture::Filtering filtering) { m_mipmap_filtering = filtering; }
- QSGTexture::Filtering mipmapFiltering() const { return (QSGTexture::Filtering) m_mipmap_filtering; }
-
- void setFiltering(QSGTexture::Filtering filtering) { m_filtering = filtering; }
- QSGTexture::Filtering filtering() const { return (QSGTexture::Filtering) m_filtering; }
-
- void setHorizontalWrapMode(QSGTexture::WrapMode mode) { m_horizontal_wrap = mode; }
- QSGTexture::WrapMode horizontalWrapMode() const { return (QSGTexture::WrapMode) m_horizontal_wrap; }
-
- void setVerticalWrapMode(QSGTexture::WrapMode mode) { m_vertical_wrap = mode; }
- QSGTexture::WrapMode verticalWrapMode() const { return (QSGTexture::WrapMode) m_vertical_wrap; }
-
-protected:
- QSGTexture *m_texture;
-
- uint m_filtering: 2;
- uint m_mipmap_filtering: 2;
- uint m_horizontal_wrap : 1;
- uint m_vertical_wrap: 1;
-
- uint m_reserved : 26;
-};
-
-
-class Q_DECLARATIVE_EXPORT QSGTextureMaterial : public QSGOpaqueTextureMaterial
-{
-public:
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // TEXTUREMATERIAL_H
diff --git a/src/declarative/scenegraph/util/qsgtexturematerial_p.h b/src/declarative/scenegraph/util/qsgtexturematerial_p.h
deleted file mode 100644
index a549f841d8..0000000000
--- a/src/declarative/scenegraph/util/qsgtexturematerial_p.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TEXTUREMATERIAL_P_H
-#define TEXTUREMATERIAL_P_H
-
-#include "qsgtexturematerial.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class Q_DECLARATIVE_EXPORT QSGOpaqueTextureMaterialShader : public QSGMaterialShader
-{
-public:
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
- virtual char const *const *attributeNames() const;
-
- static QSGMaterialType type;
-
-protected:
- virtual void initialize();
- virtual const char *vertexShader() const;
- virtual const char *fragmentShader() const;
-
- int m_matrix_id;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSGTEXTUREMATERIAL_P_H
diff --git a/src/declarative/scenegraph/util/qsgtextureprovider.cpp b/src/declarative/scenegraph/util/qsgtextureprovider.cpp
deleted file mode 100644
index 10faf2e5d4..0000000000
--- a/src/declarative/scenegraph/util/qsgtextureprovider.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgtextureprovider_p.h"
-
-#ifndef GL_CLAMP_TO_EDGE
-#define GL_CLAMP_TO_EDGE 0x812F
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QSGTextureProvider
- \brief The QSGTextureProvider class encapsulates texture based entities in QML.
-
- The QSGTextureProvider lives primarily in the scene graph rendering thread.
- */
-
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgtextureprovider_p.h b/src/declarative/scenegraph/util/qsgtextureprovider_p.h
deleted file mode 100644
index ebb6ca8507..0000000000
--- a/src/declarative/scenegraph/util/qsgtextureprovider_p.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSGTEXTUREPROVIDER_H
-#define QSGTEXTUREPROVIDER_H
-
-#include "qsgtexture.h"
-#include "qobject.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class Q_DECLARATIVE_EXPORT QSGTextureProvider : public QObject
-{
- Q_OBJECT
-public:
- virtual QSGTexture *texture() const = 0;
-
-Q_SIGNALS:
- void textureChanged();
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/scenegraph/util/qsgvertexcolormaterial.cpp b/src/declarative/scenegraph/util/qsgvertexcolormaterial.cpp
deleted file mode 100644
index 78cef55215..0000000000
--- a/src/declarative/scenegraph/util/qsgvertexcolormaterial.cpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsgvertexcolormaterial.h"
-
-#include <qopenglshaderprogram.h>
-
-QT_BEGIN_NAMESPACE
-
-class QSGVertexColorMaterialShader : public QSGMaterialShader
-{
-public:
- virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
- virtual char const *const *attributeNames() const;
-
- static QSGMaterialType type;
-
-private:
- virtual void initialize();
- virtual const char *vertexShader() const;
- virtual const char *fragmentShader() const;
-
- int m_matrix_id;
- int m_opacity_id;
-};
-
-QSGMaterialType QSGVertexColorMaterialShader::type;
-
-void QSGVertexColorMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *)
-{
- if (!(newEffect->flags() & QSGMaterial::Blending) || state.isOpacityDirty())
- program()->setUniformValue(m_opacity_id, state.opacity());
-
- if (state.isMatrixDirty())
- program()->setUniformValue(m_matrix_id, state.combinedMatrix());
-}
-
-char const *const *QSGVertexColorMaterialShader::attributeNames() const
-{
- static const char *const attr[] = { "vertexCoord", "vertexColor", 0 };
- return attr;
-}
-
-void QSGVertexColorMaterialShader::initialize()
-{
- m_matrix_id = program()->uniformLocation("matrix");
- m_opacity_id = program()->uniformLocation("opacity");
-}
-
-const char *QSGVertexColorMaterialShader::vertexShader() const {
- return
- "attribute highp vec4 vertexCoord; \n"
- "attribute highp vec4 vertexColor; \n"
- "uniform highp mat4 matrix; \n"
- "uniform highp float opacity; \n"
- "varying lowp vec4 color; \n"
- "void main() { \n"
- " gl_Position = matrix * vertexCoord; \n"
- " color = vertexColor * opacity; \n"
- "}";
-}
-
-const char *QSGVertexColorMaterialShader::fragmentShader() const {
- return
- "varying lowp vec4 color; \n"
- "void main() { \n"
- " gl_FragColor = color; \n"
- "}";
-}
-
-
-
-/*!
- \class QSGVertexColorMaterial
- \brief The QSGVertexColorMaterial class provides a convenient way of rendering per-vertex
- colored geometry in the scene graph.
-
- \inmodule QtDeclarative
-
- The vertex color material will give each vertex in a geometry a color. Pixels between
- vertices will be linearly interpolated. The colors can contain transparency.
-
- The geometry to be rendered with vertex color must have the following layout. Attribute
- position 0 must contain vertices. Attribute position 1 must contain colors, a tuple of
- 4 values with RGBA layout. Both floats in the range of 0 to 1 and unsigned bytes in
- the range 0 to 255 are valid for the color values. The
- QSGGeometry::defaultAttributes_ColoredPoint2D() constructs an attribute set
- compatible with this material.
-
- The vertex color material respects both current opacity and current matrix when
- updating it's rendering state.
- */
-
-
-QSGVertexColorMaterial::QSGVertexColorMaterial()
-{
- setFlag(Blending, true);
-}
-
-
-/*!
- int QSGVertexColorMaterial::compare() const
-
- As the vertex color material has all its state in the vertex attributes,
- all materials will be equal.
-
- \internal
- */
-
-int QSGVertexColorMaterial::compare(const QSGMaterial * /* other */) const
-{
- return 0;
-}
-
-/*!
- \internal
- */
-
-QSGMaterialType *QSGVertexColorMaterial::type() const
-{
- return &QSGVertexColorMaterialShader::type;
-}
-
-
-
-/*!
- \internal
- */
-
-QSGMaterialShader *QSGVertexColorMaterial::createShader() const
-{
- return new QSGVertexColorMaterialShader;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/scenegraph/util/qsgvertexcolormaterial.h b/src/declarative/scenegraph/util/qsgvertexcolormaterial.h
deleted file mode 100644
index c244f63834..0000000000
--- a/src/declarative/scenegraph/util/qsgvertexcolormaterial.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef VERTEXCOLORMATERIAL_H
-#define VERTEXCOLORMATERIAL_H
-
-#include <qsgmaterial.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class Q_DECLARATIVE_EXPORT QSGVertexColorMaterial : public QSGMaterial
-{
-public:
- QSGVertexColorMaterial();
-
- int compare(const QSGMaterial *other) const;
-
-protected:
- virtual QSGMaterialType *type() const;
- virtual QSGMaterialShader *createShader() const;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // VERTEXCOLORMATERIAL_H
diff --git a/src/declarative/util/qdeclarativeanimation.cpp b/src/declarative/util/qdeclarativeanimation.cpp
deleted file mode 100644
index 8c21d11037..0000000000
--- a/src/declarative/util/qdeclarativeanimation.cpp
+++ /dev/null
@@ -1,2441 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativeanimation_p.h"
-#include "qdeclarativeanimation_p_p.h"
-
-#include <private/qdeclarativestateoperations_p.h>
-#include <private/qdeclarativecontext_p.h>
-
-#include <qdeclarativepropertyvaluesource.h>
-#include <qdeclarative.h>
-#include <qdeclarativeinfo.h>
-#include <qdeclarativeexpression.h>
-#include <private/qdeclarativestringconverters_p.h>
-#include <private/qdeclarativeglobal_p.h>
-#include <private/qdeclarativemetatype_p.h>
-#include <private/qdeclarativevaluetype_p.h>
-#include <private/qdeclarativeproperty_p.h>
-#include <private/qdeclarativeengine_p.h>
-
-#include <qvariant.h>
-#include <qcolor.h>
-#include <qfile.h>
-#include <QParallelAnimationGroup>
-#include <QSequentialAnimationGroup>
-#include <QtCore/qset.h>
-#include <QtCore/qrect.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qsize.h>
-#include <QtCore/qmath.h>
-
-#include <private/qvariantanimation_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass Animation QDeclarativeAbstractAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \brief The Animation element is the base of all QML animations.
-
- The Animation element cannot be used directly in a QML file. It exists
- to provide a set of common properties and methods, available across all the
- other animation types that inherit from it. Attempting to use the Animation
- element directly will result in an error.
-*/
-
-QDeclarativeAbstractAnimation::QDeclarativeAbstractAnimation(QObject *parent)
-: QObject(*(new QDeclarativeAbstractAnimationPrivate), parent)
-{
-}
-
-QDeclarativeAbstractAnimation::~QDeclarativeAbstractAnimation()
-{
-}
-
-QDeclarativeAbstractAnimation::QDeclarativeAbstractAnimation(QDeclarativeAbstractAnimationPrivate &dd, QObject *parent)
-: QObject(dd, parent)
-{
-}
-
-/*!
- \qmlproperty bool QtQuick2::Animation::running
- This property holds whether the animation is currently running.
-
- The \c running property can be set to declaratively control whether or not
- an animation is running. The following example will animate a rectangle
- whenever the \l MouseArea is pressed.
-
- \code
- Rectangle {
- width: 100; height: 100
- NumberAnimation on x {
- running: myMouse.pressed
- from: 0; to: 100
- }
- MouseArea { id: myMouse }
- }
- \endcode
-
- Likewise, the \c running property can be read to determine if the animation
- is running. In the following example the text element will indicate whether
- or not the animation is running.
-
- \code
- NumberAnimation { id: myAnimation }
- Text { text: myAnimation.running ? "Animation is running" : "Animation is not running" }
- \endcode
-
- Animations can also be started and stopped imperatively from JavaScript
- using the \c start() and \c stop() methods.
-
- By default, animations are not running. Though, when the animations are assigned to properties,
- as property value sources using the \e on syntax, they are set to running by default.
-*/
-bool QDeclarativeAbstractAnimation::isRunning() const
-{
- Q_D(const QDeclarativeAbstractAnimation);
- return d->running;
-}
-
-// the behavior calls this function
-void QDeclarativeAbstractAnimation::notifyRunningChanged(bool running)
-{
- Q_D(QDeclarativeAbstractAnimation);
- if (d->disableUserControl && d->running != running) {
- d->running = running;
- emit runningChanged(running);
- }
-}
-
-//commence is called to start an animation when it is used as a
-//simple animation, and not as part of a transition
-void QDeclarativeAbstractAnimationPrivate::commence()
-{
- Q_Q(QDeclarativeAbstractAnimation);
-
- QDeclarativeStateActions actions;
- QDeclarativeProperties properties;
- q->transition(actions, properties, QDeclarativeAbstractAnimation::Forward);
-
- q->qtAnimation()->start();
- if (q->qtAnimation()->state() == QAbstractAnimation::Stopped) {
- running = false;
- emit q->completed();
- }
-}
-
-QDeclarativeProperty QDeclarativeAbstractAnimationPrivate::createProperty(QObject *obj, const QString &str, QObject *infoObj)
-{
- QDeclarativeProperty prop(obj, str, qmlContext(infoObj));
- if (!prop.isValid()) {
- qmlInfo(infoObj) << QDeclarativeAbstractAnimation::tr("Cannot animate non-existent property \"%1\"").arg(str);
- return QDeclarativeProperty();
- } else if (!prop.isWritable()) {
- qmlInfo(infoObj) << QDeclarativeAbstractAnimation::tr("Cannot animate read-only property \"%1\"").arg(str);
- return QDeclarativeProperty();
- }
- return prop;
-}
-
-void QDeclarativeAbstractAnimation::setRunning(bool r)
-{
- Q_D(QDeclarativeAbstractAnimation);
- if (!d->componentComplete) {
- d->running = r;
- if (r == false)
- d->avoidPropertyValueSourceStart = true;
- else if (!d->registered) {
- d->registered = true;
- QDeclarativeEnginePrivate *engPriv = QDeclarativeEnginePrivate::get(qmlEngine(this));
- engPriv->registerFinalizeCallback(this, this->metaObject()->indexOfSlot("componentFinalized()"));
- }
- return;
- }
-
- if (d->running == r)
- return;
-
- if (d->group || d->disableUserControl) {
- qmlInfo(this) << "setRunning() cannot be used on non-root animation nodes.";
- return;
- }
-
- d->running = r;
- if (d->running) {
- bool supressStart = false;
- if (d->alwaysRunToEnd && d->loopCount != 1
- && qtAnimation()->state() == QAbstractAnimation::Running) {
- //we've restarted before the final loop finished; restore proper loop count
- if (d->loopCount == -1)
- qtAnimation()->setLoopCount(d->loopCount);
- else
- qtAnimation()->setLoopCount(qtAnimation()->currentLoop() + d->loopCount);
- supressStart = true; //we want the animation to continue, rather than restart
- }
-
- if (!d->connectedTimeLine) {
- FAST_CONNECT(qtAnimation(), SIGNAL(finished()), this, SLOT(timelineComplete()))
- d->connectedTimeLine = true;
- }
- if (!supressStart)
- d->commence();
- emit started();
- } else {
- if (d->alwaysRunToEnd) {
- if (d->loopCount != 1)
- qtAnimation()->setLoopCount(qtAnimation()->currentLoop()+1); //finish the current loop
- } else
- qtAnimation()->stop();
-
- emit completed();
- }
-
- emit runningChanged(d->running);
-}
-
-/*!
- \qmlproperty bool QtQuick2::Animation::paused
- This property holds whether the animation is currently paused.
-
- The \c paused property can be set to declaratively control whether or not
- an animation is paused.
-
- Animations can also be paused and resumed imperatively from JavaScript
- using the \c pause() and \c resume() methods.
-
- By default, animations are not paused.
-*/
-bool QDeclarativeAbstractAnimation::isPaused() const
-{
- Q_D(const QDeclarativeAbstractAnimation);
- return d->paused;
-}
-
-void QDeclarativeAbstractAnimation::setPaused(bool p)
-{
- Q_D(QDeclarativeAbstractAnimation);
- if (d->paused == p)
- return;
-
- if (d->group || d->disableUserControl) {
- qmlInfo(this) << "setPaused() cannot be used on non-root animation nodes.";
- return;
- }
-
- d->paused = p;
-
- if (!d->componentComplete)
- return;
-
- if (d->paused)
- qtAnimation()->pause();
- else
- qtAnimation()->resume();
-
- emit pausedChanged(d->paused);
-}
-
-void QDeclarativeAbstractAnimation::classBegin()
-{
- Q_D(QDeclarativeAbstractAnimation);
- d->componentComplete = false;
-}
-
-void QDeclarativeAbstractAnimation::componentComplete()
-{
- Q_D(QDeclarativeAbstractAnimation);
- d->componentComplete = true;
-}
-
-void QDeclarativeAbstractAnimation::componentFinalized()
-{
- Q_D(QDeclarativeAbstractAnimation);
- if (d->running) {
- d->running = false;
- setRunning(true);
- }
- if (d->paused) {
- d->paused = false;
- setPaused(true);
- }
-}
-
-/*!
- \qmlproperty bool QtQuick2::Animation::alwaysRunToEnd
- This property holds whether the animation should run to completion when it is stopped.
-
- If this true the animation will complete its current iteration when it
- is stopped - either by setting the \c running property to false, or by
- calling the \c stop() method. The \c complete() method is not effected
- by this value.
-
- This behavior is most useful when the \c repeat property is set, as the
- animation will finish playing normally but not restart.
-
- By default, the alwaysRunToEnd property is not set.
-
- \note alwaysRunToEnd has no effect on animations in a Transition.
-*/
-bool QDeclarativeAbstractAnimation::alwaysRunToEnd() const
-{
- Q_D(const QDeclarativeAbstractAnimation);
- return d->alwaysRunToEnd;
-}
-
-void QDeclarativeAbstractAnimation::setAlwaysRunToEnd(bool f)
-{
- Q_D(QDeclarativeAbstractAnimation);
- if (d->alwaysRunToEnd == f)
- return;
-
- d->alwaysRunToEnd = f;
- emit alwaysRunToEndChanged(f);
-}
-
-/*!
- \qmlproperty int QtQuick2::Animation::loops
- This property holds the number of times the animation should play.
-
- By default, \c loops is 1: the animation will play through once and then stop.
-
- If set to Animation.Infinite, the animation will continuously repeat until it is explicitly
- stopped - either by setting the \c running property to false, or by calling
- the \c stop() method.
-
- In the following example, the rectangle will spin indefinitely.
-
- \code
- Rectangle {
- width: 100; height: 100; color: "green"
- RotationAnimation on rotation {
- loops: Animation.Infinite
- from: 0
- to: 360
- }
- }
- \endcode
-*/
-int QDeclarativeAbstractAnimation::loops() const
-{
- Q_D(const QDeclarativeAbstractAnimation);
- return d->loopCount;
-}
-
-void QDeclarativeAbstractAnimation::setLoops(int loops)
-{
- Q_D(QDeclarativeAbstractAnimation);
- if (loops < 0)
- loops = -1;
-
- if (loops == d->loopCount)
- return;
-
- d->loopCount = loops;
- qtAnimation()->setLoopCount(loops);
- emit loopCountChanged(loops);
-}
-
-
-int QDeclarativeAbstractAnimation::currentTime()
-{
- return qtAnimation()->currentLoopTime();
-}
-
-void QDeclarativeAbstractAnimation::setCurrentTime(int time)
-{
- qtAnimation()->setCurrentTime(time);
-}
-
-QDeclarativeAnimationGroup *QDeclarativeAbstractAnimation::group() const
-{
- Q_D(const QDeclarativeAbstractAnimation);
- return d->group;
-}
-
-void QDeclarativeAbstractAnimation::setGroup(QDeclarativeAnimationGroup *g)
-{
- Q_D(QDeclarativeAbstractAnimation);
- if (d->group == g)
- return;
- if (d->group)
- static_cast<QDeclarativeAnimationGroupPrivate *>(d->group->d_func())->animations.removeAll(this);
-
- d->group = g;
-
- if (d->group && !static_cast<QDeclarativeAnimationGroupPrivate *>(d->group->d_func())->animations.contains(this))
- static_cast<QDeclarativeAnimationGroupPrivate *>(d->group->d_func())->animations.append(this);
-
- //if (g) //if removed from a group, then the group should no longer be the parent
- setParent(g);
-}
-
-/*!
- \qmlmethod QtQuick2::Animation::start()
- \brief Starts the animation.
-
- If the animation is already running, calling this method has no effect. The
- \c running property will be true following a call to \c start().
-*/
-void QDeclarativeAbstractAnimation::start()
-{
- setRunning(true);
-}
-
-/*!
- \qmlmethod QtQuick2::Animation::pause()
- \brief Pauses the animation.
-
- If the animation is already paused, calling this method has no effect. The
- \c paused property will be true following a call to \c pause().
-*/
-void QDeclarativeAbstractAnimation::pause()
-{
- setPaused(true);
-}
-
-/*!
- \qmlmethod QtQuick2::Animation::resume()
- \brief Resumes a paused animation.
-
- If the animation is not paused, calling this method has no effect. The
- \c paused property will be false following a call to \c resume().
-*/
-void QDeclarativeAbstractAnimation::resume()
-{
- setPaused(false);
-}
-
-/*!
- \qmlmethod QtQuick2::Animation::stop()
- \brief Stops the animation.
-
- If the animation is not running, calling this method has no effect. The
- \c running property will be false following a call to \c stop().
-
- Normally \c stop() stops the animation immediately, and the animation has
- no further influence on property values. In this example animation
- \code
- Rectangle {
- NumberAnimation on x { from: 0; to: 100; duration: 500 }
- }
- \endcode
- was stopped at time 250ms, the \c x property will have a value of 50.
-
- However, if the \c alwaysRunToEnd property is set, the animation will
- continue running until it completes and then stop. The \c running property
- will still become false immediately.
-*/
-void QDeclarativeAbstractAnimation::stop()
-{
- setRunning(false);
-}
-
-/*!
- \qmlmethod QtQuick2::Animation::restart()
- \brief Restarts the animation.
-
- This is a convenience method, and is equivalent to calling \c stop() and
- then \c start().
-*/
-void QDeclarativeAbstractAnimation::restart()
-{
- stop();
- start();
-}
-
-/*!
- \qmlmethod QtQuick2::Animation::complete()
- \brief Stops the animation, jumping to the final property values.
-
- If the animation is not running, calling this method has no effect. The
- \c running property will be false following a call to \c complete().
-
- Unlike \c stop(), \c complete() immediately fast-forwards the animation to
- its end. In the following example,
- \code
- Rectangle {
- NumberAnimation on x { from: 0; to: 100; duration: 500 }
- }
- \endcode
- calling \c stop() at time 250ms will result in the \c x property having
- a value of 50, while calling \c complete() will set the \c x property to
- 100, exactly as though the animation had played the whole way through.
-*/
-void QDeclarativeAbstractAnimation::complete()
-{
- if (isRunning()) {
- qtAnimation()->setCurrentTime(qtAnimation()->duration());
- }
-}
-
-void QDeclarativeAbstractAnimation::setTarget(const QDeclarativeProperty &p)
-{
- Q_D(QDeclarativeAbstractAnimation);
- d->defaultProperty = p;
-
- if (!d->avoidPropertyValueSourceStart)
- setRunning(true);
-}
-
-/*
- we rely on setTarget only being called when used as a value source
- so this function allows us to do the same thing as setTarget without
- that assumption
-*/
-void QDeclarativeAbstractAnimation::setDefaultTarget(const QDeclarativeProperty &p)
-{
- Q_D(QDeclarativeAbstractAnimation);
- d->defaultProperty = p;
-}
-
-/*
- don't allow start/stop/pause/resume to be manually invoked,
- because something else (like a Behavior) already has control
- over the animation.
-*/
-void QDeclarativeAbstractAnimation::setDisableUserControl()
-{
- Q_D(QDeclarativeAbstractAnimation);
- d->disableUserControl = true;
-}
-
-void QDeclarativeAbstractAnimation::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_UNUSED(actions);
- Q_UNUSED(modified);
- Q_UNUSED(direction);
-}
-
-void QDeclarativeAbstractAnimation::timelineComplete()
-{
- Q_D(QDeclarativeAbstractAnimation);
- setRunning(false);
- if (d->alwaysRunToEnd && d->loopCount != 1) {
- //restore the proper loopCount for the next run
- qtAnimation()->setLoopCount(d->loopCount);
- }
-}
-
-/*!
- \qmlclass PauseAnimation QDeclarativePauseAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits Animation
- \brief The PauseAnimation element provides a pause for an animation.
-
- When used in a SequentialAnimation, PauseAnimation is a step when
- nothing happens, for a specified duration.
-
- A 500ms animation sequence, with a 100ms pause between two animations:
- \code
- SequentialAnimation {
- NumberAnimation { ... duration: 200 }
- PauseAnimation { duration: 100 }
- NumberAnimation { ... duration: 200 }
- }
- \endcode
-
- \sa {QML Animation and Transitions}, {declarative/animation/basics}{Animation basics example}
-*/
-QDeclarativePauseAnimation::QDeclarativePauseAnimation(QObject *parent)
-: QDeclarativeAbstractAnimation(*(new QDeclarativePauseAnimationPrivate), parent)
-{
- Q_D(QDeclarativePauseAnimation);
- d->init();
-}
-
-QDeclarativePauseAnimation::~QDeclarativePauseAnimation()
-{
-}
-
-void QDeclarativePauseAnimationPrivate::init()
-{
- Q_Q(QDeclarativePauseAnimation);
- pa = new QPauseAnimation;
- QDeclarative_setParent_noEvent(pa, q);
-}
-
-/*!
- \qmlproperty int QtQuick2::PauseAnimation::duration
- This property holds the duration of the pause in milliseconds
-
- The default value is 250.
-*/
-int QDeclarativePauseAnimation::duration() const
-{
- Q_D(const QDeclarativePauseAnimation);
- return d->pa->duration();
-}
-
-void QDeclarativePauseAnimation::setDuration(int duration)
-{
- if (duration < 0) {
- qmlInfo(this) << tr("Cannot set a duration of < 0");
- return;
- }
-
- Q_D(QDeclarativePauseAnimation);
- if (d->pa->duration() == duration)
- return;
- d->pa->setDuration(duration);
- emit durationChanged(duration);
-}
-
-QAbstractAnimation *QDeclarativePauseAnimation::qtAnimation()
-{
- Q_D(QDeclarativePauseAnimation);
- return d->pa;
-}
-
-/*!
- \qmlclass ColorAnimation QDeclarativeColorAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits PropertyAnimation
- \brief The ColorAnimation element animates changes in color values.
-
- ColorAnimation is a specialized PropertyAnimation that defines an
- animation to be applied when a color value changes.
-
- Here is a ColorAnimation applied to the \c color property of a \l Rectangle
- as a property value source. It animates the \c color property's value from
- its current value to a value of "red", over 1000 milliseconds:
-
- \snippet doc/src/snippets/declarative/coloranimation.qml 0
-
- Like any other animation element, a ColorAnimation can be applied in a
- number of ways, including transitions, behaviors and property value
- sources. The \l {QML Animation and Transitions} documentation shows a
- variety of methods for creating animations.
-
- For convenience, when a ColorAnimation is used in a \l Transition, it will
- animate any \c color properties that have been modified during the state
- change. If a \l{PropertyAnimation::}{property} or
- \l{PropertyAnimation::}{properties} are explicitly set for the animation,
- then those are used instead.
-
- \sa {QML Animation and Transitions}, {declarative/animation/basics}{Animation basics example}
-*/
-QDeclarativeColorAnimation::QDeclarativeColorAnimation(QObject *parent)
-: QDeclarativePropertyAnimation(parent)
-{
- Q_D(QDeclarativePropertyAnimation);
- d->interpolatorType = QMetaType::QColor;
- d->interpolator = QVariantAnimationPrivate::getInterpolator(d->interpolatorType);
- d->defaultToInterpolatorType = true;
-}
-
-QDeclarativeColorAnimation::~QDeclarativeColorAnimation()
-{
-}
-
-/*!
- \qmlproperty color QtQuick2::ColorAnimation::from
- This property holds the color value at which the animation should begin.
-
- For example, the following animation is not applied until a color value
- has reached "#c0c0c0":
-
- \qml
- Item {
- states: [
- // States are defined here...
- ]
-
- transition: Transition {
- NumberAnimation { from: "#c0c0c0"; duration: 2000 }
- }
- }
- \endqml
-
- If the ColorAnimation is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the starting state of the
- \l Transition, or the current value of the property at the moment the
- \l Behavior is triggered.
-
- \sa {QML Animation and Transitions}
-*/
-QColor QDeclarativeColorAnimation::from() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->from.value<QColor>();
-}
-
-void QDeclarativeColorAnimation::setFrom(const QColor &f)
-{
- QDeclarativePropertyAnimation::setFrom(f);
-}
-
-/*!
- \qmlproperty color QtQuick2::ColorAnimation::to
-
- This property holds the color value at which the animation should end.
-
- If the ColorAnimation is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the end state of the
- \l Transition, or the value of the property change that triggered the
- \l Behavior.
-
- \sa {QML Animation and Transitions}
-*/
-QColor QDeclarativeColorAnimation::to() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->to.value<QColor>();
-}
-
-void QDeclarativeColorAnimation::setTo(const QColor &t)
-{
- QDeclarativePropertyAnimation::setTo(t);
-}
-
-
-
-/*!
- \qmlclass ScriptAction QDeclarativeScriptAction
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits Animation
- \brief The ScriptAction element allows scripts to be run during an animation.
-
- ScriptAction can be used to run a script at a specific point in an animation.
-
- \qml
- SequentialAnimation {
- NumberAnimation {
- // ...
- }
- ScriptAction { script: doSomething(); }
- NumberAnimation {
- // ...
- }
- }
- \endqml
-
- When used as part of a Transition, you can also target a specific
- StateChangeScript to run using the \c scriptName property.
-
- \snippet doc/src/snippets/declarative/states/statechangescript.qml state and transition
-
- \sa StateChangeScript
-*/
-QDeclarativeScriptAction::QDeclarativeScriptAction(QObject *parent)
- :QDeclarativeAbstractAnimation(*(new QDeclarativeScriptActionPrivate), parent)
-{
- Q_D(QDeclarativeScriptAction);
- d->init();
-}
-
-QDeclarativeScriptAction::~QDeclarativeScriptAction()
-{
-}
-
-void QDeclarativeScriptActionPrivate::init()
-{
- Q_Q(QDeclarativeScriptAction);
- rsa = new QActionAnimation(&proxy);
- QDeclarative_setParent_noEvent(rsa, q);
-}
-
-/*!
- \qmlproperty script QtQuick2::ScriptAction::script
- This property holds the script to run.
-*/
-QDeclarativeScriptString QDeclarativeScriptAction::script() const
-{
- Q_D(const QDeclarativeScriptAction);
- return d->script;
-}
-
-void QDeclarativeScriptAction::setScript(const QDeclarativeScriptString &script)
-{
- Q_D(QDeclarativeScriptAction);
- d->script = script;
-}
-
-/*!
- \qmlproperty string QtQuick2::ScriptAction::scriptName
- This property holds the the name of the StateChangeScript to run.
-
- This property is only valid when ScriptAction is used as part of a transition.
- If both script and scriptName are set, scriptName will be used.
-
- \note When using scriptName in a reversible transition, the script will only
- be run when the transition is being run forwards.
-*/
-QString QDeclarativeScriptAction::stateChangeScriptName() const
-{
- Q_D(const QDeclarativeScriptAction);
- return d->name;
-}
-
-void QDeclarativeScriptAction::setStateChangeScriptName(const QString &name)
-{
- Q_D(QDeclarativeScriptAction);
- d->name = name;
-}
-
-void QDeclarativeScriptActionPrivate::execute()
-{
- Q_Q(QDeclarativeScriptAction);
- if (hasRunScriptScript && reversing)
- return;
-
- QDeclarativeScriptString scriptStr = hasRunScriptScript ? runScriptScript : script;
-
- if (!scriptStr.script().isEmpty()) {
- QDeclarativeExpression expr(scriptStr);
- expr.evaluate();
- if (expr.hasError())
- qmlInfo(q) << expr.error();
- }
-}
-
-void QDeclarativeScriptAction::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_D(QDeclarativeScriptAction);
- Q_UNUSED(modified);
-
- d->hasRunScriptScript = false;
- d->reversing = (direction == Backward);
- for (int ii = 0; ii < actions.count(); ++ii) {
- QDeclarativeAction &action = actions[ii];
-
- if (action.event && action.event->typeName() == QLatin1String("StateChangeScript")
- && static_cast<QDeclarativeStateChangeScript*>(action.event)->name() == d->name) {
- d->runScriptScript = static_cast<QDeclarativeStateChangeScript*>(action.event)->script();
- d->hasRunScriptScript = true;
- action.actionDone = true;
- break; //only match one (names should be unique)
- }
- }
-}
-
-QAbstractAnimation *QDeclarativeScriptAction::qtAnimation()
-{
- Q_D(QDeclarativeScriptAction);
- return d->rsa;
-}
-
-
-
-/*!
- \qmlclass PropertyAction QDeclarativePropertyAction
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits Animation
- \brief The PropertyAction element allows immediate property changes during animation.
-
- PropertyAction is used to specify an immediate property change during an
- animation. The property change is not animated.
-
- It is useful for setting non-animated property values during an animation.
-
- For example, here is a SequentialAnimation that sets the image's
- \l {Image::}{smooth} property to \c true, animates the width of the image,
- then sets \l {Image::}{smooth} back to \c false:
-
- \snippet doc/src/snippets/declarative/propertyaction.qml standalone
-
- PropertyAction is also useful for setting the exact point at which a property
- change should occur during a \l Transition. For example, if PropertyChanges
- was used in a \l State to rotate an item around a particular
- \l {Item::}{transformOrigin}, it might be implemented like this:
-
- \snippet doc/src/snippets/declarative/propertyaction.qml transition
-
- However, with this code, the \c transformOrigin is not set until \e after
- the animation, as a \l State is taken to define the values at the \e end of
- a transition. The animation would rotate at the default \c transformOrigin,
- then jump to \c Item.BottomRight. To fix this, insert a PropertyAction
- before the RotationAnimation begins:
-
- \snippet doc/src/snippets/declarative/propertyaction-sequential.qml sequential
-
- This immediately sets the \c transformOrigin property to the value defined
- in the end state of the \l Transition (i.e. the value defined in the
- PropertyAction object) so that the rotation animation begins with the
- correct transform origin.
-
- \sa {QML Animation and Transitions}, QtDeclarative
-*/
-QDeclarativePropertyAction::QDeclarativePropertyAction(QObject *parent)
-: QDeclarativeAbstractAnimation(*(new QDeclarativePropertyActionPrivate), parent)
-{
- Q_D(QDeclarativePropertyAction);
- d->init();
-}
-
-QDeclarativePropertyAction::~QDeclarativePropertyAction()
-{
-}
-
-void QDeclarativePropertyActionPrivate::init()
-{
- Q_Q(QDeclarativePropertyAction);
- spa = new QActionAnimation;
- QDeclarative_setParent_noEvent(spa, q);
-}
-
-QObject *QDeclarativePropertyAction::target() const
-{
- Q_D(const QDeclarativePropertyAction);
- return d->target;
-}
-
-void QDeclarativePropertyAction::setTarget(QObject *o)
-{
- Q_D(QDeclarativePropertyAction);
- if (d->target == o)
- return;
- d->target = o;
- emit targetChanged();
-}
-
-QString QDeclarativePropertyAction::property() const
-{
- Q_D(const QDeclarativePropertyAction);
- return d->propertyName;
-}
-
-void QDeclarativePropertyAction::setProperty(const QString &n)
-{
- Q_D(QDeclarativePropertyAction);
- if (d->propertyName == n)
- return;
- d->propertyName = n;
- emit propertyChanged();
-}
-
-/*!
- \qmlproperty Object QtQuick2::PropertyAction::target
- \qmlproperty list<Object> QtQuick2::PropertyAction::targets
- \qmlproperty string QtQuick2::PropertyAction::property
- \qmlproperty string QtQuick2::PropertyAction::properties
-
- These properties determine the items and their properties that are
- affected by this action.
-
- The details of how these properties are interpreted in different situations
- is covered in the \l{PropertyAnimation::properties}{corresponding} PropertyAnimation
- documentation.
-
- \sa exclude
-*/
-QString QDeclarativePropertyAction::properties() const
-{
- Q_D(const QDeclarativePropertyAction);
- return d->properties;
-}
-
-void QDeclarativePropertyAction::setProperties(const QString &p)
-{
- Q_D(QDeclarativePropertyAction);
- if (d->properties == p)
- return;
- d->properties = p;
- emit propertiesChanged(p);
-}
-
-QDeclarativeListProperty<QObject> QDeclarativePropertyAction::targets()
-{
- Q_D(QDeclarativePropertyAction);
- return QDeclarativeListProperty<QObject>(this, d->targets);
-}
-
-/*!
- \qmlproperty list<Object> QtQuick2::PropertyAction::exclude
- This property holds the objects that should not be affected by this action.
-
- \sa targets
-*/
-QDeclarativeListProperty<QObject> QDeclarativePropertyAction::exclude()
-{
- Q_D(QDeclarativePropertyAction);
- return QDeclarativeListProperty<QObject>(this, d->exclude);
-}
-
-/*!
- \qmlproperty any QtQuick2::PropertyAction::value
- This property holds the value to be set on the property.
-
- If the PropertyAction is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the end state of the
- \l Transition, or the value of the property change that triggered the
- \l Behavior.
-*/
-QVariant QDeclarativePropertyAction::value() const
-{
- Q_D(const QDeclarativePropertyAction);
- return d->value;
-}
-
-void QDeclarativePropertyAction::setValue(const QVariant &v)
-{
- Q_D(QDeclarativePropertyAction);
- if (d->value.isNull || d->value != v) {
- d->value = v;
- emit valueChanged(v);
- }
-}
-
-QAbstractAnimation *QDeclarativePropertyAction::qtAnimation()
-{
- Q_D(QDeclarativePropertyAction);
- return d->spa;
-}
-
-void QDeclarativePropertyAction::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_D(QDeclarativePropertyAction);
- Q_UNUSED(direction);
-
- struct QDeclarativeSetPropertyAnimationAction : public QAbstractAnimationAction
- {
- QDeclarativeStateActions actions;
- virtual void doAction()
- {
- for (int ii = 0; ii < actions.count(); ++ii) {
- const QDeclarativeAction &action = actions.at(ii);
- QDeclarativePropertyPrivate::write(action.property, action.toValue, QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
- }
- }
- };
-
- 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 << d->propertyName;
-
- QList<QObject*> targets = d->targets;
- if (d->target)
- targets.append(d->target);
-
- bool hasSelectors = !props.isEmpty() || !targets.isEmpty() || !d->exclude.isEmpty();
-
- if (d->defaultProperty.isValid() && !hasSelectors) {
- props << d->defaultProperty.name();
- targets << d->defaultProperty.object();
- }
-
- QDeclarativeSetPropertyAnimationAction *data = new QDeclarativeSetPropertyAnimationAction;
-
- bool hasExplicit = false;
- //an explicit animation has been specified
- if (d->value.isValid()) {
- for (int i = 0; i < props.count(); ++i) {
- for (int j = 0; j < targets.count(); ++j) {
- QDeclarativeAction myAction;
- myAction.property = d->createProperty(targets.at(j), props.at(i), this);
- if (myAction.property.isValid()) {
- myAction.toValue = d->value;
- QDeclarativePropertyAnimationPrivate::convertVariant(myAction.toValue, myAction.property.propertyType());
- data->actions << myAction;
- hasExplicit = true;
- for (int ii = 0; ii < actions.count(); ++ii) {
- QDeclarativeAction &action = actions[ii];
- if (action.property.object() == myAction.property.object() &&
- myAction.property.name() == action.property.name()) {
- modified << action.property;
- break; //### any chance there could be multiples?
- }
- }
- }
- }
- }
- }
-
- if (!hasExplicit)
- for (int ii = 0; ii < actions.count(); ++ii) {
- QDeclarativeAction &action = actions[ii];
-
- QObject *obj = action.property.object();
- QString propertyName = action.property.name();
- QObject *sObj = action.specifiedObject;
- QString sPropertyName = action.specifiedProperty;
- bool same = (obj == sObj);
-
- if ((targets.isEmpty() || targets.contains(obj) || (!same && targets.contains(sObj))) &&
- (!d->exclude.contains(obj)) && (same || (!d->exclude.contains(sObj))) &&
- (props.contains(propertyName) || (!same && props.contains(sPropertyName)))) {
- QDeclarativeAction myAction = action;
-
- if (d->value.isValid())
- myAction.toValue = d->value;
- QDeclarativePropertyAnimationPrivate::convertVariant(myAction.toValue, myAction.property.propertyType());
-
- modified << action.property;
- data->actions << myAction;
- action.fromValue = myAction.toValue;
- }
- }
-
- if (data->actions.count()) {
- d->spa->setAnimAction(data, QAbstractAnimation::DeleteWhenStopped);
- } else {
- delete data;
- }
-}
-
-/*!
- \qmlclass NumberAnimation QDeclarativeNumberAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits PropertyAnimation
- \brief The NumberAnimation element animates changes in qreal-type values.
-
- NumberAnimation is a specialized PropertyAnimation that defines an
- animation to be applied when a numerical value changes.
-
- Here is a NumberAnimation applied to the \c x property of a \l Rectangle
- as a property value source. It animates the \c x value from its current
- value to a value of 50, over 1000 milliseconds:
-
- \snippet doc/src/snippets/declarative/numberanimation.qml 0
-
- Like any other animation element, a NumberAnimation can be applied in a
- number of ways, including transitions, behaviors and property value
- sources. The \l {QML Animation and Transitions} documentation shows a
- variety of methods for creating animations.
-
- Note that NumberAnimation may not animate smoothly if there are irregular
- changes in the number value that it is tracking. If this is the case, use
- SmoothedAnimation instead.
-
- \sa {QML Animation and Transitions}, {declarative/animation/basics}{Animation basics example}
-*/
-QDeclarativeNumberAnimation::QDeclarativeNumberAnimation(QObject *parent)
-: QDeclarativePropertyAnimation(parent)
-{
- init();
-}
-
-QDeclarativeNumberAnimation::QDeclarativeNumberAnimation(QDeclarativePropertyAnimationPrivate &dd, QObject *parent)
-: QDeclarativePropertyAnimation(dd, parent)
-{
- init();
-}
-
-QDeclarativeNumberAnimation::~QDeclarativeNumberAnimation()
-{
-}
-
-void QDeclarativeNumberAnimation::init()
-{
- Q_D(QDeclarativePropertyAnimation);
- d->interpolatorType = QMetaType::QReal;
- d->interpolator = QVariantAnimationPrivate::getInterpolator(d->interpolatorType);
-}
-
-/*!
- \qmlproperty real QtQuick2::NumberAnimation::from
- This property holds the starting value for the animation.
-
- For example, the following animation is not applied until the \c x value
- has reached 100:
-
- \qml
- Item {
- states: [
- // ...
- ]
-
- transition: Transition {
- NumberAnimation { properties: "x"; from: 100; duration: 200 }
- }
- }
- \endqml
-
- If the NumberAnimation is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the starting state of the
- \l Transition, or the current value of the property at the moment the
- \l Behavior is triggered.
-
- \sa {QML Animation and Transitions}
-*/
-
-qreal QDeclarativeNumberAnimation::from() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->from.toReal();
-}
-
-void QDeclarativeNumberAnimation::setFrom(qreal f)
-{
- QDeclarativePropertyAnimation::setFrom(f);
-}
-
-/*!
- \qmlproperty real QtQuick2::NumberAnimation::to
- This property holds the end value for the animation.
-
- If the NumberAnimation is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the end state of the
- \l Transition, or the value of the property change that triggered the
- \l Behavior.
-
- \sa {QML Animation and Transitions}
-*/
-qreal QDeclarativeNumberAnimation::to() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->to.toReal();
-}
-
-void QDeclarativeNumberAnimation::setTo(qreal t)
-{
- QDeclarativePropertyAnimation::setTo(t);
-}
-
-
-
-/*!
- \qmlclass Vector3dAnimation QDeclarativeVector3dAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits PropertyAnimation
- \brief The Vector3dAnimation element animates changes in QVector3d values.
-
- Vector3dAnimation is a specialized PropertyAnimation that defines an
- animation to be applied when a Vector3d value changes.
-
- Like any other animation element, a Vector3dAnimation can be applied in a
- number of ways, including transitions, behaviors and property value
- sources. The \l {QML Animation and Transitions} documentation shows a
- variety of methods for creating animations.
-
- \sa {QML Animation and Transitions}, {declarative/animation/basics}{Animation basics example}
-*/
-QDeclarativeVector3dAnimation::QDeclarativeVector3dAnimation(QObject *parent)
-: QDeclarativePropertyAnimation(parent)
-{
- Q_D(QDeclarativePropertyAnimation);
- d->interpolatorType = QMetaType::QVector3D;
- d->interpolator = QVariantAnimationPrivate::getInterpolator(d->interpolatorType);
- d->defaultToInterpolatorType = true;
-}
-
-QDeclarativeVector3dAnimation::~QDeclarativeVector3dAnimation()
-{
-}
-
-/*!
- \qmlproperty real QtQuick2::Vector3dAnimation::from
- This property holds the starting value for the animation.
-
- If the Vector3dAnimation is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the starting state of the
- \l Transition, or the current value of the property at the moment the
- \l Behavior is triggered.
-
- \sa {QML Animation and Transitions}
-*/
-QVector3D QDeclarativeVector3dAnimation::from() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->from.value<QVector3D>();
-}
-
-void QDeclarativeVector3dAnimation::setFrom(QVector3D f)
-{
- QDeclarativePropertyAnimation::setFrom(f);
-}
-
-/*!
- \qmlproperty real QtQuick2::Vector3dAnimation::to
- This property holds the end value for the animation.
-
- If the Vector3dAnimation is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the end state of the
- \l Transition, or the value of the property change that triggered the
- \l Behavior.
-
- \sa {QML Animation and Transitions}
-*/
-QVector3D QDeclarativeVector3dAnimation::to() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->to.value<QVector3D>();
-}
-
-void QDeclarativeVector3dAnimation::setTo(QVector3D t)
-{
- QDeclarativePropertyAnimation::setTo(t);
-}
-
-
-
-/*!
- \qmlclass RotationAnimation QDeclarativeRotationAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits PropertyAnimation
- \brief The RotationAnimation element animates changes in rotation values.
-
- RotationAnimation is a specialized PropertyAnimation that gives control
- over the direction of rotation during an animation.
-
- By default, it rotates in the direction
- of the numerical change; a rotation from 0 to 240 will rotate 240 degrees
- clockwise, while a rotation from 240 to 0 will rotate 240 degrees
- counterclockwise. The \l direction property can be set to specify the
- direction in which the rotation should occur.
-
- In the following example we use RotationAnimation to animate the rotation
- between states via the shortest path:
-
- \snippet doc/src/snippets/declarative/rotationanimation.qml 0
-
- Notice the RotationAnimation did not need to set a \l target
- value. As a convenience, when used in a transition, RotationAnimation will rotate all
- properties named "rotation" or "angle". You can override this by providing
- your own properties via \l {PropertyAnimation::properties}{properties} or
- \l {PropertyAnimation::property}{property}.
-
- Also, note the \l Rectangle will be rotated around its default
- \l {Item::}{transformOrigin} (which is \c Item.Center). To use a different
- transform origin, set the origin in the PropertyChanges object and apply
- the change at the start of the animation using PropertyAction. See the
- PropertyAction documentation for more details.
-
- Like any other animation element, a RotationAnimation can be applied in a
- number of ways, including transitions, behaviors and property value
- sources. The \l {QML Animation and Transitions} documentation shows a
- variety of methods for creating animations.
-
- \sa {QML Animation and Transitions}, {declarative/animation/basics}{Animation basics example}
-*/
-QVariant _q_interpolateShortestRotation(qreal &f, qreal &t, qreal progress)
-{
- qreal newt = t;
- qreal diff = t-f;
- while(diff > 180.0){
- newt -= 360.0;
- diff -= 360.0;
- }
- while(diff < -180.0){
- newt += 360.0;
- diff += 360.0;
- }
- return QVariant(f + (newt - f) * progress);
-}
-
-QVariant _q_interpolateClockwiseRotation(qreal &f, qreal &t, qreal progress)
-{
- qreal newt = t;
- qreal diff = t-f;
- while(diff < 0.0){
- newt += 360.0;
- diff += 360.0;
- }
- return QVariant(f + (newt - f) * progress);
-}
-
-QVariant _q_interpolateCounterclockwiseRotation(qreal &f, qreal &t, qreal progress)
-{
- qreal newt = t;
- qreal diff = t-f;
- while(diff > 0.0){
- newt -= 360.0;
- diff -= 360.0;
- }
- return QVariant(f + (newt - f) * progress);
-}
-
-QDeclarativeRotationAnimation::QDeclarativeRotationAnimation(QObject *parent)
-: QDeclarativePropertyAnimation(*(new QDeclarativeRotationAnimationPrivate), parent)
-{
- Q_D(QDeclarativeRotationAnimation);
- d->interpolatorType = QMetaType::QReal;
- d->interpolator = QVariantAnimationPrivate::getInterpolator(d->interpolatorType);
- d->defaultProperties = QLatin1String("rotation,angle");
-}
-
-QDeclarativeRotationAnimation::~QDeclarativeRotationAnimation()
-{
-}
-
-/*!
- \qmlproperty real QtQuick2::RotationAnimation::from
- This property holds the starting value for the animation.
-
- For example, the following animation is not applied until the \c angle value
- has reached 100:
-
- \qml
- Item {
- states: [
- // ...
- ]
-
- transition: Transition {
- RotationAnimation { properties: "angle"; from: 100; duration: 2000 }
- }
- }
- \endqml
-
- If the RotationAnimation is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the starting state of the
- \l Transition, or the current value of the property at the moment the
- \l Behavior is triggered.
-
- \sa {QML Animation and Transitions}
-*/
-qreal QDeclarativeRotationAnimation::from() const
-{
- Q_D(const QDeclarativeRotationAnimation);
- return d->from.toReal();
-}
-
-void QDeclarativeRotationAnimation::setFrom(qreal f)
-{
- QDeclarativePropertyAnimation::setFrom(f);
-}
-
-/*!
- \qmlproperty real QtQuick2::RotationAnimation::to
- This property holds the end value for the animation..
-
- If the RotationAnimation is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the end state of the
- \l Transition, or the value of the property change that triggered the
- \l Behavior.
-
- \sa {QML Animation and Transitions}
-*/
-qreal QDeclarativeRotationAnimation::to() const
-{
- Q_D(const QDeclarativeRotationAnimation);
- return d->to.toReal();
-}
-
-void QDeclarativeRotationAnimation::setTo(qreal t)
-{
- QDeclarativePropertyAnimation::setTo(t);
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::RotationAnimation::direction
- This property holds the direction of the rotation.
-
- Possible values are:
-
- \list
- \o RotationAnimation.Numerical (default) - Rotate by linearly interpolating between the two numbers.
- A rotation from 10 to 350 will rotate 340 degrees clockwise.
- \o RotationAnimation.Clockwise - Rotate clockwise between the two values
- \o RotationAnimation.Counterclockwise - Rotate counterclockwise between the two values
- \o RotationAnimation.Shortest - Rotate in the direction that produces the shortest animation path.
- A rotation from 10 to 350 will rotate 20 degrees counterclockwise.
- \endlist
-*/
-QDeclarativeRotationAnimation::RotationDirection QDeclarativeRotationAnimation::direction() const
-{
- Q_D(const QDeclarativeRotationAnimation);
- return d->direction;
-}
-
-void QDeclarativeRotationAnimation::setDirection(QDeclarativeRotationAnimation::RotationDirection direction)
-{
- Q_D(QDeclarativeRotationAnimation);
- if (d->direction == direction)
- return;
-
- d->direction = direction;
- switch(d->direction) {
- case Clockwise:
- d->interpolator = reinterpret_cast<QVariantAnimation::Interpolator>(&_q_interpolateClockwiseRotation);
- break;
- case Counterclockwise:
- d->interpolator = reinterpret_cast<QVariantAnimation::Interpolator>(&_q_interpolateCounterclockwiseRotation);
- break;
- case Shortest:
- d->interpolator = reinterpret_cast<QVariantAnimation::Interpolator>(&_q_interpolateShortestRotation);
- break;
- default:
- d->interpolator = QVariantAnimationPrivate::getInterpolator(d->interpolatorType);
- break;
- }
-
- emit directionChanged();
-}
-
-
-
-QDeclarativeAnimationGroup::QDeclarativeAnimationGroup(QObject *parent)
-: QDeclarativeAbstractAnimation(*(new QDeclarativeAnimationGroupPrivate), parent)
-{
-}
-
-QDeclarativeAnimationGroup::QDeclarativeAnimationGroup(QDeclarativeAnimationGroupPrivate &dd, QObject *parent)
- : QDeclarativeAbstractAnimation(dd, parent)
-{
-}
-
-void QDeclarativeAnimationGroupPrivate::append_animation(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list, QDeclarativeAbstractAnimation *a)
-{
- QDeclarativeAnimationGroup *q = qobject_cast<QDeclarativeAnimationGroup *>(list->object);
- if (q) {
- a->setGroup(q);
- // This is an optimization for the parenting that already occurs via addAnimation
- QDeclarative_setParent_noEvent(a->qtAnimation(), q->d_func()->ag);
- q->d_func()->ag->addAnimation(a->qtAnimation());
- }
-}
-
-void QDeclarativeAnimationGroupPrivate::clear_animation(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list)
-{
- QDeclarativeAnimationGroup *q = qobject_cast<QDeclarativeAnimationGroup *>(list->object);
- if (q) {
- while (q->d_func()->animations.count()) {
- QDeclarativeAbstractAnimation *firstAnim = q->d_func()->animations.at(0);
- QDeclarative_setParent_noEvent(firstAnim->qtAnimation(), 0);
- q->d_func()->ag->removeAnimation(firstAnim->qtAnimation());
- firstAnim->setGroup(0);
- }
- }
-}
-
-QDeclarativeAnimationGroup::~QDeclarativeAnimationGroup()
-{
-}
-
-QDeclarativeListProperty<QDeclarativeAbstractAnimation> QDeclarativeAnimationGroup::animations()
-{
- Q_D(QDeclarativeAnimationGroup);
- QDeclarativeListProperty<QDeclarativeAbstractAnimation> list(this, d->animations);
- list.append = &QDeclarativeAnimationGroupPrivate::append_animation;
- list.clear = &QDeclarativeAnimationGroupPrivate::clear_animation;
- return list;
-}
-
-/*!
- \qmlclass SequentialAnimation QDeclarativeSequentialAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits Animation
- \brief The SequentialAnimation element allows animations to be run sequentially.
-
- The SequentialAnimation and ParallelAnimation elements allow multiple
- animations to be run together. Animations defined in a SequentialAnimation
- are run one after the other, while animations defined in a ParallelAnimation
- are run at the same time.
-
- The following example runs two number animations in a sequence. The \l Rectangle
- animates to a \c x position of 50, then to a \c y position of 50.
-
- \snippet doc/src/snippets/declarative/sequentialanimation.qml 0
-
- Animations defined within a \l Transition are automatically run in parallel,
- so SequentialAnimation can be used to enclose the animations in a \l Transition
- if this is the preferred behavior.
-
- Like any other animation element, a SequentialAnimation can be applied in a
- number of ways, including transitions, behaviors and property value
- sources. The \l {QML Animation and Transitions} documentation shows a
- variety of methods for creating animations.
-
- \note Once an animation has been grouped into a SequentialAnimation or
- ParallelAnimation, it cannot be individually started and stopped; the
- SequentialAnimation or ParallelAnimation must be started and stopped as a group.
-
- \sa ParallelAnimation, {QML Animation and Transitions}, {declarative/animation/basics}{Animation basics example}
-*/
-
-QDeclarativeSequentialAnimation::QDeclarativeSequentialAnimation(QObject *parent) :
- QDeclarativeAnimationGroup(parent)
-{
- Q_D(QDeclarativeAnimationGroup);
- d->ag = new QSequentialAnimationGroup;
- QDeclarative_setParent_noEvent(d->ag, this);
-}
-
-QDeclarativeSequentialAnimation::~QDeclarativeSequentialAnimation()
-{
-}
-
-QAbstractAnimation *QDeclarativeSequentialAnimation::qtAnimation()
-{
- Q_D(QDeclarativeAnimationGroup);
- return d->ag;
-}
-
-void QDeclarativeSequentialAnimation::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_D(QDeclarativeAnimationGroup);
-
- int inc = 1;
- int from = 0;
- if (direction == Backward) {
- inc = -1;
- from = d->animations.count() - 1;
- }
-
- bool valid = d->defaultProperty.isValid();
- for (int ii = from; ii < d->animations.count() && ii >= 0; ii += inc) {
- if (valid)
- d->animations.at(ii)->setDefaultTarget(d->defaultProperty);
- d->animations.at(ii)->transition(actions, modified, direction);
- }
-}
-
-
-
-/*!
- \qmlclass ParallelAnimation QDeclarativeParallelAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits Animation
- \brief The ParallelAnimation element allows animations to be run in parallel.
-
- The SequentialAnimation and ParallelAnimation elements allow multiple
- animations to be run together. Animations defined in a SequentialAnimation
- are run one after the other, while animations defined in a ParallelAnimation
- are run at the same time.
-
- The following animation runs two number animations in parallel. The \l Rectangle
- moves to (50,50) by animating its \c x and \c y properties at the same time.
-
- \snippet doc/src/snippets/declarative/parallelanimation.qml 0
-
- Like any other animation element, a ParallelAnimation can be applied in a
- number of ways, including transitions, behaviors and property value
- sources. The \l {QML Animation and Transitions} documentation shows a
- variety of methods for creating animations.
-
- \note Once an animation has been grouped into a SequentialAnimation or
- ParallelAnimation, it cannot be individually started and stopped; the
- SequentialAnimation or ParallelAnimation must be started and stopped as a group.
-
- \sa SequentialAnimation, {QML Animation and Transitions}, {declarative/animation/basics}{Animation basics example}
-*/
-QDeclarativeParallelAnimation::QDeclarativeParallelAnimation(QObject *parent) :
- QDeclarativeAnimationGroup(parent)
-{
- Q_D(QDeclarativeAnimationGroup);
- d->ag = new QParallelAnimationGroup;
- QDeclarative_setParent_noEvent(d->ag, this);
-}
-
-QDeclarativeParallelAnimation::~QDeclarativeParallelAnimation()
-{
-}
-
-QAbstractAnimation *QDeclarativeParallelAnimation::qtAnimation()
-{
- Q_D(QDeclarativeAnimationGroup);
- return d->ag;
-}
-
-void QDeclarativeParallelAnimation::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_D(QDeclarativeAnimationGroup);
- bool valid = d->defaultProperty.isValid();
- for (int ii = 0; ii < d->animations.count(); ++ii) {
- if (valid)
- d->animations.at(ii)->setDefaultTarget(d->defaultProperty);
- d->animations.at(ii)->transition(actions, modified, direction);
- }
-}
-
-
-
-//convert a variant from string type to another animatable type
-void QDeclarativePropertyAnimationPrivate::convertVariant(QVariant &variant, int type)
-{
- if (variant.userType() != QVariant::String) {
- variant.convert((QVariant::Type)type);
- return;
- }
-
- switch (type) {
- case QVariant::Rect: {
- variant.setValue(QDeclarativeStringConverters::rectFFromString(variant.toString()).toRect());
- break;
- }
- case QVariant::RectF: {
- variant.setValue(QDeclarativeStringConverters::rectFFromString(variant.toString()));
- break;
- }
- case QVariant::Point: {
- variant.setValue(QDeclarativeStringConverters::pointFFromString(variant.toString()).toPoint());
- break;
- }
- case QVariant::PointF: {
- variant.setValue(QDeclarativeStringConverters::pointFFromString(variant.toString()));
- break;
- }
- case QVariant::Size: {
- variant.setValue(QDeclarativeStringConverters::sizeFFromString(variant.toString()).toSize());
- break;
- }
- case QVariant::SizeF: {
- variant.setValue(QDeclarativeStringConverters::sizeFFromString(variant.toString()));
- break;
- }
- case QVariant::Color: {
- variant.setValue(QDeclarativeStringConverters::colorFromString(variant.toString()));
- break;
- }
- case QVariant::Vector3D: {
- variant.setValue(QDeclarativeStringConverters::vector3DFromString(variant.toString()));
- break;
- }
- default:
- if (QDeclarativeValueTypeFactory::isValueType((uint)type)) {
- variant.convert((QVariant::Type)type);
- } else {
- QDeclarativeMetaType::StringConverter converter = QDeclarativeMetaType::customStringConverter(type);
- if (converter)
- variant = converter(variant.toString());
- }
- break;
- }
-}
-
-/*!
- \qmlclass PropertyAnimation QDeclarativePropertyAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits Animation
- \brief The PropertyAnimation element animates changes in property values.
-
- PropertyAnimation provides a way to animate changes to a property's value.
-
- It can be used to define animations in a number of ways:
-
- \list
- \o In a \l Transition
-
- For example, to animate any objects that have changed their \c x or \c y properties
- as a result of a state change, using an \c InOutQuad easing curve:
-
- \snippet doc/src/snippets/declarative/propertyanimation.qml transition
-
-
- \o In a \l Behavior
-
- For example, to animate all changes to a rectangle's \c x property:
-
- \snippet doc/src/snippets/declarative/propertyanimation.qml behavior
-
-
- \o As a property value source
-
- For example, to repeatedly animate the rectangle's \c x property:
-
- \snippet doc/src/snippets/declarative/propertyanimation.qml propertyvaluesource
-
-
- \o In a signal handler
-
- For example, to fade out \c theObject when clicked:
- \qml
- MouseArea {
- anchors.fill: theObject
- onClicked: PropertyAnimation { target: theObject; property: "opacity"; to: 0 }
- }
- \endqml
-
- \o Standalone
-
- For example, to animate \c rect's \c width property over 500ms, from its current width to 30:
-
- \snippet doc/src/snippets/declarative/propertyanimation.qml standalone
-
- \endlist
-
- Depending on how the animation is used, the set of properties normally used will be
- different. For more information see the individual property documentation, as well
- as the \l{QML Animation and Transitions} introduction.
-
- Note that PropertyAnimation inherits the abstract \l Animation element.
- This includes additional properties and methods for controlling the animation.
-
- \sa {QML Animation and Transitions}, {declarative/animation/basics}{Animation basics example}
-*/
-
-QDeclarativePropertyAnimation::QDeclarativePropertyAnimation(QObject *parent)
-: QDeclarativeAbstractAnimation(*(new QDeclarativePropertyAnimationPrivate), parent)
-{
- Q_D(QDeclarativePropertyAnimation);
- d->init();
-}
-
-QDeclarativePropertyAnimation::QDeclarativePropertyAnimation(QDeclarativePropertyAnimationPrivate &dd, QObject *parent)
-: QDeclarativeAbstractAnimation(dd, parent)
-{
- Q_D(QDeclarativePropertyAnimation);
- d->init();
-}
-
-QDeclarativePropertyAnimation::~QDeclarativePropertyAnimation()
-{
-}
-
-void QDeclarativePropertyAnimationPrivate::init()
-{
- Q_Q(QDeclarativePropertyAnimation);
- va = new QDeclarativeBulkValueAnimator;
- QDeclarative_setParent_noEvent(va, q);
-}
-
-/*!
- \qmlproperty int QtQuick2::PropertyAnimation::duration
- This property holds the duration of the animation, in milliseconds.
-
- The default value is 250.
-*/
-int QDeclarativePropertyAnimation::duration() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->va->duration();
-}
-
-void QDeclarativePropertyAnimation::setDuration(int duration)
-{
- if (duration < 0) {
- qmlInfo(this) << tr("Cannot set a duration of < 0");
- return;
- }
-
- Q_D(QDeclarativePropertyAnimation);
- if (d->va->duration() == duration)
- return;
- d->va->setDuration(duration);
- emit durationChanged(duration);
-}
-
-/*!
- \qmlproperty real QtQuick2::PropertyAnimation::from
- This property holds the starting value for the animation.
-
- If the PropertyAnimation is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the starting state of the
- \l Transition, or the current value of the property at the moment the
- \l Behavior is triggered.
-
- \sa {QML Animation and Transitions}
-*/
-QVariant QDeclarativePropertyAnimation::from() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->from;
-}
-
-void QDeclarativePropertyAnimation::setFrom(const QVariant &f)
-{
- Q_D(QDeclarativePropertyAnimation);
- if (d->fromIsDefined && f == d->from)
- return;
- d->from = f;
- d->fromIsDefined = f.isValid();
- emit fromChanged(f);
-}
-
-/*!
- \qmlproperty real QtQuick2::PropertyAnimation::to
- This property holds the end value for the animation.
-
- If the PropertyAnimation is defined within a \l Transition or \l Behavior,
- this value defaults to the value defined in the end state of the
- \l Transition, or the value of the property change that triggered the
- \l Behavior.
-
- \sa {QML Animation and Transitions}
-*/
-QVariant QDeclarativePropertyAnimation::to() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->to;
-}
-
-void QDeclarativePropertyAnimation::setTo(const QVariant &t)
-{
- Q_D(QDeclarativePropertyAnimation);
- if (d->toIsDefined && t == d->to)
- return;
- d->to = t;
- d->toIsDefined = t.isValid();
- emit toChanged(t);
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::PropertyAnimation::easing.type
- \qmlproperty real QtQuick2::PropertyAnimation::easing.amplitude
- \qmlproperty real QtQuick2::PropertyAnimation::easing.overshoot
- \qmlproperty real QtQuick2::PropertyAnimation::easing.period
- \brief the easing curve used for the animation.
-
- To specify an easing curve you need to specify at least the type. For some curves you can also specify
- amplitude, period and/or overshoot (more details provided after the table). The default easing curve is
- \c Easing.Linear.
-
- \qml
- PropertyAnimation { properties: "y"; easing.type: Easing.InOutElastic; easing.amplitude: 2.0; easing.period: 1.5 }
- \endqml
-
- Available types are:
-
- \table
- \row
- \o \c Easing.Linear
- \o Easing curve for a linear (t) function: velocity is constant.
- \o \inlineimage qeasingcurve-linear.png
- \row
- \o \c Easing.InQuad
- \o Easing curve for a quadratic (t^2) function: accelerating from zero velocity.
- \o \inlineimage qeasingcurve-inquad.png
- \row
- \o \c Easing.OutQuad
- \o Easing curve for a quadratic (t^2) function: decelerating to zero velocity.
- \o \inlineimage qeasingcurve-outquad.png
- \row
- \o \c Easing.InOutQuad
- \o Easing curve for a quadratic (t^2) function: acceleration until halfway, then deceleration.
- \o \inlineimage qeasingcurve-inoutquad.png
- \row
- \o \c Easing.OutInQuad
- \o Easing curve for a quadratic (t^2) function: deceleration until halfway, then acceleration.
- \o \inlineimage qeasingcurve-outinquad.png
- \row
- \o \c Easing.InCubic
- \o Easing curve for a cubic (t^3) function: accelerating from zero velocity.
- \o \inlineimage qeasingcurve-incubic.png
- \row
- \o \c Easing.OutCubic
- \o Easing curve for a cubic (t^3) function: decelerating from zero velocity.
- \o \inlineimage qeasingcurve-outcubic.png
- \row
- \o \c Easing.InOutCubic
- \o Easing curve for a cubic (t^3) function: acceleration until halfway, then deceleration.
- \o \inlineimage qeasingcurve-inoutcubic.png
- \row
- \o \c Easing.OutInCubic
- \o Easing curve for a cubic (t^3) function: deceleration until halfway, then acceleration.
- \o \inlineimage qeasingcurve-outincubic.png
- \row
- \o \c Easing.InQuart
- \o Easing curve for a quartic (t^4) function: accelerating from zero velocity.
- \o \inlineimage qeasingcurve-inquart.png
- \row
- \o \c Easing.OutQuart
- \o Easing curve for a quartic (t^4) function: decelerating from zero velocity.
- \o \inlineimage qeasingcurve-outquart.png
- \row
- \o \c Easing.InOutQuart
- \o Easing curve for a quartic (t^4) function: acceleration until halfway, then deceleration.
- \o \inlineimage qeasingcurve-inoutquart.png
- \row
- \o \c Easing.OutInQuart
- \o Easing curve for a quartic (t^4) function: deceleration until halfway, then acceleration.
- \o \inlineimage qeasingcurve-outinquart.png
- \row
- \o \c Easing.InQuint
- \o Easing curve for a quintic (t^5) function: accelerating from zero velocity.
- \o \inlineimage qeasingcurve-inquint.png
- \row
- \o \c Easing.OutQuint
- \o Easing curve for a quintic (t^5) function: decelerating from zero velocity.
- \o \inlineimage qeasingcurve-outquint.png
- \row
- \o \c Easing.InOutQuint
- \o Easing curve for a quintic (t^5) function: acceleration until halfway, then deceleration.
- \o \inlineimage qeasingcurve-inoutquint.png
- \row
- \o \c Easing.OutInQuint
- \o Easing curve for a quintic (t^5) function: deceleration until halfway, then acceleration.
- \o \inlineimage qeasingcurve-outinquint.png
- \row
- \o \c Easing.InSine
- \o Easing curve for a sinusoidal (sin(t)) function: accelerating from zero velocity.
- \o \inlineimage qeasingcurve-insine.png
- \row
- \o \c Easing.OutSine
- \o Easing curve for a sinusoidal (sin(t)) function: decelerating from zero velocity.
- \o \inlineimage qeasingcurve-outsine.png
- \row
- \o \c Easing.InOutSine
- \o Easing curve for a sinusoidal (sin(t)) function: acceleration until halfway, then deceleration.
- \o \inlineimage qeasingcurve-inoutsine.png
- \row
- \o \c Easing.OutInSine
- \o Easing curve for a sinusoidal (sin(t)) function: deceleration until halfway, then acceleration.
- \o \inlineimage qeasingcurve-outinsine.png
- \row
- \o \c Easing.InExpo
- \o Easing curve for an exponential (2^t) function: accelerating from zero velocity.
- \o \inlineimage qeasingcurve-inexpo.png
- \row
- \o \c Easing.OutExpo
- \o Easing curve for an exponential (2^t) function: decelerating from zero velocity.
- \o \inlineimage qeasingcurve-outexpo.png
- \row
- \o \c Easing.InOutExpo
- \o Easing curve for an exponential (2^t) function: acceleration until halfway, then deceleration.
- \o \inlineimage qeasingcurve-inoutexpo.png
- \row
- \o \c Easing.OutInExpo
- \o Easing curve for an exponential (2^t) function: deceleration until halfway, then acceleration.
- \o \inlineimage qeasingcurve-outinexpo.png
- \row
- \o \c Easing.InCirc
- \o Easing curve for a circular (sqrt(1-t^2)) function: accelerating from zero velocity.
- \o \inlineimage qeasingcurve-incirc.png
- \row
- \o \c Easing.OutCirc
- \o Easing curve for a circular (sqrt(1-t^2)) function: decelerating from zero velocity.
- \o \inlineimage qeasingcurve-outcirc.png
- \row
- \o \c Easing.InOutCirc
- \o Easing curve for a circular (sqrt(1-t^2)) function: acceleration until halfway, then deceleration.
- \o \inlineimage qeasingcurve-inoutcirc.png
- \row
- \o \c Easing.OutInCirc
- \o Easing curve for a circular (sqrt(1-t^2)) function: deceleration until halfway, then acceleration.
- \o \inlineimage qeasingcurve-outincirc.png
- \row
- \o \c Easing.InElastic
- \o Easing curve for an elastic (exponentially decaying sine wave) function: accelerating from zero velocity.
- \br The peak amplitude can be set with the \e amplitude parameter, and the period of decay by the \e period parameter.
- \o \inlineimage qeasingcurve-inelastic.png
- \row
- \o \c Easing.OutElastic
- \o Easing curve for an elastic (exponentially decaying sine wave) function: decelerating from zero velocity.
- \br The peak amplitude can be set with the \e amplitude parameter, and the period of decay by the \e period parameter.
- \o \inlineimage qeasingcurve-outelastic.png
- \row
- \o \c Easing.InOutElastic
- \o Easing curve for an elastic (exponentially decaying sine wave) function: acceleration until halfway, then deceleration.
- \o \inlineimage qeasingcurve-inoutelastic.png
- \row
- \o \c Easing.OutInElastic
- \o Easing curve for an elastic (exponentially decaying sine wave) function: deceleration until halfway, then acceleration.
- \o \inlineimage qeasingcurve-outinelastic.png
- \row
- \o \c Easing.InBack
- \o Easing curve for a back (overshooting cubic function: (s+1)*t^3 - s*t^2) easing in: accelerating from zero velocity.
- \o \inlineimage qeasingcurve-inback.png
- \row
- \o \c Easing.OutBack
- \o Easing curve for a back (overshooting cubic function: (s+1)*t^3 - s*t^2) easing out: decelerating to zero velocity.
- \o \inlineimage qeasingcurve-outback.png
- \row
- \o \c Easing.InOutBack
- \o Easing curve for a back (overshooting cubic function: (s+1)*t^3 - s*t^2) easing in/out: acceleration until halfway, then deceleration.
- \o \inlineimage qeasingcurve-inoutback.png
- \row
- \o \c Easing.OutInBack
- \o Easing curve for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out/in: deceleration until halfway, then acceleration.
- \o \inlineimage qeasingcurve-outinback.png
- \row
- \o \c Easing.InBounce
- \o Easing curve for a bounce (exponentially decaying parabolic bounce) function: accelerating from zero velocity.
- \o \inlineimage qeasingcurve-inbounce.png
- \row
- \o \c Easing.OutBounce
- \o Easing curve for a bounce (exponentially decaying parabolic bounce) function: decelerating from zero velocity.
- \o \inlineimage qeasingcurve-outbounce.png
- \row
- \o \c Easing.InOutBounce
- \o Easing curve for a bounce (exponentially decaying parabolic bounce) function easing in/out: acceleration until halfway, then deceleration.
- \o \inlineimage qeasingcurve-inoutbounce.png
- \row
- \o \c Easing.OutInBounce
- \o Easing curve for a bounce (exponentially decaying parabolic bounce) function easing out/in: deceleration until halfway, then acceleration.
- \o \inlineimage qeasingcurve-outinbounce.png
- \endtable
-
- \c easing.amplitude is only applicable for bounce and elastic curves (curves of type
- \c Easing.InBounce, \c Easing.OutBounce, \c Easing.InOutBounce, \c Easing.OutInBounce, \c Easing.InElastic,
- \c Easing.OutElastic, \c Easing.InOutElastic or \c Easing.OutInElastic).
-
- \c easing.overshoot is only applicable if \c easing.type is: \c Easing.InBack, \c Easing.OutBack,
- \c Easing.InOutBack or \c Easing.OutInBack.
-
- \c easing.period is only applicable if easing.type is: \c Easing.InElastic, \c Easing.OutElastic,
- \c Easing.InOutElastic or \c Easing.OutInElastic.
-
- See the \l {declarative/animation/easing}{easing} example for a demonstration of
- the different easing settings.
-*/
-QEasingCurve QDeclarativePropertyAnimation::easing() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->va->easingCurve();
-}
-
-void QDeclarativePropertyAnimation::setEasing(const QEasingCurve &e)
-{
- Q_D(QDeclarativePropertyAnimation);
- if (d->va->easingCurve() == e)
- return;
-
- d->va->setEasingCurve(e);
- emit easingChanged(e);
-}
-
-QObject *QDeclarativePropertyAnimation::target() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->target;
-}
-
-void QDeclarativePropertyAnimation::setTarget(QObject *o)
-{
- Q_D(QDeclarativePropertyAnimation);
- if (d->target == o)
- return;
- d->target = o;
- emit targetChanged();
-}
-
-QString QDeclarativePropertyAnimation::property() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->propertyName;
-}
-
-void QDeclarativePropertyAnimation::setProperty(const QString &n)
-{
- Q_D(QDeclarativePropertyAnimation);
- if (d->propertyName == n)
- return;
- d->propertyName = n;
- emit propertyChanged();
-}
-
-QString QDeclarativePropertyAnimation::properties() const
-{
- Q_D(const QDeclarativePropertyAnimation);
- return d->properties;
-}
-
-void QDeclarativePropertyAnimation::setProperties(const QString &prop)
-{
- Q_D(QDeclarativePropertyAnimation);
- if (d->properties == prop)
- return;
-
- d->properties = prop;
- emit propertiesChanged(prop);
-}
-
-/*!
- \qmlproperty string QtQuick2::PropertyAnimation::properties
- \qmlproperty list<Object> QtQuick2::PropertyAnimation::targets
- \qmlproperty string QtQuick2::PropertyAnimation::property
- \qmlproperty Object QtQuick2::PropertyAnimation::target
-
- These properties are used as a set to determine which properties should be animated.
- The singular and plural forms are functionally identical, e.g.
- \qml
- NumberAnimation { target: theItem; property: "x"; to: 500 }
- \endqml
- has the same meaning as
- \qml
- NumberAnimation { targets: theItem; properties: "x"; to: 500 }
- \endqml
- The singular forms are slightly optimized, so if you do have only a single target/property
- to animate you should try to use them.
-
- The \c targets property allows multiple targets to be set. For example, this animates the
- \c x property of both \c itemA and \c itemB:
-
- \qml
- NumberAnimation { targets: [itemA, itemB]; properties: "x"; to: 500 }
- \endqml
-
- In many cases these properties do not need to be explicitly specified, as they can be
- inferred from the animation framework:
-
- \table 80%
- \row
- \o Value Source / Behavior
- \o When an animation is used as a value source or in a Behavior, the default target and property
- name to be animated can both be inferred.
- \qml
- Rectangle {
- id: theRect
- width: 100; height: 100
- color: Qt.rgba(0,0,1)
- NumberAnimation on x { to: 500; loops: Animation.Infinite } //animate theRect's x property
- Behavior on y { NumberAnimation {} } //animate theRect's y property
- }
- \endqml
- \row
- \o Transition
- \o When used in a transition, a property animation is assumed to match \e all targets
- but \e no properties. In practice, that means you need to specify at least the properties
- in order for the animation to do anything.
- \qml
- Rectangle {
- id: theRect
- width: 100; height: 100
- color: Qt.rgba(0,0,1)
- Item { id: uselessItem }
- states: State {
- name: "state1"
- PropertyChanges { target: theRect; x: 200; y: 200; z: 4 }
- PropertyChanges { target: uselessItem; x: 10; y: 10; z: 2 }
- }
- transitions: Transition {
- //animate both theRect's and uselessItem's x and y to their final values
- NumberAnimation { properties: "x,y" }
-
- //animate theRect's z to its final value
- NumberAnimation { target: theRect; property: "z" }
- }
- }
- \endqml
- \row
- \o Standalone
- \o When an animation is used standalone, both the target and property need to be
- explicitly specified.
- \qml
- Rectangle {
- id: theRect
- width: 100; height: 100
- color: Qt.rgba(0,0,1)
- //need to explicitly specify target and property
- NumberAnimation { id: theAnim; target: theRect; property: "x"; to: 500 }
- MouseArea {
- anchors.fill: parent
- onClicked: theAnim.start()
- }
- }
- \endqml
- \endtable
-
- As seen in the above example, properties is specified as a comma-separated string of property names to animate.
-
- \sa exclude, {QML Animation and Transitions}
-*/
-QDeclarativeListProperty<QObject> QDeclarativePropertyAnimation::targets()
-{
- Q_D(QDeclarativePropertyAnimation);
- return QDeclarativeListProperty<QObject>(this, d->targets);
-}
-
-/*!
- \qmlproperty list<Object> QtQuick2::PropertyAnimation::exclude
- This property holds the items not to be affected by this animation.
- \sa PropertyAnimation::targets
-*/
-QDeclarativeListProperty<QObject> QDeclarativePropertyAnimation::exclude()
-{
- Q_D(QDeclarativePropertyAnimation);
- return QDeclarativeListProperty<QObject>(this, d->exclude);
-}
-
-QAbstractAnimation *QDeclarativePropertyAnimation::qtAnimation()
-{
- Q_D(QDeclarativePropertyAnimation);
- return d->va;
-}
-
-void QDeclarativeAnimationPropertyUpdater::setValue(qreal v)
-{
- bool deleted = false;
- wasDeleted = &deleted;
- if (reverse) //QVariantAnimation sends us 1->0 when reversed, but we are expecting 0->1
- v = 1 - v;
- for (int ii = 0; ii < actions.count(); ++ii) {
- QDeclarativeAction &action = actions[ii];
-
- if (v == 1.)
- QDeclarativePropertyPrivate::write(action.property, action.toValue, QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
- else {
- if (!fromSourced && !fromDefined) {
- action.fromValue = action.property.read();
- if (interpolatorType)
- QDeclarativePropertyAnimationPrivate::convertVariant(action.fromValue, interpolatorType);
- }
- if (!interpolatorType) {
- int propType = action.property.propertyType();
- if (!prevInterpolatorType || prevInterpolatorType != propType) {
- prevInterpolatorType = propType;
- interpolator = QVariantAnimationPrivate::getInterpolator(prevInterpolatorType);
- }
- }
- if (interpolator)
- QDeclarativePropertyPrivate::write(action.property, interpolator(action.fromValue.constData(), action.toValue.constData(), v), QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
- }
- if (deleted)
- return;
- }
- wasDeleted = 0;
- fromSourced = true;
-}
-
-void QDeclarativePropertyAnimation::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_D(QDeclarativePropertyAnimation);
-
- 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 << d->propertyName;
-
- QList<QObject*> targets = d->targets;
- if (d->target)
- targets.append(d->target);
-
- bool hasSelectors = !props.isEmpty() || !targets.isEmpty() || !d->exclude.isEmpty();
- bool useType = (props.isEmpty() && d->defaultToInterpolatorType) ? true : false;
-
- if (d->defaultProperty.isValid() && !hasSelectors) {
- props << d->defaultProperty.name();
- targets << d->defaultProperty.object();
- }
-
- if (props.isEmpty() && !d->defaultProperties.isEmpty()) {
- props << d->defaultProperties.split(QLatin1Char(','));
- }
-
- QDeclarativeAnimationPropertyUpdater *data = new QDeclarativeAnimationPropertyUpdater;
- data->interpolatorType = d->interpolatorType;
- data->interpolator = d->interpolator;
- data->reverse = direction == Backward ? true : false;
- data->fromSourced = false;
- data->fromDefined = d->fromIsDefined;
-
- bool hasExplicit = false;
- //an explicit animation has been specified
- if (d->toIsDefined) {
- for (int i = 0; i < props.count(); ++i) {
- for (int j = 0; j < targets.count(); ++j) {
- QDeclarativeAction myAction;
- myAction.property = d->createProperty(targets.at(j), props.at(i), this);
- if (myAction.property.isValid()) {
- if (d->fromIsDefined) {
- myAction.fromValue = d->from;
- d->convertVariant(myAction.fromValue, d->interpolatorType ? d->interpolatorType : myAction.property.propertyType());
- }
- myAction.toValue = d->to;
- d->convertVariant(myAction.toValue, d->interpolatorType ? d->interpolatorType : myAction.property.propertyType());
- data->actions << myAction;
- hasExplicit = true;
- for (int ii = 0; ii < actions.count(); ++ii) {
- QDeclarativeAction &action = actions[ii];
- if (action.property.object() == myAction.property.object() &&
- myAction.property.name() == action.property.name()) {
- modified << action.property;
- break; //### any chance there could be multiples?
- }
- }
- }
- }
- }
- }
-
- if (!hasExplicit)
- for (int ii = 0; ii < actions.count(); ++ii) {
- QDeclarativeAction &action = actions[ii];
-
- QObject *obj = action.property.object();
- QString propertyName = action.property.name();
- QObject *sObj = action.specifiedObject;
- QString sPropertyName = action.specifiedProperty;
- bool same = (obj == sObj);
-
- if ((targets.isEmpty() || targets.contains(obj) || (!same && targets.contains(sObj))) &&
- (!d->exclude.contains(obj)) && (same || (!d->exclude.contains(sObj))) &&
- (props.contains(propertyName) || (!same && props.contains(sPropertyName))
- || (useType && action.property.propertyType() == d->interpolatorType))) {
- QDeclarativeAction myAction = action;
-
- if (d->fromIsDefined)
- myAction.fromValue = d->from;
- else
- myAction.fromValue = QVariant();
- if (d->toIsDefined)
- myAction.toValue = d->to;
-
- d->convertVariant(myAction.fromValue, d->interpolatorType ? d->interpolatorType : myAction.property.propertyType());
- d->convertVariant(myAction.toValue, d->interpolatorType ? d->interpolatorType : myAction.property.propertyType());
-
- modified << action.property;
-
- data->actions << myAction;
- action.fromValue = myAction.toValue;
- }
- }
-
- if (data->actions.count()) {
- if (!d->rangeIsSet) {
- d->va->setStartValue(qreal(0));
- d->va->setEndValue(qreal(1));
- d->rangeIsSet = true;
- }
- d->va->setAnimValue(data, QAbstractAnimation::DeleteWhenStopped);
- d->va->setFromSourcedValue(&data->fromSourced);
- d->actions = &data->actions;
- } else {
- delete data;
- d->va->setFromSourcedValue(0); //clear previous data
- d->va->setAnimValue(0, QAbstractAnimation::DeleteWhenStopped); //clear previous data
- d->actions = 0;
- }
-}
-
-
-QDeclarativeScriptActionPrivate::QDeclarativeScriptActionPrivate()
- : QDeclarativeAbstractAnimationPrivate(), hasRunScriptScript(false), reversing(false), proxy(this), rsa(0) {}
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativeanimation_p.h b/src/declarative/util/qdeclarativeanimation_p.h
deleted file mode 100644
index c84af5a53e..0000000000
--- a/src/declarative/util/qdeclarativeanimation_p.h
+++ /dev/null
@@ -1,458 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEANIMATION_H
-#define QDECLARATIVEANIMATION_H
-
-#include "qdeclarativestate_p.h"
-#include <QtGui/qvector3d.h>
-
-#include <qdeclarativepropertyvaluesource.h>
-#include <qdeclarative.h>
-#include <qdeclarativescriptstring.h>
-
-#include <QtCore/qvariant.h>
-#include <QtCore/qeasingcurve.h>
-#include <QtCore/QAbstractAnimation>
-#include <QtGui/qcolor.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeAbstractAnimationPrivate;
-class QDeclarativeAnimationGroup;
-class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativeAbstractAnimation : public QObject, public QDeclarativePropertyValueSource, public QDeclarativeParserStatus
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeAbstractAnimation)
-
- Q_INTERFACES(QDeclarativeParserStatus)
- Q_INTERFACES(QDeclarativePropertyValueSource)
- Q_ENUMS(Loops)
- Q_PROPERTY(bool running READ isRunning WRITE setRunning NOTIFY runningChanged)
- Q_PROPERTY(bool paused READ isPaused WRITE setPaused NOTIFY pausedChanged)
- Q_PROPERTY(bool alwaysRunToEnd READ alwaysRunToEnd WRITE setAlwaysRunToEnd NOTIFY alwaysRunToEndChanged)
- Q_PROPERTY(int loops READ loops WRITE setLoops NOTIFY loopCountChanged)
- Q_CLASSINFO("DefaultMethod", "start()")
-
-public:
- QDeclarativeAbstractAnimation(QObject *parent=0);
- virtual ~QDeclarativeAbstractAnimation();
-
- enum Loops { Infinite = -2 };
-
- bool isRunning() const;
- void setRunning(bool);
- bool isPaused() const;
- void setPaused(bool);
- bool alwaysRunToEnd() const;
- void setAlwaysRunToEnd(bool);
-
- int loops() const;
- void setLoops(int);
-
- int currentTime();
- void setCurrentTime(int);
-
- QDeclarativeAnimationGroup *group() const;
- void setGroup(QDeclarativeAnimationGroup *);
-
- void setDefaultTarget(const QDeclarativeProperty &);
- void setDisableUserControl();
-
- void classBegin();
- void componentComplete();
-
-Q_SIGNALS:
- void started();
- void completed();
- void runningChanged(bool);
- void pausedChanged(bool);
- void alwaysRunToEndChanged(bool);
- void loopCountChanged(int);
-
-public Q_SLOTS:
- void restart();
- void start();
- void pause();
- void resume();
- void stop();
- void complete();
-
-protected:
- QDeclarativeAbstractAnimation(QDeclarativeAbstractAnimationPrivate &dd, QObject *parent);
-
-public:
- enum TransitionDirection { Forward, Backward };
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
- virtual QAbstractAnimation *qtAnimation() = 0;
-
-private Q_SLOTS:
- void timelineComplete();
- void componentFinalized();
-private:
- virtual void setTarget(const QDeclarativeProperty &);
- void notifyRunningChanged(bool running);
- friend class QDeclarativeBehavior;
-
-
-};
-
-class QDeclarativePauseAnimationPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativePauseAnimation : public QDeclarativeAbstractAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativePauseAnimation)
-
- Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged)
-
-public:
- QDeclarativePauseAnimation(QObject *parent=0);
- virtual ~QDeclarativePauseAnimation();
-
- int duration() const;
- void setDuration(int);
-
-Q_SIGNALS:
- void durationChanged(int);
-
-protected:
- virtual QAbstractAnimation *qtAnimation();
-};
-
-class QDeclarativeScriptActionPrivate;
-class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativeScriptAction : public QDeclarativeAbstractAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeScriptAction)
-
- Q_PROPERTY(QDeclarativeScriptString script READ script WRITE setScript)
- Q_PROPERTY(QString scriptName READ stateChangeScriptName WRITE setStateChangeScriptName)
-
-public:
- QDeclarativeScriptAction(QObject *parent=0);
- virtual ~QDeclarativeScriptAction();
-
- QDeclarativeScriptString script() const;
- void setScript(const QDeclarativeScriptString &);
-
- QString stateChangeScriptName() const;
- void setStateChangeScriptName(const QString &);
-
-protected:
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
- virtual QAbstractAnimation *qtAnimation();
-};
-
-class QDeclarativePropertyActionPrivate;
-class QDeclarativePropertyAction : public QDeclarativeAbstractAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativePropertyAction)
-
- Q_PROPERTY(QObject *target READ target WRITE setTarget NOTIFY targetChanged)
- Q_PROPERTY(QString property READ property WRITE setProperty NOTIFY propertyChanged)
- Q_PROPERTY(QString properties READ properties WRITE setProperties NOTIFY propertiesChanged)
- Q_PROPERTY(QDeclarativeListProperty<QObject> targets READ targets)
- Q_PROPERTY(QDeclarativeListProperty<QObject> exclude READ exclude)
- Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged)
-
-public:
- QDeclarativePropertyAction(QObject *parent=0);
- virtual ~QDeclarativePropertyAction();
-
- QObject *target() const;
- void setTarget(QObject *);
-
- QString property() const;
- void setProperty(const QString &);
-
- QString properties() const;
- void setProperties(const QString &);
-
- QDeclarativeListProperty<QObject> targets();
- QDeclarativeListProperty<QObject> exclude();
-
- QVariant value() const;
- void setValue(const QVariant &);
-
-Q_SIGNALS:
- void valueChanged(const QVariant &);
- void propertiesChanged(const QString &);
- void targetChanged();
- void propertyChanged();
-
-protected:
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
- virtual QAbstractAnimation *qtAnimation();
-};
-
-class QDeclarativePropertyAnimationPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativePropertyAnimation : public QDeclarativeAbstractAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativePropertyAnimation)
-
- 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(QEasingCurve easing READ easing WRITE setEasing NOTIFY easingChanged)
- Q_PROPERTY(QObject *target READ target WRITE setTarget NOTIFY targetChanged)
- Q_PROPERTY(QString property READ property WRITE setProperty NOTIFY propertyChanged)
- Q_PROPERTY(QString properties READ properties WRITE setProperties NOTIFY propertiesChanged)
- Q_PROPERTY(QDeclarativeListProperty<QObject> targets READ targets)
- Q_PROPERTY(QDeclarativeListProperty<QObject> exclude READ exclude)
-
-public:
- QDeclarativePropertyAnimation(QObject *parent=0);
- virtual ~QDeclarativePropertyAnimation();
-
- virtual int duration() const;
- virtual void setDuration(int);
-
- QVariant from() const;
- void setFrom(const QVariant &);
-
- QVariant to() const;
- void setTo(const QVariant &);
-
- QEasingCurve easing() const;
- void setEasing(const QEasingCurve &);
-
- QObject *target() const;
- void setTarget(QObject *);
-
- QString property() const;
- void setProperty(const QString &);
-
- QString properties() const;
- void setProperties(const QString &);
-
- QDeclarativeListProperty<QObject> targets();
- QDeclarativeListProperty<QObject> exclude();
-
-protected:
- QDeclarativePropertyAnimation(QDeclarativePropertyAnimationPrivate &dd, QObject *parent);
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
- virtual QAbstractAnimation *qtAnimation();
-
-Q_SIGNALS:
- void durationChanged(int);
- void fromChanged(QVariant);
- void toChanged(QVariant);
- void easingChanged(const QEasingCurve &);
- void propertiesChanged(const QString &);
- void targetChanged();
- void propertyChanged();
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativeColorAnimation : public QDeclarativePropertyAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativePropertyAnimation)
- Q_PROPERTY(QColor from READ from WRITE setFrom)
- Q_PROPERTY(QColor to READ to WRITE setTo)
-
-public:
- QDeclarativeColorAnimation(QObject *parent=0);
- virtual ~QDeclarativeColorAnimation();
-
- QColor from() const;
- void setFrom(const QColor &);
-
- QColor to() const;
- void setTo(const QColor &);
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativeNumberAnimation : public QDeclarativePropertyAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativePropertyAnimation)
-
- Q_PROPERTY(qreal from READ from WRITE setFrom)
- Q_PROPERTY(qreal to READ to WRITE setTo)
-
-public:
- QDeclarativeNumberAnimation(QObject *parent=0);
- virtual ~QDeclarativeNumberAnimation();
-
- qreal from() const;
- void setFrom(qreal);
-
- qreal to() const;
- void setTo(qreal);
-
-protected:
- QDeclarativeNumberAnimation(QDeclarativePropertyAnimationPrivate &dd, QObject *parent);
-
-private:
- void init();
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativeVector3dAnimation : public QDeclarativePropertyAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativePropertyAnimation)
-
- Q_PROPERTY(QVector3D from READ from WRITE setFrom)
- Q_PROPERTY(QVector3D to READ to WRITE setTo)
-
-public:
- QDeclarativeVector3dAnimation(QObject *parent=0);
- virtual ~QDeclarativeVector3dAnimation();
-
- QVector3D from() const;
- void setFrom(QVector3D);
-
- QVector3D to() const;
- void setTo(QVector3D);
-};
-
-class QDeclarativeRotationAnimationPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativeRotationAnimation : public QDeclarativePropertyAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeRotationAnimation)
- Q_ENUMS(RotationDirection)
-
- Q_PROPERTY(qreal from READ from WRITE setFrom)
- Q_PROPERTY(qreal to READ to WRITE setTo)
- Q_PROPERTY(RotationDirection direction READ direction WRITE setDirection NOTIFY directionChanged)
-
-public:
- QDeclarativeRotationAnimation(QObject *parent=0);
- virtual ~QDeclarativeRotationAnimation();
-
- qreal from() const;
- void setFrom(qreal);
-
- qreal to() const;
- void setTo(qreal);
-
- enum RotationDirection { Numerical, Shortest, Clockwise, Counterclockwise };
- RotationDirection direction() const;
- void setDirection(RotationDirection direction);
-
-Q_SIGNALS:
- void directionChanged();
-};
-
-class QDeclarativeAnimationGroupPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativeAnimationGroup : public QDeclarativeAbstractAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeAnimationGroup)
-
- Q_CLASSINFO("DefaultProperty", "animations")
- Q_PROPERTY(QDeclarativeListProperty<QDeclarativeAbstractAnimation> animations READ animations)
-
-public:
- QDeclarativeAnimationGroup(QObject *parent);
- virtual ~QDeclarativeAnimationGroup();
-
- QDeclarativeListProperty<QDeclarativeAbstractAnimation> animations();
- friend class QDeclarativeAbstractAnimation;
-
-protected:
- QDeclarativeAnimationGroup(QDeclarativeAnimationGroupPrivate &dd, QObject *parent);
-};
-
-class QDeclarativeSequentialAnimation : public QDeclarativeAnimationGroup
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeAnimationGroup)
-
-public:
- QDeclarativeSequentialAnimation(QObject *parent=0);
- virtual ~QDeclarativeSequentialAnimation();
-
-protected:
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
- virtual QAbstractAnimation *qtAnimation();
-};
-
-class QDeclarativeParallelAnimation : public QDeclarativeAnimationGroup
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeAnimationGroup)
-
-public:
- QDeclarativeParallelAnimation(QObject *parent=0);
- virtual ~QDeclarativeParallelAnimation();
-
-protected:
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
- virtual QAbstractAnimation *qtAnimation();
-};
-
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeAbstractAnimation)
-QML_DECLARE_TYPE(QDeclarativePauseAnimation)
-QML_DECLARE_TYPE(QDeclarativeScriptAction)
-QML_DECLARE_TYPE(QDeclarativePropertyAction)
-QML_DECLARE_TYPE(QDeclarativePropertyAnimation)
-QML_DECLARE_TYPE(QDeclarativeColorAnimation)
-QML_DECLARE_TYPE(QDeclarativeNumberAnimation)
-QML_DECLARE_TYPE(QDeclarativeSequentialAnimation)
-QML_DECLARE_TYPE(QDeclarativeParallelAnimation)
-QML_DECLARE_TYPE(QDeclarativeVector3dAnimation)
-QML_DECLARE_TYPE(QDeclarativeRotationAnimation)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVEANIMATION_H
diff --git a/src/declarative/util/qdeclarativeanimation_p_p.h b/src/declarative/util/qdeclarativeanimation_p_p.h
deleted file mode 100644
index dfeb767877..0000000000
--- a/src/declarative/util/qdeclarativeanimation_p_p.h
+++ /dev/null
@@ -1,366 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEANIMATION_P_H
-#define QDECLARATIVEANIMATION_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 "qdeclarativeanimation_p.h"
-
-#include <private/qdeclarativenullablevalue_p_p.h>
-
-#include <qdeclarative.h>
-#include <qdeclarativecontext.h>
-
-#include <QtCore/QPauseAnimation>
-#include <QtCore/QVariantAnimation>
-#include <QtCore/QAnimationGroup>
-#include <QDebug>
-
-#include <private/qobject_p.h>
-#include <private/qvariantanimation_p.h>
-
-QT_BEGIN_NAMESPACE
-
-//interface for classes that provide animation actions for QActionAnimation
-class QAbstractAnimationAction
-{
-public:
- virtual ~QAbstractAnimationAction() {}
- virtual void doAction() = 0;
-};
-
-//templated animation action
-//allows us to specify an action that calls a function of a class.
-//(so that class doesn't have to inherit QDeclarativeAbstractAnimationAction)
-template<class T, void (T::*method)()>
-class QAnimationActionProxy : public QAbstractAnimationAction
-{
-public:
- QAnimationActionProxy(T *p) : m_p(p) {}
- virtual void doAction() { (m_p->*method)(); }
-
-private:
- T *m_p;
-};
-
-//performs an action of type QAbstractAnimationAction
-class Q_AUTOTEST_EXPORT QActionAnimation : public QAbstractAnimation
-{
- Q_OBJECT
-public:
- QActionAnimation(QObject *parent = 0) : QAbstractAnimation(parent), animAction(0), policy(KeepWhenStopped) {}
- QActionAnimation(QAbstractAnimationAction *action, QObject *parent = 0)
- : QAbstractAnimation(parent), animAction(action), policy(KeepWhenStopped) {}
- ~QActionAnimation() { if (policy == DeleteWhenStopped) { delete animAction; animAction = 0; } }
- virtual int duration() const { return 0; }
- void setAnimAction(QAbstractAnimationAction *action, DeletionPolicy p)
- {
- if (state() == Running)
- stop();
- if (policy == DeleteWhenStopped)
- delete animAction;
- animAction = action;
- policy = p;
- }
-protected:
- virtual void updateCurrentTime(int) {}
-
- virtual void updateState(State newState, State /*oldState*/)
- {
- if (newState == Running) {
- if (animAction) {
- animAction->doAction();
- if (state() == Stopped && policy == DeleteWhenStopped) {
- delete animAction;
- animAction = 0;
- }
- }
- }
- }
-
-private:
- QAbstractAnimationAction *animAction;
- DeletionPolicy policy;
-};
-
-class QDeclarativeBulkValueUpdater
-{
-public:
- virtual ~QDeclarativeBulkValueUpdater() {}
- virtual void setValue(qreal value) = 0;
-};
-
-//animates QDeclarativeBulkValueUpdater (assumes start and end values will be reals or compatible)
-class Q_AUTOTEST_EXPORT QDeclarativeBulkValueAnimator : public QVariantAnimation
-{
- Q_OBJECT
-public:
- QDeclarativeBulkValueAnimator(QObject *parent = 0) : QVariantAnimation(parent), animValue(0), fromSourced(0), policy(KeepWhenStopped) {}
- ~QDeclarativeBulkValueAnimator() { if (policy == DeleteWhenStopped) { delete animValue; animValue = 0; } }
- void setAnimValue(QDeclarativeBulkValueUpdater *value, DeletionPolicy p)
- {
- if (state() == Running)
- stop();
- if (policy == DeleteWhenStopped)
- delete animValue;
- animValue = value;
- policy = p;
- }
- QDeclarativeBulkValueUpdater *getAnimValue() const
- {
- return animValue;
- }
- void setFromSourcedValue(bool *value)
- {
- fromSourced = value;
- }
-protected:
- virtual void updateCurrentValue(const QVariant &value)
- {
- if (state() == QAbstractAnimation::Stopped)
- return;
-
- if (animValue)
- animValue->setValue(value.toReal());
- }
- virtual void updateState(State newState, State oldState)
- {
- QVariantAnimation::updateState(newState, oldState);
- if (newState == Running) {
- //check for new from every loop
- if (fromSourced)
- *fromSourced = false;
- }
- }
-
-private:
- QDeclarativeBulkValueUpdater *animValue;
- bool *fromSourced;
- DeletionPolicy policy;
-};
-
-//an animation that just gives a tick
-template<class T, void (T::*method)(int)>
-class QTickAnimationProxy : public QAbstractAnimation
-{
- //Q_OBJECT //doesn't work with templating
-public:
- QTickAnimationProxy(T *p, QObject *parent = 0) : QAbstractAnimation(parent), m_p(p) {}
- virtual int duration() const { return -1; }
-protected:
- virtual void updateCurrentTime(int msec) { (m_p->*method)(msec); }
-
-private:
- T *m_p;
-};
-
-class QDeclarativeAbstractAnimationPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeAbstractAnimation)
-public:
- QDeclarativeAbstractAnimationPrivate()
- : running(false), paused(false), alwaysRunToEnd(false),
- connectedTimeLine(false), componentComplete(true),
- avoidPropertyValueSourceStart(false), disableUserControl(false),
- registered(false), loopCount(1), group(0) {}
-
- bool running:1;
- bool paused:1;
- bool alwaysRunToEnd:1;
- bool connectedTimeLine:1;
- bool componentComplete:1;
- bool avoidPropertyValueSourceStart:1;
- bool disableUserControl:1;
- bool registered:1;
-
- int loopCount;
-
- void commence();
-
- QDeclarativeProperty defaultProperty;
-
- QDeclarativeAnimationGroup *group;
-
- static QDeclarativeProperty createProperty(QObject *obj, const QString &str, QObject *infoObj);
-};
-
-class QDeclarativePauseAnimationPrivate : public QDeclarativeAbstractAnimationPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativePauseAnimation)
-public:
- QDeclarativePauseAnimationPrivate()
- : QDeclarativeAbstractAnimationPrivate(), pa(0) {}
-
- void init();
-
- QPauseAnimation *pa;
-};
-
-class QDeclarativeScriptActionPrivate : public QDeclarativeAbstractAnimationPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeScriptAction)
-public:
- QDeclarativeScriptActionPrivate();
-
- void init();
-
- QDeclarativeScriptString script;
- QString name;
- QDeclarativeScriptString runScriptScript;
- bool hasRunScriptScript;
- bool reversing;
-
- void execute();
-
- QAnimationActionProxy<QDeclarativeScriptActionPrivate,
- &QDeclarativeScriptActionPrivate::execute> proxy;
- QActionAnimation *rsa;
-};
-
-class QDeclarativePropertyActionPrivate : public QDeclarativeAbstractAnimationPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativePropertyAction)
-public:
- QDeclarativePropertyActionPrivate()
- : QDeclarativeAbstractAnimationPrivate(), target(0), spa(0) {}
-
- void init();
-
- QObject *target;
- QString propertyName;
- QString properties;
- QList<QObject *> targets;
- QList<QObject *> exclude;
-
- QDeclarativeNullableValue<QVariant> value;
-
- QActionAnimation *spa;
-};
-
-class QDeclarativeAnimationGroupPrivate : public QDeclarativeAbstractAnimationPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeAnimationGroup)
-public:
- QDeclarativeAnimationGroupPrivate()
- : QDeclarativeAbstractAnimationPrivate(), ag(0) {}
-
- static void append_animation(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list, QDeclarativeAbstractAnimation *role);
- static void clear_animation(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list);
- QList<QDeclarativeAbstractAnimation *> animations;
- QAnimationGroup *ag;
-};
-
-class QDeclarativePropertyAnimationPrivate : public QDeclarativeAbstractAnimationPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativePropertyAnimation)
-public:
- QDeclarativePropertyAnimationPrivate()
- : QDeclarativeAbstractAnimationPrivate(), target(0), fromSourced(false), fromIsDefined(false), toIsDefined(false),
- rangeIsSet(false), defaultToInterpolatorType(0), interpolatorType(0), interpolator(0), va(0), actions(0) {}
-
- void init();
-
- QVariant from;
- QVariant to;
-
- QObject *target;
- QString propertyName;
- QString properties;
- QList<QObject *> targets;
- QList<QObject *> exclude;
- QString defaultProperties;
-
- bool fromSourced;
- bool fromIsDefined:1;
- bool toIsDefined:1;
- bool rangeIsSet:1;
- bool defaultToInterpolatorType:1;
- int interpolatorType;
- QVariantAnimation::Interpolator interpolator;
-
- QDeclarativeBulkValueAnimator *va;
-
- // for animations that don't use the QDeclarativeBulkValueAnimator
- QDeclarativeStateActions *actions;
-
- static QVariant interpolateVariant(const QVariant &from, const QVariant &to, qreal progress);
- static void convertVariant(QVariant &variant, int type);
-};
-
-class QDeclarativeRotationAnimationPrivate : public QDeclarativePropertyAnimationPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeRotationAnimation)
-public:
- QDeclarativeRotationAnimationPrivate() : direction(QDeclarativeRotationAnimation::Numerical) {}
-
- QDeclarativeRotationAnimation::RotationDirection direction;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativeAnimationPropertyUpdater : public QDeclarativeBulkValueUpdater
-{
-public:
- QDeclarativeStateActions actions;
- int interpolatorType; //for Number/ColorAnimation
- int prevInterpolatorType; //for generic
- QVariantAnimation::Interpolator interpolator;
- bool reverse;
- bool fromSourced;
- bool fromDefined;
- bool *wasDeleted;
- QDeclarativeAnimationPropertyUpdater() : prevInterpolatorType(0), wasDeleted(0) {}
- ~QDeclarativeAnimationPropertyUpdater() { if (wasDeleted) *wasDeleted = true; }
- void setValue(qreal v);
-};
-
-QT_END_NAMESPACE
-
-#endif // QDECLARATIVEANIMATION_P_H
diff --git a/src/declarative/util/qdeclarativebehavior.cpp b/src/declarative/util/qdeclarativebehavior.cpp
deleted file mode 100644
index 6fb36197ef..0000000000
--- a/src/declarative/util/qdeclarativebehavior.cpp
+++ /dev/null
@@ -1,228 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativebehavior_p.h"
-
-#include "qdeclarativeanimation_p.h"
-#include <qdeclarativecontext.h>
-#include <qdeclarativeinfo.h>
-#include <private/qdeclarativeproperty_p.h>
-#include <private/qdeclarativeguard_p.h>
-#include <private/qdeclarativeengine_p.h>
-
-#include <private/qobject_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeBehaviorPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeBehavior)
-public:
- QDeclarativeBehaviorPrivate() : animation(0), enabled(true), finalized(false)
- , blockRunningChanged(false) {}
-
- QDeclarativeProperty property;
- QVariant targetValue;
- QDeclarativeGuard<QDeclarativeAbstractAnimation> animation;
- bool enabled;
- bool finalized;
- bool blockRunningChanged;
-};
-
-/*!
- \qmlclass Behavior QDeclarativeBehavior
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \brief The Behavior element allows you to specify a default animation for a property change.
-
- A Behavior defines the default animation to be applied whenever a
- particular property value changes.
-
- For example, the following Behavior defines a NumberAnimation to be run
- whenever the \l Rectangle's \c width value changes. When the MouseArea
- is clicked, the \c width is changed, triggering the behavior's animation:
-
- \snippet doc/src/snippets/declarative/behavior.qml 0
-
- Note that a property cannot have more than one assigned Behavior. To provide
- multiple animations within a Behavior, use ParallelAnimation or
- SequentialAnimation.
-
- If a \l{QML States}{state change} has a \l Transition that matches the same property as a
- Behavior, the \l Transition animation overrides the Behavior for that
- state change. For general advice on using Behaviors to animate state changes, see
- \l{Using QML Behaviors with States}.
-
- \sa {QML Animation and Transitions}, {declarative/animation/behaviors}{Behavior example}, QtDeclarative
-*/
-
-
-QDeclarativeBehavior::QDeclarativeBehavior(QObject *parent)
- : QObject(*(new QDeclarativeBehaviorPrivate), parent)
-{
-}
-
-QDeclarativeBehavior::~QDeclarativeBehavior()
-{
-}
-
-/*!
- \qmlproperty Animation QtQuick2::Behavior::animation
- \default
-
- This property holds the animation to run when the behavior is triggered.
-*/
-
-QDeclarativeAbstractAnimation *QDeclarativeBehavior::animation()
-{
- Q_D(QDeclarativeBehavior);
- return d->animation;
-}
-
-void QDeclarativeBehavior::setAnimation(QDeclarativeAbstractAnimation *animation)
-{
- Q_D(QDeclarativeBehavior);
- if (d->animation) {
- qmlInfo(this) << tr("Cannot change the animation assigned to a Behavior.");
- return;
- }
-
- d->animation = animation;
- if (d->animation) {
- d->animation->setDefaultTarget(d->property);
- d->animation->setDisableUserControl();
- FAST_CONNECT(d->animation->qtAnimation(),
- SIGNAL(stateChanged(QAbstractAnimation::State,QAbstractAnimation::State)),
- this,
- SLOT(qtAnimationStateChanged(QAbstractAnimation::State,QAbstractAnimation::State)))
- }
-}
-
-
-void QDeclarativeBehavior::qtAnimationStateChanged(QAbstractAnimation::State newState,QAbstractAnimation::State)
-{
- Q_D(QDeclarativeBehavior);
- if (!d->blockRunningChanged)
- d->animation->notifyRunningChanged(newState == QAbstractAnimation::Running);
-}
-
-
-/*!
- \qmlproperty bool QtQuick2::Behavior::enabled
-
- This property holds whether the behavior will be triggered when the tracked
- property changes value.
-
- By default a Behavior is enabled.
-*/
-
-bool QDeclarativeBehavior::enabled() const
-{
- Q_D(const QDeclarativeBehavior);
- return d->enabled;
-}
-
-void QDeclarativeBehavior::setEnabled(bool enabled)
-{
- Q_D(QDeclarativeBehavior);
- if (d->enabled == enabled)
- return;
- d->enabled = enabled;
- emit enabledChanged();
-}
-
-void QDeclarativeBehavior::write(const QVariant &value)
-{
- Q_D(QDeclarativeBehavior);
- bool bypass = !d->enabled || !d->finalized;
- if (!bypass)
- qmlExecuteDeferred(this);
- if (!d->animation || bypass) {
- QDeclarativePropertyPrivate::write(d->property, value, QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
- d->targetValue = value;
- return;
- }
-
- if (d->animation->isRunning() && value == d->targetValue)
- return;
-
- const QVariant &currentValue = d->property.read();
- d->targetValue = value;
-
- if (d->animation->qtAnimation()->duration() != -1
- && d->animation->qtAnimation()->state() != QAbstractAnimation::Stopped) {
- d->blockRunningChanged = true;
- d->animation->qtAnimation()->stop();
- }
-
- QDeclarativeStateOperation::ActionList actions;
- QDeclarativeAction action;
- action.property = d->property;
- action.fromValue = currentValue;
- action.toValue = value;
- actions << action;
-
- QList<QDeclarativeProperty> after;
- d->animation->transition(actions, after, QDeclarativeAbstractAnimation::Forward);
- d->animation->qtAnimation()->start();
- d->blockRunningChanged = false;
- if (!after.contains(d->property))
- QDeclarativePropertyPrivate::write(d->property, value, QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
-}
-
-void QDeclarativeBehavior::setTarget(const QDeclarativeProperty &property)
-{
- Q_D(QDeclarativeBehavior);
- d->property = property;
- if (d->animation)
- d->animation->setDefaultTarget(property);
-
- QDeclarativeEnginePrivate *engPriv = QDeclarativeEnginePrivate::get(qmlEngine(this));
- engPriv->registerFinalizeCallback(this, this->metaObject()->indexOfSlot("componentFinalized()"));
-}
-
-void QDeclarativeBehavior::componentFinalized()
-{
- Q_D(QDeclarativeBehavior);
- d->finalized = true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativebehavior_p.h b/src/declarative/util/qdeclarativebehavior_p.h
deleted file mode 100644
index 613461abb1..0000000000
--- a/src/declarative/util/qdeclarativebehavior_p.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEBEHAVIOR_H
-#define QDECLARATIVEBEHAVIOR_H
-
-#include <private/qdeclarativeglobal_p.h>
-
-#include <private/qdeclarativepropertyvalueinterceptor_p.h>
-#include <qdeclarative.h>
-#include <QtCore/QAbstractAnimation>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeAbstractAnimation;
-class QDeclarativeBehaviorPrivate;
-class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativeBehavior : public QObject, public QDeclarativePropertyValueInterceptor
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeBehavior)
-
- Q_INTERFACES(QDeclarativePropertyValueInterceptor)
- Q_CLASSINFO("DefaultProperty", "animation")
- Q_PROPERTY(QDeclarativeAbstractAnimation *animation READ animation WRITE setAnimation)
- Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
- Q_CLASSINFO("DeferredPropertyNames", "animation")
-
-public:
- QDeclarativeBehavior(QObject *parent=0);
- ~QDeclarativeBehavior();
-
- virtual void setTarget(const QDeclarativeProperty &);
- virtual void write(const QVariant &value);
-
- QDeclarativeAbstractAnimation *animation();
- void setAnimation(QDeclarativeAbstractAnimation *);
-
- bool enabled() const;
- void setEnabled(bool enabled);
-
-Q_SIGNALS:
- void enabledChanged();
-
-private Q_SLOTS:
- void componentFinalized();
- void qtAnimationStateChanged(QAbstractAnimation::State,QAbstractAnimation::State);
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeBehavior)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVEBEHAVIOR_H
diff --git a/src/declarative/util/qdeclarativebind.cpp b/src/declarative/util/qdeclarativebind.cpp
deleted file mode 100644
index 20b2caa582..0000000000
--- a/src/declarative/util/qdeclarativebind.cpp
+++ /dev/null
@@ -1,309 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativebind_p.h"
-
-#include <private/qdeclarativenullablevalue_p_p.h>
-#include <private/qdeclarativeproperty_p.h>
-#include <private/qdeclarativebinding_p.h>
-#include <private/qdeclarativeguard_p.h>
-
-#include <qdeclarativeengine.h>
-#include <qdeclarativecontext.h>
-#include <qdeclarativeproperty.h>
-#include <qdeclarativeinfo.h>
-
-#include <QtCore/qfile.h>
-#include <QtCore/qdebug.h>
-
-#include <private/qobject_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeBindPrivate : public QObjectPrivate
-{
-public:
- QDeclarativeBindPrivate() : componentComplete(true), obj(0), prevBind(0) {}
- ~QDeclarativeBindPrivate() { if (prevBind) prevBind->destroy(); }
-
- QDeclarativeNullableValue<bool> when;
- bool componentComplete;
- QDeclarativeGuard<QObject> obj;
- QString propName;
- QDeclarativeNullableValue<QVariant> value;
- QDeclarativeProperty prop;
- QDeclarativeAbstractBinding *prevBind;
-};
-
-
-/*!
- \qmlclass Binding QDeclarativeBind
- \inqmlmodule QtQuick 2
- \ingroup qml-working-with-data
- \brief The Binding element allows arbitrary property bindings to be created.
-
- \section1 Binding to an inaccessible property
-
- Sometimes it is necessary to bind to a property of an object that wasn't
- directly instantiated by QML - generally a property of a class exported
- to QML by C++. In these cases, regular property binding doesn't work. Binding
- allows you to bind any value to any property.
-
- For example, imagine a C++ application that maps an "app.enteredText"
- property into QML. You could use Binding to update the enteredText property
- like this.
- \code
- TextEdit { id: myTextField; text: "Please type here..." }
- Binding { target: app; property: "enteredText"; value: myTextField.text }
- \endcode
- Whenever the text in the TextEdit is updated, the C++ property will be
- updated also.
-
- \section1 "Single-branch" conditional binding
-
- In some circumstances you may want to control the value of a property
- only when a certain condition is true (and relinquish control in all
- other cirumstances). This often isn't possible to accomplish with a direct
- binding, as you need to supply values for all possible branches.
-
- \qml
- // warning: "Unable to assign [undefined] to double value"
- value: if (mouse.pressed) mouse.mouseX
- \endqml
-
- The above example will produce a warning whenever we release the mouse, as the value
- of the binding is undefined when the mouse isn't pressed. We can use the Binding
- element to rewrite the above code and avoid the warning.
-
- \qml
- Binding on value {
- when: mouse.pressed
- value: mouse.mouseX
- }
- \endqml
-
- The Binding element will also restore any previously set direct bindings on
- the property. In that sense, it functions much like a simplified State.
-
- \qml
- // this is equivilant to the above Binding
- State {
- name: "pressed"
- when: mouse.pressed
- PropertyChanges {
- target: obj
- value: mouse.mouseX
- }
- }
- \endqml
-
- If the binding target or binding property is changed, the bound value is
- immediately pushed onto the new target.
-
- \sa QtDeclarative
-*/
-QDeclarativeBind::QDeclarativeBind(QObject *parent)
- : QObject(*(new QDeclarativeBindPrivate), parent)
-{
-}
-
-QDeclarativeBind::~QDeclarativeBind()
-{
-}
-
-/*!
- \qmlproperty bool QtQuick2::Binding::when
-
- This property holds when the binding is active.
- This should be set to an expression that evaluates to true when you want the binding to be active.
-
- \code
- Binding {
- target: contactName; property: 'text'
- value: name; when: list.ListView.isCurrentItem
- }
- \endcode
-
- When the binding becomes inactive again, any direct bindings that were previously
- set on the property will be restored.
-*/
-bool QDeclarativeBind::when() const
-{
- Q_D(const QDeclarativeBind);
- return d->when;
-}
-
-void QDeclarativeBind::setWhen(bool v)
-{
- Q_D(QDeclarativeBind);
- if (!d->when.isNull && d->when == v)
- return;
-
- d->when = v;
- eval();
-}
-
-/*!
- \qmlproperty Object QtQuick2::Binding::target
-
- The object to be updated.
-*/
-QObject *QDeclarativeBind::object()
-{
- Q_D(const QDeclarativeBind);
- return d->obj;
-}
-
-void QDeclarativeBind::setObject(QObject *obj)
-{
- Q_D(QDeclarativeBind);
- if (d->obj && d->when.isValid() && d->when) {
- /* if we switch the object at runtime, we need to restore the
- previous binding on the old object before continuing */
- d->when = false;
- eval();
- d->when = true;
- }
- d->obj = obj;
- if (d->componentComplete)
- d->prop = QDeclarativeProperty(d->obj, d->propName);
- eval();
-}
-
-/*!
- \qmlproperty string QtQuick2::Binding::property
-
- The property to be updated.
-*/
-QString QDeclarativeBind::property() const
-{
- Q_D(const QDeclarativeBind);
- return d->propName;
-}
-
-void QDeclarativeBind::setProperty(const QString &p)
-{
- Q_D(QDeclarativeBind);
- if (!d->propName.isEmpty() && d->when.isValid() && d->when) {
- /* if we switch the property name at runtime, we need to restore the
- previous binding on the old object before continuing */
- d->when = false;
- eval();
- d->when = true;
- }
- d->propName = p;
- if (d->componentComplete)
- d->prop = QDeclarativeProperty(d->obj, d->propName);
- eval();
-}
-
-/*!
- \qmlproperty any QtQuick2::Binding::value
-
- The value to be set on the target object and property. This can be a
- constant (which isn't very useful), or a bound expression.
-*/
-QVariant QDeclarativeBind::value() const
-{
- Q_D(const QDeclarativeBind);
- return d->value.value;
-}
-
-void QDeclarativeBind::setValue(const QVariant &v)
-{
- Q_D(QDeclarativeBind);
- d->value = v;
- eval();
-}
-
-void QDeclarativeBind::setTarget(const QDeclarativeProperty &p)
-{
- Q_D(QDeclarativeBind);
- d->prop = p;
-}
-
-void QDeclarativeBind::classBegin()
-{
- Q_D(QDeclarativeBind);
- d->componentComplete = false;
-}
-
-void QDeclarativeBind::componentComplete()
-{
- Q_D(QDeclarativeBind);
- d->componentComplete = true;
- if (!d->prop.isValid())
- d->prop = QDeclarativeProperty(d->obj, d->propName);
- eval();
-}
-
-void QDeclarativeBind::eval()
-{
- Q_D(QDeclarativeBind);
- if (!d->prop.isValid() || d->value.isNull || !d->componentComplete)
- return;
-
- if (d->when.isValid()) {
- if (!d->when) {
- //restore any previous binding
- if (d->prevBind) {
- QDeclarativeAbstractBinding *tmp = d->prevBind;
- d->prevBind = 0;
- tmp = QDeclarativePropertyPrivate::setBinding(d->prop, tmp);
- if (tmp) //should this ever be true?
- tmp->destroy();
- }
- return;
- }
-
- //save any set binding for restoration
- QDeclarativeAbstractBinding *tmp;
- tmp = QDeclarativePropertyPrivate::setBinding(d->prop, 0);
- if (tmp && d->prevBind)
- d->prevBind->destroy();
- else if (!d->prevBind)
- d->prevBind = tmp;
- }
-
- d->prop.write(d->value.value);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativebind_p.h b/src/declarative/util/qdeclarativebind_p.h
deleted file mode 100644
index 38f15a9328..0000000000
--- a/src/declarative/util/qdeclarativebind_p.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEBIND_H
-#define QDECLARATIVEBIND_H
-
-#include <qdeclarative.h>
-
-#include <QtCore/qobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeBindPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativeBind : public QObject, public QDeclarativePropertyValueSource, public QDeclarativeParserStatus
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeBind)
- Q_INTERFACES(QDeclarativeParserStatus)
- Q_INTERFACES(QDeclarativePropertyValueSource)
- 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:
- QDeclarativeBind(QObject *parent=0);
- ~QDeclarativeBind();
-
- bool when() const;
- void setWhen(bool);
-
- QObject *object();
- void setObject(QObject *);
-
- QString property() const;
- void setProperty(const QString &);
-
- QVariant value() const;
- void setValue(const QVariant &);
-
-protected:
- virtual void setTarget(const QDeclarativeProperty &);
- virtual void classBegin();
- virtual void componentComplete();
-
-private:
- void eval();
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeBind)
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/util/qdeclarativechangeset.cpp b/src/declarative/util/qdeclarativechangeset.cpp
deleted file mode 100644
index 81cbe3e10a..0000000000
--- a/src/declarative/util/qdeclarativechangeset.cpp
+++ /dev/null
@@ -1,479 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativechangeset_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QDeclarativeChangeSet::QDeclarativeChangeSet()
- : m_moveCounter(0)
- , m_difference(0)
-{
-}
-
-QDeclarativeChangeSet::QDeclarativeChangeSet(const QDeclarativeChangeSet &changeSet)
- : m_removes(changeSet.m_removes)
- , m_inserts(changeSet.m_inserts)
- , m_changes(changeSet.m_changes)
- , m_moveCounter(changeSet.m_moveCounter)
- , m_difference(0)
-{
-}
-
-QDeclarativeChangeSet::~QDeclarativeChangeSet()
-{
-}
-
-QDeclarativeChangeSet &QDeclarativeChangeSet::operator =(const QDeclarativeChangeSet &changeSet)
-{
- m_removes = changeSet.m_removes;
- m_inserts = changeSet.m_inserts;
- m_changes = changeSet.m_changes;
- m_moveCounter = changeSet.m_moveCounter;
- m_difference = changeSet.m_difference;
- return *this;
-}
-
-void QDeclarativeChangeSet::insert(int index, int count)
-{
- applyInsertions(QVector<Insert>() << Insert(index, count));
-}
-
-void QDeclarativeChangeSet::remove(int index, int count)
-{
- QVector<Insert> i;
- applyRemovals(QVector<Remove>() << Remove(index, count), i);
-}
-
-void QDeclarativeChangeSet::move(int from, int to, int count)
-{
- apply(QVector<Remove>() << Remove(from, count, -2), QVector<Insert>() << Insert(to, count, -2));
-}
-
-void QDeclarativeChangeSet::change(int index, int count)
-{
- applyChanges(QVector<Change>() << Change(index, count));
-}
-
-void QDeclarativeChangeSet::apply(const QDeclarativeChangeSet &changeSet)
-{
- apply(changeSet.m_removes, changeSet.m_inserts, changeSet.m_changes);
-}
-
-void QDeclarativeChangeSet::apply(const QVector<Remove> &removals)
-{
- QVector<Remove> r = removals;
- QVector<Insert> i;
- applyRemovals(r, i);
-}
-
-void QDeclarativeChangeSet::apply(const QVector<Insert> &insertions)
-{
- QVector<Insert> i = insertions;
- applyInsertions(i);
-}
-
-void QDeclarativeChangeSet::apply(const QVector<Change> &changes)
-{
- QVector<Change> c = changes;
- applyChanges(c);
-}
-
-void QDeclarativeChangeSet::apply(const QVector<Remove> &removals, const QVector<Insert> &insertions, const QVector<Change> &changes)
-{
- QVector<Remove> r = removals;
- QVector<Insert> i = insertions;
- QVector<Change> c = changes;
- applyRemovals(r, i);
- applyInsertions(i);
- applyChanges(c);
-}
-
-void QDeclarativeChangeSet::applyRemovals(QVector<Remove> &removals, QVector<Insert> &insertions)
-{
- int removeCount = 0;
- int insertCount = 0;
- QVector<Insert>::iterator insert = m_inserts.begin();
- QVector<Change>::iterator change = m_changes.begin();
- QVector<Remove>::iterator rit = removals.begin();
- for (; rit != removals.end(); ++rit) {
- int index = rit->index + removeCount;
- int count = rit->count;
-
- QVector<Insert>::iterator iit = insertions.begin();
- for (; rit->moveId != -1 && iit != insertions.end() && iit->moveId != rit->moveId; ++iit) {}
-
- for (QVector<Remove>::iterator nrit = rit + 1; nrit != removals.end(); nrit = rit + 1) {
- if (nrit->index != rit->index || (rit->moveId == -1) != (nrit->moveId == -1))
- break;
- if (nrit->moveId != -1) {
- QVector<Insert>::iterator niit = iit + 1;
- if (niit->moveId != nrit->moveId || niit->index != iit->index + iit->count)
- break;
- niit->index = iit->index;
- niit->count += iit->count;
- iit = insertions.erase(iit);
- }
- nrit->count += rit->count;
- rit = removals.erase(rit);
- }
-
- for (; change != m_changes.end() && change->end() < rit->index; ++change) {}
- for (; change != m_changes.end() && change->index > rit->end(); ++change) {
- change->count -= qMin(change->end(), rit->end()) - qMax(change->index, rit->index);
- if (change->count == 0) {
- change = m_changes.erase(change);
- } else if (rit->index < change->index) {
- change->index = rit->index;
- }
- }
- for (; insert != m_inserts.end() && insert->end() <= index; ++insert) {
- insertCount += insert->count;
- insert->index -= removeCount;
- }
- for (; insert != m_inserts.end() && insert->index < index + count; ++insert) {
- const int offset = insert->index - index;
- const int difference = qMin(insert->end(), index + count) - qMax(insert->index, index);
- const int moveId = rit->moveId != -1 ? m_moveCounter++ : -1;
- if (insert->moveId != -1) {
- QVector<Remove>::iterator remove = m_removes.begin();
- for (; remove != m_removes.end() && remove->moveId != insert->moveId; ++remove) {}
- Q_ASSERT(remove != m_removes.end());
- const int offset = index - insert->index;
- if (rit->moveId != -1 && offset < 0) {
- const int moveId = m_moveCounter++;
- iit = insertions.insert(iit, Insert(iit->index, -offset, moveId));
- ++iit;
- iit->index += -offset;
- iit->count -= -offset;
- rit = removals.insert(rit, Remove(rit->index, -offset, moveId));
- ++rit;
- rit->count -= -offset;
- }
-
- if (offset > 0) {
- const int moveId = m_moveCounter++;
- insert = m_inserts.insert(insert, Insert(insert->index, offset, moveId));
- ++insert;
- insert->index += offset;
- insert->count -= offset;
- remove = m_removes.insert(remove, Remove(remove->index, offset, moveId));
- ++remove;
- remove->count -= offset;
- rit->index -= offset;
- index += offset;
- count -= offset;
- }
-
- if (remove->count == difference) {
- remove->moveId = moveId;
- } else {
- remove = m_removes.insert(remove, Remove(remove->index, difference, moveId));
- ++remove;
- remove->count -= difference;
- }
- } else if (rit->moveId != -1 && offset > 0) {
- const int moveId = m_moveCounter++;
- iit = insertions.insert(iit, Insert(iit->index, offset, moveId));
- ++iit;
- iit->index += offset;
- iit->count -= offset;
- rit = removals.insert(rit, Remove(rit->index, offset, moveId));
- ++rit;
- rit->count -= offset;
- index += offset;
- count -= offset;
- }
-
- if (rit->moveId != -1 && difference > 0) {
- iit = insertions.insert(iit, Insert(
- iit->index, difference, insert->moveId != -1 ? moveId : -1));
- ++iit;
- iit->index += difference;
- iit->count -= difference;
- }
-
- insert->count -= difference;
- rit->count -= difference;
- if (insert->count == 0) {
- insert = m_inserts.erase(insert);
- --insert;
- } else if (index <= insert->index) {
- insert->index = rit->index;
- } else {
- rit->index -= insert->count;
- }
- index += difference;
- count -= difference;
- removeCount += difference;
- }
- rit->index -= insertCount;
- removeCount += rit->count;
-
- if (rit->count == 0) {
- if (rit->moveId != -1 && iit->count == 0)
- insertions.erase(iit);
- rit = removals.erase(rit);
- --rit;
- } else if (rit->moveId != -1) {
- const int moveId = m_moveCounter++;
- rit->moveId = moveId;
- iit->moveId = moveId;
- }
- }
- for (; change != m_changes.end(); ++change)
- change->index -= removeCount;
- for (; insert != m_inserts.end(); ++insert)
- insert->index -= removeCount;
-
- removeCount = 0;
- QVector<Remove>::iterator remove = m_removes.begin();
- for (rit = removals.begin(); rit != removals.end(); ++rit) {
- QVector<Insert>::iterator iit = insertions.begin();
- int index = rit->index + removeCount;
- for (; rit->moveId != -1 && iit != insertions.end() && iit->moveId != rit->moveId; ++iit) {}
- for (; remove != m_removes.end() && index > remove->index; ++remove)
- remove->index -= removeCount;
- while (remove != m_removes.end() && index + rit->count > remove->index) {
- int count = 0;
- const int offset = remove->index - index - removeCount;
- QVector<Remove>::iterator rend = remove;
- for (; rend != m_removes.end()
- && rit->moveId == -1
- && rend->moveId == -1
- && rit->index + rit->count >= rend->index; ++rend) {
- count += rend->count;
- }
- if (remove != rend) {
- const int difference = rend == m_removes.end() || rit->index + rit->count < rend->index - removeCount
- ? rit->count
- : offset;
- count += difference;
-
- index += difference;
- rit->count -= difference;
- removeCount += difference;
- remove->index = rit->index;
- remove->count = count;
- remove = m_removes.erase(++remove, rend);
- } else if (rit->moveId != -1) {
- if (offset > 0) {
- const int moveId = m_moveCounter++;
- iit = insertions.insert(iit, Insert(iit->index, offset, moveId));
- ++iit;
- iit->index += offset;
- iit->count -= offset;
- remove = m_removes.insert(remove, Remove(rit->index, offset, moveId));
- ++remove;
- rit->count -= offset;
- removeCount += offset;
- }
- remove->index = rit->index;
- index += offset;
-
- ++remove;
- } else {
- if (offset > 0) {
- remove = m_removes.insert(remove, Remove(rit->index, offset));
- ++remove;
- rit->count -= offset;
- removeCount += offset;
- }
- remove->index = rit->index;
- index += offset;
-
- ++remove;
- }
- index += count;
- }
-
- if (rit->count > 0) {
- remove = m_removes.insert(remove, *rit);
- ++remove;
- }
- removeCount += rit->count;
- }
- for (; remove != m_removes.end(); ++remove)
- remove->index -= removeCount;
- m_difference -= removeCount;
-}
-
-void QDeclarativeChangeSet::applyInsertions(QVector<Insert> &insertions)
-{
- int insertCount = 0;
- QVector<Insert>::iterator insert = m_inserts.begin();
- QVector<Change>::iterator change = m_changes.begin();
- for (QVector<Insert>::iterator iit = insertions.begin(); iit != insertions.end(); ++iit) {
- int index = iit->index - insertCount;
- int count = iit->count;
- for (; change != m_changes.end() && change->index >= index; ++change)
- change->index += insertCount;
- if (change != m_changes.end() && change->index < index + count) {
- int offset = index - change->index;
- change = m_changes.insert(change, Change(change->index + insertCount, offset));
- ++change;
- change->index += count + offset;
- change->count -= offset;
- }
- for (; insert != m_inserts.end() && iit->index > insert->index + insert->count; ++insert)
- insert->index += insertCount;
- if (insert == m_inserts.end()) {
- insert = m_inserts.insert(insert, *iit);
- ++insert;
- insertCount += iit->count;
- } else {
- const int offset = index - insert->index;
- if (offset < 0 || (offset == 0 && (iit->moveId != -1 || insert->moveId != -1))) {
- insert = m_inserts.insert(insert, *iit);
- ++insert;
- } else if (iit->moveId == -1 && insert->moveId == -1) {
- insert->index -= iit->count;
- insert->count += iit->count;
- } else if (offset < insert->count) {
- const int moveId = insert->moveId != -1 ? m_moveCounter++ : -1;
- insert = m_inserts.insert(insert, Insert(insert->index + insertCount, offset, moveId));
- ++insert;
- insert->index += offset;
- insert->count -= offset;
- insert = m_inserts.insert(insert, *iit);
- ++insert;
-
- if (insert->moveId != -1) {
- QVector<Remove>::iterator remove = m_removes.begin();
- for (; remove != m_removes.end() && remove->moveId != insert->moveId; ++remove) {}
- Q_ASSERT(remove != m_removes.end());
- if (remove->count == offset) {
- remove->moveId = moveId;
- } else {
- remove = m_removes.insert(remove, Remove(remove->index, offset, moveId));
- ++remove;
- remove->count -= offset;
- }
- }
- } else {
- ++insert;
- insert = m_inserts.insert(insert, *iit);
- ++insert;
- }
- insertCount += iit->count;
- }
- }
- for (; change != m_changes.end(); ++change)
- change->index += insertCount;
- for (; insert != m_inserts.end(); ++insert)
- insert->index += insertCount;
- m_difference += insertCount;
-}
-
-void QDeclarativeChangeSet::applyChanges(QVector<Change> &changes)
-{
- QVector<Insert>::iterator insert = m_inserts.begin();
- QVector<Change>::iterator change = m_changes.begin();
- for (QVector<Change>::iterator cit = changes.begin(); cit != changes.end(); ++cit) {
- for (; insert != m_inserts.end() && insert->end() < cit->index; ++insert) {}
- for (; insert != m_inserts.end() && insert->index < cit->end(); ++insert) {
- const int offset = insert->index - cit->index;
- const int count = cit->count + cit->index - insert->index - insert->count;
- if (offset == 0) {
- cit->index = insert->index + insert->count;
- cit->count = count;
- } else {
- cit = changes.insert(++cit, Change(insert->index + insert->count, count));
- --cit;
- cit->count = offset;
- }
- }
-
- for (; change != m_changes.end() && change->index + change->count < cit->index; ++change) {}
- if (change == m_changes.end() || change->index > cit->index + cit->count) {
- if (cit->count > 0) {
- change = m_changes.insert(change, *cit);
- ++change;
- }
- } else {
- if (cit->index < change->index) {
- change->count += change->index - cit->index;
- change->index = cit->index;
- }
-
- if (cit->index + cit->count > change->index + change->count) {
- change->count = cit->index + cit->count - change->index;
- QVector<Change>::iterator rbegin = change;
- QVector<Change>::iterator rend = ++rbegin;
- for (; rend != m_changes.end() && rend->index <= change->index + change->count; ++rend) {
- if (rend->index + rend->count > change->index + change->count)
- change->count = rend->index + rend->count - change->index;
- }
- if (rbegin != rend) {
- change = m_changes.erase(rbegin, rend);
- --change;
- }
- }
- }
- }
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeChangeSet &set)
-{
- debug.nospace() << "QDeclarativeChangeSet(";
- foreach (const QDeclarativeChangeSet::Remove &remove, set.removes()) debug << remove;
- foreach (const QDeclarativeChangeSet::Insert &insert, set.inserts()) debug << insert;
- foreach (const QDeclarativeChangeSet::Change &change, set.changes()) debug << change;
- return debug.nospace() << ")";
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeChangeSet::Remove &remove)
-{
- return (debug.nospace() << "Remove(" << remove.index << "," << remove.count << "," << remove.moveId << ")").space();
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeChangeSet::Insert &insert)
-{
- return (debug.nospace() << "Insert(" << insert.index << "," << insert.count << "," << insert.moveId << ")").space();
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeChangeSet::Change &change)
-{
- return (debug.nospace() << "Change(" << change.index << "," << change.count << ")").space();
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/util/qdeclarativechangeset_p.h b/src/declarative/util/qdeclarativechangeset_p.h
deleted file mode 100644
index b7554da503..0000000000
--- a/src/declarative/util/qdeclarativechangeset_p.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVECHANGESET_P_H
-#define QDECLARATIVECHANGESET_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 <QtCore/qdebug.h>
-#include <QtCore/qvector.h>
-
-QT_BEGIN_NAMESPACE
-
-class Q_AUTOTEST_EXPORT QDeclarativeChangeSet
-{
-public:
- struct MoveKey
- {
- MoveKey() : moveId(-1), offset(0) {}
- MoveKey(int moveId, int offset) : moveId(moveId), offset(offset) {}
- int moveId;
- int offset;
- };
-
- struct Change
- {
- Change() : index(0), count(0), moveId(-1) {}
- Change(int index, int count) : index(index), count(count), moveId(-1) {}
- Change(int index, int count, int moveId) : index(index), count(count), moveId(moveId) {}
-
- int index;
- int count;
- int moveId;
-
- bool isMove() const { return moveId >= 0; }
-
- MoveKey moveKey(int index) const { return MoveKey(moveId, index - Change::index); }
-
- int start() const { return index; }
- int end() const { return index + count; }
- };
-
-
- struct Insert : public Change
- {
- Insert() {}
- Insert(int index, int count) : Change(index, count) {}
- Insert(int index, int count, int moveId) : Change(index, count, moveId) {}
- };
-
- struct Remove : public Change
- {
- Remove() {}
- Remove(int index, int count) : Change(index, count) {}
- Remove(int index, int count, int moveId) : Change(index, count, moveId) {}
- };
-
- QDeclarativeChangeSet();
- QDeclarativeChangeSet(const QDeclarativeChangeSet &changeSet);
- ~QDeclarativeChangeSet();
-
- QDeclarativeChangeSet &operator =(const QDeclarativeChangeSet &changeSet);
-
- const QVector<Remove> &removes() const { return m_removes; }
- const QVector<Insert> &inserts() const { return m_inserts; }
- const QVector<Change> &changes() const {return m_changes; }
-
- void insert(int index, int count);
- void remove(int index, int count);
- void move(int from, int to, int count);
- void change(int index, int count);
-
- void apply(const QDeclarativeChangeSet &changeSet);
- void apply(const QVector<Remove> &removals);
- void apply(const QVector<Insert> &insertions);
- void apply(const QVector<Change> &changes);
- void apply(
- const QVector<Remove> &removals,
- const QVector<Insert> &insertions,
- const QVector<Change> &changes = QVector<Change>());
-
- bool isEmpty() const { return m_removes.empty() && m_inserts.empty() && m_changes.empty(); }
-
- void clear()
- {
- m_removes.clear();
- m_inserts.clear();
- m_changes.clear();
- m_moveCounter = 0;
- m_difference = 0;
- }
-
- int moveCounter() const { return m_moveCounter; }
- int difference() const { return m_difference; }
-
-private:
- void applyRemovals(QVector<Remove> &removals, QVector<Insert> &insertions);
- void applyInsertions(QVector<Insert> &insertions);
- void applyChanges(QVector<Change> &changes);
-
- QVector<Remove> m_removes;
- QVector<Insert> m_inserts;
- QVector<Change> m_changes;
- int m_moveCounter;
- int m_difference;
-};
-
-inline uint qHash(const QDeclarativeChangeSet::MoveKey &key) { return qHash(qMakePair(key.moveId, key.offset)); }
-inline bool operator ==(const QDeclarativeChangeSet::MoveKey &l, const QDeclarativeChangeSet::MoveKey &r) {
- return l.moveId == r.moveId && l.offset == r.offset; }
-
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeChangeSet &change);
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeChangeSet::Remove &remove);
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeChangeSet::Insert &insert);
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeChangeSet::Change &change);
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/declarative/util/qdeclarativeconnections.cpp b/src/declarative/util/qdeclarativeconnections.cpp
deleted file mode 100644
index ee2c6edcc5..0000000000
--- a/src/declarative/util/qdeclarativeconnections.cpp
+++ /dev/null
@@ -1,302 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativeconnections_p.h"
-
-#include <private/qdeclarativeexpression_p.h>
-#include <private/qdeclarativeproperty_p.h>
-#include <private/qdeclarativeboundsignal_p.h>
-#include <qdeclarativecontext.h>
-#include <private/qdeclarativecontext_p.h>
-#include <qdeclarativeinfo.h>
-
-#include <QtCore/qdebug.h>
-#include <QtCore/qstringlist.h>
-
-#include <private/qobject_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeConnectionsPrivate : public QObjectPrivate
-{
-public:
- QDeclarativeConnectionsPrivate() : target(0), targetSet(false), ignoreUnknownSignals(false), componentcomplete(true) {}
-
- QList<QDeclarativeBoundSignal*> boundsignals;
- QObject *target;
-
- bool targetSet;
- bool ignoreUnknownSignals;
- bool componentcomplete;
-
- QByteArray data;
-};
-
-/*!
- \qmlclass Connections QDeclarativeConnections
- \inqmlmodule QtQuick 2
- \ingroup qml-utility-elements
- \brief A Connections element describes generalized connections to signals.
-
- A Connections object creates a connection to a QML signal.
-
- When connecting to signals in QML, the usual way is to create an
- "on<Signal>" handler that reacts when a signal is received, like this:
-
- \qml
- MouseArea {
- onClicked: { foo(parameters) }
- }
- \endqml
-
- However, it is not possible to connect to a signal in this way in some
- cases, such as when:
-
- \list
- \i Multiple connections to the same signal are required
- \i Creating connections outside the scope of the signal sender
- \i Connecting to targets not defined in QML
- \endlist
-
- When any of these are needed, the Connections element can be used instead.
-
- For example, the above code can be changed to use a Connections object,
- like this:
-
- \qml
- MouseArea {
- Connections {
- onClicked: foo(parameters)
- }
- }
- \endqml
-
- More generally, the Connections object can be a child of some object other than
- the sender of the signal:
-
- \qml
- MouseArea {
- id: area
- }
- // ...
- \endqml
- \qml
- Connections {
- target: area
- onClicked: foo(parameters)
- }
- \endqml
-
- \sa QtDeclarative
-*/
-QDeclarativeConnections::QDeclarativeConnections(QObject *parent) :
- QObject(*(new QDeclarativeConnectionsPrivate), parent)
-{
-}
-
-QDeclarativeConnections::~QDeclarativeConnections()
-{
-}
-
-/*!
- \qmlproperty Object QtQuick2::Connections::target
- This property holds the object that sends the signal.
-
- If this property is not set, the \c target defaults to the parent of the Connection.
-
- If set to null, no connection is made and any signal handlers are ignored
- until the target is not null.
-*/
-QObject *QDeclarativeConnections::target() const
-{
- Q_D(const QDeclarativeConnections);
- return d->targetSet ? d->target : parent();
-}
-
-void QDeclarativeConnections::setTarget(QObject *obj)
-{
- Q_D(QDeclarativeConnections);
- d->targetSet = true; // even if setting to 0, it is *set*
- if (d->target == obj)
- return;
- foreach (QDeclarativeBoundSignal *s, d->boundsignals) {
- // It is possible that target is being changed due to one of our signal
- // handlers -> use deleteLater().
- if (s->isEvaluating())
- s->deleteLater();
- else
- delete s;
- }
- d->boundsignals.clear();
- d->target = obj;
- connectSignals();
- emit targetChanged();
-}
-
-/*!
- \qmlproperty bool QtQuick2::Connections::ignoreUnknownSignals
-
- Normally, a connection to a non-existent signal produces runtime errors.
-
- If this property is set to \c true, such errors are ignored.
- This is useful if you intend to connect to different types of objects, handling
- a different set of signals for each object.
-*/
-bool QDeclarativeConnections::ignoreUnknownSignals() const
-{
- Q_D(const QDeclarativeConnections);
- return d->ignoreUnknownSignals;
-}
-
-void QDeclarativeConnections::setIgnoreUnknownSignals(bool ignore)
-{
- Q_D(QDeclarativeConnections);
- d->ignoreUnknownSignals = ignore;
-}
-
-
-
-QByteArray
-QDeclarativeConnectionsParser::compile(const QList<QDeclarativeCustomParserProperty> &props)
-{
- QByteArray rv;
- QDataStream ds(&rv, QIODevice::WriteOnly);
-
- for(int ii = 0; ii < props.count(); ++ii)
- {
- QString propName = props.at(ii).name();
- int propLine = props.at(ii).location().line;
-
- if (!propName.startsWith(QLatin1String("on")) || !propName.at(2).isUpper()) {
- error(props.at(ii), QDeclarativeConnections::tr("Cannot assign to non-existent property \"%1\"").arg(propName));
- return QByteArray();
- }
-
- QList<QVariant> values = props.at(ii).assignedValues();
-
- for (int i = 0; i < values.count(); ++i) {
- const QVariant &value = values.at(i);
-
- if (value.userType() == qMetaTypeId<QDeclarativeCustomParserNode>()) {
- error(props.at(ii), QDeclarativeConnections::tr("Connections: nested objects not allowed"));
- return QByteArray();
- } else if (value.userType() == qMetaTypeId<QDeclarativeCustomParserProperty>()) {
- error(props.at(ii), QDeclarativeConnections::tr("Connections: syntax error"));
- return QByteArray();
- } else {
- QDeclarativeScript::Variant v = qvariant_cast<QDeclarativeScript::Variant>(value);
- if (v.isScript()) {
- ds << propName;
- ds << rewriteSignalHandler(v.asScript(), propName);
- ds << propLine;
- } else {
- error(props.at(ii), QDeclarativeConnections::tr("Connections: script expected"));
- return QByteArray();
- }
- }
- }
- }
-
- return rv;
-}
-
-void QDeclarativeConnectionsParser::setCustomData(QObject *object,
- const QByteArray &data)
-{
- QDeclarativeConnectionsPrivate *p =
- static_cast<QDeclarativeConnectionsPrivate *>(QObjectPrivate::get(object));
- p->data = data;
-}
-
-
-void QDeclarativeConnections::connectSignals()
-{
- Q_D(QDeclarativeConnections);
- if (!d->componentcomplete || (d->targetSet && !target()))
- return;
-
- QDataStream ds(d->data);
- while (!ds.atEnd()) {
- QString propName;
- ds >> propName;
- QString script;
- ds >> script;
- int line;
- ds >> line;
- QDeclarativeProperty prop(target(), propName);
- if (prop.isValid() && (prop.type() & QDeclarativeProperty::SignalProperty)) {
- QDeclarativeBoundSignal *signal =
- new QDeclarativeBoundSignal(target(), prop.method(), this);
-
- QString location;
- QDeclarativeContextData *ctxtdata = 0;
- QDeclarativeData *ddata = QDeclarativeData::get(this);
- if (ddata) {
- ctxtdata = ddata->outerContext;
- if (ctxtdata && !ctxtdata->url.isEmpty())
- location = ddata->outerContext->url.toString();
- }
-
- QDeclarativeExpression *expression = ctxtdata ?
- QDeclarativeExpressionPrivate::create(ctxtdata, 0, script, true, location, line) : 0;
- signal->setExpression(expression);
- d->boundsignals += signal;
- } else {
- if (!d->ignoreUnknownSignals)
- qmlInfo(this) << tr("Cannot assign to non-existent property \"%1\"").arg(propName);
- }
- }
-}
-
-void QDeclarativeConnections::classBegin()
-{
- Q_D(QDeclarativeConnections);
- d->componentcomplete=false;
-}
-
-void QDeclarativeConnections::componentComplete()
-{
- Q_D(QDeclarativeConnections);
- d->componentcomplete=true;
- connectSignals();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativeconnections_p.h b/src/declarative/util/qdeclarativeconnections_p.h
deleted file mode 100644
index 86e1341689..0000000000
--- a/src/declarative/util/qdeclarativeconnections_p.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVECONNECTIONS_H
-#define QDECLARATIVECONNECTIONS_H
-
-#include <qdeclarative.h>
-#include <private/qdeclarativecustomparser_p.h>
-
-#include <QtCore/qobject.h>
-#include <QtCore/qstring.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeBoundSignal;
-class QDeclarativeContext;
-class QDeclarativeConnectionsPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativeConnections : public QObject, public QDeclarativeParserStatus
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeConnections)
-
- Q_INTERFACES(QDeclarativeParserStatus)
- Q_PROPERTY(QObject *target READ target WRITE setTarget NOTIFY targetChanged)
- Q_PROPERTY(bool ignoreUnknownSignals READ ignoreUnknownSignals WRITE setIgnoreUnknownSignals)
-
-public:
- QDeclarativeConnections(QObject *parent=0);
- ~QDeclarativeConnections();
-
- QObject *target() const;
- void setTarget(QObject *);
-
- bool ignoreUnknownSignals() const;
- void setIgnoreUnknownSignals(bool ignore);
-
-Q_SIGNALS:
- void targetChanged();
-
-private:
- void connectSignals();
- void classBegin();
- void componentComplete();
-};
-
-class QDeclarativeConnectionsParser : public QDeclarativeCustomParser
-{
-public:
- virtual QByteArray compile(const QList<QDeclarativeCustomParserProperty> &);
- virtual void setCustomData(QObject *, const QByteArray &);
-};
-
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeConnections)
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/util/qdeclarativefontloader.cpp b/src/declarative/util/qdeclarativefontloader.cpp
deleted file mode 100644
index e95bd11a7b..0000000000
--- a/src/declarative/util/qdeclarativefontloader.cpp
+++ /dev/null
@@ -1,335 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativefontloader_p.h"
-
-#include <qdeclarativecontext.h>
-#include <qdeclarativeengine.h>
-
-#include <QStringList>
-#include <QUrl>
-#include <QDebug>
-#include <QNetworkRequest>
-#include <QNetworkReply>
-#include <QFontDatabase>
-
-#include <private/qobject_p.h>
-#include <private/qdeclarativeengine_p.h>
-#include <qdeclarativeinfo.h>
-
-QT_BEGIN_NAMESPACE
-
-#define FONTLOADER_MAXIMUM_REDIRECT_RECURSION 16
-
-class QDeclarativeFontObject : public QObject
-{
-Q_OBJECT
-
-public:
- QDeclarativeFontObject(int _id);
-
- void download(const QUrl &url, QNetworkAccessManager *manager);
-
-Q_SIGNALS:
- void fontDownloaded(const QString&, QDeclarativeFontLoader::Status);
-
-private Q_SLOTS:
- void replyFinished();
-
-public:
- int id;
-
-private:
- QNetworkReply *reply;
- int redirectCount;
-
- Q_DISABLE_COPY(QDeclarativeFontObject)
-};
-
-QDeclarativeFontObject::QDeclarativeFontObject(int _id = -1)
- : QObject(0), id(_id), reply(0), redirectCount(0) {}
-
-
-void QDeclarativeFontObject::download(const QUrl &url, QNetworkAccessManager *manager)
-{
- QNetworkRequest req(url);
- req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
- reply = manager->get(req);
- QObject::connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
-}
-
-void QDeclarativeFontObject::replyFinished()
-{
- if (reply) {
- redirectCount++;
- if (redirectCount < FONTLOADER_MAXIMUM_REDIRECT_RECURSION) {
- QVariant redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
- if (redirect.isValid()) {
- QUrl url = reply->url().resolved(redirect.toUrl());
- QNetworkAccessManager *manager = reply->manager();
- reply->deleteLater();
- reply = 0;
- download(url, manager);
- return;
- }
- }
- redirectCount = 0;
-
- if (!reply->error()) {
- id = QFontDatabase::addApplicationFontFromData(reply->readAll());
- if (id != -1)
- emit fontDownloaded(QFontDatabase::applicationFontFamilies(id).at(0), QDeclarativeFontLoader::Ready);
- else
- emit fontDownloaded(QString(), QDeclarativeFontLoader::Error);
- } else {
- emit fontDownloaded(QString(), QDeclarativeFontLoader::Error);
- }
- reply->deleteLater();
- reply = 0;
- }
-}
-
-
-class QDeclarativeFontLoaderPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeFontLoader)
-
-public:
- QDeclarativeFontLoaderPrivate() : status(QDeclarativeFontLoader::Null) {}
-
- QUrl url;
- QString name;
- QDeclarativeFontLoader::Status status;
- static QHash<QUrl, QDeclarativeFontObject*> fonts;
-};
-
-QHash<QUrl, QDeclarativeFontObject*> QDeclarativeFontLoaderPrivate::fonts;
-
-/*!
- \qmlclass FontLoader QDeclarativeFontLoader
- \inqmlmodule QtQuick 2
- \ingroup qml-utility-elements
- \brief The FontLoader element allows fonts to be loaded by name or URL.
-
- The FontLoader element is used to load fonts by name or URL.
-
- The \l status indicates when the font has been loaded, which is useful
- for fonts loaded from remote sources.
-
- For example:
- \qml
- import QtQuick 1.0
-
- Column {
- FontLoader { id: fixedFont; name: "Courier" }
- FontLoader { id: webFont; source: "http://www.mysite.com/myfont.ttf" }
-
- Text { text: "Fixed-size font"; font.family: fixedFont.name }
- Text { text: "Fancy font"; font.family: webFont.name }
- }
- \endqml
-
- \sa {declarative/text/fonts}{Fonts example}
-*/
-QDeclarativeFontLoader::QDeclarativeFontLoader(QObject *parent)
- : QObject(*(new QDeclarativeFontLoaderPrivate), parent)
-{
-}
-
-QDeclarativeFontLoader::~QDeclarativeFontLoader()
-{
-}
-
-/*!
- \qmlproperty url QtQuick2::FontLoader::source
- The url of the font to load.
-*/
-QUrl QDeclarativeFontLoader::source() const
-{
- Q_D(const QDeclarativeFontLoader);
- return d->url;
-}
-
-void QDeclarativeFontLoader::setSource(const QUrl &url)
-{
- Q_D(QDeclarativeFontLoader);
- if (url == d->url)
- return;
- d->url = url;
- emit sourceChanged();
-
- QString localFile = QDeclarativeEnginePrivate::urlToLocalFileOrQrc(d->url);
- if (!localFile.isEmpty()) {
- if (!d->fonts.contains(d->url)) {
- int id = QFontDatabase::addApplicationFont(localFile);
- if (id != -1) {
- updateFontInfo(QFontDatabase::applicationFontFamilies(id).at(0), Ready);
- QDeclarativeFontObject *fo = new QDeclarativeFontObject(id);
- d->fonts[d->url] = fo;
- } else {
- updateFontInfo(QString(), Error);
- }
- } else {
- updateFontInfo(QFontDatabase::applicationFontFamilies(d->fonts[d->url]->id).at(0), Ready);
- }
- } else {
- if (!d->fonts.contains(d->url)) {
- QDeclarativeFontObject *fo = new QDeclarativeFontObject;
- d->fonts[d->url] = fo;
- fo->download(d->url, qmlEngine(this)->networkAccessManager());
- d->status = Loading;
- emit statusChanged();
- QObject::connect(fo, SIGNAL(fontDownloaded(QString,QDeclarativeFontLoader::Status)),
- this, SLOT(updateFontInfo(QString,QDeclarativeFontLoader::Status)));
- } else {
- QDeclarativeFontObject *fo = d->fonts[d->url];
- if (fo->id == -1) {
- d->status = Loading;
- emit statusChanged();
- QObject::connect(fo, SIGNAL(fontDownloaded(QString,QDeclarativeFontLoader::Status)),
- this, SLOT(updateFontInfo(QString,QDeclarativeFontLoader::Status)));
- }
- else
- updateFontInfo(QFontDatabase::applicationFontFamilies(fo->id).at(0), Ready);
- }
- }
-}
-
-void QDeclarativeFontLoader::updateFontInfo(const QString& name, QDeclarativeFontLoader::Status status)
-{
- Q_D(QDeclarativeFontLoader);
-
- if (name != d->name) {
- d->name = name;
- emit nameChanged();
- }
- if (status != d->status) {
- if (status == Error)
- qmlInfo(this) << "Cannot load font: \"" << d->url.toString() << "\"";
- d->status = status;
- emit statusChanged();
- }
-}
-
-/*!
- \qmlproperty string QtQuick2::FontLoader::name
-
- This property holds the name of the font family.
- It is set automatically when a font is loaded using the \c url property.
-
- Use this to set the \c font.family property of a \c Text item.
-
- Example:
- \qml
- Item {
- width: 200; height: 50
-
- FontLoader {
- id: webFont
- source: "http://www.mysite.com/myfont.ttf"
- }
- Text {
- text: "Fancy font"
- font.family: webFont.name
- }
- }
- \endqml
-*/
-QString QDeclarativeFontLoader::name() const
-{
- Q_D(const QDeclarativeFontLoader);
- return d->name;
-}
-
-void QDeclarativeFontLoader::setName(const QString &name)
-{
- Q_D(QDeclarativeFontLoader);
- if (d->name == name)
- return;
- d->name = name;
- emit nameChanged();
- d->status = Ready;
- emit statusChanged();
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::FontLoader::status
-
- This property holds the status of font loading. It can be one of:
- \list
- \o FontLoader.Null - no font has been set
- \o FontLoader.Ready - the font has been loaded
- \o FontLoader.Loading - the font is currently being loaded
- \o FontLoader.Error - an error occurred while loading the font
- \endlist
-
- Use this status to provide an update or respond to the status change in some way.
- For example, you could:
-
- \list
- \o Trigger a state change:
- \qml
- State { name: 'loaded'; when: loader.status == FontLoader.Ready }
- \endqml
-
- \o Implement an \c onStatusChanged signal handler:
- \qml
- FontLoader {
- id: loader
- onStatusChanged: if (loader.status == FontLoader.Ready) console.log('Loaded')
- }
- \endqml
-
- \o Bind to the status value:
- \qml
- Text { text: loader.status == FontLoader.Ready ? 'Loaded' : 'Not loaded' }
- \endqml
- \endlist
-*/
-QDeclarativeFontLoader::Status QDeclarativeFontLoader::status() const
-{
- Q_D(const QDeclarativeFontLoader);
- return d->status;
-}
-
-QT_END_NAMESPACE
-
-#include <qdeclarativefontloader.moc>
diff --git a/src/declarative/util/qdeclarativefontloader_p.h b/src/declarative/util/qdeclarativefontloader_p.h
deleted file mode 100644
index 26cad5eff4..0000000000
--- a/src/declarative/util/qdeclarativefontloader_p.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEFONTLOADER_H
-#define QDECLARATIVEFONTLOADER_H
-
-#include <qdeclarative.h>
-
-#include <QtCore/qobject.h>
-#include <QtCore/qurl.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeFontLoaderPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativeFontLoader : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeFontLoader)
- Q_ENUMS(Status)
-
- Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
- Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
- Q_PROPERTY(Status status READ status NOTIFY statusChanged)
-
-public:
- enum Status { Null = 0, Ready, Loading, Error };
-
- QDeclarativeFontLoader(QObject *parent = 0);
- ~QDeclarativeFontLoader();
-
- QUrl source() const;
- void setSource(const QUrl &url);
-
- QString name() const;
- void setName(const QString &name);
-
- Status status() const;
-
-private Q_SLOTS:
- void updateFontInfo(const QString&, QDeclarativeFontLoader::Status);
-
-Q_SIGNALS:
- void sourceChanged();
- void nameChanged();
- void statusChanged();
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeFontLoader)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVEFONTLOADER_H
-
diff --git a/src/declarative/util/qdeclarativelistaccessor.cpp b/src/declarative/util/qdeclarativelistaccessor.cpp
deleted file mode 100644
index 0063514e59..0000000000
--- a/src/declarative/util/qdeclarativelistaccessor.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativelistaccessor_p.h"
-
-#include <private/qdeclarativemetatype_p.h>
-
-#include <QtCore/qstringlist.h>
-#include <QtCore/qdebug.h>
-
-// ### Remove me
-#include <private/qdeclarativeengine_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QDeclarativeListAccessor::QDeclarativeListAccessor()
-: m_type(Invalid)
-{
-}
-
-QDeclarativeListAccessor::~QDeclarativeListAccessor()
-{
-}
-
-QVariant QDeclarativeListAccessor::list() const
-{
- return d;
-}
-
-void QDeclarativeListAccessor::setList(const QVariant &v, QDeclarativeEngine *engine)
-{
- d = v;
-
- QDeclarativeEnginePrivate *enginePrivate = engine?QDeclarativeEnginePrivate::get(engine):0;
-
- if (!d.isValid()) {
- m_type = Invalid;
- } else if (d.userType() == QVariant::StringList) {
- m_type = StringList;
- } else if (d.userType() == QMetaType::QVariantList) {
- m_type = VariantList;
- } else if (d.canConvert(QVariant::Int)) {
- m_type = Integer;
- } else if ((!enginePrivate && QDeclarativeMetaType::isQObject(d.userType())) ||
- (enginePrivate && enginePrivate->isQObject(d.userType()))) {
- QObject *data = enginePrivate?enginePrivate->toQObject(v):QDeclarativeMetaType::toQObject(v);
- d = QVariant::fromValue(data);
- m_type = Instance;
- } else if (d.userType() == qMetaTypeId<QDeclarativeListReference>()) {
- m_type = ListProperty;
- } else {
- m_type = Instance;
- }
-}
-
-int QDeclarativeListAccessor::count() const
-{
- switch(m_type) {
- case StringList:
- return qvariant_cast<QStringList>(d).count();
- case VariantList:
- return qvariant_cast<QVariantList>(d).count();
- case ListProperty:
- return ((QDeclarativeListReference *)d.constData())->count();
- case Instance:
- return 1;
- case Integer:
- return d.toInt();
- default:
- case Invalid:
- return 0;
- }
-}
-
-QVariant QDeclarativeListAccessor::at(int idx) const
-{
- Q_ASSERT(idx >= 0 && idx < count());
- switch(m_type) {
- case StringList:
- return QVariant::fromValue(qvariant_cast<QStringList>(d).at(idx));
- case VariantList:
- return qvariant_cast<QVariantList>(d).at(idx);
- case ListProperty:
- return QVariant::fromValue(((QDeclarativeListReference *)d.constData())->at(idx));
- case Instance:
- return d;
- case Integer:
- return QVariant(idx);
- default:
- case Invalid:
- return QVariant();
- }
-}
-
-bool QDeclarativeListAccessor::isValid() const
-{
- return m_type != Invalid;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativelistaccessor_p.h b/src/declarative/util/qdeclarativelistaccessor_p.h
deleted file mode 100644
index f13dca8fcf..0000000000
--- a/src/declarative/util/qdeclarativelistaccessor_p.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVELISTACCESSOR_H
-#define QDECLARATIVELISTACCESSOR_H
-
-#include <QtCore/QVariant>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeEngine;
-class Q_AUTOTEST_EXPORT QDeclarativeListAccessor
-{
-public:
- QDeclarativeListAccessor();
- ~QDeclarativeListAccessor();
-
- QVariant list() const;
- void setList(const QVariant &, QDeclarativeEngine * = 0);
-
- bool isValid() const;
-
- int count() const;
- QVariant at(int) const;
-
- enum Type { Invalid, StringList, VariantList, ListProperty, Instance, Integer };
- Type type() const { return m_type; }
-
-private:
- Type m_type;
- QVariant d;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDECLARATIVELISTACCESSOR_H
diff --git a/src/declarative/util/qdeclarativelistcompositor.cpp b/src/declarative/util/qdeclarativelistcompositor.cpp
deleted file mode 100644
index d73d76e386..0000000000
--- a/src/declarative/util/qdeclarativelistcompositor.cpp
+++ /dev/null
@@ -1,1203 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativelistcompositor_p.h"
-
-#include <QtCore/qvarlengtharray.h>
-
-//#define QT_DECLARATIVE_VERIFY_MINIMAL
-//#define QT_DECLARATIVE_VERIFY_INTEGRITY
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_DECLARATIVE_VERIFY_MINIMAL
-#define QT_DECLARATIVE_VERIFY_INTEGRITY
-static bool qt_verifyMinimal(
- const QDeclarativeListCompositor::iterator &begin,
- const QDeclarativeListCompositor::iterator &end)
-{
- bool minimal = true;
- int index = 0;
-
- for (const QDeclarativeListCompositor::Range *range = begin->next; range != *end; range = range->next, ++index) {
- if (range->previous->list == range->list
- && range->previous->flags == (range->flags & ~QDeclarativeListCompositor::AppendFlag)
- && range->previous->end() == range->index) {
- qWarning() << index << "Consecutive ranges";
- qWarning() << *range->previous;
- qWarning() << *range;
- minimal = false;
- }
- }
-
- return minimal;
-}
-
-#endif
-
-#ifdef QT_DECLARATIVE_VERIFY_INTEGRITY
-static bool qt_printInfo(const QDeclarativeListCompositor &compositor)
-{
- qWarning() << compositor;
- return true;
-}
-
-static bool qt_verifyIntegrity(
- const QDeclarativeListCompositor::iterator &begin,
- const QDeclarativeListCompositor::iterator &end,
- const QDeclarativeListCompositor::iterator &cachedIt)
-{
- bool valid = true;
-
- int index = 0;
- QDeclarativeListCompositor::iterator it;
- for (it = begin; *it != *end; *it = it->next) {
- if (it->count == 0 && !it->append()) {
- qWarning() << index << "Empty non-append range";
- valid = false;
- }
- if (it->count < 0) {
- qWarning() << index << "Negative count";
- valid = false;
- }
- if (it->list && it->flags != QDeclarativeListCompositor::CacheFlag && it->index < 0) {
- qWarning() << index <<"Negative index";
- valid = false;
- }
- if (it->previous->next != it.range) {
- qWarning() << index << "broken list: it->previous->next != it.range";
- valid = false;
- }
- if (it->next->previous != it.range) {
- qWarning() << index << "broken list: it->next->previous != it.range";
- valid = false;
- }
- if (*it == *cachedIt) {
- for (int i = 0; i < end.groupCount; ++i) {
- int groupIndex = it.index[i];
- if (cachedIt->flags & (1 << i))
- groupIndex += cachedIt.offset;
- if (groupIndex != cachedIt.index[i]) {
- qWarning() << index
- << "invalid cached index"
- << QDeclarativeListCompositor::Group(i)
- << "Expected:"
- << groupIndex
- << "Actual"
- << cachedIt.index[i]
- << cachedIt;
- valid = false;
- }
- }
- }
- it.incrementIndexes(it->count);
- ++index;
- }
-
- for (int i = 0; i < end.groupCount; ++i) {
- if (end.index[i] != it.index[i]) {
- qWarning() << "Group" << i << "count invalid. Expected:" << end.index[i] << "Actual:" << it.index[i];
- valid = false;
- }
- }
- return valid;
-}
-#endif
-
-#if defined(QT_DECLARATIVE_VERIFY_MINIMAL)
-# define QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR Q_ASSERT(!(!(qt_verifyIntegrity(iterator(m_ranges.next, 0, Default, m_groupCount), m_end, m_cacheIt) \
- && qt_verifyMinimal(iterator(m_ranges.next, 0, Default, m_groupCount), m_end)) \
- && qt_printInfo(*this)));
-#elif defined(QT_DECLARATIVE_VERIFY_INTEGRITY)
-# define QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR Q_ASSERT(!(!qt_verifyIntegrity(iterator(m_ranges.next, 0, Default, m_groupCount), m_end, m_cacheIt) \
- && qt_printInfo(*this)));
-#else
-# define QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR
-#endif
-
-//#define QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(args) qDebug() << m_end.index[1] << m_end.index[0] << Q_FUNC_INFO args;
-#define QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(args)
-
-QDeclarativeListCompositor::iterator &QDeclarativeListCompositor::iterator::operator +=(int difference)
-{
- Q_ASSERT(difference >= 0);
- while (!(range->flags & groupFlag)) {
- incrementIndexes(range->count - offset);
- offset = 0;
- range = range->next;
- }
- decrementIndexes(offset);
- offset += difference;
- while (offset >= range->count || !(range->flags & groupFlag)) {
- if (range->flags & groupFlag)
- offset -= range->count;
- incrementIndexes(range->count);
- range = range->next;
- }
- incrementIndexes(offset);
- return *this;
-}
-
-QDeclarativeListCompositor::iterator &QDeclarativeListCompositor::iterator::operator -=(int difference)
-{
- Q_ASSERT(difference >= 0);
- while (!(range->flags & groupFlag)) {
- decrementIndexes(offset);
- range = range->previous;
- offset = range->count;
- }
- decrementIndexes(offset);
- offset -= difference;
- while (offset < 0) {
- range = range->previous;
- if (range->flags & groupFlag)
- offset += range->count;
- decrementIndexes(range->count);
- }
- incrementIndexes(offset);
- return *this;
-}
-
-QDeclarativeListCompositor::insert_iterator &QDeclarativeListCompositor::insert_iterator::operator +=(int difference)
-{
- Q_ASSERT(difference >= 0);
- while (!(range->flags & groupFlag)) {
- incrementIndexes(range->count - offset);
- offset = 0;
- range = range->next;
- }
- decrementIndexes(offset);
- offset += difference;
- while (offset > range->count
- || (offset == range->count && !range->append() && offset > 0)
- || (!(range->flags & groupFlag) && offset > 0)) {
- if (range->flags & groupFlag)
- offset -= range->count;
- incrementIndexes(range->count);
- range = range->next;
- }
- incrementIndexes(offset);
- return *this;
-}
-
-QDeclarativeListCompositor::insert_iterator &QDeclarativeListCompositor::insert_iterator::operator -=(int difference)
-{
- Q_ASSERT(difference >= 0);
- while (!(range->flags & groupFlag) && range->previous->flags) {
- decrementIndexes(offset);
- range = range->previous;
- offset = (range->flags & (GroupMask | CacheFlag)) ? range->count : 0;
- }
- decrementIndexes(offset);
- offset -= difference;
- while (offset < 0) {
- range = range->previous;
- if (range->flags & groupFlag)
- offset += range->count;
- decrementIndexes(range->count);
- }
- incrementIndexes(offset);
- for (Range *previous = range->previous; offset == 0 && previous->prepend(); previous = previous->previous) {
- if (previous->append() && previous->inGroup()) {
- offset = previous->count;
- range = previous;
- } else if (!previous->inGroup()) {
- break;
- }
- }
-
- return *this;
-}
-
-QDeclarativeListCompositor::QDeclarativeListCompositor()
- : m_end(m_ranges.next, 0, Default, 2)
- , m_cacheIt(m_end)
- , m_groupCount(2)
- , m_defaultFlags(PrependFlag | DefaultFlag)
- , m_removeFlags(AppendFlag | PrependFlag | GroupMask)
-{
-}
-
-QDeclarativeListCompositor::~QDeclarativeListCompositor()
-{
- for (Range *next, *range = m_ranges.next; range != &m_ranges; range = next) {
- next = range->next;
- delete range;
- }
-}
-
-inline QDeclarativeListCompositor::Range *QDeclarativeListCompositor::insert(
- Range *before, void *list, int index, int count, int flags)
-{
- return new Range(before, list, index, count, flags);
-}
-
-inline QDeclarativeListCompositor::Range *QDeclarativeListCompositor::erase(
- Range *range)
-{
- Range *next = range->next;
- next->previous = range->previous;
- next->previous->next = range->next;
- delete range;
- return next;
-}
-
-void QDeclarativeListCompositor::setGroupCount(int count)
-{
- m_groupCount = count;
- m_end = iterator(&m_ranges, 0, Default, m_groupCount);
- m_cacheIt = m_end;
-}
-
-int QDeclarativeListCompositor::count(Group group) const
-{
- return m_end.index[group];
-}
-
-QDeclarativeListCompositor::iterator QDeclarativeListCompositor::find(Group group, int index)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< group << index)
- Q_ASSERT(index >=0 && index < count(group));
- if (m_cacheIt == m_end) {
- m_cacheIt = iterator(m_ranges.next, 0, group, m_groupCount);
- m_cacheIt += index;
- } else {
- const int offset = index - m_cacheIt.index[group];
- m_cacheIt.setGroup(group);
- if (offset > 0) {
- m_cacheIt += offset;
- } else if (offset < 0) {
- m_cacheIt -= -offset;
- } else if (offset == 0) {
- m_cacheIt -= 0;
- m_cacheIt += 0;
- }
- }
- Q_ASSERT(m_cacheIt.index[group] == index);
- Q_ASSERT(m_cacheIt->inGroup(group));
- QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR
- return m_cacheIt;
-}
-
-QDeclarativeListCompositor::iterator QDeclarativeListCompositor::find(Group group, int index) const
-{
- return const_cast<QDeclarativeListCompositor *>(this)->find(group, index);
-}
-
-QDeclarativeListCompositor::insert_iterator QDeclarativeListCompositor::findInsertPosition(Group group, int index)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< group << index)
- Q_ASSERT(index >=0 && index <= count(group));
- insert_iterator it;
- if (m_cacheIt == m_end) {
- it = iterator(m_ranges.next, 0, group, m_groupCount);
- it += index;
- } else {
- const int offset = index - m_cacheIt.index[group];
- it = m_cacheIt;
- it.setGroup(group);
- if (offset > 0) {
- it += offset;
- } else if (offset < 0) {
- it -= -offset;
- } else if (offset == 0) {
- it -= 0;
- it += 0;
- }
- }
- Q_ASSERT(it.index[group] == index);
- return it;
-}
-
-QDeclarativeListCompositor::iterator QDeclarativeListCompositor::begin(Group group)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< group)
- m_cacheIt = iterator(m_ranges.next, 0, group, m_groupCount);
- m_cacheIt += 0;
- return m_cacheIt;
-}
-
-void QDeclarativeListCompositor::append(
- void *list, int index, int count, int flags, QVector<Insert> *inserts)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< list << index << count << flags)
- insert(m_end, list, index, count, flags, inserts);
-}
-
-void QDeclarativeListCompositor::insert(
- Group group, int before, void *list, int index, int count, int flags, QVector<Insert> *inserts)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< group << before << list << index << count << flags)
- insert(findInsertPosition(group, before), list, index, count, flags, inserts);
-}
-
-QDeclarativeListCompositor::iterator QDeclarativeListCompositor::insert(
- iterator before, void *list, int index, int count, int flags, QVector<Insert> *inserts)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< before << list << index << count << flags)
- if (inserts) {
- inserts->append(Insert(before, count, flags & GroupMask));
- }
- if (before.offset > 0) {
- *before = insert(
- *before, before->list, before->index, before.offset, before->flags & ~AppendFlag)->next;
- before->index += before.offset;
- before->count -= before.offset;
- before.offset = 0;
- }
-
- if (!(flags & AppendFlag) && *before != m_ranges.next
- && before->previous->list == list
- && before->previous->flags == flags
- && (!list || before->previous->end() == index)) {
- before->previous->count += count;
- before.incrementIndexes(count, flags);
- } else {
- *before = insert(*before, list, index, count, flags);
- before.offset = 0;
- }
-
- if (!(flags & AppendFlag) && before->next != &m_ranges
- && before->list == before->next->list
- && before->flags == before->next->flags
- && (!list || before->end() == before->next->index)) {
- before->next->index = before->index;
- before->next->count += before->count;
- *before = erase(*before);
- }
-
- m_end.incrementIndexes(count, flags);
- m_cacheIt = before;
- QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR
- return before;
-}
-
-void QDeclarativeListCompositor::setFlags(
- Group group, int index, int count, int flags, QVector<Insert> *inserts)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< group << index << count << flags)
- setFlags(find(group, index), count, flags, inserts);
-}
-
-void QDeclarativeListCompositor::setFlags(
- iterator from, int count, int flags, QVector<Insert> *inserts)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< from << count << flags)
- if (!flags || !count)
- return;
-
- if (from.offset > 0) {
- *from = insert(*from, from->list, from->index, from.offset, from->flags & ~AppendFlag)->next;
- from->index += from.offset;
- from->count -= from.offset;
- from.offset = 0;
- }
-
- for (; count > 0; *from = from->next) {
- if (from != from.group) {
- from.incrementIndexes(from->count);
- continue;
- }
- const int difference = qMin(count, from->count);
- count -= difference;
-
- const int insertFlags = ~from->flags & flags;
- const int setFlags = (from->flags | flags) & ~AppendFlag;
- if (insertFlags && inserts)
- inserts->append(Insert(from, difference, insertFlags | (from->flags & CacheFlag)));
- m_end.incrementIndexes(difference, insertFlags);
- from.incrementIndexes(difference, setFlags);
-
- if (from->previous != &m_ranges
- && from->previous->list == from->list
- && (!from->list || from->previous->end() == from->index)
- && from->previous->flags == setFlags) {
- from->previous->count += difference;
- from->index += difference;
- from->count -= difference;
- if (from->count == 0) {
- if (from->append())
- from->previous->flags |= AppendFlag;
- *from = erase(*from)->previous;
- continue;
- } else {
- break;
- }
- } else if (!insertFlags) {
- from.incrementIndexes(from->count - difference);
- continue;
- } else if (difference < from->count) {
- *from = insert(*from, from->list, from->index, difference, setFlags)->next;
- from->index += difference;
- from->count -= difference;
- } else {
- from->flags |= flags;
- continue;
- }
- from.incrementIndexes(from->count);
- }
-
- if (from->previous != &m_ranges
- && from->previous->list == from->list
- && (!from->list || from->previous->end() == from->index)
- && from->previous->flags == (from->flags & ~AppendFlag)) {
- from.offset = from->previous->count;
- from->previous->count += from->count;
- from->previous->flags = from->flags;
- *from = erase(*from)->previous;
- }
- m_cacheIt = from;
- QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR
-}
-
-void QDeclarativeListCompositor::clearFlags(
- Group group, int index, int count, int flags, QVector<Remove> *removes)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< group << index << count << flags)
- clearFlags(find(group, index), count, flags, removes);
-}
-
-void QDeclarativeListCompositor::clearFlags(
- iterator from, int count, int flags, QVector<Remove> *removes)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< from << count << flags)
- if (!flags || !count)
- return;
-
- const bool clearCache = flags & CacheFlag;
-
- if (from.offset > 0) {
- *from = insert(*from, from->list, from->index, from.offset, from->flags & ~AppendFlag)->next;
- from->index += from.offset;
- from->count -= from.offset;
- from.offset = 0;
- }
-
- for (; count > 0; *from = from->next) {
- if (from != from.group) {
- from.incrementIndexes(from->count);
- continue;
- }
- const int difference = qMin(count, from->count);
- count -= difference;
-
- const int removeFlags = from->flags & flags & ~(AppendFlag | PrependFlag);
- const int clearedFlags = from->flags & ~(flags | AppendFlag);
- if (removeFlags && removes) {
- const int maskedFlags = clearCache
- ? (removeFlags & ~CacheFlag)
- : (removeFlags | (from->flags & CacheFlag));
- if (maskedFlags)
- removes->append(Remove(from, difference, maskedFlags));
- }
- m_end.decrementIndexes(difference, removeFlags);
- from.incrementIndexes(difference, clearedFlags);
-
- if (from->previous != &m_ranges
- && from->previous->list == from->list
- && (!from->list || clearedFlags == CacheFlag || from->previous->end() == from->index)
- && from->previous->flags == clearedFlags) {
- from->previous->count += difference;
- from->index += difference;
- from->count -= difference;
- if (from->count == 0) {
- if (from->append())
- from->previous->flags |= AppendFlag;
- *from = erase(*from)->previous;
- } else {
- from.incrementIndexes(from->count);
- }
- } else if (difference < from->count) {
- if (clearedFlags)
- *from = insert(*from, from->list, from->index, difference, clearedFlags)->next;
- from->index += difference;
- from->count -= difference;
- from.incrementIndexes(from->count);
- } else if (clearedFlags) {
- from->flags &= ~flags;
- } else {
- *from = erase(*from)->previous;
- }
- }
-
- if (*from != &m_ranges && from->previous != &m_ranges
- && from->previous->list == from->list
- && (!from->list || from->previous->end() == from->index)
- && from->previous->flags == (from->flags & ~AppendFlag)) {
- from.offset = from->previous->count;
- from->previous->count += from->count;
- from->previous->flags = from->flags;
- *from = erase(*from)->previous;
- }
- m_cacheIt = from;
- QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR
-}
-
-void QDeclarativeListCompositor::removeList(void *list, QVector<Remove> *removes, bool destroyed)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< list << destroyed)
- for (iterator it(m_ranges.next, 0, Default, m_groupCount); *it != &m_ranges; *it = it->next) {
- if (it->list == list) {
- const int flags = it->flags & (GroupMask | CacheFlag);
- if (flags) {
- removes->append(Remove(it, it->count, flags));
- m_end.decrementIndexes(it->count, flags);
- }
- if (destroyed)
- it->list = 0;
- if (it->inCache()) {
- it->flags = CacheFlag;
- it.cacheIndex += it->count;
- } else {
- *it = erase(*it)->previous;
- }
- } else {
- it.incrementIndexes(it->count);
- }
- }
- m_cacheIt = m_end;
- QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR
-}
-
-bool QDeclarativeListCompositor::verifyMoveTo(
- Group fromGroup, int from, Group toGroup, int to, int count) const
-{
- if (fromGroup != toGroup) {
- // determine how many items from the destination group intersect with the source group.
- iterator fromIt = find(fromGroup, from);
-
- int intersectingCount = 0;
-
- for (; count > 0; *fromIt = fromIt->next) {
- if (*fromIt == &m_ranges)
- return false;
- if (!fromIt->inGroup(fromGroup))
- continue;
- if (fromIt->inGroup(toGroup))
- intersectingCount += qMin(count, fromIt->count - fromIt.offset);
- count -= fromIt->count - fromIt.offset;
- fromIt.offset = 0;
- }
- count = intersectingCount;
- }
-
- return to >= 0 && to + count <= m_end.index[toGroup];
-}
-
-void QDeclarativeListCompositor::move(
- Group fromGroup,
- int from,
- Group toGroup,
- int to,
- int count,
- QVector<Remove> *removes,
- QVector<Insert> *inserts)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< fromGroup << from << toGroup << to << count)
- Q_ASSERT(count != 0);
- Q_ASSERT(from >=0 && from + count <= m_end.index[toGroup]);
- Q_ASSERT(verifyMoveTo(fromGroup, from, toGroup, to, count));
-
- iterator fromIt = find(fromGroup, from);
- if (fromIt.offset > 0) {
- *fromIt = insert(
- *fromIt, fromIt->list, fromIt->index, fromIt.offset, fromIt->flags & ~AppendFlag)->next;
- fromIt->index += fromIt.offset;
- fromIt->count -= fromIt.offset;
- fromIt.offset = 0;
- }
-
- Range movedFlags;
- for (int moveId = 0; count > 0;) {
- if (fromIt != fromIt.group) {
- fromIt.incrementIndexes(fromIt->count);
- *fromIt = fromIt->next;
- continue;
- }
- int difference = qMin(count, fromIt->count);
-
- new Range(
- &movedFlags,
- fromIt->list,
- fromIt->index,
- difference,
- fromIt->flags & ~(PrependFlag | AppendFlag));
- if (removes)
- removes->append(Remove(fromIt, difference, fromIt->flags, moveId++));
- count -= difference;
- fromIt->count -= difference;
-
- int removeIndex = fromIt->index;
- if (fromIt->prepend()
- && fromIt->previous != &m_ranges
- && fromIt->previous->flags == PrependFlag
- && fromIt->previous->list == fromIt->list
- && fromIt->previous->end() == fromIt->index) {
- fromIt->previous->count += difference;
- } else if (fromIt->prepend()) {
- *fromIt = insert(*fromIt, fromIt->list, removeIndex, difference, PrependFlag)->next;
- }
- fromIt->index += difference;
-
- if (fromIt->count == 0) {
- if (fromIt->append())
- fromIt->previous->flags |= AppendFlag;
- *fromIt = erase(*fromIt);
-
- if (*fromIt != m_ranges.next && fromIt->flags == PrependFlag
- && fromIt->previous != &m_ranges
- && fromIt->previous->flags == PrependFlag
- && fromIt->previous->list == fromIt->list
- && fromIt->previous->end() == fromIt->index) {
- fromIt.incrementIndexes(fromIt->count);
- fromIt->previous->count += fromIt->count;
- *fromIt = erase(*fromIt);
- }
- } else if (count > 0) {
- *fromIt = fromIt->next;
- }
- }
-
- if (*fromIt != m_ranges.next
- && *fromIt != &m_ranges
- && fromIt->previous->list == fromIt->list
- && (!fromIt->list || fromIt->previous->end() == fromIt->index)
- && fromIt->previous->flags == (fromIt->flags & ~AppendFlag)) {
- if (fromIt == fromIt.group)
- fromIt.offset = fromIt->previous->count;
- fromIt.offset = fromIt->previous->count;
- fromIt->previous->count += fromIt->count;
- fromIt->previous->flags = fromIt->flags;
- *fromIt = erase(*fromIt)->previous;
- }
-
- insert_iterator toIt = fromIt;
- toIt.setGroup(toGroup);
- const int difference = to - toIt.index[toGroup];
- if (difference > 0)
- toIt += difference;
- else
- toIt -= -difference;
-
- if (toIt.offset > 0) {
- *toIt = insert(*toIt, toIt->list, toIt->index, toIt.offset, toIt->flags & ~AppendFlag)->next;
- toIt->index += toIt.offset;
- toIt->count -= toIt.offset;
- toIt.offset = 0;
- }
-
- for (Range *range = movedFlags.previous; range != &movedFlags; range = range->previous) {
- if (*toIt != &m_ranges
- && range->list == toIt->list
- && (!range->list || range->end() == toIt->index)
- && range->flags == (toIt->flags & ~AppendFlag)) {
- toIt->index -= range->count;
- toIt->count += range->count;
- } else {
- *toIt = insert(*toIt, range->list, range->index, range->count, range->flags);
- }
- }
-
- if (*toIt != m_ranges.next
- && toIt->previous->list == toIt->list
- && (!toIt->list || (toIt->previous->end() == toIt->index && toIt->previous->flags == (toIt->flags & ~AppendFlag)))) {
- toIt.offset = toIt->previous->count;
- toIt->previous->count += toIt->count;
- toIt->previous->flags = toIt->flags;
- *toIt = erase(*toIt)->previous;
- }
- Insert insert(toIt, 0, 0, 0);
- for (Range *next, *range = movedFlags.next; range != &movedFlags; range = next) {
- insert.count = range->count;
- insert.flags = range->flags;
- if (inserts)
- inserts->append(insert);
- for (int i = 0; i < m_groupCount; ++i) {
- if (insert.inGroup(i))
- insert.index[i] += range->count;
- }
- ++insert.moveId;
- next = range->next;
- delete range;
- }
-
- m_cacheIt = toIt;
- QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR
-}
-
-void QDeclarativeListCompositor::clear()
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR( )
- for (Range *range = m_ranges.next; range != &m_ranges; range = erase(range)) {}
- m_end = iterator(m_ranges.next, 0, Default, m_groupCount);
- m_cacheIt = m_end;
-}
-
-void QDeclarativeListCompositor::listItemsInserted(
- QVector<Insert> *translatedInsertions,
- void *list,
- const QVector<QDeclarativeChangeSet::Insert> &insertions,
- const QVector<MovedFlags> *movedFlags)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< list << insertions)
- for (iterator it(m_ranges.next, 0, Default, m_groupCount); *it != &m_ranges; *it = it->next) {
- if (it->list != list || it->flags == CacheFlag) {
- it.incrementIndexes(it->count);
- continue;
- } else if (it->flags & MovedFlag) {
- it->flags &= ~MovedFlag;
- it.incrementIndexes(it->count);
- continue;
- }
- foreach (const QDeclarativeChangeSet::Insert &insertion, insertions) {
- int offset = insertion.index - it->index;
- if ((offset > 0 && offset < it->count)
- || (offset == 0 && it->prepend())
- || (offset == it->count && it->append())) {
- if (it->prepend()) {
- int flags = m_defaultFlags;
- if (insertion.isMove()) {
- for (QVector<MovedFlags>::const_iterator move = movedFlags->begin();
- move != movedFlags->end();
- ++move) {
- if (move->moveId == insertion.moveId) {
- flags = move->flags;
- break;
- }
- }
- }
- if (flags & ~(AppendFlag | PrependFlag)) {
- Insert translatedInsert(it, insertion.count, flags, insertion.moveId);
- for (int i = 0; i < m_groupCount; ++i) {
- if (it->inGroup(i))
- translatedInsert.index[i] += offset;
- }
- translatedInsertions->append(translatedInsert);
- }
- if ((it->flags & ~AppendFlag) == flags) {
- it->count += insertion.count;
- } else if (offset == 0
- && it->previous != &m_ranges
- && it->previous->list == list
- && it->previous->end() == insertion.index
- && it->previous->flags == flags) {
- it->previous->count += insertion.count;
- it->index += insertion.count;
- it.incrementIndexes(insertion.count);
- } else {
- if (offset > 0) {
- it.incrementIndexes(offset);
- *it = insert(*it, it->list, it->index, offset, it->flags & ~AppendFlag)->next;
- }
- *it = insert(*it, it->list, insertion.index, insertion.count, flags)->next;
- it.incrementIndexes(insertion.count, flags);
- it->index += offset + insertion.count;
- it->count -= offset;
- }
- m_end.incrementIndexes(insertion.count, flags);
- } else {
- if (offset > 0) {
- *it = insert(*it, it->list, it->index, offset, it->flags)->next;
- it->index += offset;
- it->count -= offset;
- }
- it->index += insertion.count;
- }
- } else if (offset <= 0) {
- it->index += insertion.count;
- }
- }
- it.incrementIndexes(it->count);
- }
- m_cacheIt = m_end;
- QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR
-}
-
-void QDeclarativeListCompositor::listItemsInserted(
- void *list, int index, int count, QVector<Insert> *translatedInsertions)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< list << index << count)
- Q_ASSERT(count > 0);
-
- QVector<QDeclarativeChangeSet::Insert> insertions;
- insertions.append(QDeclarativeChangeSet::Insert(index, count));
-
- listItemsInserted(translatedInsertions, list, insertions);
-}
-
-void QDeclarativeListCompositor::listItemsRemoved(
- QVector<Remove> *translatedRemovals,
- void *list,
- QVector<QDeclarativeChangeSet::Remove> *removals,
- QVector<QDeclarativeChangeSet::Insert> *insertions,
- QVector<MovedFlags> *movedFlags, int moveId)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< list << *removals)
-
- for (iterator it(m_ranges.next, 0, Default, m_groupCount);
- *it != &m_ranges && !removals->isEmpty();
- *it = it->next) {
- if (it->list != list || it->flags == CacheFlag) {
- it.incrementIndexes(it->count);
- continue;
- }
- bool removed = false;
- for (QVector<QDeclarativeChangeSet::Remove>::iterator removal = removals->begin();
- !removed && removal != removals->end();
- ++removal) {
- int relativeIndex = removal->index - it->index;
- int itemsRemoved = removal->count;
- if (relativeIndex + removal->count > 0 && relativeIndex < it->count) {
- const int offset = qMax(0, relativeIndex);
- int removeCount = qMin(it->count, relativeIndex + removal->count) - offset;
- it->count -= removeCount;
- int removeFlags = it->flags & m_removeFlags;
- Remove translatedRemoval(it, removeCount, it->flags);
- for (int i = 0; i < m_groupCount; ++i) {
- if (it->inGroup(i))
- translatedRemoval.index[i] += offset;
- }
- if (removal->isMove()) {
- QVector<QDeclarativeChangeSet::Insert>::iterator insertion = insertions->begin();
- for (; insertion != insertions->end() && insertion->moveId != removal->moveId;
- ++insertion) {}
- Q_ASSERT(insertion != insertions->end());
- Q_ASSERT(insertion->count == removal->count);
-
- if (relativeIndex < 0) {
- int splitMoveId = ++moveId;
- removal = removals->insert(removal, QDeclarativeChangeSet::Remove(
- removal->index, -relativeIndex, splitMoveId));
- ++removal;
- removal->count -= -relativeIndex;
- insertion = insertions->insert(insertion, QDeclarativeChangeSet::Insert(
- insertion->index, -relativeIndex, splitMoveId));
- ++insertion;
- insertion->index += -relativeIndex;
- insertion->count -= -relativeIndex;
- }
-
- if (it->prepend()) {
- removeFlags |= it->flags & CacheFlag;
- translatedRemoval.moveId = ++moveId;
- movedFlags->append(MovedFlags(moveId, it->flags & ~AppendFlag));
-
- removal = removals->insert(removal, QDeclarativeChangeSet::Remove(
- removal->index, removeCount, translatedRemoval.moveId));
- ++removal;
- insertion = insertions->insert(insertion, QDeclarativeChangeSet::Insert(
- insertion->index, removeCount, translatedRemoval.moveId));
- ++insertion;
-
- removal->count -= removeCount;
- insertion->index += removeCount;
- insertion->count -= removeCount;
- if (removal->count == 0) {
- removal = removals->erase(removal);
- insertion = insertions->erase(insertion);
- --removal;
- --insertion;
- }
- } else {
- if (offset > 0) {
- *it = insert(*it, it->list, it->index, offset, it->flags & ~AppendFlag)->next;
- it->index += offset;
- it->count -= offset;
- it.incrementIndexes(offset);
- }
- if (it->previous != &m_ranges
- && it->previous->list == it->list
- && it->end() == insertion->index
- && it->previous->flags == (it->flags | MovedFlag)) {
- it->previous->count += removeCount;
- } else {
- *it = insert(*it, it->list, insertion->index, removeCount, it->flags | MovedFlag)->next;
- }
- translatedRemoval.flags = 0;
- removeFlags = 0;
- }
- } else if (it->inCache()) {
- if (offset > 0) {
- *it = insert(*it, it->list, it->index, offset, it->flags & ~AppendFlag)->next;
- it->index += offset;
- it->count -= offset;
- it.incrementIndexes(offset);
- }
- if (it->previous != &m_ranges
- && it->previous->list == it->list
- && it->previous->flags == CacheFlag) {
- it->previous->count += removeCount;
- } else {
- *it = insert(*it, it->list, -1, removeCount, CacheFlag)->next;
- }
- it.index[Cache] += removeCount;
- }
- if (removeFlags & GroupMask)
- translatedRemovals->append(translatedRemoval);
- m_end.decrementIndexes(removeCount, removeFlags);
- if (it->count == 0 && !it->append()) {
- *it = erase(*it)->previous;
- removed = true;
- } else if (relativeIndex <= 0) {
- it->index = removal->index;
- }
- } else if (relativeIndex < 0) {
- it->index -= itemsRemoved;
-
- if (it->previous != &m_ranges
- && it->previous->list == it->list
- && it->previous->end() == it->index
- && it->previous->flags == (it->flags & ~AppendFlag)) {
- it->previous->count += it->count;
- it->previous->flags = it->flags;
- it.incrementIndexes(it->count);
- *it = erase(*it);
- removed = true;
- }
- }
- }
- if (it->flags == CacheFlag && it->next->flags == CacheFlag && it->next->list == it->list) {
- it.index[Cache] += it->next->count;
- it->count += it->next->count;
- erase(it->next);
- } else if (!removed) {
- it.incrementIndexes(it->count);
- }
- }
- m_cacheIt = m_end;
- QT_DECLARATIVE_VERIFY_LISTCOMPOSITOR
-}
-
-void QDeclarativeListCompositor::listItemsRemoved(
- void *list, int index, int count, QVector<Remove> *translatedRemovals)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< list << index << count)
- Q_ASSERT(count >= 0);
-
- QVector<QDeclarativeChangeSet::Remove> removals;
- removals.append(QDeclarativeChangeSet::Remove(index, count));
- listItemsRemoved(translatedRemovals, list, &removals, 0, 0, 0);
-}
-
-void QDeclarativeListCompositor::listItemsMoved(
- void *list,
- int from,
- int to,
- int count,
- QVector<Remove> *translatedRemovals,
- QVector<Insert> *translatedInsertions)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< list << from << to << count)
- Q_ASSERT(count >= 0);
-
- QVector<QDeclarativeChangeSet::Remove> removals;
- QVector<QDeclarativeChangeSet::Insert> insertions;
- QVector<MovedFlags> movedFlags;
- removals.append(QDeclarativeChangeSet::Remove(from, count, 0));
- insertions.append(QDeclarativeChangeSet::Insert(to, count, 0));
-
- listItemsRemoved(translatedRemovals, list, &removals, &insertions, &movedFlags, 0);
- listItemsInserted(translatedInsertions, list, insertions, &movedFlags);
-}
-
-void QDeclarativeListCompositor::listItemsChanged(
- QVector<Change> *translatedChanges,
- void *list,
- const QVector<QDeclarativeChangeSet::Change> &changes)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< list << changes)
- for (iterator it(m_ranges.next, 0, Default, m_groupCount); *it != &m_ranges; *it = it->next) {
- if (it->list != list || it->flags == CacheFlag) {
- it.incrementIndexes(it->count);
- continue;
- } else if (!it->inGroup()) {
- continue;
- }
- foreach (const QDeclarativeChangeSet::Change &change, changes) {
- const int offset = change.index - it->index;
- if (offset + change.count > 0 && offset < it->count) {
- const int changeOffset = qMax(0, offset);
- const int changeCount = qMin(it->count, offset + change.count) - changeOffset;
-
- Change translatedChange(it, changeCount, it->flags);
- for (int i = 0; i < m_groupCount; ++i) {
- if (it->inGroup(i))
- translatedChange.index[i] += changeOffset;
- }
- translatedChanges->append(translatedChange);
- }
- }
- it.incrementIndexes(it->count);
- }
-}
-
-void QDeclarativeListCompositor::listItemsChanged(
- void *list, int index, int count, QVector<Change> *translatedChanges)
-{
- QT_DECLARATIVE_TRACE_LISTCOMPOSITOR(<< list << index << count)
- Q_ASSERT(count >= 0);
- QVector<QDeclarativeChangeSet::Change> changes;
- changes.append(QDeclarativeChangeSet::Change(index, count));
- listItemsChanged(translatedChanges, list, changes);
-}
-
-void QDeclarativeListCompositor::listChanged(
- void *list,
- const QDeclarativeChangeSet &changeSet,
- QVector<Remove> *translatedRemovals,
- QVector<Insert> *translatedInsertions,
- QVector<Change> *translatedChanges)
-{
- QVector<QDeclarativeChangeSet::Remove> removals = changeSet.removes();
- QVector<QDeclarativeChangeSet::Insert> insertions = changeSet.inserts();
- QVector<MovedFlags> movedFlags;
- listItemsRemoved(translatedRemovals, list, &removals, &insertions, &movedFlags, changeSet.moveCounter());
- listItemsInserted(translatedInsertions, list, insertions, &movedFlags);
- listItemsChanged(translatedChanges, list, changeSet.changes());
-}
-
-void QDeclarativeListCompositor::transition(
- Group from,
- Group to,
- QVector<QDeclarativeChangeSet::Remove> *removes,
- QVector<QDeclarativeChangeSet::Insert> *inserts)
-{
- int removeCount = 0;
- for (iterator it(m_ranges.next, 0, Default, m_groupCount); *it != &m_ranges; *it = it->next) {
- if (it == from && it != to) {
- removes->append(QDeclarativeChangeSet::Remove(it.index[from]- removeCount, it->count));
- removeCount += it->count;
- } else if (it != from && it == to) {
- inserts->append(QDeclarativeChangeSet::Insert(it.index[to], it->count));
- }
- it.incrementIndexes(it->count);
- }
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::Group &group)
-{
- switch (group) {
- case QDeclarativeListCompositor::Cache: return debug << "Cache";
- case QDeclarativeListCompositor::Default: return debug << "Default";
- default: return (debug.nospace() << "Group" << int(group)).space();
- }
-
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::Range &range)
-{
- (debug.nospace()
- << "Range("
- << range.list) << " "
- << range.index << " "
- << range.count << " "
- << (range.append() ? "A" : "0")
- << (range.prepend() ? "P" : "0");
- for (int i = QDeclarativeListCompositor::MaximumGroupCount - 1; i >= 2; --i)
- debug << (range.inGroup(i) ? "1" : "0");
- return (debug
- << (range.inGroup(QDeclarativeListCompositor::Default) ? "D" : "0")
- << (range.inGroup(QDeclarativeListCompositor::Cache) ? "C" : "0"));
-}
-
-static void qt_print_indexes(QDebug &debug, int count, const int *indexes)
-{
- for (int i = count - 1; i >= 0; --i)
- debug << indexes[i];
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::iterator &it)
-{
- (debug.nospace() << "iterator(" << it.group).space() << "offset:" << it.offset;
- qt_print_indexes(debug, it.groupCount, it.index);
- return ((debug << **it).nospace() << ")").space();
-}
-
-static QDebug qt_print_change(QDebug debug, const char *name, const QDeclarativeListCompositor::Change &change)
-{
- debug.nospace() << name << "(" << change.moveId << " " << change.count << " ";
- for (int i = QDeclarativeListCompositor::MaximumGroupCount - 1; i >= 2; --i)
- debug << (change.inGroup(i) ? "1" : "0");
- debug << (change.inGroup(QDeclarativeListCompositor::Default) ? "D" : "0")
- << (change.inGroup(QDeclarativeListCompositor::Cache) ? "C" : "0");
- int i = QDeclarativeListCompositor::MaximumGroupCount - 1;
- for (; i >= 0 && !change.inGroup(i); --i) {}
- for (; i >= 0; --i)
- debug << " " << change.index[i];
- return (debug << ")").maybeSpace();
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::Change &change)
-{
- return qt_print_change(debug, "Change", change);
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::Remove &remove)
-{
- return qt_print_change(debug, "Remove", remove);
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::Insert &insert)
-{
- return qt_print_change(debug, "Insert", insert);
-}
-
-QDebug operator <<(QDebug debug, const QDeclarativeListCompositor &list)
-{
- int indexes[QDeclarativeListCompositor::MaximumGroupCount];
- for (int i = 0; i < QDeclarativeListCompositor::MaximumGroupCount; ++i)
- indexes[i] = 0;
- debug.nospace() << "QDeclarativeListCompositor(";
- qt_print_indexes(debug, list.m_groupCount, list.m_end.index);
- for (QDeclarativeListCompositor::Range *range = list.m_ranges.next; range != &list.m_ranges; range = range->next) {
- (debug << "\n").space();
- qt_print_indexes(debug, list.m_groupCount, indexes);
- debug << " " << *range;
-
- for (int i = 0; i < list.m_groupCount; ++i) {
- if (range->inGroup(i))
- indexes[i] += range->count;
- }
- }
- return (debug << ")").maybeSpace();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativelistcompositor_p.h b/src/declarative/util/qdeclarativelistcompositor_p.h
deleted file mode 100644
index c808f6fe80..0000000000
--- a/src/declarative/util/qdeclarativelistcompositor_p.h
+++ /dev/null
@@ -1,371 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVELISTCOMPOSITOR_P_H
-#define QDECLARATIVELISTCOMPOSITOR_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 <QtCore/qglobal.h>
-#include <QtCore/qvector.h>
-
-#include <private/qdeclarativechangeset_p.h>
-
-#include <QtCore/qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-class Q_AUTOTEST_EXPORT QDeclarativeListCompositor
-{
-public:
- enum { MaximumGroupCount = 11 };
-
- enum Group
- {
- Cache = 0,
- Default = 1,
- Persisted = 2
- };
-
- enum Flag
- {
- CacheFlag = 0x000001,
- DefaultFlag = 0x000002,
- PersistedFlag = 0x000004,
- GroupMask = 0x00FFFE,
- PrependFlag = 0x100000,
- AppendFlag = 0x200000,
- MovedFlag = 0x400000
- };
-
- class Range
- {
- public:
- Range() : next(this), previous(this), list(0), index(0), count(0), flags(0) {}
- Range(Range *next, void *list, int index, int count, uint flags)
- : next(next), previous(next->previous), list(list), index(index), count(count), flags(flags) {
- next->previous = this; previous->next = this; }
-
- Range *next;
- Range *previous;
- void *list;
- int index;
- int count;
- int flags;
-
- inline int start() const { return index; }
- inline int end() const { return index + count; }
-
- inline int groups() const { return flags & GroupMask; }
-
- inline bool inGroup() const { return flags & GroupMask; }
- inline bool inCache() const { return flags & CacheFlag; }
- inline bool inGroup(int group) const { return flags & (1 << group); }
-
- inline bool prepend() const { return flags & PrependFlag; }
- inline bool append() const { return flags & AppendFlag; }
- };
-
- class Q_AUTOTEST_EXPORT iterator
- {
- public:
- inline iterator();
- inline iterator(const iterator &it);
- inline iterator(Range *range, int offset, Group group, int groupCount);
- inline ~iterator() {}
-
- bool operator ==(const iterator &it) const { return range == it.range && offset == it.offset; }
- bool operator !=(const iterator &it) const { return range != it.range || offset != it.offset; }
-
- bool operator ==(Group group) const { return range->flags & (1 << group); }
- bool operator !=(Group group) const { return !(range->flags & (1 << group)); }
-
- Range *&operator *() { return range; }
- Range * const &operator *() const { return range; }
- Range *operator ->() { return range; }
- const Range *operator ->() const { return range; }
-
- iterator &operator +=(int difference);
- iterator &operator -=(int difference);
-
- template<typename T> T *list() const { return static_cast<T *>(range->list); }
- int modelIndex() const { return range->index + offset; }
-
- void incrementIndexes(int difference) { incrementIndexes(difference, range->flags); }
- void decrementIndexes(int difference) { decrementIndexes(difference, range->flags); }
-
- inline void incrementIndexes(int difference, int flags);
- inline void decrementIndexes(int difference, int flags);
-
- void setGroup(Group g) { group = g; groupFlag = 1 << g; }
-
- Range *range;
- int offset;
- Group group;
- int groupFlag;
- int groupCount;
- union {
- struct {
- int cacheIndex;
- };
- int index[MaximumGroupCount];
- };
- };
-
- class Q_AUTOTEST_EXPORT insert_iterator : public iterator
- {
- public:
- inline insert_iterator() {}
- inline insert_iterator(const iterator &it) : iterator(it) {}
- inline insert_iterator(Range *, int, Group, int);
- inline ~insert_iterator() {}
-
- insert_iterator &operator +=(int difference);
- insert_iterator &operator -=(int difference);
- };
-
- struct Change
- {
- inline Change() {}
- inline Change(iterator it, int count, int flags, int moveId = -1);
- int count;
- int flags;
- int moveId;
- union {
- struct {
- int cacheIndex;
- };
- int index[MaximumGroupCount];
- };
-
- inline bool isMove() const { return moveId >= 0; }
- inline bool inCache() const { return flags & CacheFlag; }
- inline bool inGroup() const { return flags & GroupMask; }
- inline bool inGroup(int group) const { return flags & (CacheFlag << group); }
-
- inline int groups() const { return flags & GroupMask; }
- };
-
- struct Insert : public Change
- {
- Insert() {}
- Insert(iterator it, int count, int flags, int moveId = -1)
- : Change(it, count, flags, moveId) {}
- };
-
- struct Remove : public Change
- {
- Remove() {}
- Remove(iterator it, int count, int flags, int moveId = -1)
- : Change(it, count, flags, moveId) {}
- };
-
- QDeclarativeListCompositor();
- ~QDeclarativeListCompositor();
-
- int defaultGroups() const { return m_defaultFlags & ~PrependFlag; }
- void setDefaultGroups(int groups) { m_defaultFlags = groups | PrependFlag; }
- void setDefaultGroup(Group group) { m_defaultFlags |= (1 << group); }
- void clearDefaultGroup(Group group) { m_defaultFlags &= ~(1 << group); }
- void setRemoveGroups(int groups) { m_removeFlags = PrependFlag | AppendFlag | groups; }
- void setGroupCount(int count);
-
- int count(Group group) const;
- iterator find(Group group, int index);
- iterator find(Group group, int index) const;
- insert_iterator findInsertPosition(Group group, int index);
-
- iterator begin(Group group);
- const iterator &end() { return m_end; }
-
- void append(void *list, int index, int count, int flags, QVector<Insert> *inserts = 0);
- void insert(Group group, int before, void *list, int index, int count, int flags, QVector<Insert> *inserts = 0);
- iterator insert(iterator before, void *list, int index, int count, int flags, QVector<Insert> *inserts = 0);
-
- void setFlags(Group group, int index, int count, int flags, QVector<Insert> *inserts = 0);
- void setFlags(iterator from, int count, int flags, QVector<Insert> *inserts = 0);
-
- void clearFlags(Group group, int index, int count, int flags, QVector<Remove> *removals = 0);
- void clearFlags(iterator from, int count, int flags, QVector<Remove> *removals = 0);
-
- void removeList(void *list, QVector<Remove> *removals, bool destroyed);
-
- bool verifyMoveTo(Group fromGroup, int from, Group toGroup, int to, int count) const;
-
- void move(
- Group fromGroup,
- int from,
- Group toGroup,
- int to,
- int count,
- QVector<Remove> *removals = 0,
- QVector<Insert> *inserts = 0);
- void clear();
-
- void listItemsInserted(void *list, int index, int count, QVector<Insert> *inserts);
- void listItemsRemoved(void *list, int index, int count, QVector<Remove> *removals);
- void listItemsMoved(void *list, int from, int to, int count, QVector<Remove> *removals, QVector<Insert> *inserts);
- void listItemsChanged(void *list, int index, int count, QVector<Change> *changes);
- void listChanged(
- void *list,
- const QDeclarativeChangeSet &changeSet,
- QVector<Remove> *removals,
- QVector<Insert> *inserts,
- QVector<Change> *changes);
-
- void transition(
- Group from,
- Group to,
- QVector<QDeclarativeChangeSet::Remove> *removes,
- QVector<QDeclarativeChangeSet::Insert> *inserts);
-
-private:
- Range m_ranges;
- iterator m_end;
- iterator m_cacheIt;
- int m_groupCount;
- int m_defaultFlags;
- int m_removeFlags;
-
- inline Range *insert(Range *before, void *list, int index, int count, int flags);
- inline Range *erase(Range *range);
-
- struct MovedFlags
- {
- MovedFlags() {}
- MovedFlags(int moveId, int flags) : moveId(moveId), flags(flags) {}
-
- int moveId;
- int flags;
- };
-
- void listItemsRemoved(
- QVector<Remove> *translatedRemovals,
- void *list,
- QVector<QDeclarativeChangeSet::Remove> *removals,
- QVector<QDeclarativeChangeSet::Insert> *insertions = 0,
- QVector<MovedFlags> *movedFlags = 0,
- int moveId = 0);
- void listItemsInserted(
- QVector<Insert> *translatedInsertions,
- void *list,
- const QVector<QDeclarativeChangeSet::Insert> &insertions,
- const QVector<MovedFlags> *movedFlags = 0);
- void listItemsChanged(
- QVector<Change> *translatedChanges,
- void *list,
- const QVector<QDeclarativeChangeSet::Change> &changes);
-
- friend Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeListCompositor &list);
-};
-
-inline QDeclarativeListCompositor::iterator::iterator()
- : range(0), offset(0), group(Default), groupCount(0) {}
-inline QDeclarativeListCompositor::iterator::iterator(const iterator &it)
- : range(it.range)
- , offset(it.offset)
- , group(it.group)
- , groupFlag(it.groupFlag)
- , groupCount(it.groupCount)
-{
- for (int i = 0; i < groupCount; ++i)
- index[i] = it.index[i];
-}
-
-inline QDeclarativeListCompositor::iterator::iterator(
- Range *range, int offset, Group group, int groupCount)
- : range(range)
- , offset(offset)
- , group(group)
- , groupFlag(1 << group)
- , groupCount(groupCount)
-{
- for (int i = 0; i < groupCount; ++i)
- index[i] = 0;
-}
-
-inline void QDeclarativeListCompositor::iterator::incrementIndexes(int difference, int flags)
-{
- for (int i = 0; i < groupCount; ++i) {
- if (flags & (1 << i))
- index[i] += difference;
- }
-}
-
-inline void QDeclarativeListCompositor::iterator::decrementIndexes(int difference, int flags)
-{
- for (int i = 0; i < groupCount; ++i) {
- if (flags & (1 << i))
- index[i] -= difference;
- }
-}
-
-inline QDeclarativeListCompositor::insert_iterator::insert_iterator(
- Range *range, int offset, Group group, int groupCount)
- : iterator(range, offset, group, groupCount) {}
-
-inline QDeclarativeListCompositor::Change::Change(iterator it, int count, int flags, int moveId)
- : count(count), flags(flags), moveId(moveId)
-{
- for (int i = 0; i < MaximumGroupCount; ++i)
- index[i] = it.index[i];
-}
-
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::Group &group);
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::Range &range);
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::iterator &it);
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::Change &change);
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::Remove &remove);
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeListCompositor::Insert &insert);
-Q_AUTOTEST_EXPORT QDebug operator <<(QDebug debug, const QDeclarativeListCompositor &list);
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/declarative/util/qdeclarativepackage.cpp b/src/declarative/util/qdeclarativepackage.cpp
deleted file mode 100644
index 1d46574f02..0000000000
--- a/src/declarative/util/qdeclarativepackage.cpp
+++ /dev/null
@@ -1,202 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativepackage_p.h"
-
-#include <private/qobject_p.h>
-#include <private/qdeclarativeguard_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass Package QDeclarativePackage
- \inqmlmodule QtQuick 2
- \ingroup qml-working-with-data
- \brief Package provides a collection of named items.
-
- The Package class is used in conjunction with
- VisualDataModel to enable delegates with a shared context
- to be provided to multiple views.
-
- Any item within a Package may be assigned a name via the
- \l{Package::name}{Package.name} attached property.
-
- The example below creates a Package containing two named items;
- \e list and \e grid. The third element in the package (the \l Rectangle) is parented to whichever
- delegate it should appear in. This allows an item to move
- between views.
-
- \snippet examples/declarative/modelviews/package/Delegate.qml 0
-
- These named items are used as the delegates by the two views who
- reference the special \l{VisualDataModel::parts} property to select
- a model which provides the chosen delegate.
-
- \snippet examples/declarative/modelviews/package/view.qml 0
-
- \sa {declarative/modelviews/package}{Package example}, {declarative/photoviewer}{Photo Viewer example}, QtDeclarative
-*/
-
-/*!
- \qmlattachedproperty string QtQuick2::Package::name
- This attached property holds the name of an item within a Package.
-*/
-
-
-class QDeclarativePackagePrivate : public QObjectPrivate
-{
-public:
- QDeclarativePackagePrivate() {}
-
- struct DataGuard : public QDeclarativeGuard<QObject>
- {
- DataGuard(QObject *obj, QList<DataGuard> *l) : list(l) { (QDeclarativeGuard<QObject>&)*this = obj; }
- QList<DataGuard> *list;
- void objectDestroyed(QObject *) {
- // we assume priv will always be destroyed after objectDestroyed calls
- list->removeOne(*this);
- }
- };
-
- QList<DataGuard> dataList;
- static void data_append(QDeclarativeListProperty<QObject> *prop, QObject *o) {
- QList<DataGuard> *list = static_cast<QList<DataGuard> *>(prop->data);
- list->append(DataGuard(o, list));
- }
- static void data_clear(QDeclarativeListProperty<QObject> *prop) {
- QList<DataGuard> *list = static_cast<QList<DataGuard> *>(prop->data);
- list->clear();
- }
- static QObject *data_at(QDeclarativeListProperty<QObject> *prop, int index) {
- QList<DataGuard> *list = static_cast<QList<DataGuard> *>(prop->data);
- return list->at(index);
- }
- static int data_count(QDeclarativeListProperty<QObject> *prop) {
- QList<DataGuard> *list = static_cast<QList<DataGuard> *>(prop->data);
- return list->count();
- }
-};
-
-QHash<QObject *, QDeclarativePackageAttached *> QDeclarativePackageAttached::attached;
-
-QDeclarativePackageAttached::QDeclarativePackageAttached(QObject *parent)
-: QObject(parent)
-{
- attached.insert(parent, this);
-}
-
-QDeclarativePackageAttached::~QDeclarativePackageAttached()
-{
- attached.remove(parent());
-}
-
-QString QDeclarativePackageAttached::name() const
-{
- return _name;
-}
-
-void QDeclarativePackageAttached::setName(const QString &n)
-{
- _name = n;
-}
-
-QDeclarativePackage::QDeclarativePackage(QObject *parent)
- : QObject(*(new QDeclarativePackagePrivate), parent)
-{
-}
-
-QDeclarativePackage::~QDeclarativePackage()
-{
- Q_D(QDeclarativePackage);
- for (int ii = 0; ii < d->dataList.count(); ++ii) {
- QObject *obj = d->dataList.at(ii);
- obj->setParent(this);
- }
-}
-
-QDeclarativeListProperty<QObject> QDeclarativePackage::data()
-{
- Q_D(QDeclarativePackage);
- return QDeclarativeListProperty<QObject>(this, &d->dataList, QDeclarativePackagePrivate::data_append,
- QDeclarativePackagePrivate::data_count,
- QDeclarativePackagePrivate::data_at,
- QDeclarativePackagePrivate::data_clear);
-}
-
-bool QDeclarativePackage::hasPart(const QString &name)
-{
- Q_D(QDeclarativePackage);
- for (int ii = 0; ii < d->dataList.count(); ++ii) {
- QObject *obj = d->dataList.at(ii);
- QDeclarativePackageAttached *a = QDeclarativePackageAttached::attached.value(obj);
- if (a && a->name() == name)
- return true;
- }
- return false;
-}
-
-QObject *QDeclarativePackage::part(const QString &name)
-{
- Q_D(QDeclarativePackage);
- if (name.isEmpty() && !d->dataList.isEmpty())
- return d->dataList.at(0);
-
- for (int ii = 0; ii < d->dataList.count(); ++ii) {
- QObject *obj = d->dataList.at(ii);
- QDeclarativePackageAttached *a = QDeclarativePackageAttached::attached.value(obj);
- if (a && a->name() == name)
- return obj;
- }
-
- if (name == QLatin1String("default") && !d->dataList.isEmpty())
- return d->dataList.at(0);
-
- return 0;
-}
-
-QDeclarativePackageAttached *QDeclarativePackage::qmlAttachedProperties(QObject *o)
-{
- return new QDeclarativePackageAttached(o);
-}
-
-
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativepackage_p.h b/src/declarative/util/qdeclarativepackage_p.h
deleted file mode 100644
index 8ae88488d0..0000000000
--- a/src/declarative/util/qdeclarativepackage_p.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEPACKAGE_H
-#define QDECLARATIVEPACKAGE_H
-
-#include <qdeclarative.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativePackagePrivate;
-class QDeclarativePackageAttached;
-class Q_AUTOTEST_EXPORT QDeclarativePackage : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativePackage)
-
- Q_CLASSINFO("DefaultProperty", "data")
- Q_PROPERTY(QDeclarativeListProperty<QObject> data READ data)
-
-public:
- QDeclarativePackage(QObject *parent=0);
- virtual ~QDeclarativePackage();
-
- QDeclarativeListProperty<QObject> data();
-
- QObject *part(const QString & = QString());
- bool hasPart(const QString &);
-
- static QDeclarativePackageAttached *qmlAttachedProperties(QObject *);
-};
-
-class QDeclarativePackageAttached : public QObject
-{
-Q_OBJECT
-Q_PROPERTY(QString name READ name WRITE setName)
-public:
- QDeclarativePackageAttached(QObject *parent);
- virtual ~QDeclarativePackageAttached();
-
- QString name() const;
- void setName(const QString &n);
-
- static QHash<QObject *, QDeclarativePackageAttached *> attached;
-private:
- QString _name;
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativePackage)
-QML_DECLARE_TYPEINFO(QDeclarativePackage, QML_HAS_ATTACHED_PROPERTIES)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVEPACKAGE_H
diff --git a/src/declarative/util/qdeclarativepath.cpp b/src/declarative/util/qdeclarativepath.cpp
deleted file mode 100644
index 2ba7c372e2..0000000000
--- a/src/declarative/util/qdeclarativepath.cpp
+++ /dev/null
@@ -1,1484 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativepath_p.h"
-#include "qdeclarativepath_p_p.h"
-#include "qdeclarativesvgparser_p.h"
-
-#include <QSet>
-#include <QTime>
-
-#include <private/qbezier_p.h>
-#include <QtCore/qmath.h>
-#include <QtCore/qnumeric.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass PathElement QDeclarativePathElement
- \inqmlmodule QtQuick 2
- \ingroup qml-view-elements
- \brief PathElement is the base path type.
-
- This type is the base for all path types. It cannot
- be instantiated.
-
- \sa Path, PathAttribute, PathPercent, PathLine, PathQuad, PathCubic
-*/
-
-/*!
- \qmlclass Path QDeclarativePath
- \inqmlmodule QtQuick 2
- \ingroup qml-view-elements
- \brief A Path object defines a path for use by \l PathView.
-
- A Path is composed of one or more path segments - PathLine, PathQuad,
- PathCubic.
-
- The spacing of the items along the Path can be adjusted via a
- PathPercent object.
-
- PathAttribute allows named attributes with values to be defined
- along the path.
-
- \sa PathView, PathAttribute, PathPercent, PathLine, PathQuad, PathCubic
-*/
-QDeclarativePath::QDeclarativePath(QObject *parent)
- : QObject(*(new QDeclarativePathPrivate), parent)
-{
-}
-
-QDeclarativePath::~QDeclarativePath()
-{
-}
-
-/*!
- \qmlproperty real QtQuick2::Path::startX
- \qmlproperty real QtQuick2::Path::startY
- These properties hold the starting position of the path.
-*/
-qreal QDeclarativePath::startX() const
-{
- Q_D(const QDeclarativePath);
- return d->startX.isNull ? 0 : d->startX.value;
-}
-
-void QDeclarativePath::setStartX(qreal x)
-{
- Q_D(QDeclarativePath);
- if (d->startX.isValid() && qFuzzyCompare(x, d->startX))
- return;
- d->startX = x;
- emit startXChanged();
- processPath();
-}
-
-bool QDeclarativePath::hasStartX() const
-{
- Q_D(const QDeclarativePath);
- return d->startX.isValid();
-}
-
-qreal QDeclarativePath::startY() const
-{
- Q_D(const QDeclarativePath);
- return d->startY.isNull ? 0 : d->startY.value;
-}
-
-void QDeclarativePath::setStartY(qreal y)
-{
- Q_D(QDeclarativePath);
- if (d->startY.isValid() && qFuzzyCompare(y, d->startY))
- return;
- d->startY = y;
- emit startYChanged();
- processPath();
-}
-
-bool QDeclarativePath::hasStartY() const
-{
- Q_D(const QDeclarativePath);
- return d->startY.isValid();
-}
-
-/*!
- \qmlproperty bool QtQuick2::Path::closed
- This property holds whether the start and end of the path are identical.
-*/
-bool QDeclarativePath::isClosed() const
-{
- Q_D(const QDeclarativePath);
- return d->closed;
-}
-
-bool QDeclarativePath::hasEnd() const
-{
- Q_D(const QDeclarativePath);
- for (int i = d->_pathElements.count() - 1; i > -1; --i) {
- if (QDeclarativeCurve *curve = qobject_cast<QDeclarativeCurve *>(d->_pathElements.at(i))) {
- if ((!curve->hasX() && !curve->hasRelativeX()) || (!curve->hasY() && !curve->hasRelativeY()))
- return false;
- else
- return true;
- }
- }
- return hasStartX() && hasStartY();
-}
-
-/*!
- \qmlproperty list<PathElement> QtQuick2::Path::pathElements
- This property holds the objects composing the path.
-
- \default
-
- A path can contain the following path objects:
- \list
- \i \l PathLine - a straight line to a given position.
- \i \l PathQuad - a quadratic Bezier curve to a given position with a control point.
- \i \l PathCubic - a cubic Bezier curve to a given position with two control points.
- \i \l PathAttribute - an attribute at a given position in the path.
- \i \l PathPercent - a way to spread out items along various segments of the path.
- \endlist
-
- \snippet doc/src/snippets/declarative/pathview/pathattributes.qml 2
-*/
-
-QDeclarativeListProperty<QDeclarativePathElement> QDeclarativePath::pathElements()
-{
- Q_D(QDeclarativePath);
- return QDeclarativeListProperty<QDeclarativePathElement>(this, d->_pathElements);
-}
-
-void QDeclarativePath::interpolate(int idx, const QString &name, qreal value)
-{
- Q_D(QDeclarativePath);
- interpolate(d->_attributePoints, idx, name, value);
-}
-
-void QDeclarativePath::interpolate(QList<AttributePoint> &attributePoints, int idx, const QString &name, qreal value)
-{
- if (!idx)
- return;
-
- qreal lastValue = 0;
- qreal lastPercent = 0;
- int search = idx - 1;
- while(search >= 0) {
- const AttributePoint &point = attributePoints.at(search);
- if (point.values.contains(name)) {
- lastValue = point.values.value(name);
- lastPercent = point.origpercent;
- break;
- }
- --search;
- }
-
- ++search;
-
- const AttributePoint &curPoint = attributePoints.at(idx);
-
- for (int ii = search; ii < idx; ++ii) {
- AttributePoint &point = attributePoints[ii];
-
- qreal val = lastValue + (value - lastValue) * (point.origpercent - lastPercent) / (curPoint.origpercent - lastPercent);
- point.values.insert(name, val);
- }
-}
-
-void QDeclarativePath::endpoint(const QString &name)
-{
- Q_D(QDeclarativePath);
- const AttributePoint &first = d->_attributePoints.first();
- qreal val = first.values.value(name);
- for (int ii = d->_attributePoints.count() - 1; ii >= 0; ii--) {
- const AttributePoint &point = d->_attributePoints.at(ii);
- if (point.values.contains(name)) {
- for (int jj = ii + 1; jj < d->_attributePoints.count(); ++jj) {
- AttributePoint &setPoint = d->_attributePoints[jj];
- setPoint.values.insert(name, val);
- }
- return;
- }
- }
-}
-
-void QDeclarativePath::endpoint(QList<AttributePoint> &attributePoints, const QString &name)
-{
- const AttributePoint &first = attributePoints.first();
- qreal val = first.values.value(name);
- for (int ii = attributePoints.count() - 1; ii >= 0; ii--) {
- const AttributePoint &point = attributePoints.at(ii);
- if (point.values.contains(name)) {
- for (int jj = ii + 1; jj < attributePoints.count(); ++jj) {
- AttributePoint &setPoint = attributePoints[jj];
- setPoint.values.insert(name, val);
- }
- return;
- }
- }
-}
-
-static QString percentString(QLatin1String("_qfx_percent"));
-
-void QDeclarativePath::processPath()
-{
- Q_D(QDeclarativePath);
-
- if (!d->componentComplete)
- return;
-
- d->_pointCache.clear();
- d->prevBez.isValid = false;
-
- d->_path = createPath(QPointF(), QPointF(), d->_attributes, d->pathLength, d->_attributePoints, &d->closed);
-
- emit changed();
-}
-
-QPainterPath QDeclarativePath::createPath(const QPointF &startPoint, const QPointF &endPoint, const QStringList &attributes, qreal &pathLength, QList<AttributePoint> &attributePoints, bool *closed)
-{
- Q_D(QDeclarativePath);
-
- pathLength = 0;
- attributePoints.clear();
-
- if (!d->componentComplete)
- return QPainterPath();
-
- QPainterPath path;
-
- AttributePoint first;
- for (int ii = 0; ii < attributes.count(); ++ii)
- first.values[attributes.at(ii)] = 0;
- attributePoints << first;
-
- qreal startX = d->startX.isValid() ? d->startX.value : startPoint.x();
- qreal startY = d->startY.isValid() ? d->startY.value : startPoint.y();
- path.moveTo(startX, startY);
-
- bool usesPercent = false;
- int index = 0;
- foreach (QDeclarativePathElement *pathElement, d->_pathElements) {
- if (QDeclarativeCurve *curve = qobject_cast<QDeclarativeCurve *>(pathElement)) {
- QDeclarativePathData data;
- data.index = index;
- data.endPoint = endPoint;
- data.curves = d->_pathCurves;
- curve->addToPath(path, data);
- AttributePoint p;
- p.origpercent = path.length();
- attributePoints << p;
- ++index;
- } else if (QDeclarativePathAttribute *attribute = qobject_cast<QDeclarativePathAttribute *>(pathElement)) {
- AttributePoint &point = attributePoints.last();
- point.values[attribute->name()] = attribute->value();
- interpolate(attributePoints, attributePoints.count() - 1, attribute->name(), attribute->value());
- } else if (QDeclarativePathPercent *percent = qobject_cast<QDeclarativePathPercent *>(pathElement)) {
- AttributePoint &point = attributePoints.last();
- point.values[percentString] = percent->value();
- interpolate(attributePoints, attributePoints.count() - 1, percentString, percent->value());
- usesPercent = true;
- }
- }
-
- // Fixup end points
- const AttributePoint &last = attributePoints.last();
- for (int ii = 0; ii < attributes.count(); ++ii) {
- if (!last.values.contains(attributes.at(ii)))
- endpoint(attributePoints, attributes.at(ii));
- }
- if (usesPercent && !last.values.contains(percentString)) {
- d->_attributePoints.last().values[percentString] = 1;
- interpolate(d->_attributePoints.count() - 1, percentString, 1);
- }
-
-
- // Adjust percent
- qreal length = path.length();
- qreal prevpercent = 0;
- qreal prevorigpercent = 0;
- for (int ii = 0; ii < attributePoints.count(); ++ii) {
- const AttributePoint &point = attributePoints.at(ii);
- if (point.values.contains(percentString)) { //special string for QDeclarativePathPercent
- if ( ii > 0) {
- qreal scale = (attributePoints[ii].origpercent/length - prevorigpercent) /
- (point.values.value(percentString)-prevpercent);
- attributePoints[ii].scale = scale;
- }
- attributePoints[ii].origpercent /= length;
- attributePoints[ii].percent = point.values.value(percentString);
- prevorigpercent = attributePoints[ii].origpercent;
- prevpercent = attributePoints[ii].percent;
- } else {
- attributePoints[ii].origpercent /= length;
- attributePoints[ii].percent = attributePoints[ii].origpercent;
- }
- }
-
- if (closed) {
- QPointF end = path.currentPosition();
- *closed = length > 0 && startX == end.x() && startY == end.y();
- }
- pathLength = length;
-
- return path;
-}
-
-void QDeclarativePath::classBegin()
-{
- Q_D(QDeclarativePath);
- d->componentComplete = false;
-}
-
-void QDeclarativePath::componentComplete()
-{
- Q_D(QDeclarativePath);
- QSet<QString> attrs;
- d->componentComplete = true;
-
- // First gather up all the attributes
- foreach (QDeclarativePathElement *pathElement, d->_pathElements) {
- if (QDeclarativeCurve *curve =
- qobject_cast<QDeclarativeCurve *>(pathElement))
- d->_pathCurves.append(curve);
- else if (QDeclarativePathAttribute *attribute =
- qobject_cast<QDeclarativePathAttribute *>(pathElement))
- attrs.insert(attribute->name());
- }
- d->_attributes = attrs.toList();
-
- processPath();
-
- foreach (QDeclarativePathElement *pathElement, d->_pathElements)
- connect(pathElement, SIGNAL(changed()), this, SLOT(processPath()));
-}
-
-QPainterPath QDeclarativePath::path() const
-{
- Q_D(const QDeclarativePath);
- return d->_path;
-}
-
-QStringList QDeclarativePath::attributes() const
-{
- Q_D(const QDeclarativePath);
- if (!d->componentComplete) {
- QSet<QString> attrs;
-
- // First gather up all the attributes
- foreach (QDeclarativePathElement *pathElement, d->_pathElements) {
- if (QDeclarativePathAttribute *attribute =
- qobject_cast<QDeclarativePathAttribute *>(pathElement))
- attrs.insert(attribute->name());
- }
- return attrs.toList();
- }
- return d->_attributes;
-}
-
-static inline QBezier nextBezier(const QPainterPath &path, int *current, qreal *bezLength, bool reverse = false)
-{
- const int lastElement = reverse ? 0 : path.elementCount() - 1;
- const int start = reverse ? *current - 1 : *current + 1;
- for (int i=start; reverse ? i >= lastElement : i <= lastElement; reverse ? --i : ++i) {
- const QPainterPath::Element &e = path.elementAt(i);
-
- switch (e.type) {
- case QPainterPath::MoveToElement:
- break;
- case QPainterPath::LineToElement:
- {
- QLineF line(path.elementAt(i-1), e);
- *bezLength = line.length();
- QPointF a = path.elementAt(i-1);
- QPointF delta = e - a;
- *current = i;
- return QBezier::fromPoints(a, a + delta / 3, a + 2 * delta / 3, e);
- }
- case QPainterPath::CurveToElement:
- {
- QBezier b = QBezier::fromPoints(path.elementAt(i-1),
- e,
- path.elementAt(i+1),
- path.elementAt(i+2));
- *bezLength = b.length();
- *current = i;
- return b;
- }
- default:
- break;
- }
- }
- *current = lastElement;
- *bezLength = 0;
- return QBezier();
-}
-
-//derivative of the equation
-static inline qreal slopeAt(qreal t, qreal a, qreal b, qreal c, qreal d)
-{
- return 3*t*t*(d - 3*c + 3*b - a) + 6*t*(c - 2*b + a) + 3*(b - a);
-}
-
-void QDeclarativePath::createPointCache() const
-{
- Q_D(const QDeclarativePath);
- qreal pathLength = d->pathLength;
- if (pathLength <= 0 || qIsNaN(pathLength))
- return;
- // more points means less jitter between items as they move along the
- // path, but takes longer to generate
- const int points = qCeil(pathLength*5);
- const int lastElement = d->_path.elementCount() - 1;
- d->_pointCache.resize(points+1);
-
- int currElement = -1;
- qreal bezLength = 0;
- QBezier currBez = nextBezier(d->_path, &currElement, &bezLength);
- qreal currLength = bezLength;
- qreal epc = currLength / pathLength;
-
- for (int i = 0; i < d->_pointCache.size(); i++) {
- //find which set we are in
- qreal prevPercent = 0;
- qreal prevOrigPercent = 0;
- for (int ii = 0; ii < d->_attributePoints.count(); ++ii) {
- qreal percent = qreal(i)/points;
- const AttributePoint &point = d->_attributePoints.at(ii);
- if (percent < point.percent || ii == d->_attributePoints.count() - 1) { //### || is special case for very last item
- qreal elementPercent = (percent - prevPercent);
-
- qreal spc = prevOrigPercent + elementPercent * point.scale;
-
- while (spc > epc) {
- if (currElement > lastElement)
- break;
- currBez = nextBezier(d->_path, &currElement, &bezLength);
- if (bezLength == 0.0) {
- currLength = pathLength;
- epc = 1.0;
- break;
- }
- currLength += bezLength;
- epc = currLength / pathLength;
- }
- qreal realT = (pathLength * spc - (currLength - bezLength)) / bezLength;
- d->_pointCache[i] = currBez.pointAt(qBound(qreal(0), realT, qreal(1)));
- break;
- }
- prevOrigPercent = point.origpercent;
- prevPercent = point.percent;
- }
- }
-}
-
-QPointF QDeclarativePath::sequentialPointAt(qreal p, qreal *angle) const
-{
- Q_D(const QDeclarativePath);
- return sequentialPointAt(d->_path, d->pathLength, d->_attributePoints, d->prevBez, p, angle);
-}
-
-QPointF QDeclarativePath::sequentialPointAt(const QPainterPath &path, const qreal &pathLength, const QList<AttributePoint> &attributePoints, QDeclarativeCachedBezier &prevBez, qreal p, qreal *angle)
-{
- if (!prevBez.isValid)
- return p > .5 ? backwardsPointAt(path, pathLength, attributePoints, prevBez, p, angle) :
- forwardsPointAt(path, pathLength, attributePoints, prevBez, p, angle);
-
- return p < prevBez.p ? backwardsPointAt(path, pathLength, attributePoints, prevBez, p, angle) :
- forwardsPointAt(path, pathLength, attributePoints, prevBez, p, angle);
-}
-
-QPointF QDeclarativePath::forwardsPointAt(const QPainterPath &path, const qreal &pathLength, const QList<AttributePoint> &attributePoints, QDeclarativeCachedBezier &prevBez, qreal p, qreal *angle)
-{
- if (pathLength <= 0 || qIsNaN(pathLength))
- return path.pointAtPercent(0); //expensive?
-
- const int lastElement = path.elementCount() - 1;
- bool haveCachedBez = prevBez.isValid;
- int currElement = haveCachedBez ? prevBez.element : -1;
- qreal bezLength = haveCachedBez ? prevBez.bezLength : 0;
- QBezier currBez = haveCachedBez ? prevBez.bezier : nextBezier(path, &currElement, &bezLength);
- qreal currLength = haveCachedBez ? prevBez.currLength : bezLength;
- qreal epc = currLength / pathLength;
-
- //find which set we are in
- qreal prevPercent = 0;
- qreal prevOrigPercent = 0;
- for (int ii = 0; ii < attributePoints.count(); ++ii) {
- qreal percent = p;
- const AttributePoint &point = attributePoints.at(ii);
- if (percent < point.percent || ii == attributePoints.count() - 1) {
- qreal elementPercent = (percent - prevPercent);
-
- qreal spc = prevOrigPercent + elementPercent * point.scale;
-
- while (spc > epc) {
- Q_ASSERT(!(currElement > lastElement));
- Q_UNUSED(lastElement);
- currBez = nextBezier(path, &currElement, &bezLength);
- currLength += bezLength;
- epc = currLength / pathLength;
- }
- prevBez.element = currElement;
- prevBez.bezLength = bezLength;
- prevBez.currLength = currLength;
- prevBez.bezier = currBez;
- prevBez.p = p;
- prevBez.isValid = true;
-
- qreal realT = (pathLength * spc - (currLength - bezLength)) / bezLength;
-
- if (angle) {
- qreal m1 = slopeAt(realT, currBez.x1, currBez.x2, currBez.x3, currBez.x4);
- qreal m2 = slopeAt(realT, currBez.y1, currBez.y2, currBez.y3, currBez.y4);
- *angle = QLineF(0, 0, m1, m2).angle();
- }
-
- return currBez.pointAt(qBound(qreal(0), realT, qreal(1)));
- }
- prevOrigPercent = point.origpercent;
- prevPercent = point.percent;
- }
-
- return QPointF(0,0);
-}
-
-//ideally this should be merged with forwardsPointAt
-QPointF QDeclarativePath::backwardsPointAt(const QPainterPath &path, const qreal &pathLength, const QList<AttributePoint> &attributePoints, QDeclarativeCachedBezier &prevBez, qreal p, qreal *angle)
-{
- if (pathLength <= 0 || qIsNaN(pathLength))
- return path.pointAtPercent(0);
-
- const int firstElement = 0;
- bool haveCachedBez = prevBez.isValid;
- int currElement = haveCachedBez ? prevBez.element : path.elementCount();
- qreal bezLength = haveCachedBez ? prevBez.bezLength : 0;
- QBezier currBez = haveCachedBez ? prevBez.bezier : nextBezier(path, &currElement, &bezLength, true /*reverse*/);
- qreal currLength = haveCachedBez ? prevBez.currLength : pathLength;
- qreal prevLength = currLength - bezLength;
- qreal epc = prevLength / pathLength;
-
- for (int ii = attributePoints.count() - 1; ii > 0; --ii) {
- qreal percent = p;
- const AttributePoint &point = attributePoints.at(ii);
- const AttributePoint &prevPoint = attributePoints.at(ii-1);
- if (percent > prevPoint.percent || ii == 1) {
- qreal elementPercent = (percent - prevPoint.percent);
-
- qreal spc = prevPoint.origpercent + elementPercent * point.scale;
-
- while (spc < epc) {
- Q_ASSERT(!(currElement < firstElement));
- Q_UNUSED(firstElement);
- currBez = nextBezier(path, &currElement, &bezLength, true /*reverse*/);
- currLength = prevLength;
- prevLength = currLength - bezLength;
- epc = prevLength / pathLength;
- }
- prevBez.element = currElement;
- prevBez.bezLength = bezLength;
- prevBez.currLength = currLength;
- prevBez.bezier = currBez;
- prevBez.p = p;
- prevBez.isValid = true;
-
- qreal realT = (pathLength * spc - (currLength - bezLength)) / bezLength;
-
- if (angle) {
- qreal m1 = slopeAt(realT, currBez.x1, currBez.x2, currBez.x3, currBez.x4);
- qreal m2 = slopeAt(realT, currBez.y1, currBez.y2, currBez.y3, currBez.y4);
- *angle = QLineF(0, 0, m1, m2).angle();
- }
-
- return currBez.pointAt(qBound(qreal(0), realT, qreal(1)));
- }
- }
-
- return QPointF(0,0);
-}
-
-QPointF QDeclarativePath::pointAt(qreal p) const
-{
- Q_D(const QDeclarativePath);
- if (d->_pointCache.isEmpty()) {
- createPointCache();
- if (d->_pointCache.isEmpty())
- return QPointF();
- }
- int idx = qRound(p*d->_pointCache.size());
- if (idx >= d->_pointCache.size())
- idx = d->_pointCache.size() - 1;
- else if (idx < 0)
- idx = 0;
- return d->_pointCache.at(idx);
-}
-
-qreal QDeclarativePath::attributeAt(const QString &name, qreal percent) const
-{
- Q_D(const QDeclarativePath);
- if (percent < 0 || percent > 1)
- return 0;
-
- for (int ii = 0; ii < d->_attributePoints.count(); ++ii) {
- const AttributePoint &point = d->_attributePoints.at(ii);
-
- if (point.percent == percent) {
- return point.values.value(name);
- } else if (point.percent > percent) {
- qreal lastValue =
- ii?(d->_attributePoints.at(ii - 1).values.value(name)):0;
- qreal lastPercent =
- ii?(d->_attributePoints.at(ii - 1).percent):0;
- qreal curValue = point.values.value(name);
- qreal curPercent = point.percent;
-
- return lastValue + (curValue - lastValue) * (percent - lastPercent) / (curPercent - lastPercent);
- }
- }
-
- return 0;
-}
-
-/****************************************************************************/
-
-qreal QDeclarativeCurve::x() const
-{
- return _x.isNull ? 0 : _x.value;
-}
-
-void QDeclarativeCurve::setX(qreal x)
-{
- if (_x.isNull || _x != x) {
- _x = x;
- emit xChanged();
- emit changed();
- }
-}
-
-bool QDeclarativeCurve::hasX()
-{
- return _x.isValid();
-}
-
-qreal QDeclarativeCurve::y() const
-{
- return _y.isNull ? 0 : _y.value;
-}
-
-void QDeclarativeCurve::setY(qreal y)
-{
- if (_y.isNull || _y != y) {
- _y = y;
- emit yChanged();
- emit changed();
- }
-}
-
-bool QDeclarativeCurve::hasY()
-{
- return _y.isValid();
-}
-
-qreal QDeclarativeCurve::relativeX() const
-{
- return _relativeX;
-}
-
-void QDeclarativeCurve::setRelativeX(qreal x)
-{
- if (_relativeX.isNull || _relativeX != x) {
- _relativeX = x;
- emit relativeXChanged();
- emit changed();
- }
-}
-
-bool QDeclarativeCurve::hasRelativeX()
-{
- return _relativeX.isValid();
-}
-
-qreal QDeclarativeCurve::relativeY() const
-{
- return _relativeY;
-}
-
-void QDeclarativeCurve::setRelativeY(qreal y)
-{
- if (_relativeY.isNull || _relativeY != y) {
- _relativeY = y;
- emit relativeYChanged();
- emit changed();
- }
-}
-
-bool QDeclarativeCurve::hasRelativeY()
-{
- return _relativeY.isValid();
-}
-
-/****************************************************************************/
-
-/*!
- \qmlclass PathAttribute QDeclarativePathAttribute
- \inqmlmodule QtQuick 2
- \ingroup qml-view-elements
- \brief The PathAttribute allows setting an attribute at a given position in a Path.
-
- The PathAttribute object allows attributes consisting of a name and
- a value to be specified for various points along a path. The
- attributes are exposed to the delegate as
- \l{qdeclarativeintroduction.html#attached-properties} {Attached Properties}.
- The value of an attribute at any particular point along the path is interpolated
- from the PathAttributes bounding that point.
-
- The example below shows a path with the items scaled to 30% with
- opacity 50% at the top of the path and scaled 100% with opacity
- 100% at the bottom. Note the use of the PathView.iconScale and
- PathView.iconOpacity attached properties to set the scale and opacity
- of the delegate.
-
- \table
- \row
- \o \image declarative-pathattribute.png
- \o
- \snippet doc/src/snippets/declarative/pathview/pathattributes.qml 0
- (see the PathView documentation for the specification of ContactModel.qml
- used for ContactModel above.)
- \endtable
-
-
- \sa Path
-*/
-
-/*!
- \qmlproperty string QtQuick2::PathAttribute::name
- This property holds the name of the attribute to change.
-
- This attribute will be available to the delegate as PathView.<name>
-
- Note that using an existing Item property name such as "opacity" as an
- attribute is allowed. This is because path attributes add a new
- \l{qdeclarativeintroduction.html#attached-properties} {Attached Property}
- which in no way clashes with existing properties.
-*/
-
-/*!
- the name of the attribute to change.
-*/
-
-QString QDeclarativePathAttribute::name() const
-{
- return _name;
-}
-
-void QDeclarativePathAttribute::setName(const QString &name)
-{
- if (_name == name)
- return;
- _name = name;
- emit nameChanged();
-}
-
-/*!
- \qmlproperty real QtQuick2::PathAttribute::value
- This property holds the value for the attribute.
-
- The value specified can be used to influence the visual appearance
- of an item along the path. For example, the following Path specifies
- an attribute named \e itemRotation, which has the value \e 0 at the
- beginning of the path, and the value 90 at the end of the path.
-
- \qml
- Path {
- startX: 0
- startY: 0
- PathAttribute { name: "itemRotation"; value: 0 }
- PathLine { x: 100; y: 100 }
- PathAttribute { name: "itemRotation"; value: 90 }
- }
- \endqml
-
- In our delegate, we can then bind the \e rotation property to the
- \l{qdeclarativeintroduction.html#attached-properties} {Attached Property}
- \e PathView.itemRotation created for this attribute.
-
- \qml
- Rectangle {
- width: 10; height: 10
- rotation: PathView.itemRotation
- }
- \endqml
-
- As each item is positioned along the path, it will be rotated accordingly:
- an item at the beginning of the path with be not be rotated, an item at
- the end of the path will be rotated 90 degrees, and an item mid-way along
- the path will be rotated 45 degrees.
-*/
-
-/*!
- the new value of the attribute.
-*/
-qreal QDeclarativePathAttribute::value() const
-{
- return _value;
-}
-
-void QDeclarativePathAttribute::setValue(qreal value)
-{
- if (_value != value) {
- _value = value;
- emit valueChanged();
- emit changed();
- }
-}
-
-/****************************************************************************/
-
-/*!
- \qmlclass PathLine QDeclarativePathLine
- \inqmlmodule QtQuick 2
- \ingroup qml-view-elements
- \brief The PathLine defines a straight line.
-
- The example below creates a path consisting of a straight line from
- 0,100 to 200,100:
-
- \qml
- Path {
- startX: 0; startY: 100
- PathLine { x: 200; y: 100 }
- }
- \endqml
-
- \sa Path, PathQuad, PathCubic
-*/
-
-/*!
- \qmlproperty real QtQuick2::PathLine::x
- \qmlproperty real QtQuick2::PathLine::y
-
- Defines the end point of the line.
-*/
-
-inline QPointF positionForCurve(const QDeclarativePathData &data, const QPointF &prevPoint)
-{
- QDeclarativeCurve *curve = data.curves.at(data.index);
- bool isEnd = data.index == data.curves.size() - 1;
- return QPointF(curve->hasRelativeX() ? prevPoint.x() + curve->relativeX() : !isEnd || curve->hasX() ? curve->x() : data.endPoint.x(),
- curve->hasRelativeY() ? prevPoint.y() + curve->relativeY() : !isEnd || curve->hasY() ? curve->y() : data.endPoint.y());
-}
-
-void QDeclarativePathLine::addToPath(QPainterPath &path, const QDeclarativePathData &data)
-{
- path.lineTo(positionForCurve(data, path.currentPosition()));
-}
-
-/****************************************************************************/
-
-/*!
- \qmlclass PathQuad QDeclarativePathQuad
- \inqmlmodule QtQuick 2
- \ingroup qml-view-elements
- \brief The PathQuad defines a quadratic Bezier curve with a control point.
-
- The following QML produces the path shown below:
- \table
- \row
- \o \image declarative-pathquad.png
- \o
- \qml
- Path {
- startX: 0; startY: 0
- PathQuad { x: 200; y: 0; controlX: 100; controlY: 150 }
- }
- \endqml
- \endtable
-
- \sa Path, PathCubic, PathLine
-*/
-
-/*!
- \qmlproperty real QtQuick2::PathQuad::x
- \qmlproperty real QtQuick2::PathQuad::y
-
- Defines the end point of the curve.
-*/
-
-/*!
- \qmlproperty real QtQuick2::PathQuad::controlX
- \qmlproperty real QtQuick2::PathQuad::controlY
-
- Defines the position of the control point.
-*/
-
-/*!
- the x position of the control point.
-*/
-qreal QDeclarativePathQuad::controlX() const
-{
- return _controlX;
-}
-
-void QDeclarativePathQuad::setControlX(qreal x)
-{
- if (_controlX != x) {
- _controlX = x;
- emit controlXChanged();
- emit changed();
- }
-}
-
-
-/*!
- the y position of the control point.
-*/
-qreal QDeclarativePathQuad::controlY() const
-{
- return _controlY;
-}
-
-void QDeclarativePathQuad::setControlY(qreal y)
-{
- if (_controlY != y) {
- _controlY = y;
- emit controlYChanged();
- emit changed();
- }
-}
-
-qreal QDeclarativePathQuad::relativeControlX() const
-{
- return _relativeControlX;
-}
-
-void QDeclarativePathQuad::setRelativeControlX(qreal x)
-{
- if (_relativeControlX.isNull || _relativeControlX != x) {
- _relativeControlX = x;
- emit relativeControlXChanged();
- emit changed();
- }
-}
-
-bool QDeclarativePathQuad::hasRelativeControlX()
-{
- return _relativeControlX.isValid();
-}
-
-qreal QDeclarativePathQuad::relativeControlY() const
-{
- return _relativeControlY;
-}
-
-void QDeclarativePathQuad::setRelativeControlY(qreal y)
-{
- if (_relativeControlY.isNull || _relativeControlY != y) {
- _relativeControlY = y;
- emit relativeControlYChanged();
- emit changed();
- }
-}
-
-bool QDeclarativePathQuad::hasRelativeControlY()
-{
- return _relativeControlY.isValid();
-}
-
-void QDeclarativePathQuad::addToPath(QPainterPath &path, const QDeclarativePathData &data)
-{
- const QPointF &prevPoint = path.currentPosition();
- QPointF controlPoint(hasRelativeControlX() ? prevPoint.x() + relativeControlX() : controlX(),
- hasRelativeControlY() ? prevPoint.y() + relativeControlY() : controlY());
- path.quadTo(controlPoint, positionForCurve(data, path.currentPosition()));
-}
-
-/****************************************************************************/
-
-/*!
- \qmlclass PathCubic QDeclarativePathCubic
- \inqmlmodule QtQuick 2
- \ingroup qml-view-elements
- \brief The PathCubic defines a cubic Bezier curve with two control points.
-
- The following QML produces the path shown below:
- \table
- \row
- \o \image declarative-pathcubic.png
- \o
- \qml
- Path {
- startX: 20; startY: 0
- PathCubic {
- x: 180; y: 0
- control1X: -10; control1Y: 90
- control2X: 210; control2Y: 90
- }
- }
- \endqml
- \endtable
-
- \sa Path, PathQuad, PathLine
-*/
-
-/*!
- \qmlproperty real QtQuick2::PathCubic::x
- \qmlproperty real QtQuick2::PathCubic::y
-
- Defines the end point of the curve.
-*/
-
-/*!
- \qmlproperty real QtQuick2::PathCubic::control1X
- \qmlproperty real QtQuick2::PathCubic::control1Y
-
- Defines the position of the first control point.
-*/
-qreal QDeclarativePathCubic::control1X() const
-{
- return _control1X;
-}
-
-void QDeclarativePathCubic::setControl1X(qreal x)
-{
- if (_control1X != x) {
- _control1X = x;
- emit control1XChanged();
- emit changed();
- }
-}
-
-qreal QDeclarativePathCubic::control1Y() const
-{
- return _control1Y;
-}
-
-void QDeclarativePathCubic::setControl1Y(qreal y)
-{
- if (_control1Y != y) {
- _control1Y = y;
- emit control1YChanged();
- emit changed();
- }
-}
-
-/*!
- \qmlproperty real QtQuick2::PathCubic::control2X
- \qmlproperty real QtQuick2::PathCubic::control2Y
-
- Defines the position of the second control point.
-*/
-qreal QDeclarativePathCubic::control2X() const
-{
- return _control2X;
-}
-
-void QDeclarativePathCubic::setControl2X(qreal x)
-{
- if (_control2X != x) {
- _control2X = x;
- emit control2XChanged();
- emit changed();
- }
-}
-
-qreal QDeclarativePathCubic::control2Y() const
-{
- return _control2Y;
-}
-
-void QDeclarativePathCubic::setControl2Y(qreal y)
-{
- if (_control2Y != y) {
- _control2Y = y;
- emit control2YChanged();
- emit changed();
- }
-}
-
-qreal QDeclarativePathCubic::relativeControl1X() const
-{
- return _relativeControl1X;
-}
-
-void QDeclarativePathCubic::setRelativeControl1X(qreal x)
-{
- if (_relativeControl1X.isNull || _relativeControl1X != x) {
- _relativeControl1X = x;
- emit relativeControl1XChanged();
- emit changed();
- }
-}
-
-bool QDeclarativePathCubic::hasRelativeControl1X()
-{
- return _relativeControl1X.isValid();
-}
-
-qreal QDeclarativePathCubic::relativeControl1Y() const
-{
- return _relativeControl1Y;
-}
-
-void QDeclarativePathCubic::setRelativeControl1Y(qreal y)
-{
- if (_relativeControl1Y.isNull || _relativeControl1Y != y) {
- _relativeControl1Y = y;
- emit relativeControl1YChanged();
- emit changed();
- }
-}
-
-bool QDeclarativePathCubic::hasRelativeControl1Y()
-{
- return _relativeControl1Y.isValid();
-}
-
-qreal QDeclarativePathCubic::relativeControl2X() const
-{
- return _relativeControl2X;
-}
-
-void QDeclarativePathCubic::setRelativeControl2X(qreal x)
-{
- if (_relativeControl2X.isNull || _relativeControl2X != x) {
- _relativeControl2X = x;
- emit relativeControl2XChanged();
- emit changed();
- }
-}
-
-bool QDeclarativePathCubic::hasRelativeControl2X()
-{
- return _relativeControl2X.isValid();
-}
-
-qreal QDeclarativePathCubic::relativeControl2Y() const
-{
- return _relativeControl2Y;
-}
-
-void QDeclarativePathCubic::setRelativeControl2Y(qreal y)
-{
- if (_relativeControl2Y.isNull || _relativeControl2Y != y) {
- _relativeControl2Y = y;
- emit relativeControl2YChanged();
- emit changed();
- }
-}
-
-bool QDeclarativePathCubic::hasRelativeControl2Y()
-{
- return _relativeControl2Y.isValid();
-}
-
-void QDeclarativePathCubic::addToPath(QPainterPath &path, const QDeclarativePathData &data)
-{
- const QPointF &prevPoint = path.currentPosition();
- QPointF controlPoint1(hasRelativeControl1X() ? prevPoint.x() + relativeControl1X() : control1X(),
- hasRelativeControl1Y() ? prevPoint.y() + relativeControl1Y() : control1Y());
- QPointF controlPoint2(hasRelativeControl2X() ? prevPoint.x() + relativeControl2X() : control2X(),
- hasRelativeControl2Y() ? prevPoint.y() + relativeControl2Y() : control2Y());
- path.cubicTo(controlPoint1, controlPoint2, positionForCurve(data, path.currentPosition()));
-}
-
-/****************************************************************************/
-
-inline QPointF previousPathPosition(const QPainterPath &path)
-{
- int count = path.elementCount();
- if (count < 1)
- return QPointF();
-
- int index = path.elementAt(count-1).type == QPainterPath::CurveToDataElement ? count - 4 : count - 2;
- return index > -1 ? QPointF(path.elementAt(index)) : path.pointAtPercent(0);
-}
-
-void QDeclarativePathCatmullRomCurve::addToPath(QPainterPath &path, const QDeclarativePathData &data)
-{
- //here we convert catmull-rom spline to bezier for use in QPainterPath.
- //basic conversion algorithm:
- // catmull-rom points * inverse bezier matrix * catmull-rom matrix = bezier points
- //each point in the catmull-rom spline produces a bezier endpoint + 2 control points
- //calculations for each point use a moving window of 4 points
- // (previous 2 points + current point + next point)
- QPointF prevFar, prev, point, next;
-
- //get previous points
- int index = data.index - 1;
- QDeclarativeCurve *curve = index == -1 ? 0 : data.curves.at(index);
- if (qobject_cast<QDeclarativePathCatmullRomCurve*>(curve)) {
- prev = path.currentPosition();
- prevFar = previousPathPosition(path);
- } else
- prevFar = prev = path.currentPosition();
-
- //get current point
- point = positionForCurve(data, path.currentPosition());
-
- //get next point
- index = data.index + 1;
- if (index < data.curves.count() && qobject_cast<QDeclarativePathCatmullRomCurve*>(data.curves.at(index))) {
- QDeclarativePathData nextData;
- nextData.index = index;
- nextData.endPoint = data.endPoint;
- nextData.curves = data.curves;
- next = positionForCurve(nextData, point);
- } else
- next = point;
-
- /*
- full conversion matrix (inverse bezier * catmull-rom):
- 0.000, 1.000, 0.000, 0.000,
- -0.167, 1.000, 0.167, 0.000,
- 0.000, 0.167, 1.000, -0.167,
- 0.000, 0.000, 1.000, 0.000
-
- conversion doesn't require full matrix multiplication,
- so below we simplify
- */
- QPointF control1(prevFar.x() * qreal(-0.167) +
- prev.x() +
- point.x() * qreal(0.167),
- prevFar.y() * qreal(-0.167) +
- prev.y() +
- point.y() * qreal(0.167));
-
- QPointF control2(prev.x() * qreal(0.167) +
- point.x() +
- next.x() * qreal(-0.167),
- prev.y() * qreal(0.167) +
- point.y() +
- next.y() * qreal(-0.167));
-
- path.cubicTo(control1, control2, point);
-}
-
-/****************************************************************************/
-
-qreal QDeclarativePathArc::radiusX() const
-{
- return _radiusX;
-}
-
-void QDeclarativePathArc::setRadiusX(qreal radius)
-{
- if (_radiusX == radius)
- return;
-
- _radiusX = radius;
- emit radiusXChanged();
-}
-
-qreal QDeclarativePathArc::radiusY() const
-{
- return _radiusY;
-}
-
-void QDeclarativePathArc::setRadiusY(qreal radius)
-{
- if (_radiusY == radius)
- return;
-
- _radiusY = radius;
- emit radiusYChanged();
-}
-
-bool QDeclarativePathArc::useLargeArc() const
-{
- return _useLargeArc;
-}
-
-void QDeclarativePathArc::setUseLargeArc(bool largeArc)
-{
- if (_useLargeArc == largeArc)
- return;
-
- _useLargeArc = largeArc;
- emit useLargeArcChanged();
-}
-
-QDeclarativePathArc::ArcDirection QDeclarativePathArc::direction() const
-{
- return _direction;
-}
-
-void QDeclarativePathArc::setDirection(ArcDirection direction)
-{
- if (_direction == direction)
- return;
-
- _direction = direction;
- emit directionChanged();
-}
-
-void QDeclarativePathArc::addToPath(QPainterPath &path, const QDeclarativePathData &data)
-{
- const QPointF &startPoint = path.currentPosition();
- const QPointF &endPoint = positionForCurve(data, startPoint);
- QDeclarativeSvgParser::pathArc(path,
- _radiusX,
- _radiusY,
- 0, //xAxisRotation
- _useLargeArc,
- _direction == Clockwise ? 1 : 0,
- endPoint.x(),
- endPoint.y(),
- startPoint.x(), startPoint.y());
-}
-
-/****************************************************************************/
-
-QString QDeclarativePathSvg::path() const
-{
- return _path;
-}
-
-void QDeclarativePathSvg::setPath(const QString &path)
-{
- if (_path == path)
- return;
-
- _path = path;
- emit pathChanged();
-}
-
-void QDeclarativePathSvg::addToPath(QPainterPath &path, const QDeclarativePathData &)
-{
- QDeclarativeSvgParser::parsePathDataFast(_path, path);
-}
-
-/****************************************************************************/
-
-/*!
- \qmlclass PathPercent QDeclarativePathPercent
- \inqmlmodule QtQuick 2
- \ingroup qml-view-elements
- \brief The PathPercent manipulates the way a path is interpreted.
-
- PathPercent allows you to manipulate the spacing between items on a
- PathView's path. You can use it to bunch together items on part of
- the path, and spread them out on other parts of the path.
-
- The examples below show the normal distribution of items along a path
- compared to a distribution which places 50% of the items along the
- PathLine section of the path.
- \table
- \row
- \o \image declarative-nopercent.png
- \o
- \qml
- PathView {
- // ...
- Path {
- startX: 20; startY: 0
- PathQuad { x: 50; y: 80; controlX: 0; controlY: 80 }
- PathLine { x: 150; y: 80 }
- PathQuad { x: 180; y: 0; controlX: 200; controlY: 80 }
- }
- }
- \endqml
- \row
- \o \image declarative-percent.png
- \o
- \qml
- PathView {
- // ...
- Path {
- startX: 20; startY: 0
- PathQuad { x: 50; y: 80; controlX: 0; controlY: 80 }
- PathPercent { value: 0.25 }
- PathLine { x: 150; y: 80 }
- PathPercent { value: 0.75 }
- PathQuad { x: 180; y: 0; controlX: 200; controlY: 80 }
- PathPercent { value: 1 }
- }
- }
- \endqml
- \endtable
-
- \sa Path
-*/
-
-/*!
- \qmlproperty real QtQuick2::PathPercent::value
- The proportion of items that should be laid out up to this point.
-
- This value should always be higher than the last value specified
- by a PathPercent at a previous position in the Path.
-
- In the following example we have a Path made up of three PathLines.
- Normally, the items of the PathView would be laid out equally along
- this path, with an equal number of items per line segment. PathPercent
- allows us to specify that the first and third lines should each hold
- 10% of the laid out items, while the second line should hold the remaining
- 80%.
-
- \qml
- PathView {
- // ...
- Path {
- startX: 0; startY: 0
- PathLine { x:100; y: 0; }
- PathPercent { value: 0.1 }
- PathLine { x: 100; y: 100 }
- PathPercent { value: 0.9 }
- PathLine { x: 100; y: 0 }
- PathPercent { value: 1 }
- }
- }
- \endqml
-*/
-
-qreal QDeclarativePathPercent::value() const
-{
- return _value;
-}
-
-void QDeclarativePathPercent::setValue(qreal value)
-{
- if (_value != value) {
- _value = value;
- emit valueChanged();
- emit changed();
- }
-}
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativepath_p.h b/src/declarative/util/qdeclarativepath_p.h
deleted file mode 100644
index 537afb3b0b..0000000000
--- a/src/declarative/util/qdeclarativepath_p.h
+++ /dev/null
@@ -1,452 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEPATH_H
-#define QDECLARATIVEPATH_H
-
-#include <qdeclarative.h>
-
-#include <private/qdeclarativenullablevalue_p_p.h>
-#include <private/qbezier_p.h>
-
-#include <QtCore/QObject>
-#include <QtGui/QPainterPath>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeCurve;
-struct QDeclarativePathData
-{
- int index;
- QPointF endPoint;
- QList<QDeclarativeCurve*> curves;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativePathElement : public QObject
-{
- Q_OBJECT
-public:
- QDeclarativePathElement(QObject *parent=0) : QObject(parent) {}
-Q_SIGNALS:
- void changed();
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativePathAttribute : public QDeclarativePathElement
-{
- Q_OBJECT
-
- Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
- Q_PROPERTY(qreal value READ value WRITE setValue NOTIFY valueChanged)
-public:
- QDeclarativePathAttribute(QObject *parent=0) : QDeclarativePathElement(parent), _value(0) {}
-
-
- QString name() const;
- void setName(const QString &name);
-
- qreal value() const;
- void setValue(qreal value);
-
-Q_SIGNALS:
- void nameChanged();
- void valueChanged();
-
-private:
- QString _name;
- qreal _value;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativeCurve : public QDeclarativePathElement
-{
- Q_OBJECT
-
- Q_PROPERTY(qreal x READ x WRITE setX NOTIFY xChanged)
- Q_PROPERTY(qreal y READ y WRITE setY NOTIFY yChanged)
- Q_PROPERTY(qreal relativeX READ relativeX WRITE setRelativeX NOTIFY relativeXChanged)
- Q_PROPERTY(qreal relativeY READ relativeY WRITE setRelativeY NOTIFY relativeYChanged)
-public:
- QDeclarativeCurve(QObject *parent=0) : QDeclarativePathElement(parent) {}
-
- qreal x() const;
- void setX(qreal x);
- bool hasX();
-
- qreal y() const;
- void setY(qreal y);
- bool hasY();
-
- qreal relativeX() const;
- void setRelativeX(qreal x);
- bool hasRelativeX();
-
- qreal relativeY() const;
- void setRelativeY(qreal y);
- bool hasRelativeY();
-
- virtual void addToPath(QPainterPath &, const QDeclarativePathData &) {}
-
-Q_SIGNALS:
- void xChanged();
- void yChanged();
- void relativeXChanged();
- void relativeYChanged();
-
-private:
- QDeclarativeNullableValue<qreal> _x;
- QDeclarativeNullableValue<qreal> _y;
- QDeclarativeNullableValue<qreal> _relativeX;
- QDeclarativeNullableValue<qreal> _relativeY;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativePathLine : public QDeclarativeCurve
-{
- Q_OBJECT
-public:
- QDeclarativePathLine(QObject *parent=0) : QDeclarativeCurve(parent) {}
-
- void addToPath(QPainterPath &path, const QDeclarativePathData &);
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativePathQuad : public QDeclarativeCurve
-{
- Q_OBJECT
-
- Q_PROPERTY(qreal controlX READ controlX WRITE setControlX NOTIFY controlXChanged)
- Q_PROPERTY(qreal controlY READ controlY WRITE setControlY NOTIFY controlYChanged)
- Q_PROPERTY(qreal relativeControlX READ relativeControlX WRITE setRelativeControlX NOTIFY relativeControlXChanged)
- Q_PROPERTY(qreal relativeControlY READ relativeControlY WRITE setRelativeControlY NOTIFY relativeControlYChanged)
-public:
- QDeclarativePathQuad(QObject *parent=0) : QDeclarativeCurve(parent), _controlX(0), _controlY(0) {}
-
- qreal controlX() const;
- void setControlX(qreal x);
-
- qreal controlY() const;
- void setControlY(qreal y);
-
- qreal relativeControlX() const;
- void setRelativeControlX(qreal x);
- bool hasRelativeControlX();
-
- qreal relativeControlY() const;
- void setRelativeControlY(qreal y);
- bool hasRelativeControlY();
-
- void addToPath(QPainterPath &path, const QDeclarativePathData &);
-
-Q_SIGNALS:
- void controlXChanged();
- void controlYChanged();
- void relativeControlXChanged();
- void relativeControlYChanged();
-
-private:
- qreal _controlX;
- qreal _controlY;
- QDeclarativeNullableValue<qreal> _relativeControlX;
- QDeclarativeNullableValue<qreal> _relativeControlY;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativePathCubic : public QDeclarativeCurve
-{
- Q_OBJECT
-
- Q_PROPERTY(qreal control1X READ control1X WRITE setControl1X NOTIFY control1XChanged)
- Q_PROPERTY(qreal control1Y READ control1Y WRITE setControl1Y NOTIFY control1YChanged)
- Q_PROPERTY(qreal control2X READ control2X WRITE setControl2X NOTIFY control2XChanged)
- Q_PROPERTY(qreal control2Y READ control2Y WRITE setControl2Y NOTIFY control2YChanged)
- Q_PROPERTY(qreal relativeControl1X READ relativeControl1X WRITE setRelativeControl1X NOTIFY relativeControl1XChanged)
- Q_PROPERTY(qreal relativeControl1Y READ relativeControl1Y WRITE setRelativeControl1Y NOTIFY relativeControl1YChanged)
- Q_PROPERTY(qreal relativeControl2X READ relativeControl2X WRITE setRelativeControl2X NOTIFY relativeControl2XChanged)
- Q_PROPERTY(qreal relativeControl2Y READ relativeControl2Y WRITE setRelativeControl2Y NOTIFY relativeControl2YChanged)
-public:
- QDeclarativePathCubic(QObject *parent=0) : QDeclarativeCurve(parent), _control1X(0), _control1Y(0), _control2X(0), _control2Y(0) {}
-
- qreal control1X() const;
- void setControl1X(qreal x);
-
- qreal control1Y() const;
- void setControl1Y(qreal y);
-
- qreal control2X() const;
- void setControl2X(qreal x);
-
- qreal control2Y() const;
- void setControl2Y(qreal y);
-
- qreal relativeControl1X() const;
- void setRelativeControl1X(qreal x);
- bool hasRelativeControl1X();
-
- qreal relativeControl1Y() const;
- void setRelativeControl1Y(qreal y);
- bool hasRelativeControl1Y();
-
- qreal relativeControl2X() const;
- void setRelativeControl2X(qreal x);
- bool hasRelativeControl2X();
-
- qreal relativeControl2Y() const;
- void setRelativeControl2Y(qreal y);
- bool hasRelativeControl2Y();
-
- void addToPath(QPainterPath &path, const QDeclarativePathData &);
-
-Q_SIGNALS:
- void control1XChanged();
- void control1YChanged();
- void control2XChanged();
- void control2YChanged();
- void relativeControl1XChanged();
- void relativeControl1YChanged();
- void relativeControl2XChanged();
- void relativeControl2YChanged();
-
-private:
- qreal _control1X;
- qreal _control1Y;
- qreal _control2X;
- qreal _control2Y;
- QDeclarativeNullableValue<qreal> _relativeControl1X;
- QDeclarativeNullableValue<qreal> _relativeControl1Y;
- QDeclarativeNullableValue<qreal> _relativeControl2X;
- QDeclarativeNullableValue<qreal> _relativeControl2Y;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativePathCatmullRomCurve : public QDeclarativeCurve
-{
- Q_OBJECT
-public:
- QDeclarativePathCatmullRomCurve(QObject *parent=0) : QDeclarativeCurve(parent) {}
-
- void addToPath(QPainterPath &path, const QDeclarativePathData &);
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativePathArc : public QDeclarativeCurve
-{
- Q_OBJECT
- Q_PROPERTY(qreal radiusX READ radiusX WRITE setRadiusX NOTIFY radiusXChanged)
- Q_PROPERTY(qreal radiusY READ radiusY WRITE setRadiusY NOTIFY radiusYChanged)
- Q_PROPERTY(bool useLargeArc READ useLargeArc WRITE setUseLargeArc NOTIFY useLargeArcChanged)
- Q_PROPERTY(ArcDirection direction READ direction WRITE setDirection NOTIFY directionChanged)
-
-public:
- QDeclarativePathArc(QObject *parent=0)
- : QDeclarativeCurve(parent), _radiusX(0), _radiusY(0), _useLargeArc(false), _direction(Clockwise) {}
-
- enum ArcDirection { Clockwise, Counterclockwise };
- Q_ENUMS(ArcDirection)
-
- qreal radiusX() const;
- void setRadiusX(qreal);
-
- qreal radiusY() const;
- void setRadiusY(qreal);
-
- bool useLargeArc() const;
- void setUseLargeArc(bool);
-
- ArcDirection direction() const;
- void setDirection(ArcDirection direction);
-
- void addToPath(QPainterPath &path, const QDeclarativePathData &);
-
-Q_SIGNALS:
- void radiusXChanged();
- void radiusYChanged();
- void useLargeArcChanged();
- void directionChanged();
-
-private:
- qreal _radiusX;
- qreal _radiusY;
- bool _useLargeArc;
- ArcDirection _direction;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativePathSvg : public QDeclarativeCurve
-{
- Q_OBJECT
- Q_PROPERTY(QString path READ path WRITE setPath NOTIFY pathChanged)
-public:
- QDeclarativePathSvg(QObject *parent=0) : QDeclarativeCurve(parent) {}
-
- QString path() const;
- void setPath(const QString &path);
-
- void addToPath(QPainterPath &path, const QDeclarativePathData &);
-
-Q_SIGNALS:
- void pathChanged();
-
-private:
- QString _path;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativePathPercent : public QDeclarativePathElement
-{
- Q_OBJECT
- Q_PROPERTY(qreal value READ value WRITE setValue NOTIFY valueChanged)
-public:
- QDeclarativePathPercent(QObject *parent=0) : QDeclarativePathElement(parent) {}
-
- qreal value() const;
- void setValue(qreal value);
-
-signals:
- void valueChanged();
-
-private:
- qreal _value;
-};
-
-struct QDeclarativeCachedBezier
-{
- QDeclarativeCachedBezier() : isValid(false) {}
- QBezier bezier;
- int element;
- qreal bezLength;
- qreal currLength;
- qreal p;
- bool isValid;
-};
-
-class QDeclarativePathPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativePath : public QObject, public QDeclarativeParserStatus
-{
- Q_OBJECT
-
- Q_INTERFACES(QDeclarativeParserStatus)
- Q_PROPERTY(QDeclarativeListProperty<QDeclarativePathElement> pathElements READ pathElements)
- Q_PROPERTY(qreal startX READ startX WRITE setStartX NOTIFY startXChanged)
- Q_PROPERTY(qreal startY READ startY WRITE setStartY NOTIFY startYChanged)
- Q_PROPERTY(bool closed READ isClosed NOTIFY changed)
- Q_CLASSINFO("DefaultProperty", "pathElements")
- Q_INTERFACES(QDeclarativeParserStatus)
-public:
- QDeclarativePath(QObject *parent=0);
- ~QDeclarativePath();
-
- QDeclarativeListProperty<QDeclarativePathElement> pathElements();
-
- qreal startX() const;
- void setStartX(qreal x);
- bool hasStartX() const;
-
- qreal startY() const;
- void setStartY(qreal y);
- bool hasStartY() const;
-
- bool isClosed() const;
- bool hasEnd() const;
-
- QPainterPath path() const;
- QStringList attributes() const;
- qreal attributeAt(const QString &, qreal) const;
- QPointF pointAt(qreal) const;
- QPointF sequentialPointAt(qreal p, qreal *angle = 0) const;
-
-Q_SIGNALS:
- void changed();
- void startXChanged();
- void startYChanged();
-
-protected:
- virtual void componentComplete();
- virtual void classBegin();
-
-private Q_SLOTS:
- void processPath();
-
-private:
- struct AttributePoint {
- AttributePoint() : percent(0), scale(1), origpercent(0) {}
- AttributePoint(const AttributePoint &other)
- : percent(other.percent), scale(other.scale), origpercent(other.origpercent), values(other.values) {}
- AttributePoint &operator=(const AttributePoint &other) {
- percent = other.percent; scale = other.scale; origpercent = other.origpercent; values = other.values; return *this;
- }
- qreal percent; //massaged percent along the painter path
- qreal scale;
- qreal origpercent; //'real' percent along the painter path
- QHash<QString, qreal> values;
- };
-
- void interpolate(int idx, const QString &name, qreal value);
- void endpoint(const QString &name);
- void createPointCache() const;
-
- static void interpolate(QList<AttributePoint> &points, int idx, const QString &name, qreal value);
- static void endpoint(QList<AttributePoint> &attributePoints, const QString &name);
- static QPointF forwardsPointAt(const QPainterPath &path, const qreal &pathLength, const QList<AttributePoint> &attributePoints, QDeclarativeCachedBezier &prevBez, qreal p, qreal *angle = 0);
- static QPointF backwardsPointAt(const QPainterPath &path, const qreal &pathLength, const QList<AttributePoint> &attributePoints, QDeclarativeCachedBezier &prevBez, qreal p, qreal *angle = 0);
-
-private:
- Q_DISABLE_COPY(QDeclarativePath)
- Q_DECLARE_PRIVATE(QDeclarativePath)
- friend class QQuickPathAnimationUpdater;
-
-public:
- QPainterPath createPath(const QPointF &startPoint, const QPointF &endPoint, const QStringList &attributes, qreal &pathLength, QList<AttributePoint> &attributePoints, bool *closed = 0);
- static QPointF sequentialPointAt(const QPainterPath &path, const qreal &pathLength, const QList<AttributePoint> &attributePoints, QDeclarativeCachedBezier &prevBez, qreal p, qreal *angle = 0);
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativePathElement)
-QML_DECLARE_TYPE(QDeclarativePathAttribute)
-QML_DECLARE_TYPE(QDeclarativeCurve)
-QML_DECLARE_TYPE(QDeclarativePathLine)
-QML_DECLARE_TYPE(QDeclarativePathQuad)
-QML_DECLARE_TYPE(QDeclarativePathCubic)
-QML_DECLARE_TYPE(QDeclarativePathCatmullRomCurve)
-QML_DECLARE_TYPE(QDeclarativePathArc)
-QML_DECLARE_TYPE(QDeclarativePathSvg)
-QML_DECLARE_TYPE(QDeclarativePathPercent)
-QML_DECLARE_TYPE(QDeclarativePath)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVEPATH_H
diff --git a/src/declarative/util/qdeclarativepath_p_p.h b/src/declarative/util/qdeclarativepath_p_p.h
deleted file mode 100644
index 910b7627d3..0000000000
--- a/src/declarative/util/qdeclarativepath_p_p.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEPATH_P_H
-#define QDECLARATIVEPATH_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 "qdeclarativepath_p.h"
-
-#include <qdeclarative.h>
-#include <QtCore/QStringList>
-
-#include <private/qobject_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativePathPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativePath)
-
-public:
- QDeclarativePathPrivate() : pathLength(0), closed(false), componentComplete(true) { }
-
- QPainterPath _path;
- QList<QDeclarativePathElement*> _pathElements;
- mutable QVector<QPointF> _pointCache;
- QList<QDeclarativePath::AttributePoint> _attributePoints;
- QStringList _attributes;
- QList<QDeclarativeCurve*> _pathCurves;
- mutable QDeclarativeCachedBezier prevBez;
- QDeclarativeNullableValue<qreal> startX;
- QDeclarativeNullableValue<qreal> startY;
- qreal pathLength;
- bool closed;
- bool componentComplete;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/declarative/util/qdeclarativepathinterpolator.cpp b/src/declarative/util/qdeclarativepathinterpolator.cpp
deleted file mode 100644
index 569884d33a..0000000000
--- a/src/declarative/util/qdeclarativepathinterpolator.cpp
+++ /dev/null
@@ -1,122 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativepathinterpolator_p.h"
-
-#include "qdeclarativepath_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QDeclarativePathInterpolator::QDeclarativePathInterpolator(QObject *parent) :
- QObject(parent), _path(0), _x(0), _y(0), _angle(0), _progress(0)
-{
-}
-
-QDeclarativePath *QDeclarativePathInterpolator::path() const
-{
- return _path;
-}
-
-void QDeclarativePathInterpolator::setPath(QDeclarativePath *path)
-{
- if (_path == path)
- return;
- if (_path)
- disconnect(_path, SIGNAL(changed()), this, SLOT(_q_pathUpdated()));
- _path = path;
- connect(_path, SIGNAL(changed()), this, SLOT(_q_pathUpdated()));
- emit pathChanged();
-}
-
-qreal QDeclarativePathInterpolator::progress() const
-{
- return _progress;
-}
-
-void QDeclarativePathInterpolator::setProgress(qreal progress)
-{
- if (progress == _progress)
- return;
- _progress = progress;
- emit progressChanged();
- _q_pathUpdated();
-}
-
-qreal QDeclarativePathInterpolator::x() const
-{
- return _x;
-}
-
-qreal QDeclarativePathInterpolator::y() const
-{
- return _y;
-}
-
-qreal QDeclarativePathInterpolator::angle() const
-{
- return _angle;
-}
-
-void QDeclarativePathInterpolator::_q_pathUpdated()
-{
- if (! _path)
- return;
-
- qreal angle = 0;
- const QPointF pt = _path->sequentialPointAt(_progress, &angle);
-
- if (_x != pt.x()) {
- _x = pt.x();
- emit xChanged();
- }
-
- if (_y != pt.y()) {
- _y = pt.y();
- emit yChanged();
- }
-
- if (angle != _angle) {
- _angle = angle;
- emit angleChanged();
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativepathinterpolator_p.h b/src/declarative/util/qdeclarativepathinterpolator_p.h
deleted file mode 100644
index cb8ccfa8fb..0000000000
--- a/src/declarative/util/qdeclarativepathinterpolator_p.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEPATHINTERPOLATOR_P_H
-#define QDECLARATIVEPATHINTERPOLATOR_P_H
-
-#include <qdeclarative.h>
-#include <QObject>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativePath;
-class Q_AUTOTEST_EXPORT QDeclarativePathInterpolator : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QDeclarativePath *path READ path WRITE setPath NOTIFY pathChanged)
- Q_PROPERTY(qreal progress READ progress WRITE setProgress NOTIFY progressChanged)
- Q_PROPERTY(qreal x READ x NOTIFY xChanged)
- Q_PROPERTY(qreal y READ y NOTIFY yChanged)
- Q_PROPERTY(qreal angle READ angle NOTIFY angleChanged)
-public:
- explicit QDeclarativePathInterpolator(QObject *parent = 0);
-
- QDeclarativePath *path() const;
- void setPath(QDeclarativePath *path);
-
- qreal progress() const;
- void setProgress(qreal progress);
-
- qreal x() const;
- qreal y() const;
- qreal angle() const;
-
-Q_SIGNALS:
- void pathChanged();
- void progressChanged();
- void xChanged();
- void yChanged();
- void angleChanged();
-
-private Q_SLOTS:
- void _q_pathUpdated();
-
-private:
- QDeclarativePath *_path;
- qreal _x;
- qreal _y;
- qreal _angle;
- qreal _progress;
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativePathInterpolator)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVEPATHINTERPOLATOR_P_H
diff --git a/src/declarative/util/qdeclarativepixmapcache.cpp b/src/declarative/util/qdeclarativepixmapcache.cpp
deleted file mode 100644
index b57bfac585..0000000000
--- a/src/declarative/util/qdeclarativepixmapcache.cpp
+++ /dev/null
@@ -1,1241 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativepixmapcache_p.h"
-#include <qdeclarativenetworkaccessmanagerfactory.h>
-#include <qdeclarativeimageprovider.h>
-
-#include <qdeclarativeengine.h>
-#include <private/qdeclarativeglobal_p.h>
-#include <private/qdeclarativeengine_p.h>
-
-#include <private/qsgtexture_p.h>
-
-#include <QCoreApplication>
-#include <QImageReader>
-#include <QHash>
-#include <QNetworkReply>
-#include <QPixmapCache>
-#include <QFile>
-#include <QThread>
-#include <QMutex>
-#include <QMutexLocker>
-#include <QWaitCondition>
-#include <QBuffer>
-#include <QWaitCondition>
-#include <QtCore/qdebug.h>
-#include <private/qobject_p.h>
-#include <QSslError>
-#include <QOpenGLContext>
-
-#define IMAGEREQUEST_MAX_REQUEST_COUNT 8
-#define IMAGEREQUEST_MAX_REDIRECT_RECURSION 16
-#define CACHE_EXPIRE_TIME 30
-#define CACHE_REMOVAL_FRACTION 4
-
-QT_BEGIN_NAMESPACE
-
-// The cache limit describes the maximum "junk" in the cache.
-static int cache_limit = 2048 * 1024; // 2048 KB cache limit for embedded in qpixmapcache.cpp
-
-QSGTexture *QDeclarativeDefaultTextureFactory::createTexture() const
-{
- QSGPlainTexture *t = new QSGPlainTexture();
- t->setImage(im);
- return t;
-}
-
-class QDeclarativePixmapReader;
-class QDeclarativePixmapData;
-class QDeclarativePixmapReply : public QObject
-{
- Q_OBJECT
-public:
- enum ReadError { NoError, Loading, Decoding };
-
- QDeclarativePixmapReply(QDeclarativePixmapData *);
- ~QDeclarativePixmapReply();
-
- QDeclarativePixmapData *data;
- QDeclarativeEngine *engineForReader; // always access reader inside readerMutex
- QSize requestSize;
- QUrl url;
-
- bool loading;
- int redirectCount;
-
- class Event : public QEvent {
- public:
- Event(ReadError, const QString &, const QSize &, QDeclarativeTextureFactory *factory, const QImage &image);
-
- ReadError error;
- QString errorString;
- QSize implicitSize;
- QImage image;
- QDeclarativeTextureFactory *textureFactory;
- };
- void postReply(ReadError, const QString &, const QSize &, const QImage &image);
- void postReply(ReadError, const QString &, const QSize &, QDeclarativeTextureFactory *factory, const QImage &image);
-
-
-Q_SIGNALS:
- void finished();
- void downloadProgress(qint64, qint64);
-
-protected:
- bool event(QEvent *event);
-
-private:
- Q_DISABLE_COPY(QDeclarativePixmapReply)
-
-public:
- static int finishedIndex;
- static int downloadProgressIndex;
-};
-
-class QDeclarativePixmapReaderThreadObject : public QObject {
- Q_OBJECT
-public:
- QDeclarativePixmapReaderThreadObject(QDeclarativePixmapReader *);
- void processJobs();
- virtual bool event(QEvent *e);
-private slots:
- void networkRequestDone();
-private:
- QDeclarativePixmapReader *reader;
-};
-
-class QDeclarativePixmapData;
-class QDeclarativePixmapReader : public QThread
-{
- Q_OBJECT
-public:
- QDeclarativePixmapReader(QDeclarativeEngine *eng);
- ~QDeclarativePixmapReader();
-
- QDeclarativePixmapReply *getImage(QDeclarativePixmapData *);
- void cancel(QDeclarativePixmapReply *rep);
-
- static QDeclarativePixmapReader *instance(QDeclarativeEngine *engine);
- static QDeclarativePixmapReader *existingInstance(QDeclarativeEngine *engine);
-
-protected:
- void run();
-
-private:
- friend class QDeclarativePixmapReaderThreadObject;
- void processJobs();
- void processJob(QDeclarativePixmapReply *, const QUrl &, const QSize &);
- void networkRequestDone(QNetworkReply *);
-
- QList<QDeclarativePixmapReply*> jobs;
- QList<QDeclarativePixmapReply*> cancelled;
- QDeclarativeEngine *engine;
- QObject *eventLoopQuitHack;
-
- QMutex mutex;
- QDeclarativePixmapReaderThreadObject *threadObject;
- QWaitCondition waitCondition;
-
- QNetworkAccessManager *networkAccessManager();
- QNetworkAccessManager *accessManager;
-
- QHash<QNetworkReply*,QDeclarativePixmapReply*> replies;
-
- static int replyDownloadProgress;
- static int replyFinished;
- static int downloadProgress;
- static int threadNetworkRequestDone;
- static QHash<QDeclarativeEngine *,QDeclarativePixmapReader*> readers;
-public:
- static QMutex readerMutex;
-};
-
-class QDeclarativePixmapData
-{
-public:
- QDeclarativePixmapData(QDeclarativePixmap *pixmap, const QUrl &u, const QSize &s, const QString &e)
- : refCount(1), inCache(false), pixmapStatus(QDeclarativePixmap::Error),
- url(u), errorString(e), requestSize(s), textureFactory(0), reply(0), prevUnreferenced(0),
- prevUnreferencedPtr(0), nextUnreferenced(0)
- {
- declarativePixmaps.insert(pixmap);
- }
-
- QDeclarativePixmapData(QDeclarativePixmap *pixmap, const QUrl &u, const QSize &r)
- : refCount(1), inCache(false), pixmapStatus(QDeclarativePixmap::Loading),
- url(u), requestSize(r), textureFactory(0), reply(0), prevUnreferenced(0), prevUnreferencedPtr(0),
- nextUnreferenced(0)
- {
- declarativePixmaps.insert(pixmap);
- }
-
- QDeclarativePixmapData(QDeclarativePixmap *pixmap, const QUrl &u, const QImage &p, const QSize &s, const QSize &r)
- : refCount(1), inCache(false), privatePixmap(false), pixmapStatus(QDeclarativePixmap::Ready),
- url(u), image(p), implicitSize(s), requestSize(r), textureFactory(new QDeclarativeDefaultTextureFactory(p)), reply(0), prevUnreferenced(0),
- prevUnreferencedPtr(0), nextUnreferenced(0)
- {
- declarativePixmaps.insert(pixmap);
- }
-
- QDeclarativePixmapData(QDeclarativePixmap *pixmap, const QUrl &u, QDeclarativeTextureFactory *factory, const QImage &p, const QSize &s, const QSize &r)
- : refCount(1), inCache(false), privatePixmap(false), pixmapStatus(QDeclarativePixmap::Ready),
- url(u), image(p), implicitSize(s), requestSize(r), textureFactory(factory), reply(0), prevUnreferenced(0),
- prevUnreferencedPtr(0), nextUnreferenced(0)
- {
- declarativePixmaps.insert(pixmap);
- }
-
- QDeclarativePixmapData(QDeclarativePixmap *pixmap, const QImage &p)
- : refCount(1), inCache(false), privatePixmap(true), pixmapStatus(QDeclarativePixmap::Ready),
- image(p), implicitSize(p.size()), requestSize(p.size()), textureFactory(new QDeclarativeDefaultTextureFactory(p)), reply(0), prevUnreferenced(0),
- prevUnreferencedPtr(0), nextUnreferenced(0)
- {
- declarativePixmaps.insert(pixmap);
- }
-
- ~QDeclarativePixmapData()
- {
- while (!declarativePixmaps.isEmpty()) {
- QDeclarativePixmap *referencer = declarativePixmaps.first();
- declarativePixmaps.remove(referencer);
- referencer->d = 0;
- }
- delete textureFactory;
- }
-
- int cost() const;
- void addref();
- void release();
- void addToCache();
- void removeFromCache();
-
- uint refCount;
-
- bool inCache:1;
- bool privatePixmap:1;
-
- QDeclarativePixmap::Status pixmapStatus;
- QUrl url;
- QString errorString;
- QImage image;
- QSize implicitSize;
- QSize requestSize;
-
- QDeclarativeTextureFactory *textureFactory;
-
- QIntrusiveList<QDeclarativePixmap, &QDeclarativePixmap::dataListNode> declarativePixmaps;
- QDeclarativePixmapReply *reply;
-
- QDeclarativePixmapData *prevUnreferenced;
- QDeclarativePixmapData**prevUnreferencedPtr;
- QDeclarativePixmapData *nextUnreferenced;
-};
-
-int QDeclarativePixmapReply::finishedIndex = -1;
-int QDeclarativePixmapReply::downloadProgressIndex = -1;
-
-// XXX
-QHash<QDeclarativeEngine *,QDeclarativePixmapReader*> QDeclarativePixmapReader::readers;
-QMutex QDeclarativePixmapReader::readerMutex;
-
-int QDeclarativePixmapReader::replyDownloadProgress = -1;
-int QDeclarativePixmapReader::replyFinished = -1;
-int QDeclarativePixmapReader::downloadProgress = -1;
-int QDeclarativePixmapReader::threadNetworkRequestDone = -1;
-
-
-void QDeclarativePixmapReply::postReply(ReadError error, const QString &errorString,
- const QSize &implicitSize, const QImage &image)
-{
- loading = false;
- QCoreApplication::postEvent(this, new Event(error, errorString, implicitSize, new QDeclarativeDefaultTextureFactory(image), image));
-}
-
-void QDeclarativePixmapReply::postReply(ReadError error, const QString &errorString,
- const QSize &implicitSize, QDeclarativeTextureFactory *factory,
- const QImage &image)
-{
- loading = false;
- QCoreApplication::postEvent(this, new Event(error, errorString, implicitSize, factory, image));
-}
-
-QDeclarativePixmapReply::Event::Event(ReadError e, const QString &s, const QSize &iSize, QDeclarativeTextureFactory *factory, const QImage &i)
- : QEvent(QEvent::User), error(e), errorString(s), implicitSize(iSize), image(i), textureFactory(factory)
-{
-}
-
-QNetworkAccessManager *QDeclarativePixmapReader::networkAccessManager()
-{
- if (!accessManager) {
- Q_ASSERT(threadObject);
- accessManager = QDeclarativeEnginePrivate::get(engine)->createNetworkAccessManager(threadObject);
- }
- return accessManager;
-}
-
-static bool readImage(const QUrl& url, QIODevice *dev, QImage *image, QString *errorString, QSize *impsize,
- const QSize &requestSize)
-{
- QImageReader imgio(dev);
-
- bool force_scale = false;
- if (url.path().endsWith(QLatin1String(".svg"),Qt::CaseInsensitive)) {
- imgio.setFormat("svg"); // QSvgPlugin::capabilities bug QTBUG-9053
- force_scale = true;
- }
-
- bool scaled = false;
- if (requestSize.width() > 0 || requestSize.height() > 0) {
- QSize s = imgio.size();
- if (requestSize.width() && (force_scale || requestSize.width() < s.width())) {
- if (requestSize.height() <= 0)
- s.setHeight(s.height()*requestSize.width()/s.width());
- s.setWidth(requestSize.width()); scaled = true;
- }
- if (requestSize.height() && (force_scale || requestSize.height() < s.height())) {
- if (requestSize.width() <= 0)
- s.setWidth(s.width()*requestSize.height()/s.height());
- s.setHeight(requestSize.height()); scaled = true;
- }
- if (scaled) { imgio.setScaledSize(s); }
- }
-
- if (impsize)
- *impsize = imgio.size();
-
- if (imgio.read(image)) {
- if (impsize && impsize->width() < 0)
- *impsize = image->size();
- return true;
- } else {
- if (errorString)
- *errorString = QDeclarativePixmap::tr("Error decoding: %1: %2").arg(url.toString())
- .arg(imgio.errorString());
- return false;
- }
-}
-
-QDeclarativePixmapReader::QDeclarativePixmapReader(QDeclarativeEngine *eng)
-: QThread(eng), engine(eng), threadObject(0), accessManager(0)
-{
- eventLoopQuitHack = new QObject;
- eventLoopQuitHack->moveToThread(this);
- connect(eventLoopQuitHack, SIGNAL(destroyed(QObject*)), SLOT(quit()), Qt::DirectConnection);
- start(QThread::LowestPriority);
-}
-
-QDeclarativePixmapReader::~QDeclarativePixmapReader()
-{
- readerMutex.lock();
- readers.remove(engine);
- readerMutex.unlock();
-
- mutex.lock();
- // manually cancel all outstanding jobs.
- foreach (QDeclarativePixmapReply *reply, jobs) {
- delete reply;
- }
- jobs.clear();
- QList<QDeclarativePixmapReply*> activeJobs = replies.values();
- foreach (QDeclarativePixmapReply *reply, activeJobs) {
- if (reply->loading) {
- cancelled.append(reply);
- reply->data = 0;
- }
- }
- if (threadObject) threadObject->processJobs();
- mutex.unlock();
-
- eventLoopQuitHack->deleteLater();
- wait();
-}
-
-void QDeclarativePixmapReader::networkRequestDone(QNetworkReply *reply)
-{
- QDeclarativePixmapReply *job = replies.take(reply);
-
- if (job) {
- job->redirectCount++;
- if (job->redirectCount < IMAGEREQUEST_MAX_REDIRECT_RECURSION) {
- QVariant redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
- if (redirect.isValid()) {
- QUrl url = reply->url().resolved(redirect.toUrl());
- QNetworkRequest req(url);
- req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
-
- reply->deleteLater();
- reply = networkAccessManager()->get(req);
-
- QMetaObject::connect(reply, replyDownloadProgress, job, downloadProgress);
- QMetaObject::connect(reply, replyFinished, threadObject, threadNetworkRequestDone);
-
- replies.insert(reply, job);
- return;
- }
- }
-
- QImage image;
- QDeclarativePixmapReply::ReadError error = QDeclarativePixmapReply::NoError;
- QString errorString;
- QSize readSize;
- if (reply->error()) {
- error = QDeclarativePixmapReply::Loading;
- errorString = reply->errorString();
- } else {
- QByteArray all = reply->readAll();
- QBuffer buff(&all);
- buff.open(QIODevice::ReadOnly);
- if (!readImage(reply->url(), &buff, &image, &errorString, &readSize, job->requestSize))
- error = QDeclarativePixmapReply::Decoding;
- }
- // send completion event to the QDeclarativePixmapReply
- mutex.lock();
- if (!cancelled.contains(job)) {
- job->postReply(error, errorString, readSize, image);
- }
- mutex.unlock();
- }
- reply->deleteLater();
-
- // kick off event loop again incase we have dropped below max request count
- threadObject->processJobs();
-}
-
-QDeclarativePixmapReaderThreadObject::QDeclarativePixmapReaderThreadObject(QDeclarativePixmapReader *i)
-: reader(i)
-{
-}
-
-void QDeclarativePixmapReaderThreadObject::processJobs()
-{
- QCoreApplication::postEvent(this, new QEvent(QEvent::User));
-}
-
-bool QDeclarativePixmapReaderThreadObject::event(QEvent *e)
-{
- if (e->type() == QEvent::User) {
- reader->processJobs();
- return true;
- } else {
- return QObject::event(e);
- }
-}
-
-void QDeclarativePixmapReaderThreadObject::networkRequestDone()
-{
- QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
- reader->networkRequestDone(reply);
-}
-
-void QDeclarativePixmapReader::processJobs()
-{
- QMutexLocker locker(&mutex);
-
- while (true) {
- if (cancelled.isEmpty() && (jobs.isEmpty() || replies.count() >= IMAGEREQUEST_MAX_REQUEST_COUNT))
- return; // Nothing else to do
-
- // Clean cancelled jobs
- if (cancelled.count()) {
- for (int i = 0; i < cancelled.count(); ++i) {
- QDeclarativePixmapReply *job = cancelled.at(i);
- QNetworkReply *reply = replies.key(job, 0);
- if (reply && reply->isRunning()) {
- // cancel any jobs already started
- replies.remove(reply);
- reply->close();
- }
- // deleteLater, since not owned by this thread
- job->deleteLater();
- }
- cancelled.clear();
- }
-
- if (!jobs.isEmpty() && replies.count() < IMAGEREQUEST_MAX_REQUEST_COUNT) {
- QDeclarativePixmapReply *runningJob = jobs.takeLast();
- runningJob->loading = true;
-
- QUrl url = runningJob->url;
- QSize requestSize = runningJob->requestSize;
- locker.unlock();
- processJob(runningJob, url, requestSize);
- locker.relock();
- }
- }
-}
-
-void QDeclarativePixmapReader::processJob(QDeclarativePixmapReply *runningJob, const QUrl &url,
- const QSize &requestSize)
-{
- // fetch
- if (url.scheme() == QLatin1String("image")) {
- // Use QmlImageProvider
- QSize readSize;
- QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(engine);
- QDeclarativeImageProvider::ImageType imageType = ep->getImageProviderType(url);
- if (imageType == QDeclarativeImageProvider::Invalid) {
- QDeclarativePixmapReply::ReadError errorCode = QDeclarativePixmapReply::Loading;
- QString errorStr = QDeclarativePixmap::tr("Invalid image provider: %1").arg(url.toString());
- QImage image;
- mutex.lock();
- if (!cancelled.contains(runningJob))
- runningJob->postReply(errorCode, errorStr, readSize, image);
- mutex.unlock();
- } else if (imageType == QDeclarativeImageProvider::Image) {
- QImage image = ep->getImageFromProvider(url, &readSize, requestSize);
- QDeclarativePixmapReply::ReadError errorCode = QDeclarativePixmapReply::NoError;
- QString errorStr;
- if (image.isNull()) {
- errorCode = QDeclarativePixmapReply::Loading;
- errorStr = QDeclarativePixmap::tr("Failed to get image from provider: %1").arg(url.toString());
- }
- mutex.lock();
- if (!cancelled.contains(runningJob))
- runningJob->postReply(errorCode, errorStr, readSize, image);
- mutex.unlock();
- } else {
- QDeclarativeTextureFactory *t = ep->getTextureFromProvider(url, &readSize, requestSize);
- QDeclarativePixmapReply::ReadError errorCode = QDeclarativePixmapReply::NoError;
- QString errorStr;
- if (!t) {
- errorCode = QDeclarativePixmapReply::Loading;
- errorStr = QDeclarativePixmap::tr("Failed to get texture from provider: %1").arg(url.toString());
- }
- mutex.lock();
- if (!cancelled.contains(runningJob))
- runningJob->postReply(errorCode, errorStr, readSize, t, QImage());
- mutex.unlock();
-
- }
-
- } else {
- QString lf = QDeclarativeEnginePrivate::urlToLocalFileOrQrc(url);
- if (!lf.isEmpty()) {
- // Image is local - load/decode immediately
- QImage image;
- QDeclarativePixmapReply::ReadError errorCode = QDeclarativePixmapReply::NoError;
- QString errorStr;
- QFile f(lf);
- QSize readSize;
- if (f.open(QIODevice::ReadOnly)) {
- if (!readImage(url, &f, &image, &errorStr, &readSize, requestSize))
- errorCode = QDeclarativePixmapReply::Loading;
- } else {
- errorStr = QDeclarativePixmap::tr("Cannot open: %1").arg(url.toString());
- errorCode = QDeclarativePixmapReply::Loading;
- }
- mutex.lock();
- if (!cancelled.contains(runningJob))
- runningJob->postReply(errorCode, errorStr, readSize, image);
- mutex.unlock();
- } else {
- // Network resource
- QNetworkRequest req(url);
- req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
- QNetworkReply *reply = networkAccessManager()->get(req);
-
- QMetaObject::connect(reply, replyDownloadProgress, runningJob, downloadProgress);
- QMetaObject::connect(reply, replyFinished, threadObject, threadNetworkRequestDone);
-
- replies.insert(reply, runningJob);
- }
- }
-}
-
-QDeclarativePixmapReader *QDeclarativePixmapReader::instance(QDeclarativeEngine *engine)
-{
- // XXX NOTE: must be called within readerMutex locking.
- QDeclarativePixmapReader *reader = readers.value(engine);
- if (!reader) {
- reader = new QDeclarativePixmapReader(engine);
- readers.insert(engine, reader);
- }
-
- return reader;
-}
-
-QDeclarativePixmapReader *QDeclarativePixmapReader::existingInstance(QDeclarativeEngine *engine)
-{
- // XXX NOTE: must be called within readerMutex locking.
- return readers.value(engine, 0);
-}
-
-QDeclarativePixmapReply *QDeclarativePixmapReader::getImage(QDeclarativePixmapData *data)
-{
- mutex.lock();
- QDeclarativePixmapReply *reply = new QDeclarativePixmapReply(data);
- reply->engineForReader = engine;
- jobs.append(reply);
- // XXX
- if (threadObject) threadObject->processJobs();
- mutex.unlock();
- return reply;
-}
-
-void QDeclarativePixmapReader::cancel(QDeclarativePixmapReply *reply)
-{
- mutex.lock();
- if (reply->loading) {
- cancelled.append(reply);
- reply->data = 0;
- // XXX
- if (threadObject) threadObject->processJobs();
- } else {
- jobs.removeAll(reply);
- delete reply;
- }
- mutex.unlock();
-}
-
-void QDeclarativePixmapReader::run()
-{
- if (replyDownloadProgress == -1) {
- const QMetaObject *nr = &QNetworkReply::staticMetaObject;
- const QMetaObject *pr = &QDeclarativePixmapReply::staticMetaObject;
- const QMetaObject *ir = &QDeclarativePixmapReaderThreadObject::staticMetaObject;
- replyDownloadProgress = nr->indexOfSignal("downloadProgress(qint64,qint64)");
- replyFinished = nr->indexOfSignal("finished()");
- downloadProgress = pr->indexOfSignal("downloadProgress(qint64,qint64)");
- threadNetworkRequestDone = ir->indexOfSlot("networkRequestDone()");
- }
-
- mutex.lock();
- threadObject = new QDeclarativePixmapReaderThreadObject(this);
- mutex.unlock();
-
- processJobs();
- exec();
-
- delete threadObject;
- threadObject = 0;
-}
-
-class QDeclarativePixmapKey
-{
-public:
- const QUrl *url;
- const QSize *size;
-};
-
-inline bool operator==(const QDeclarativePixmapKey &lhs, const QDeclarativePixmapKey &rhs)
-{
- return *lhs.size == *rhs.size && *lhs.url == *rhs.url;
-}
-
-inline uint qHash(const QDeclarativePixmapKey &key)
-{
- return qHash(*key.url) ^ key.size->width() ^ key.size->height();
-}
-
-class QSGContext;
-
-class QDeclarativePixmapStore : public QObject
-{
- Q_OBJECT
-public:
- QDeclarativePixmapStore();
- ~QDeclarativePixmapStore();
-
- void unreferencePixmap(QDeclarativePixmapData *);
- void referencePixmap(QDeclarativePixmapData *);
-
-protected:
- virtual void timerEvent(QTimerEvent *);
-
-public:
- QHash<QDeclarativePixmapKey, QDeclarativePixmapData *> m_cache;
-
-private:
- void shrinkCache(int remove);
-
- QDeclarativePixmapData *m_unreferencedPixmaps;
- QDeclarativePixmapData *m_lastUnreferencedPixmap;
-
- int m_unreferencedCost;
- int m_timerId;
-};
-Q_GLOBAL_STATIC(QDeclarativePixmapStore, pixmapStore);
-
-
-QDeclarativePixmapStore::QDeclarativePixmapStore()
-: m_unreferencedPixmaps(0), m_lastUnreferencedPixmap(0), m_unreferencedCost(0), m_timerId(-1)
-{
-}
-
-QDeclarativePixmapStore::~QDeclarativePixmapStore()
-{
- int leakedPixmaps = 0;
- QList<QDeclarativePixmapData*> cachedData = m_cache.values();
-
- // unreference all (leaked) pixmaps
- foreach (QDeclarativePixmapData* pixmap, cachedData) {
- int currRefCount = pixmap->refCount;
- if (currRefCount) {
- leakedPixmaps++;
- while (currRefCount > 0) {
- pixmap->release();
- currRefCount--;
- }
- }
- }
-
- // free all unreferenced pixmaps
- while (m_lastUnreferencedPixmap) {
- shrinkCache(20);
- }
-
- if (leakedPixmaps)
- qDebug("Number of leaked pixmaps: %i", leakedPixmaps);
-}
-
-void QDeclarativePixmapStore::unreferencePixmap(QDeclarativePixmapData *data)
-{
- Q_ASSERT(data->prevUnreferenced == 0);
- Q_ASSERT(data->prevUnreferencedPtr == 0);
- Q_ASSERT(data->nextUnreferenced == 0);
-
- data->nextUnreferenced = m_unreferencedPixmaps;
- data->prevUnreferencedPtr = &m_unreferencedPixmaps;
-
- m_unreferencedPixmaps = data;
- if (m_unreferencedPixmaps->nextUnreferenced) {
- m_unreferencedPixmaps->nextUnreferenced->prevUnreferenced = m_unreferencedPixmaps;
- m_unreferencedPixmaps->nextUnreferenced->prevUnreferencedPtr = &m_unreferencedPixmaps->nextUnreferenced;
- }
-
- if (!m_lastUnreferencedPixmap)
- m_lastUnreferencedPixmap = data;
-
- m_unreferencedCost += data->cost();
-
- shrinkCache(-1); // Shrink the cache incase it has become larger than cache_limit
-
- if (m_timerId == -1 && m_unreferencedPixmaps)
- m_timerId = startTimer(CACHE_EXPIRE_TIME * 1000);
-}
-
-void QDeclarativePixmapStore::referencePixmap(QDeclarativePixmapData *data)
-{
- Q_ASSERT(data->prevUnreferencedPtr);
-
- *data->prevUnreferencedPtr = data->nextUnreferenced;
- if (data->nextUnreferenced) {
- data->nextUnreferenced->prevUnreferencedPtr = data->prevUnreferencedPtr;
- data->nextUnreferenced->prevUnreferenced = data->prevUnreferenced;
- }
- if (m_lastUnreferencedPixmap == data)
- m_lastUnreferencedPixmap = data->prevUnreferenced;
-
- data->nextUnreferenced = 0;
- data->prevUnreferencedPtr = 0;
- data->prevUnreferenced = 0;
-
- m_unreferencedCost -= data->cost();
-}
-
-void QDeclarativePixmapStore::shrinkCache(int remove)
-{
- while ((remove > 0 || m_unreferencedCost > cache_limit) && m_lastUnreferencedPixmap) {
- QDeclarativePixmapData *data = m_lastUnreferencedPixmap;
- Q_ASSERT(data->nextUnreferenced == 0);
-
- *data->prevUnreferencedPtr = 0;
- m_lastUnreferencedPixmap = data->prevUnreferenced;
- data->prevUnreferencedPtr = 0;
- data->prevUnreferenced = 0;
-
- remove -= data->cost();
- m_unreferencedCost -= data->cost();
- data->removeFromCache();
- delete data;
- }
-}
-
-void QDeclarativePixmapStore::timerEvent(QTimerEvent *)
-{
- int removalCost = m_unreferencedCost / CACHE_REMOVAL_FRACTION;
-
- shrinkCache(removalCost);
-
- if (m_unreferencedPixmaps == 0) {
- killTimer(m_timerId);
- m_timerId = -1;
- }
-}
-
-QDeclarativePixmapReply::QDeclarativePixmapReply(QDeclarativePixmapData *d)
-: data(d), engineForReader(0), requestSize(d->requestSize), url(d->url), loading(false), redirectCount(0)
-{
- if (finishedIndex == -1) {
- finishedIndex = QDeclarativePixmapReply::staticMetaObject.indexOfSignal("finished()");
- downloadProgressIndex = QDeclarativePixmapReply::staticMetaObject.indexOfSignal("downloadProgress(qint64,qint64)");
- }
-}
-
-QDeclarativePixmapReply::~QDeclarativePixmapReply()
-{
-}
-
-bool QDeclarativePixmapReply::event(QEvent *event)
-{
- if (event->type() == QEvent::User) {
-
- if (data) {
- Event *de = static_cast<Event *>(event);
- data->pixmapStatus = (de->error == NoError) ? QDeclarativePixmap::Ready : QDeclarativePixmap::Error;
-
- if (data->pixmapStatus == QDeclarativePixmap::Ready) {
- if (de->textureFactory) {
- data->textureFactory = de->textureFactory;
- }
- data->image = de->image;
- data->implicitSize = de->implicitSize;
- } else {
- data->errorString = de->errorString;
- data->removeFromCache(); // We don't continue to cache error'd pixmaps
- }
-
- data->reply = 0;
- emit finished();
- }
-
- delete this;
- return true;
- } else {
- return QObject::event(event);
- }
-}
-
-int QDeclarativePixmapData::cost() const
-{
- if (textureFactory)
- return textureFactory->textureByteCount();
- return image.byteCount();
-}
-
-void QDeclarativePixmapData::addref()
-{
- ++refCount;
- if (prevUnreferencedPtr)
- pixmapStore()->referencePixmap(this);
-}
-
-void QDeclarativePixmapData::release()
-{
- Q_ASSERT(refCount > 0);
- --refCount;
- if (refCount == 0) {
- if (reply) {
- QDeclarativePixmapReply *cancelReply = reply;
- reply->data = 0;
- reply = 0;
- QDeclarativePixmapReader::readerMutex.lock();
- QDeclarativePixmapReader *reader = QDeclarativePixmapReader::existingInstance(cancelReply->engineForReader);
- if (reader)
- reader->cancel(cancelReply);
- QDeclarativePixmapReader::readerMutex.unlock();
- }
-
- if (pixmapStatus == QDeclarativePixmap::Ready) {
- pixmapStore()->unreferencePixmap(this);
- } else {
- removeFromCache();
- delete this;
- }
- }
-}
-
-void QDeclarativePixmapData::addToCache()
-{
- if (!inCache) {
- QDeclarativePixmapKey key = { &url, &requestSize };
- pixmapStore()->m_cache.insert(key, this);
- inCache = true;
- }
-}
-
-void QDeclarativePixmapData::removeFromCache()
-{
- if (inCache) {
- QDeclarativePixmapKey key = { &url, &requestSize };
- pixmapStore()->m_cache.remove(key);
- inCache = false;
- }
-}
-
-static QDeclarativePixmapData* createPixmapDataSync(QDeclarativePixmap *declarativePixmap, QDeclarativeEngine *engine, const QUrl &url, const QSize &requestSize, bool *ok)
-{
- if (url.scheme() == QLatin1String("image")) {
- QSize readSize;
- QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(engine);
- QDeclarativeImageProvider::ImageType imageType = ep->getImageProviderType(url);
-
- switch (imageType) {
- case QDeclarativeImageProvider::Invalid:
- return new QDeclarativePixmapData(declarativePixmap, url, requestSize,
- QDeclarativePixmap::tr("Invalid image provider: %1").arg(url.toString()));
- case QDeclarativeImageProvider::Texture:
- {
- QDeclarativeTextureFactory *texture = ep->getTextureFromProvider(url, &readSize, requestSize);
- if (texture) {
- *ok = true;
- return new QDeclarativePixmapData(declarativePixmap, url, texture, QImage(), readSize, requestSize);
- }
- }
-
- case QDeclarativeImageProvider::Image:
- {
- QImage image = ep->getImageFromProvider(url, &readSize, requestSize);
- if (!image.isNull()) {
- *ok = true;
- return new QDeclarativePixmapData(declarativePixmap, url, image, readSize, requestSize);
- }
- }
- case QDeclarativeImageProvider::Pixmap:
- {
- QPixmap pixmap = ep->getPixmapFromProvider(url, &readSize, requestSize);
- if (!pixmap.isNull()) {
- *ok = true;
- return new QDeclarativePixmapData(declarativePixmap, url, pixmap.toImage(), readSize, requestSize);
- }
- }
- }
-
- // provider has bad image type, or provider returned null image
- return new QDeclarativePixmapData(declarativePixmap, url, requestSize,
- QDeclarativePixmap::tr("Failed to get image from provider: %1").arg(url.toString()));
- }
-
- QString localFile = QDeclarativeEnginePrivate::urlToLocalFileOrQrc(url);
- if (localFile.isEmpty())
- return 0;
-
- QFile f(localFile);
- QSize readSize;
- QString errorString;
-
- if (f.open(QIODevice::ReadOnly)) {
- QImage image;
-
- if (readImage(url, &f, &image, &errorString, &readSize, requestSize)) {
- *ok = true;
- return new QDeclarativePixmapData(declarativePixmap, url, image, readSize, requestSize);
- }
- errorString = QDeclarativePixmap::tr("Invalid image data: %1").arg(url.toString());
-
- } else {
- errorString = QDeclarativePixmap::tr("Cannot open: %1").arg(url.toString());
- }
- return new QDeclarativePixmapData(declarativePixmap, url, requestSize, errorString);
-}
-
-
-struct QDeclarativePixmapNull {
- QUrl url;
- QImage image;
- QSize size;
-};
-Q_GLOBAL_STATIC(QDeclarativePixmapNull, nullPixmap);
-
-QDeclarativePixmap::QDeclarativePixmap()
-: d(0)
-{
-}
-
-QDeclarativePixmap::QDeclarativePixmap(QDeclarativeEngine *engine, const QUrl &url)
-: d(0)
-{
- load(engine, url);
-}
-
-QDeclarativePixmap::QDeclarativePixmap(QDeclarativeEngine *engine, const QUrl &url, const QSize &size)
-: d(0)
-{
- load(engine, url, size);
-}
-
-QDeclarativePixmap::~QDeclarativePixmap()
-{
- if (d) {
- d->declarativePixmaps.remove(this);
- d->release();
- d = 0;
- }
-}
-
-bool QDeclarativePixmap::isNull() const
-{
- return d == 0;
-}
-
-bool QDeclarativePixmap::isReady() const
-{
- return status() == Ready;
-}
-
-bool QDeclarativePixmap::isError() const
-{
- return status() == Error;
-}
-
-bool QDeclarativePixmap::isLoading() const
-{
- return status() == Loading;
-}
-
-QString QDeclarativePixmap::error() const
-{
- if (d)
- return d->errorString;
- else
- return QString();
-}
-
-QDeclarativePixmap::Status QDeclarativePixmap::status() const
-{
- if (d)
- return d->pixmapStatus;
- else
- return Null;
-}
-
-const QUrl &QDeclarativePixmap::url() const
-{
- if (d)
- return d->url;
- else
- return nullPixmap()->url;
-}
-
-const QSize &QDeclarativePixmap::implicitSize() const
-{
- if (d)
- return d->implicitSize;
- else
- return nullPixmap()->size;
-}
-
-const QSize &QDeclarativePixmap::requestSize() const
-{
- if (d)
- return d->requestSize;
- else
- return nullPixmap()->size;
-}
-
-QDeclarativeTextureFactory *QDeclarativePixmap::textureFactory() const
-{
- if (d)
- return d->textureFactory;
-
- return 0;
-}
-
-const QImage &QDeclarativePixmap::image() const
-{
- if (d)
- return d->image;
- else
- return nullPixmap()->image;
-}
-
-void QDeclarativePixmap::setImage(const QImage &p)
-{
- clear();
-
- if (!p.isNull())
- d = new QDeclarativePixmapData(this, p);
-}
-
-int QDeclarativePixmap::width() const
-{
- if (d)
- return d->textureFactory ? d->textureFactory->textureSize().width() : d->image.width();
- else
- return 0;
-}
-
-int QDeclarativePixmap::height() const
-{
- if (d)
- return d->textureFactory ? d->textureFactory->textureSize().height() : d->image.height();
- else
- return 0;
-}
-
-QRect QDeclarativePixmap::rect() const
-{
- if (d)
- return d->textureFactory ? QRect(QPoint(), d->textureFactory->textureSize()) : d->image.rect();
- else
- return QRect();
-}
-
-void QDeclarativePixmap::load(QDeclarativeEngine *engine, const QUrl &url)
-{
- load(engine, url, QSize(), QDeclarativePixmap::Cache);
-}
-
-void QDeclarativePixmap::load(QDeclarativeEngine *engine, const QUrl &url, QDeclarativePixmap::Options options)
-{
- load(engine, url, QSize(), options);
-}
-
-void QDeclarativePixmap::load(QDeclarativeEngine *engine, const QUrl &url, const QSize &size)
-{
- load(engine, url, size, QDeclarativePixmap::Cache);
-}
-
-void QDeclarativePixmap::load(QDeclarativeEngine *engine, const QUrl &url, const QSize &requestSize, QDeclarativePixmap::Options options)
-{
- if (d) {
- d->declarativePixmaps.remove(this);
- d->release();
- d = 0;
- }
-
- QDeclarativePixmapKey key = { &url, &requestSize };
- QDeclarativePixmapStore *store = pixmapStore();
-
- QHash<QDeclarativePixmapKey, QDeclarativePixmapData *>::Iterator iter = store->m_cache.find(key);
-
- if (iter == store->m_cache.end()) {
- if (options & QDeclarativePixmap::Asynchronous) {
- // pixmaps can only be loaded synchronously
- if (url.scheme() == QLatin1String("image")
- && QDeclarativeEnginePrivate::get(engine)->getImageProviderType(url) == QDeclarativeImageProvider::Pixmap) {
- options &= ~QDeclarativePixmap::Asynchronous;
- }
- }
-
- if (!(options & QDeclarativePixmap::Asynchronous)) {
- bool ok = false;
- d = createPixmapDataSync(this, engine, url, requestSize, &ok);
- if (ok) {
- if (options & QDeclarativePixmap::Cache)
- d->addToCache();
- return;
- }
- if (d) // loadable, but encountered error while loading
- return;
- }
-
- if (!engine)
- return;
-
- d = new QDeclarativePixmapData(this, url, requestSize);
- if (options & QDeclarativePixmap::Cache)
- d->addToCache();
-
- QDeclarativePixmapReader::readerMutex.lock();
- d->reply = QDeclarativePixmapReader::instance(engine)->getImage(d);
- QDeclarativePixmapReader::readerMutex.unlock();
- } else {
- d = *iter;
- d->addref();
- d->declarativePixmaps.insert(this);
- }
-}
-
-void QDeclarativePixmap::clear()
-{
- if (d) {
- d->declarativePixmaps.remove(this);
- d->release();
- d = 0;
- }
-}
-
-void QDeclarativePixmap::clear(QObject *obj)
-{
- if (d) {
- if (d->reply)
- QObject::disconnect(d->reply, 0, obj, 0);
- d->declarativePixmaps.remove(this);
- d->release();
- d = 0;
- }
-}
-
-bool QDeclarativePixmap::connectFinished(QObject *object, const char *method)
-{
- if (!d || !d->reply) {
- qWarning("QDeclarativePixmap: connectFinished() called when not loading.");
- return false;
- }
-
- return QObject::connect(d->reply, SIGNAL(finished()), object, method);
-}
-
-bool QDeclarativePixmap::connectFinished(QObject *object, int method)
-{
- if (!d || !d->reply) {
- qWarning("QDeclarativePixmap: connectFinished() called when not loading.");
- return false;
- }
-
- return QMetaObject::connect(d->reply, QDeclarativePixmapReply::finishedIndex, object, method);
-}
-
-bool QDeclarativePixmap::connectDownloadProgress(QObject *object, const char *method)
-{
- if (!d || !d->reply) {
- qWarning("QDeclarativePixmap: connectDownloadProgress() called when not loading.");
- return false;
- }
-
- return QObject::connect(d->reply, SIGNAL(downloadProgress(qint64,qint64)), object, method);
-}
-
-bool QDeclarativePixmap::connectDownloadProgress(QObject *object, int method)
-{
- if (!d || !d->reply) {
- qWarning("QDeclarativePixmap: connectDownloadProgress() called when not loading.");
- return false;
- }
-
- return QMetaObject::connect(d->reply, QDeclarativePixmapReply::downloadProgressIndex, object, method);
-}
-
-QT_END_NAMESPACE
-
-#include <qdeclarativepixmapcache.moc>
diff --git a/src/declarative/util/qdeclarativepixmapcache_p.h b/src/declarative/util/qdeclarativepixmapcache_p.h
deleted file mode 100644
index a0e35aba5d..0000000000
--- a/src/declarative/util/qdeclarativepixmapcache_p.h
+++ /dev/null
@@ -1,143 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEPIXMAPCACHE_H
-#define QDECLARATIVEPIXMAPCACHE_H
-
-#include <QtCore/qcoreapplication.h>
-#include <QtCore/qstring.h>
-#include <QtGui/qpixmap.h>
-#include <QtCore/qurl.h>
-
-#include <private/qintrusivelist_p.h>
-#include <qdeclarativeimageprovider.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeEngine;
-class QDeclarativePixmapData;
-class QDeclarativeTextureFactory;
-
-class QDeclarativeDefaultTextureFactory : public QDeclarativeTextureFactory
-{
- Q_OBJECT
-public:
- QDeclarativeDefaultTextureFactory(const QImage &i)
- : im(i)
- {
- }
-
- QSGTexture *createTexture() const;
- QSize textureSize() const { return im.size(); }
- int textureByteCount() const { return im.byteCount(); }
- QImage image() const { return im; }
-
-private:
- QImage im;
-};
-
-class Q_DECLARATIVE_EXPORT QDeclarativePixmap
-{
- Q_DECLARE_TR_FUNCTIONS(QDeclarativePixmap)
-public:
- QDeclarativePixmap();
- QDeclarativePixmap(QDeclarativeEngine *, const QUrl &);
- QDeclarativePixmap(QDeclarativeEngine *, const QUrl &, const QSize &);
- ~QDeclarativePixmap();
-
- enum Status { Null, Ready, Error, Loading };
-
- enum Option {
- Asynchronous = 0x00000001,
- Cache = 0x00000002
- };
- Q_DECLARE_FLAGS(Options, Option)
-
- bool isNull() const;
- bool isReady() const;
- bool isError() const;
- bool isLoading() const;
-
- Status status() const;
- QString error() const;
- const QUrl &url() const;
- const QSize &implicitSize() const;
- const QSize &requestSize() const;
- const QImage &image() const;
- void setImage(const QImage &);
-
- QDeclarativeTextureFactory *textureFactory() const;
-
- QRect rect() const;
- int width() const;
- int height() const;
-
- void load(QDeclarativeEngine *, const QUrl &);
- void load(QDeclarativeEngine *, const QUrl &, QDeclarativePixmap::Options options);
- void load(QDeclarativeEngine *, const QUrl &, const QSize &);
- void load(QDeclarativeEngine *, const QUrl &, const QSize &, QDeclarativePixmap::Options options);
-
- void clear();
- void clear(QObject *);
-
- bool connectFinished(QObject *, const char *);
- bool connectFinished(QObject *, int);
- bool connectDownloadProgress(QObject *, const char *);
- bool connectDownloadProgress(QObject *, int);
-
-private:
- Q_DISABLE_COPY(QDeclarativePixmap)
- QDeclarativePixmapData *d;
- QIntrusiveListNode dataListNode;
- friend class QDeclarativePixmapData;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QDeclarativePixmap::Options)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDECLARATIVEPIXMAPCACHE_H
diff --git a/src/declarative/util/qdeclarativepropertychanges.cpp b/src/declarative/util/qdeclarativepropertychanges.cpp
deleted file mode 100644
index d6035fa9d2..0000000000
--- a/src/declarative/util/qdeclarativepropertychanges.cpp
+++ /dev/null
@@ -1,796 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativepropertychanges_p.h"
-
-#include <private/qdeclarativeopenmetaobject_p.h>
-#include <private/qdeclarativerewrite_p.h>
-#include <private/qdeclarativeengine_p.h>
-
-#include <qdeclarativeinfo.h>
-#include <private/qdeclarativecustomparser_p.h>
-#include <private/qdeclarativescript_p.h>
-#include <qdeclarativeexpression.h>
-#include <private/qdeclarativebinding_p.h>
-#include <qdeclarativecontext.h>
-#include <private/qdeclarativeguard_p.h>
-#include <private/qdeclarativeproperty_p.h>
-#include <private/qdeclarativecontext_p.h>
-#include <private/qdeclarativestate_p_p.h>
-
-#include <QtCore/qdebug.h>
-
-#include <private/qobject_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass PropertyChanges QDeclarativePropertyChanges
- \inqmlmodule QtQuick 2
- \ingroup qml-state-elements
- \brief The PropertyChanges element describes new property bindings or values for a state.
-
- PropertyChanges is used to define the property values or bindings in a
- \l State. This enables an item's property values to be changed when it
- \l {QML States}{changes between states}.
-
- To create a PropertyChanges object, specify the \l target item whose
- properties are to be modified, and define the new property values or
- bindings. For example:
-
- \snippet doc/src/snippets/declarative/propertychanges.qml import
- \codeline
- \snippet doc/src/snippets/declarative/propertychanges.qml 0
-
- When the mouse is pressed, the \l Rectangle changes to the \e resized
- state. In this state, the PropertyChanges object sets the rectangle's
- color to blue and the \c height value to that of \c container.height.
-
- Note this automatically binds \c rect.height to \c container.height
- in the \e resized state. If a property binding should not be
- established, and the height should just be set to the value of
- \c container.height at the time of the state change, set the \l explicit
- property to \c true.
-
- A PropertyChanges object can also override the default signal handler
- for an object to implement a signal handler specific to the new state:
-
- \qml
- PropertyChanges {
- target: myMouseArea
- onClicked: doSomethingDifferent()
- }
- \endqml
-
- \note PropertyChanges can be used to change anchor margins, but not other anchor
- values; use AnchorChanges for this instead. Similarly, to change an \l Item's
- \l {Item::}{parent} value, use ParentChanges instead.
-
-
- \section2 Resetting property values
-
- The \c undefined value can be used to reset the property value for a state.
- In the following example, when \c myText changes to the \e widerText
- state, its \c width property is reset, giving the text its natural width
- and displaying the whole string on a single line.
-
- \snippet doc/src/snippets/declarative/propertychanges.qml reset
-
-
- \section2 Immediate property changes in transitions
-
- When \l{QML Animation and Transitions}{Transitions} are used to animate
- state changes, they animate properties from their values in the current
- state to those defined in the new state (as defined by PropertyChanges
- objects). However, it is sometimes desirable to set a property value
- \e immediately during a \l Transition, without animation; in these cases,
- the PropertyAction element can be used to force an immediate property
- change.
-
- See the PropertyAction documentation for more details.
-
- \sa {declarative/animation/states}{states example}, {qmlstate}{States}, QtDeclarative
-*/
-
-/*!
- \qmlproperty Object QtQuick2::PropertyChanges::target
- This property holds the object which contains the properties to be changed.
-*/
-
-class QDeclarativeReplaceSignalHandler : public QDeclarativeActionEvent
-{
-public:
- QDeclarativeReplaceSignalHandler() : expression(0), reverseExpression(0),
- rewindExpression(0), ownedExpression(0) {}
- ~QDeclarativeReplaceSignalHandler() {
- delete ownedExpression;
- }
-
- virtual QString typeName() const { return QLatin1String("ReplaceSignalHandler"); }
-
- QDeclarativeProperty property;
- QDeclarativeExpression *expression;
- QDeclarativeExpression *reverseExpression;
- QDeclarativeExpression *rewindExpression;
- QDeclarativeGuard<QDeclarativeExpression> ownedExpression;
-
- virtual void execute(Reason) {
- ownedExpression = QDeclarativePropertyPrivate::setSignalExpression(property, expression);
- if (ownedExpression == expression)
- ownedExpression = 0;
- }
-
- virtual bool isReversable() { return true; }
- virtual void reverse(Reason) {
- ownedExpression = QDeclarativePropertyPrivate::setSignalExpression(property, reverseExpression);
- if (ownedExpression == reverseExpression)
- ownedExpression = 0;
- }
-
- virtual void saveOriginals() {
- saveCurrentValues();
- reverseExpression = rewindExpression;
- }
-
- virtual bool needsCopy() { return true; }
- virtual void copyOriginals(QDeclarativeActionEvent *other)
- {
- QDeclarativeReplaceSignalHandler *rsh = static_cast<QDeclarativeReplaceSignalHandler*>(other);
- saveCurrentValues();
- if (rsh == this)
- return;
- reverseExpression = rsh->reverseExpression;
- if (rsh->ownedExpression == reverseExpression) {
- ownedExpression = rsh->ownedExpression;
- rsh->ownedExpression = 0;
- }
- }
-
- virtual void rewind() {
- ownedExpression = QDeclarativePropertyPrivate::setSignalExpression(property, rewindExpression);
- if (ownedExpression == rewindExpression)
- ownedExpression = 0;
- }
- virtual void saveCurrentValues() {
- rewindExpression = QDeclarativePropertyPrivate::signalExpression(property);
- }
-
- virtual bool override(QDeclarativeActionEvent*other) {
- if (other == this)
- return true;
- if (other->typeName() != typeName())
- return false;
- if (static_cast<QDeclarativeReplaceSignalHandler*>(other)->property == property)
- return true;
- return false;
- }
-};
-
-
-class QDeclarativePropertyChangesPrivate : public QDeclarativeStateOperationPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativePropertyChanges)
-public:
- QDeclarativePropertyChangesPrivate() : decoded(true), restore(true),
- isExplicit(false) {}
-
- QDeclarativeGuard<QObject> object;
- QByteArray data;
-
- bool decoded : 1;
- bool restore : 1;
- bool isExplicit : 1;
-
- void decode();
-
- class ExpressionChange {
- public:
- ExpressionChange(const QString &_name,
- QDeclarativeBinding::Identifier _id,
- QDeclarativeExpression *_expr)
- : name(_name), id(_id), expression(_expr) {}
- QString name;
- QDeclarativeBinding::Identifier id;
- QDeclarativeExpression *expression;
- };
-
- QList<QPair<QString, QVariant> > properties;
- QList<ExpressionChange> expressions;
- QList<QDeclarativeReplaceSignalHandler*> signalReplacements;
-
- QDeclarativeProperty property(const QString &);
-};
-
-void
-QDeclarativePropertyChangesParser::compileList(QList<QPair<QString, QVariant> > &list,
- const QString &pre,
- const QDeclarativeCustomParserProperty &prop)
-{
- QString propName = pre + prop.name();
-
- QList<QVariant> values = prop.assignedValues();
- for (int ii = 0; ii < values.count(); ++ii) {
- const QVariant &value = values.at(ii);
-
- if (value.userType() == qMetaTypeId<QDeclarativeCustomParserNode>()) {
- error(qvariant_cast<QDeclarativeCustomParserNode>(value),
- QDeclarativePropertyChanges::tr("PropertyChanges does not support creating state-specific objects."));
- continue;
- } else if(value.userType() == qMetaTypeId<QDeclarativeCustomParserProperty>()) {
-
- QDeclarativeCustomParserProperty prop =
- qvariant_cast<QDeclarativeCustomParserProperty>(value);
- QString pre = propName + QLatin1Char('.');
- compileList(list, pre, prop);
-
- } else {
- list << qMakePair(propName, value);
- }
- }
-}
-
-QByteArray
-QDeclarativePropertyChangesParser::compile(const QList<QDeclarativeCustomParserProperty> &props)
-{
- QList<QPair<QString, QVariant> > data;
- for(int ii = 0; ii < props.count(); ++ii)
- compileList(data, QString(), props.at(ii));
-
- QByteArray rv;
- QDataStream ds(&rv, QIODevice::WriteOnly);
-
- ds << data.count();
- for(int ii = 0; ii < data.count(); ++ii) {
- QDeclarativeScript::Variant v = qvariant_cast<QDeclarativeScript::Variant>(data.at(ii).second);
- QVariant var;
- bool isScript = v.isScript();
- QDeclarativeBinding::Identifier id = 0;
- switch(v.type()) {
- case QDeclarativeScript::Variant::Boolean:
- var = QVariant(v.asBoolean());
- break;
- case QDeclarativeScript::Variant::Number:
- var = QVariant(v.asNumber());
- break;
- case QDeclarativeScript::Variant::String:
- var = QVariant(v.asString());
- break;
- case QDeclarativeScript::Variant::Invalid:
- case QDeclarativeScript::Variant::Script:
- var = QVariant(v.asScript());
- {
- // Pre-rewrite the expression
- id = rewriteBinding(v, data.at(ii).first);
- }
- break;
- }
-
- ds << data.at(ii).first << isScript << var;
- if (isScript)
- ds << id;
- }
-
- return rv;
-}
-
-void QDeclarativePropertyChangesPrivate::decode()
-{
- Q_Q(QDeclarativePropertyChanges);
- if (decoded)
- return;
-
- QDataStream ds(&data, QIODevice::ReadOnly);
-
- int count;
- ds >> count;
- for (int ii = 0; ii < count; ++ii) {
- QString name;
- bool isScript;
- QVariant data;
- QDeclarativeBinding::Identifier id = QDeclarativeBinding::Invalid;
- ds >> name;
- ds >> isScript;
- ds >> data;
- if (isScript)
- ds >> id;
-
- QDeclarativeProperty prop = property(name); //### better way to check for signal property?
- if (prop.type() & QDeclarativeProperty::SignalProperty) {
- QDeclarativeExpression *expression = new QDeclarativeExpression(qmlContext(q), object, data.toString());
- QDeclarativeData *ddata = QDeclarativeData::get(q);
- if (ddata && ddata->outerContext && !ddata->outerContext->url.isEmpty())
- expression->setSourceLocation(ddata->outerContext->url.toString(), ddata->lineNumber);
- QDeclarativeReplaceSignalHandler *handler = new QDeclarativeReplaceSignalHandler;
- handler->property = prop;
- handler->expression = expression;
- signalReplacements << handler;
- } else if (isScript) {
- QDeclarativeExpression *expression = new QDeclarativeExpression(qmlContext(q), object, data.toString());
- QDeclarativeData *ddata = QDeclarativeData::get(q);
- if (ddata && ddata->outerContext && !ddata->outerContext->url.isEmpty())
- expression->setSourceLocation(ddata->outerContext->url.toString(), ddata->lineNumber);
- expressions << ExpressionChange(name, id, expression);
- } else {
- properties << qMakePair(name, data);
- }
- }
-
- decoded = true;
- data.clear();
-}
-
-void QDeclarativePropertyChangesParser::setCustomData(QObject *object,
- const QByteArray &data)
-{
- QDeclarativePropertyChangesPrivate *p =
- static_cast<QDeclarativePropertyChangesPrivate *>(QObjectPrivate::get(object));
- p->data = data;
- p->decoded = false;
-}
-
-QDeclarativePropertyChanges::QDeclarativePropertyChanges()
-: QDeclarativeStateOperation(*(new QDeclarativePropertyChangesPrivate))
-{
-}
-
-QDeclarativePropertyChanges::~QDeclarativePropertyChanges()
-{
- Q_D(QDeclarativePropertyChanges);
- for(int ii = 0; ii < d->expressions.count(); ++ii)
- delete d->expressions.at(ii).expression;
- for(int ii = 0; ii < d->signalReplacements.count(); ++ii)
- delete d->signalReplacements.at(ii);
-}
-
-QObject *QDeclarativePropertyChanges::object() const
-{
- Q_D(const QDeclarativePropertyChanges);
- return d->object;
-}
-
-void QDeclarativePropertyChanges::setObject(QObject *o)
-{
- Q_D(QDeclarativePropertyChanges);
- d->object = o;
-}
-
-/*!
- \qmlproperty bool QtQuick2::PropertyChanges::restoreEntryValues
-
- This property holds whether the previous values should be restored when
- leaving the state.
-
- The default value is \c true. Setting this value to \c false creates a
- temporary state that has permanent effects on property values.
-*/
-bool QDeclarativePropertyChanges::restoreEntryValues() const
-{
- Q_D(const QDeclarativePropertyChanges);
- return d->restore;
-}
-
-void QDeclarativePropertyChanges::setRestoreEntryValues(bool v)
-{
- Q_D(QDeclarativePropertyChanges);
- d->restore = v;
-}
-
-QDeclarativeProperty
-QDeclarativePropertyChangesPrivate::property(const QString &property)
-{
- Q_Q(QDeclarativePropertyChanges);
- QDeclarativeProperty prop(object, property, qmlContext(q));
- if (!prop.isValid()) {
- qmlInfo(q) << QDeclarativePropertyChanges::tr("Cannot assign to non-existent property \"%1\"").arg(property);
- return QDeclarativeProperty();
- } else if (!(prop.type() & QDeclarativeProperty::SignalProperty) && !prop.isWritable()) {
- qmlInfo(q) << QDeclarativePropertyChanges::tr("Cannot assign to read-only property \"%1\"").arg(property);
- return QDeclarativeProperty();
- }
- return prop;
-}
-
-QDeclarativePropertyChanges::ActionList QDeclarativePropertyChanges::actions()
-{
- Q_D(QDeclarativePropertyChanges);
-
- d->decode();
-
- ActionList list;
-
- for (int ii = 0; ii < d->properties.count(); ++ii) {
-
- QDeclarativeAction a(d->object, d->properties.at(ii).first,
- qmlContext(this), d->properties.at(ii).second);
-
- if (a.property.isValid()) {
- a.restore = restoreEntryValues();
- list << a;
- }
- }
-
- for (int ii = 0; ii < d->signalReplacements.count(); ++ii) {
-
- QDeclarativeReplaceSignalHandler *handler = d->signalReplacements.at(ii);
-
- if (handler->property.isValid()) {
- QDeclarativeAction a;
- a.event = handler;
- list << a;
- }
- }
-
- for (int ii = 0; ii < d->expressions.count(); ++ii) {
-
- const QString &property = d->expressions.at(ii).name;
- QDeclarativeProperty prop = d->property(property);
-
- if (prop.isValid()) {
- QDeclarativeAction a;
- a.restore = restoreEntryValues();
- a.property = prop;
- a.fromValue = a.property.read();
- a.specifiedObject = d->object;
- a.specifiedProperty = property;
-
- if (d->isExplicit) {
- a.toValue = d->expressions.at(ii).expression->evaluate();
- } else {
- QDeclarativeExpression *e = d->expressions.at(ii).expression;
-
- QDeclarativeBinding::Identifier id = d->expressions.at(ii).id;
- QDeclarativeBinding *newBinding = id != QDeclarativeBinding::Invalid ? QDeclarativeBinding::createBinding(id, object(), qmlContext(this), e->sourceFile(), e->lineNumber()) : 0;
- if (!newBinding) {
- newBinding = new QDeclarativeBinding(e->expression(), object(), qmlContext(this));
- newBinding->setSourceLocation(e->sourceFile(), e->lineNumber());
- }
- newBinding->setTarget(prop);
- a.toBinding = newBinding;
- a.deletableToBinding = true;
- }
-
- list << a;
- }
- }
-
- return list;
-}
-
-/*!
- \qmlproperty bool QtQuick2::PropertyChanges::explicit
-
- If explicit is set to true, any potential bindings will be interpreted as
- once-off assignments that occur when the state is entered.
-
- In the following example, the addition of explicit prevents \c myItem.width from
- being bound to \c parent.width. Instead, it is assigned the value of \c parent.width
- at the time of the state change.
- \qml
- PropertyChanges {
- target: myItem
- explicit: true
- width: parent.width
- }
- \endqml
-
- By default, explicit is false.
-*/
-bool QDeclarativePropertyChanges::isExplicit() const
-{
- Q_D(const QDeclarativePropertyChanges);
- return d->isExplicit;
-}
-
-void QDeclarativePropertyChanges::setIsExplicit(bool e)
-{
- Q_D(QDeclarativePropertyChanges);
- d->isExplicit = e;
-}
-
-bool QDeclarativePropertyChanges::containsValue(const QString &name) const
-{
- Q_D(const QDeclarativePropertyChanges);
- typedef QPair<QString, QVariant> PropertyEntry;
-
- QListIterator<PropertyEntry> propertyIterator(d->properties);
- while (propertyIterator.hasNext()) {
- const PropertyEntry &entry = propertyIterator.next();
- if (entry.first == name) {
- return true;
- }
- }
-
- return false;
-}
-
-bool QDeclarativePropertyChanges::containsExpression(const QString &name) const
-{
- Q_D(const QDeclarativePropertyChanges);
- typedef QDeclarativePropertyChangesPrivate::ExpressionChange ExpressionEntry;
-
- QListIterator<ExpressionEntry> expressionIterator(d->expressions);
- while (expressionIterator.hasNext()) {
- const ExpressionEntry &entry = expressionIterator.next();
- if (entry.name == name) {
- return true;
- }
- }
-
- return false;
-}
-
-bool QDeclarativePropertyChanges::containsProperty(const QString &name) const
-{
- return containsValue(name) || containsExpression(name);
-}
-
-void QDeclarativePropertyChanges::changeValue(const QString &name, const QVariant &value)
-{
- Q_D(QDeclarativePropertyChanges);
- typedef QPair<QString, QVariant> PropertyEntry;
- typedef QDeclarativePropertyChangesPrivate::ExpressionChange ExpressionEntry;
-
- QMutableListIterator<ExpressionEntry> expressionIterator(d->expressions);
- while (expressionIterator.hasNext()) {
- const ExpressionEntry &entry = expressionIterator.next();
- if (entry.name == name) {
- expressionIterator.remove();
- if (state() && state()->isStateActive()) {
- QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(d->property(name));
- if (oldBinding) {
- QDeclarativePropertyPrivate::setBinding(d->property(name), 0);
- oldBinding->destroy();
- }
- d->property(name).write(value);
- }
-
- d->properties.append(PropertyEntry(name, value));
- return;
- }
- }
-
- QMutableListIterator<PropertyEntry> propertyIterator(d->properties);
- while (propertyIterator.hasNext()) {
- PropertyEntry &entry = propertyIterator.next();
- if (entry.first == name) {
- entry.second = value;
- if (state() && state()->isStateActive())
- d->property(name).write(value);
- return;
- }
- }
-
- QDeclarativeAction action;
- action.restore = restoreEntryValues();
- action.property = d->property(name);
- action.fromValue = action.property.read();
- action.specifiedObject = object();
- action.specifiedProperty = name;
- action.toValue = value;
-
- propertyIterator.insert(PropertyEntry(name, value));
- if (state() && state()->isStateActive()) {
- state()->addEntryToRevertList(action);
- QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(action.property);
- if (oldBinding)
- oldBinding->setEnabled(false, QDeclarativePropertyPrivate::DontRemoveBinding | QDeclarativePropertyPrivate::BypassInterceptor);
- d->property(name).write(value);
- }
-}
-
-void QDeclarativePropertyChanges::changeExpression(const QString &name, const QString &expression)
-{
- Q_D(QDeclarativePropertyChanges);
- typedef QPair<QString, QVariant> PropertyEntry;
- typedef QDeclarativePropertyChangesPrivate::ExpressionChange ExpressionEntry;
-
- bool hadValue = false;
-
- QMutableListIterator<PropertyEntry> propertyIterator(d->properties);
- while (propertyIterator.hasNext()) {
- PropertyEntry &entry = propertyIterator.next();
- if (entry.first == name) {
- propertyIterator.remove();
- hadValue = true;
- break;
- }
- }
-
- QMutableListIterator<ExpressionEntry> expressionIterator(d->expressions);
- while (expressionIterator.hasNext()) {
- const ExpressionEntry &entry = expressionIterator.next();
- if (entry.name == name) {
- entry.expression->setExpression(expression);
- if (state() && state()->isStateActive()) {
- QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(d->property(name));
- if (oldBinding) {
- QDeclarativePropertyPrivate::setBinding(d->property(name), 0);
- oldBinding->destroy();
- }
-
- QDeclarativeBinding *newBinding = new QDeclarativeBinding(expression, object(), qmlContext(this));
- newBinding->setTarget(d->property(name));
- QDeclarativePropertyPrivate::setBinding(d->property(name), newBinding, QDeclarativePropertyPrivate::DontRemoveBinding | QDeclarativePropertyPrivate::BypassInterceptor);
- }
- return;
- }
- }
-
- QDeclarativeExpression *newExpression = new QDeclarativeExpression(qmlContext(this), d->object, expression);
- expressionIterator.insert(ExpressionEntry(name, QDeclarativeBinding::Invalid, newExpression));
-
- if (state() && state()->isStateActive()) {
- if (hadValue) {
- QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(d->property(name));
- if (oldBinding) {
- oldBinding->setEnabled(false, QDeclarativePropertyPrivate::DontRemoveBinding | QDeclarativePropertyPrivate::BypassInterceptor);
- state()->changeBindingInRevertList(object(), name, oldBinding);
- }
-
- QDeclarativeBinding *newBinding = new QDeclarativeBinding(expression, object(), qmlContext(this));
- newBinding->setTarget(d->property(name));
- QDeclarativePropertyPrivate::setBinding(d->property(name), newBinding, QDeclarativePropertyPrivate::DontRemoveBinding | QDeclarativePropertyPrivate::BypassInterceptor);
- } else {
- QDeclarativeAction action;
- action.restore = restoreEntryValues();
- action.property = d->property(name);
- action.fromValue = action.property.read();
- action.specifiedObject = object();
- action.specifiedProperty = name;
-
-
- if (d->isExplicit) {
- action.toValue = newExpression->evaluate();
- } else {
- QDeclarativeBinding *newBinding = new QDeclarativeBinding(newExpression->expression(), object(), qmlContext(this));
- newBinding->setTarget(d->property(name));
- action.toBinding = newBinding;
- action.deletableToBinding = true;
-
- state()->addEntryToRevertList(action);
- QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(action.property);
- if (oldBinding)
- oldBinding->setEnabled(false, QDeclarativePropertyPrivate::DontRemoveBinding | QDeclarativePropertyPrivate::BypassInterceptor);
-
- QDeclarativePropertyPrivate::setBinding(action.property, newBinding, QDeclarativePropertyPrivate::DontRemoveBinding | QDeclarativePropertyPrivate::BypassInterceptor);
- }
- }
- }
- // what about the signal handler?
-}
-
-QVariant QDeclarativePropertyChanges::property(const QString &name) const
-{
- Q_D(const QDeclarativePropertyChanges);
- typedef QPair<QString, QVariant> PropertyEntry;
- typedef QDeclarativePropertyChangesPrivate::ExpressionChange ExpressionEntry;
-
- QListIterator<PropertyEntry> propertyIterator(d->properties);
- while (propertyIterator.hasNext()) {
- const PropertyEntry &entry = propertyIterator.next();
- if (entry.first == name) {
- return entry.second;
- }
- }
-
- QListIterator<ExpressionEntry> expressionIterator(d->expressions);
- while (expressionIterator.hasNext()) {
- const ExpressionEntry &entry = expressionIterator.next();
- if (entry.name == name) {
- return QVariant(entry.expression->expression());
- }
- }
-
- return QVariant();
-}
-
-void QDeclarativePropertyChanges::removeProperty(const QString &name)
-{
- Q_D(QDeclarativePropertyChanges);
- typedef QPair<QString, QVariant> PropertyEntry;
- typedef QDeclarativePropertyChangesPrivate::ExpressionChange ExpressionEntry;
-
- QMutableListIterator<ExpressionEntry> expressionIterator(d->expressions);
- while (expressionIterator.hasNext()) {
- const ExpressionEntry &entry = expressionIterator.next();
- if (entry.name == name) {
- expressionIterator.remove();
- state()->removeEntryFromRevertList(object(), name);
- return;
- }
- }
-
- QMutableListIterator<PropertyEntry> propertyIterator(d->properties);
- while (propertyIterator.hasNext()) {
- const PropertyEntry &entry = propertyIterator.next();
- if (entry.first == name) {
- propertyIterator.remove();
- state()->removeEntryFromRevertList(object(), name);
- return;
- }
- }
-}
-
-QVariant QDeclarativePropertyChanges::value(const QString &name) const
-{
- Q_D(const QDeclarativePropertyChanges);
- typedef QPair<QString, QVariant> PropertyEntry;
-
- QListIterator<PropertyEntry> propertyIterator(d->properties);
- while (propertyIterator.hasNext()) {
- const PropertyEntry &entry = propertyIterator.next();
- if (entry.first == name) {
- return entry.second;
- }
- }
-
- return QVariant();
-}
-
-QString QDeclarativePropertyChanges::expression(const QString &name) const
-{
- Q_D(const QDeclarativePropertyChanges);
- typedef QDeclarativePropertyChangesPrivate::ExpressionChange ExpressionEntry;
-
- QListIterator<ExpressionEntry> expressionIterator(d->expressions);
- while (expressionIterator.hasNext()) {
- const ExpressionEntry &entry = expressionIterator.next();
- if (entry.name == name) {
- return entry.expression->expression();
- }
- }
-
- return QString();
-}
-
-void QDeclarativePropertyChanges::detachFromState()
-{
- if (state())
- state()->removeAllEntriesFromRevertList(object());
-}
-
-void QDeclarativePropertyChanges::attachToState()
-{
- if (state())
- state()->addEntriesToRevertList(actions());
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativepropertychanges_p.h b/src/declarative/util/qdeclarativepropertychanges_p.h
deleted file mode 100644
index 6d3e032b57..0000000000
--- a/src/declarative/util/qdeclarativepropertychanges_p.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEPROPERTYCHANGES_H
-#define QDECLARATIVEPROPERTYCHANGES_H
-
-#include "qdeclarativestateoperations_p.h"
-#include <private/qdeclarativecustomparser_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativePropertyChangesPrivate;
-class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativePropertyChanges : public QDeclarativeStateOperation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativePropertyChanges)
-
- Q_PROPERTY(QObject *target READ object WRITE setObject)
- Q_PROPERTY(bool restoreEntryValues READ restoreEntryValues WRITE setRestoreEntryValues)
- Q_PROPERTY(bool explicit READ isExplicit WRITE setIsExplicit)
-public:
- QDeclarativePropertyChanges();
- ~QDeclarativePropertyChanges();
-
- QObject *object() const;
- void setObject(QObject *);
-
- bool restoreEntryValues() const;
- void setRestoreEntryValues(bool);
-
- bool isExplicit() const;
- void setIsExplicit(bool);
-
- virtual ActionList actions();
-
- bool containsProperty(const QString &name) const;
- bool containsValue(const QString &name) const;
- bool containsExpression(const QString &name) const;
- void changeValue(const QString &name, const QVariant &value);
- void changeExpression(const QString &name, const QString &expression);
- void removeProperty(const QString &name);
- QVariant value(const QString &name) const;
- QString expression(const QString &name) const;
-
- void detachFromState();
- void attachToState();
-
- QVariant property(const QString &name) const;
-};
-
-class QDeclarativePropertyChangesParser : public QDeclarativeCustomParser
-{
-public:
- QDeclarativePropertyChangesParser()
- : QDeclarativeCustomParser(AcceptsAttachedProperties) {}
-
- void compileList(QList<QPair<QString, QVariant> > &list, const QString &pre, const QDeclarativeCustomParserProperty &prop);
-
- virtual QByteArray compile(const QList<QDeclarativeCustomParserProperty> &);
- virtual void setCustomData(QObject *, const QByteArray &);
-};
-
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativePropertyChanges)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVEPROPERTYCHANGES_H
diff --git a/src/declarative/util/qdeclarativesmoothedanimation.cpp b/src/declarative/util/qdeclarativesmoothedanimation.cpp
deleted file mode 100644
index 45c6885fbb..0000000000
--- a/src/declarative/util/qdeclarativesmoothedanimation.cpp
+++ /dev/null
@@ -1,503 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativesmoothedanimation_p.h"
-#include "qdeclarativesmoothedanimation_p_p.h"
-
-#include "qdeclarativeanimation_p_p.h"
-
-#include <qdeclarativeproperty.h>
-#include <private/qdeclarativeproperty_p.h>
-
-#include <private/qdeclarativeglobal_p.h>
-
-#include <QtCore/qdebug.h>
-
-#include <math.h>
-
-#define DELAY_STOP_TIMER_INTERVAL 32
-
-QT_BEGIN_NAMESPACE
-
-QSmoothedAnimation::QSmoothedAnimation(QObject *parent)
- : QAbstractAnimation(parent), to(0), velocity(200), userDuration(-1), maximumEasingTime(-1),
- reversingMode(QDeclarativeSmoothedAnimation::Eased), initialVelocity(0),
- trackVelocity(0), initialValue(0), invert(false), finalDuration(-1), lastTime(0)
-{
-}
-
-void QSmoothedAnimation::restart()
-{
- initialVelocity = trackVelocity;
- if (state() != QAbstractAnimation::Running)
- start();
- else
- init();
-}
-
-void QSmoothedAnimation::updateState(QAbstractAnimation::State newState, QAbstractAnimation::State /*oldState*/)
-{
- if (newState == QAbstractAnimation::Running)
- init();
-}
-
-void QSmoothedAnimation::timerEvent(QTimerEvent *event)
-{
- if (event->timerId() == delayedStopTimer.timerId()) {
- delayedStopTimer.stop();
- stop();
- } else {
- QAbstractAnimation::timerEvent(event);
- }
-}
-
-void QSmoothedAnimation::delayedStop()
-{
- if (!delayedStopTimer.isActive())
- delayedStopTimer.start(DELAY_STOP_TIMER_INTERVAL, this);
-}
-
-int QSmoothedAnimation::duration() const
-{
- return -1;
-}
-
-bool QSmoothedAnimation::recalc()
-{
- s = to - initialValue;
- vi = initialVelocity;
-
- s = (invert? -1.0: 1.0) * s;
-
- if (userDuration > 0 && velocity > 0) {
- tf = s / velocity;
- if (tf > (userDuration / 1000.)) tf = (userDuration / 1000.);
- } else if (userDuration > 0) {
- tf = userDuration / 1000.;
- } else if (velocity > 0) {
- tf = s / velocity;
- } else {
- return false;
- }
-
- finalDuration = ceil(tf * 1000.0);
-
- if (maximumEasingTime == 0) {
- a = 0;
- d = 0;
- tp = 0;
- td = tf;
- vp = velocity;
- sp = 0;
- sd = s;
- } else if (maximumEasingTime != -1 && tf > (maximumEasingTime / 1000.)) {
- qreal met = maximumEasingTime / 1000.;
- /* tp| |td
- * vp_ _______
- * / \
- * vi_ / \
- * \
- * \ _ 0
- * |ta| |ta|
- */
- qreal ta = met / 2.;
- a = (s - (vi * tf - 0.5 * vi * ta)) / (tf * ta - ta * ta);
-
- vp = vi + a * ta;
- d = vp / ta;
- tp = ta;
- sp = vi * ta + 0.5 * a * tp * tp;
- sd = sp + vp * (tf - 2 * ta);
- td = tf - ta;
- } else {
- qreal c1 = 0.25 * tf * tf;
- qreal c2 = 0.5 * vi * tf - s;
- qreal c3 = -0.25 * vi * vi;
-
- qreal a1 = (-c2 + sqrt(c2 * c2 - 4 * c1 * c3)) / (2. * c1);
-
- qreal tp1 = 0.5 * tf - 0.5 * vi / a1;
- qreal vp1 = a1 * tp1 + vi;
-
- qreal sp1 = 0.5 * a1 * tp1 * tp1 + vi * tp1;
-
- a = a1;
- d = a1;
- tp = tp1;
- td = tp1;
- vp = vp1;
- sp = sp1;
- sd = sp1;
- }
- return true;
-}
-
-qreal QSmoothedAnimation::easeFollow(qreal time_seconds)
-{
- qreal value;
- if (time_seconds < tp) {
- trackVelocity = vi + time_seconds * a;
- value = 0.5 * a * time_seconds * time_seconds + vi * time_seconds;
- } else if (time_seconds < td) {
- time_seconds -= tp;
- trackVelocity = vp;
- value = sp + time_seconds * vp;
- } else if (time_seconds < tf) {
- time_seconds -= td;
- trackVelocity = vp - time_seconds * a;
- value = sd - 0.5 * d * time_seconds * time_seconds + vp * time_seconds;
- } else {
- trackVelocity = 0;
- value = s;
- delayedStop();
- }
-
- // to normalize 's' between [0..1], divide 'value' by 's'
- return value;
-}
-
-void QSmoothedAnimation::updateCurrentTime(int t)
-{
- qreal time_seconds = qreal(t - lastTime) / 1000.;
-
- qreal value = easeFollow(time_seconds);
- value *= (invert? -1.0: 1.0);
- QDeclarativePropertyPrivate::write(target, initialValue + value,
- QDeclarativePropertyPrivate::BypassInterceptor
- | QDeclarativePropertyPrivate::DontRemoveBinding);
-}
-
-void QSmoothedAnimation::init()
-{
- if (velocity == 0) {
- stop();
- return;
- }
-
- if (delayedStopTimer.isActive())
- delayedStopTimer.stop();
-
- initialValue = target.read().toReal();
- lastTime = this->currentTime();
-
- if (to == initialValue) {
- stop();
- return;
- }
-
- bool hasReversed = trackVelocity != 0. &&
- ((!invert) == ((initialValue - to) > 0));
-
- if (hasReversed) {
- switch (reversingMode) {
- default:
- case QDeclarativeSmoothedAnimation::Eased:
- initialVelocity = -trackVelocity;
- break;
- case QDeclarativeSmoothedAnimation::Sync:
- QDeclarativePropertyPrivate::write(target, to,
- QDeclarativePropertyPrivate::BypassInterceptor
- | QDeclarativePropertyPrivate::DontRemoveBinding);
- trackVelocity = 0;
- stop();
- return;
- case QDeclarativeSmoothedAnimation::Immediate:
- initialVelocity = 0;
- break;
- }
- }
-
- trackVelocity = initialVelocity;
-
- invert = (to < initialValue);
-
- if (!recalc()) {
- QDeclarativePropertyPrivate::write(target, to,
- QDeclarativePropertyPrivate::BypassInterceptor
- | QDeclarativePropertyPrivate::DontRemoveBinding);
- stop();
- return;
- }
-}
-
-/*!
- \qmlclass SmoothedAnimation QDeclarativeSmoothedAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits NumberAnimation
- \brief The SmoothedAnimation element allows a property to smoothly track a value.
-
- A SmoothedAnimation animates a property's value to a set target value
- using an ease in/out quad easing curve. When the target value changes,
- the easing curves used to animate between the old and new target values
- are smoothly spliced together to create a smooth movement to the new
- target value that maintains the current velocity.
-
- The follow example shows one \l Rectangle tracking the position of another
- using SmoothedAnimation. The green rectangle's \c x and \c y values are
- bound to those of the red rectangle. Whenever these values change, the
- green rectangle smoothly animates to its new position:
-
- \snippet doc/src/snippets/declarative/smoothedanimation.qml 0
-
- A SmoothedAnimation can be configured by setting the \l velocity at which the
- animation should occur, or the \l duration that the animation should take.
- If both the \l velocity and \l duration are specified, the one that results in
- the quickest animation is chosen for each change in the target value.
-
- For example, animating from 0 to 800 will take 4 seconds if a velocity
- of 200 is set, will take 8 seconds with a duration of 8000 set, and will
- take 4 seconds with both a velocity of 200 and a duration of 8000 set.
- Animating from 0 to 20000 will take 10 seconds if a velocity of 200 is set,
- will take 8 seconds with a duration of 8000 set, and will take 8 seconds
- with both a velocity of 200 and a duration of 8000 set.
-
- The default velocity of SmoothedAnimation is 200 units/second. Note that if the range of the
- value being animated is small, then the velocity will need to be adjusted
- appropriately. For example, the opacity of an item ranges from 0 - 1.0.
- To enable a smooth animation in this range the velocity will need to be
- set to a value such as 0.5 units/second. Animating from 0 to 1.0 with a velocity
- of 0.5 will take 2000 ms to complete.
-
- Like any other animation element, a SmoothedAnimation can be applied in a
- number of ways, including transitions, behaviors and property value
- sources. The \l {QML Animation and Transitions} documentation shows a
- variety of methods for creating animations.
-
- \sa SpringAnimation, NumberAnimation, {QML Animation and Transitions}, {declarative/animation/basics}{Animation basics example}
-*/
-
-QDeclarativeSmoothedAnimation::QDeclarativeSmoothedAnimation(QObject *parent)
-: QDeclarativeNumberAnimation(*(new QDeclarativeSmoothedAnimationPrivate), parent)
-{
-}
-
-QDeclarativeSmoothedAnimation::~QDeclarativeSmoothedAnimation()
-{
-}
-
-QDeclarativeSmoothedAnimationPrivate::QDeclarativeSmoothedAnimationPrivate()
- : wrapperGroup(new QParallelAnimationGroup), anim(new QSmoothedAnimation)
-{
- Q_Q(QDeclarativeSmoothedAnimation);
- QDeclarative_setParent_noEvent(wrapperGroup, q);
- QDeclarative_setParent_noEvent(anim, q);
-}
-
-void QDeclarativeSmoothedAnimationPrivate::updateRunningAnimations()
-{
- foreach(QSmoothedAnimation* ease, activeAnimations.values()){
- ease->maximumEasingTime = anim->maximumEasingTime;
- ease->reversingMode = anim->reversingMode;
- ease->velocity = anim->velocity;
- ease->userDuration = anim->userDuration;
- ease->init();
- }
-}
-
-QAbstractAnimation* QDeclarativeSmoothedAnimation::qtAnimation()
-{
- Q_D(QDeclarativeSmoothedAnimation);
- return d->wrapperGroup;
-}
-
-void QDeclarativeSmoothedAnimation::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_D(QDeclarativeSmoothedAnimation);
- QDeclarativeNumberAnimation::transition(actions, modified, direction);
-
- if (!d->actions)
- return;
-
- QSet<QAbstractAnimation*> anims;
- for (int i = 0; i < d->actions->size(); i++) {
- QSmoothedAnimation *ease;
- bool needsRestart;
- if (!d->activeAnimations.contains((*d->actions)[i].property)) {
- ease = new QSmoothedAnimation();
- d->wrapperGroup->addAnimation(ease);
- d->activeAnimations.insert((*d->actions)[i].property, ease);
- needsRestart = false;
- } else {
- ease = d->activeAnimations.value((*d->actions)[i].property);
- needsRestart = true;
- }
- ease->target = (*d->actions)[i].property;
- ease->to = (*d->actions)[i].toValue.toReal();
-
- // copying public members from main value holder animation
- ease->maximumEasingTime = d->anim->maximumEasingTime;
- ease->reversingMode = d->anim->reversingMode;
- ease->velocity = d->anim->velocity;
- ease->userDuration = d->anim->userDuration;
-
- ease->initialVelocity = ease->trackVelocity;
-
- if (needsRestart)
- ease->init();
- anims.insert(ease);
- }
-
- for (int i = d->wrapperGroup->animationCount() - 1; i >= 0 ; --i) {
- if (!anims.contains(d->wrapperGroup->animationAt(i))) {
- QSmoothedAnimation *ease = static_cast<QSmoothedAnimation*>(d->wrapperGroup->animationAt(i));
- d->activeAnimations.remove(ease->target);
- d->wrapperGroup->takeAnimation(i);
- delete ease;
- }
- }
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::SmoothedAnimation::reversingMode
-
- Sets how the SmoothedAnimation behaves if an animation direction is reversed.
-
- Possible values are:
-
- \list
- \o SmoothedAnimation.Eased (default) - the animation will smoothly decelerate, and then reverse direction
- \o SmoothedAnimation.Immediate - the animation will immediately begin accelerating in the reverse direction, beginning with a velocity of 0
- \o SmoothedAnimation.Sync - the property is immediately set to the target value
- \endlist
-*/
-QDeclarativeSmoothedAnimation::ReversingMode QDeclarativeSmoothedAnimation::reversingMode() const
-{
- Q_D(const QDeclarativeSmoothedAnimation);
- return (QDeclarativeSmoothedAnimation::ReversingMode) d->anim->reversingMode;
-}
-
-void QDeclarativeSmoothedAnimation::setReversingMode(ReversingMode m)
-{
- Q_D(QDeclarativeSmoothedAnimation);
- if (d->anim->reversingMode == m)
- return;
-
- d->anim->reversingMode = m;
- emit reversingModeChanged();
- d->updateRunningAnimations();
-}
-
-/*!
- \qmlproperty int QtQuick2::SmoothedAnimation::duration
-
- This property holds the animation duration, in msecs, used when tracking the source.
-
- Setting this to -1 (the default) disables the duration value.
-
- If the velocity value and the duration value are both enabled, then the animation will
- use whichever gives the shorter duration.
-*/
-int QDeclarativeSmoothedAnimation::duration() const
-{
- Q_D(const QDeclarativeSmoothedAnimation);
- return d->anim->userDuration;
-}
-
-void QDeclarativeSmoothedAnimation::setDuration(int duration)
-{
- Q_D(QDeclarativeSmoothedAnimation);
- if (duration != -1)
- QDeclarativeNumberAnimation::setDuration(duration);
- if(duration == d->anim->userDuration)
- return;
- d->anim->userDuration = duration;
- d->updateRunningAnimations();
-}
-
-qreal QDeclarativeSmoothedAnimation::velocity() const
-{
- Q_D(const QDeclarativeSmoothedAnimation);
- return d->anim->velocity;
-}
-
-/*!
- \qmlproperty real QtQuick2::SmoothedAnimation::velocity
-
- This property holds the average velocity allowed when tracking the 'to' value.
-
- The default velocity of SmoothedAnimation is 200 units/second.
-
- Setting this to -1 disables the velocity value.
-
- If the velocity value and the duration value are both enabled, then the animation will
- use whichever gives the shorter duration.
-*/
-void QDeclarativeSmoothedAnimation::setVelocity(qreal v)
-{
- Q_D(QDeclarativeSmoothedAnimation);
- if (d->anim->velocity == v)
- return;
-
- d->anim->velocity = v;
- emit velocityChanged();
- d->updateRunningAnimations();
-}
-
-/*!
- \qmlproperty int QtQuick2::SmoothedAnimation::maximumEasingTime
-
- This property specifies the maximum time, in msecs, any "eases" during the follow should take.
- Setting this property causes the velocity to "level out" after at a time. Setting
- a negative value reverts to the normal mode of easing over the entire animation
- duration.
-
- The default value is -1.
-*/
-int QDeclarativeSmoothedAnimation::maximumEasingTime() const
-{
- Q_D(const QDeclarativeSmoothedAnimation);
- return d->anim->maximumEasingTime;
-}
-
-void QDeclarativeSmoothedAnimation::setMaximumEasingTime(int v)
-{
- Q_D(QDeclarativeSmoothedAnimation);
- if(v == d->anim->maximumEasingTime)
- return;
- d->anim->maximumEasingTime = v;
- emit maximumEasingTimeChanged();
- d->updateRunningAnimations();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativesmoothedanimation_p.h b/src/declarative/util/qdeclarativesmoothedanimation_p.h
deleted file mode 100644
index 9417383c1e..0000000000
--- a/src/declarative/util/qdeclarativesmoothedanimation_p.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVESMOOTHEDANIMATION_H
-#define QDECLARATIVESMOOTHEDANIMATION_H
-
-#include <qdeclarative.h>
-#include "qdeclarativeanimation_p.h"
-
-#include <QtCore/qobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeProperty;
-class QDeclarativeSmoothedAnimationPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativeSmoothedAnimation : public QDeclarativeNumberAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeSmoothedAnimation)
- Q_ENUMS(ReversingMode)
-
- Q_PROPERTY(qreal velocity READ velocity WRITE setVelocity NOTIFY velocityChanged)
- Q_PROPERTY(ReversingMode reversingMode READ reversingMode WRITE setReversingMode NOTIFY reversingModeChanged)
- Q_PROPERTY(qreal maximumEasingTime READ maximumEasingTime WRITE setMaximumEasingTime NOTIFY maximumEasingTimeChanged)
-
-public:
- enum ReversingMode { Eased, Immediate, Sync };
-
- QDeclarativeSmoothedAnimation(QObject *parent = 0);
- ~QDeclarativeSmoothedAnimation();
-
- ReversingMode reversingMode() const;
- void setReversingMode(ReversingMode);
-
- virtual int duration() const;
- virtual void setDuration(int);
-
- qreal velocity() const;
- void setVelocity(qreal);
-
- int maximumEasingTime() const;
- void setMaximumEasingTime(int);
-
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
- QAbstractAnimation* qtAnimation();
-
-Q_SIGNALS:
- void velocityChanged();
- void reversingModeChanged();
- void maximumEasingTimeChanged();
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeSmoothedAnimation)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVESMOOTHEDANIMATION_H
diff --git a/src/declarative/util/qdeclarativesmoothedanimation_p_p.h b/src/declarative/util/qdeclarativesmoothedanimation_p_p.h
deleted file mode 100644
index 08b1450342..0000000000
--- a/src/declarative/util/qdeclarativesmoothedanimation_p_p.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVESMOOTHEDANIMATION_P_H
-#define QDECLARATIVESMOOTHEDANIMATION_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 "qdeclarativesmoothedanimation_p.h"
-#include "qdeclarativeanimation_p.h"
-
-#include "qdeclarativeanimation_p_p.h"
-
-#include <qparallelanimationgroup.h>
-
-#include <private/qobject_p.h>
-#include <QBasicTimer>
-
-QT_BEGIN_NAMESPACE
-
-class Q_AUTOTEST_EXPORT QSmoothedAnimation : public QAbstractAnimation
-{
-public:
- QSmoothedAnimation(QObject *parent=0);
-
- qreal to;
- qreal velocity;
- int userDuration;
-
- int maximumEasingTime;
- QDeclarativeSmoothedAnimation::ReversingMode reversingMode;
-
- qreal initialVelocity;
- qreal trackVelocity;
-
- QDeclarativeProperty target;
-
- int duration() const;
- void restart();
- void init();
-
-protected:
- virtual void updateCurrentTime(int);
- virtual void updateState(QAbstractAnimation::State, QAbstractAnimation::State);
- virtual void timerEvent(QTimerEvent *);
-
-private:
- qreal easeFollow(qreal);
- qreal initialValue;
-
- bool invert;
-
- int finalDuration;
-
- // Parameters for use in updateCurrentTime()
- qreal a; // Acceleration
- qreal d; // Deceleration
- qreal tf; // Total time
- qreal tp; // Time at which peak velocity occurs
- qreal td; // Time at which deceleration begins
- qreal vp; // Velocity at tp
- qreal sp; // Displacement at tp
- qreal sd; // Displacement at td
- qreal vi; // "Normalized" initialvelocity
- qreal s; // Total s
-
- int lastTime;
-
- bool recalc();
- void delayedStop();
-
- QBasicTimer delayedStopTimer;
-};
-
-class QDeclarativeSmoothedAnimationPrivate : public QDeclarativePropertyAnimationPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeSmoothedAnimation)
-public:
- QDeclarativeSmoothedAnimationPrivate();
- void updateRunningAnimations();
-
- QParallelAnimationGroup *wrapperGroup;
- QSmoothedAnimation *anim;
- QHash<QDeclarativeProperty, QSmoothedAnimation*> activeAnimations;
-};
-
-QT_END_NAMESPACE
-
-#endif // QDECLARATIVESMOOTHEDANIMATION_P_H
diff --git a/src/declarative/util/qdeclarativespringanimation.cpp b/src/declarative/util/qdeclarativespringanimation.cpp
deleted file mode 100644
index b0b12c7ba4..0000000000
--- a/src/declarative/util/qdeclarativespringanimation.cpp
+++ /dev/null
@@ -1,462 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativespringanimation_p.h"
-
-#include "qdeclarativeanimation_p_p.h"
-#include <private/qdeclarativeproperty_p.h>
-
-#include <QtCore/qdebug.h>
-
-#include <private/qobject_p.h>
-
-#include <limits.h>
-#include <math.h>
-
-QT_BEGIN_NAMESPACE
-
-
-class QDeclarativeSpringAnimationPrivate : public QDeclarativePropertyAnimationPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeSpringAnimation)
-public:
-
-
- struct SpringAnimation {
- SpringAnimation()
- : currentValue(0), to(0), velocity(0), start(0), duration(0) {}
- qreal currentValue;
- qreal to;
- qreal velocity;
- int start;
- int duration;
- };
- QHash<QDeclarativeProperty, SpringAnimation> activeAnimations;
-
- qreal maxVelocity;
- qreal velocityms;
- int lastTime;
- qreal mass;
- qreal spring;
- qreal damping;
- qreal epsilon;
- qreal modulus;
-
- bool useMass : 1;
- bool haveModulus : 1;
-
- enum Mode {
- Track,
- Velocity,
- Spring
- };
- Mode mode;
-
- QDeclarativeSpringAnimationPrivate()
- : maxVelocity(0), velocityms(0), lastTime(0)
- , mass(1.0), spring(0.), damping(0.), epsilon(0.01)
- , modulus(0.0), useMass(false), haveModulus(false)
- , mode(Track), clock(0)
- { }
-
- void tick(int time);
- bool animate(const QDeclarativeProperty &property, SpringAnimation &animation, int elapsed);
- void updateMode();
-
- typedef QTickAnimationProxy<QDeclarativeSpringAnimationPrivate, &QDeclarativeSpringAnimationPrivate::tick> Clock;
- Clock *clock;
-};
-
-void QDeclarativeSpringAnimationPrivate::tick(int time)
-{
- if (mode == Track) {
- clock->stop();
- return;
- }
- int elapsed = time - lastTime;
- if (!elapsed)
- return;
-
- if (mode == Spring) {
- if (elapsed < 16) // capped at 62fps.
- return;
- int count = elapsed / 16;
- lastTime = time - (elapsed - count * 16);
- } else {
- lastTime = time;
- }
-
- QMutableHashIterator<QDeclarativeProperty, SpringAnimation> it(activeAnimations);
- while (it.hasNext()) {
- it.next();
- if (animate(it.key(), it.value(), elapsed))
- it.remove();
- }
-
- if (activeAnimations.isEmpty())
- clock->stop();
-}
-
-bool QDeclarativeSpringAnimationPrivate::animate(const QDeclarativeProperty &property, SpringAnimation &animation, int elapsed)
-{
- qreal srcVal = animation.to;
-
- bool stop = false;
-
- if (haveModulus) {
- animation.currentValue = fmod(animation.currentValue, modulus);
- srcVal = fmod(srcVal, modulus);
- }
- if (mode == Spring) {
- // Real men solve the spring DEs using RK4.
- // We'll do something much simpler which gives a result that looks fine.
- int count = elapsed / 16;
- for (int i = 0; i < count; ++i) {
- qreal diff = srcVal - animation.currentValue;
- if (haveModulus && qAbs(diff) > modulus / 2) {
- if (diff < 0)
- diff += modulus;
- else
- diff -= modulus;
- }
- if (useMass)
- animation.velocity = animation.velocity + (spring * diff - damping * animation.velocity) / mass;
- else
- animation.velocity = animation.velocity + spring * diff - damping * animation.velocity;
- if (maxVelocity > 0.) {
- // limit velocity
- if (animation.velocity > maxVelocity)
- animation.velocity = maxVelocity;
- else if (animation.velocity < -maxVelocity)
- animation.velocity = -maxVelocity;
- }
- animation.currentValue += animation.velocity * 16.0 / 1000.0;
- if (haveModulus) {
- animation.currentValue = fmod(animation.currentValue, modulus);
- if (animation.currentValue < 0.0)
- animation.currentValue += modulus;
- }
- }
- if (qAbs(animation.velocity) < epsilon && qAbs(srcVal - animation.currentValue) < epsilon) {
- animation.velocity = 0.0;
- animation.currentValue = srcVal;
- stop = true;
- }
- } else {
- qreal moveBy = elapsed * velocityms;
- qreal diff = srcVal - animation.currentValue;
- if (haveModulus && qAbs(diff) > modulus / 2) {
- if (diff < 0)
- diff += modulus;
- else
- diff -= modulus;
- }
- if (diff > 0) {
- animation.currentValue += moveBy;
- if (haveModulus)
- animation.currentValue = fmod(animation.currentValue, modulus);
- } else {
- animation.currentValue -= moveBy;
- if (haveModulus && animation.currentValue < 0.0)
- animation.currentValue = fmod(animation.currentValue, modulus) + modulus;
- }
- if (lastTime - animation.start >= animation.duration) {
- animation.currentValue = animation.to;
- stop = true;
- }
- }
-
- qreal old_to = animation.to;
-
- QDeclarativePropertyPrivate::write(property, animation.currentValue,
- QDeclarativePropertyPrivate::BypassInterceptor |
- QDeclarativePropertyPrivate::DontRemoveBinding);
-
- return (stop && old_to == animation.to); // do not stop if we got restarted
-}
-
-void QDeclarativeSpringAnimationPrivate::updateMode()
-{
- if (spring == 0. && maxVelocity == 0.)
- mode = Track;
- else if (spring > 0.)
- mode = Spring;
- else {
- mode = Velocity;
- QHash<QDeclarativeProperty, SpringAnimation>::iterator it;
- for (it = activeAnimations.begin(); it != activeAnimations.end(); ++it) {
- SpringAnimation &animation = *it;
- animation.start = lastTime;
- qreal dist = qAbs(animation.currentValue - animation.to);
- if (haveModulus && dist > modulus / 2)
- dist = modulus - fmod(dist, modulus);
- animation.duration = dist / velocityms;
- }
- }
-}
-
-/*!
- \qmlclass SpringAnimation QDeclarativeSpringAnimation
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \inherits NumberAnimation
-
- \brief The SpringAnimation element allows a property to track a value in a spring-like motion.
-
- SpringAnimation mimics the oscillatory behavior of a spring, with the appropriate \l spring constant to
- control the acceleration and the \l damping to control how quickly the effect dies away.
-
- You can also limit the maximum \l velocity of the animation.
-
- The following \l Rectangle moves to the position of the mouse using a
- SpringAnimation when the mouse is clicked. The use of the \l Behavior
- on the \c x and \c y values indicates that whenever these values are
- changed, a SpringAnimation should be applied.
-
- \snippet doc/src/snippets/declarative/springanimation.qml 0
-
- Like any other animation element, a SpringAnimation can be applied in a
- number of ways, including transitions, behaviors and property value
- sources. The \l {QML Animation and Transitions} documentation shows a
- variety of methods for creating animations.
-
- \sa SmoothedAnimation, {QML Animation and Transitions}, {declarative/animation/basics}{Animation basics example}, {declarative/toys/clocks}{Clocks example}
-*/
-
-QDeclarativeSpringAnimation::QDeclarativeSpringAnimation(QObject *parent)
-: QDeclarativeNumberAnimation(*(new QDeclarativeSpringAnimationPrivate),parent)
-{
- Q_D(QDeclarativeSpringAnimation);
- d->clock = new QDeclarativeSpringAnimationPrivate::Clock(d, this);
-}
-
-QDeclarativeSpringAnimation::~QDeclarativeSpringAnimation()
-{
-}
-
-/*!
- \qmlproperty real QtQuick2::SpringAnimation::velocity
-
- This property holds the maximum velocity allowed when tracking the source.
-
- The default value is 0 (no maximum velocity).
-*/
-
-qreal QDeclarativeSpringAnimation::velocity() const
-{
- Q_D(const QDeclarativeSpringAnimation);
- return d->maxVelocity;
-}
-
-void QDeclarativeSpringAnimation::setVelocity(qreal velocity)
-{
- Q_D(QDeclarativeSpringAnimation);
- d->maxVelocity = velocity;
- d->velocityms = velocity / 1000.0;
- d->updateMode();
-}
-
-/*!
- \qmlproperty real QtQuick2::SpringAnimation::spring
-
- This property describes how strongly the target is pulled towards the
- source. The default value is 0 (that is, the spring-like motion is disabled).
-
- The useful value range is 0 - 5.0.
-
- When this property is set and the \l velocity value is greater than 0,
- the \l velocity limits the maximum speed.
-*/
-qreal QDeclarativeSpringAnimation::spring() const
-{
- Q_D(const QDeclarativeSpringAnimation);
- return d->spring;
-}
-
-void QDeclarativeSpringAnimation::setSpring(qreal spring)
-{
- Q_D(QDeclarativeSpringAnimation);
- d->spring = spring;
- d->updateMode();
-}
-
-/*!
- \qmlproperty real QtQuick2::SpringAnimation::damping
- This property holds the spring damping value.
-
- This value describes how quickly the spring-like motion comes to rest.
- The default value is 0.
-
- The useful value range is 0 - 1.0. The lower the value, the faster it
- comes to rest.
-*/
-qreal QDeclarativeSpringAnimation::damping() const
-{
- Q_D(const QDeclarativeSpringAnimation);
- return d->damping;
-}
-
-void QDeclarativeSpringAnimation::setDamping(qreal damping)
-{
- Q_D(QDeclarativeSpringAnimation);
- if (damping > 1.)
- damping = 1.;
-
- d->damping = damping;
-}
-
-
-/*!
- \qmlproperty real QtQuick2::SpringAnimation::epsilon
- This property holds the spring epsilon.
-
- The epsilon is the rate and amount of change in the value which is close enough
- to 0 to be considered equal to zero. This will depend on the usage of the value.
- For pixel positions, 0.25 would suffice. For scale, 0.005 will suffice.
-
- The default is 0.01. Tuning this value can provide small performance improvements.
-*/
-qreal QDeclarativeSpringAnimation::epsilon() const
-{
- Q_D(const QDeclarativeSpringAnimation);
- return d->epsilon;
-}
-
-void QDeclarativeSpringAnimation::setEpsilon(qreal epsilon)
-{
- Q_D(QDeclarativeSpringAnimation);
- d->epsilon = epsilon;
-}
-
-/*!
- \qmlproperty real QtQuick2::SpringAnimation::modulus
- This property holds the modulus value. The default value is 0.
-
- Setting a \a modulus forces the target value to "wrap around" at the modulus.
- For example, setting the modulus to 360 will cause a value of 370 to wrap around to 10.
-*/
-qreal QDeclarativeSpringAnimation::modulus() const
-{
- Q_D(const QDeclarativeSpringAnimation);
- return d->modulus;
-}
-
-void QDeclarativeSpringAnimation::setModulus(qreal modulus)
-{
- Q_D(QDeclarativeSpringAnimation);
- if (d->modulus != modulus) {
- d->haveModulus = modulus != 0.0;
- d->modulus = modulus;
- d->updateMode();
- emit modulusChanged();
- }
-}
-
-/*!
- \qmlproperty real QtQuick2::SpringAnimation::mass
- This property holds the "mass" of the property being moved.
-
- The value is 1.0 by default.
-
- A greater mass causes slower movement and a greater spring-like
- motion when an item comes to rest.
-*/
-qreal QDeclarativeSpringAnimation::mass() const
-{
- Q_D(const QDeclarativeSpringAnimation);
- return d->mass;
-}
-
-void QDeclarativeSpringAnimation::setMass(qreal mass)
-{
- Q_D(QDeclarativeSpringAnimation);
- if (d->mass != mass && mass > 0.0) {
- d->useMass = mass != 1.0;
- d->mass = mass;
- emit massChanged();
- }
-}
-
-void QDeclarativeSpringAnimation::transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction)
-{
- Q_D(QDeclarativeSpringAnimation);
- Q_UNUSED(direction);
-
- if (d->clock->state() != QAbstractAnimation::Running) {
- d->lastTime = 0;
- }
-
- QDeclarativeNumberAnimation::transition(actions, modified, direction);
-
- if (!d->actions)
- return;
-
- if (!d->actions->isEmpty()) {
- for (int i = 0; i < d->actions->size(); ++i) {
- const QDeclarativeProperty &property = d->actions->at(i).property;
- QDeclarativeSpringAnimationPrivate::SpringAnimation &animation
- = d->activeAnimations[property];
- animation.to = d->actions->at(i).toValue.toReal();
- animation.start = d->lastTime;
- if (d->fromIsDefined)
- animation.currentValue = d->actions->at(i).fromValue.toReal();
- else
- animation.currentValue = property.read().toReal();
- if (d->mode == QDeclarativeSpringAnimationPrivate::Velocity) {
- qreal dist = qAbs(animation.currentValue - animation.to);
- if (d->haveModulus && dist > d->modulus / 2)
- dist = d->modulus - fmod(dist, d->modulus);
- animation.duration = dist / d->velocityms;
- }
- }
- }
-}
-
-
-QAbstractAnimation *QDeclarativeSpringAnimation::qtAnimation()
-{
- Q_D(QDeclarativeSpringAnimation);
- return d->clock;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativespringanimation_p.h b/src/declarative/util/qdeclarativespringanimation_p.h
deleted file mode 100644
index 14a34b47c5..0000000000
--- a/src/declarative/util/qdeclarativespringanimation_p.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVESPRINGANIMATION_H
-#define QDECLARATIVESPRINGANIMATION_H
-
-#include <qdeclarative.h>
-#include "qdeclarativeanimation_p.h"
-
-#include <QtCore/qobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeSpringAnimationPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativeSpringAnimation : public QDeclarativeNumberAnimation
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeSpringAnimation)
- Q_INTERFACES(QDeclarativePropertyValueSource)
-
- 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(qreal modulus READ modulus WRITE setModulus NOTIFY modulusChanged)
- Q_PROPERTY(qreal mass READ mass WRITE setMass NOTIFY massChanged)
-
-public:
- QDeclarativeSpringAnimation(QObject *parent=0);
- ~QDeclarativeSpringAnimation();
-
- qreal velocity() const;
- void setVelocity(qreal velocity);
-
- qreal spring() const;
- void setSpring(qreal spring);
-
- qreal damping() const;
- void setDamping(qreal damping);
-
- qreal epsilon() const;
- void setEpsilon(qreal epsilon);
-
- qreal mass() const;
- void setMass(qreal modulus);
-
- qreal modulus() const;
- void setModulus(qreal modulus);
-
- virtual void transition(QDeclarativeStateActions &actions,
- QDeclarativeProperties &modified,
- TransitionDirection direction);
-
-protected:
- virtual QAbstractAnimation *qtAnimation();
-
-Q_SIGNALS:
- void modulusChanged();
- void massChanged();
- void syncChanged();
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeSpringAnimation)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVESPRINGANIMATION_H
diff --git a/src/declarative/util/qdeclarativestate.cpp b/src/declarative/util/qdeclarativestate.cpp
deleted file mode 100644
index 1250c0c2b5..0000000000
--- a/src/declarative/util/qdeclarativestate.cpp
+++ /dev/null
@@ -1,734 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativestate_p_p.h"
-#include "qdeclarativestate_p.h"
-
-#include "qdeclarativestategroup_p.h"
-#include "qdeclarativestateoperations_p.h"
-
-#include <private/qdeclarativeglobal_p.h>
-
-#include <QtCore/qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG);
-
-QDeclarativeAction::QDeclarativeAction()
-: restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false), fromBinding(0), event(0),
- specifiedObject(0)
-{
-}
-
-QDeclarativeAction::QDeclarativeAction(QObject *target, const QString &propertyName,
- const QVariant &value)
-: restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false),
- property(target, propertyName, qmlEngine(target)), toValue(value),
- fromBinding(0), event(0),
- specifiedObject(target), specifiedProperty(propertyName)
-{
- if (property.isValid())
- fromValue = property.read();
-}
-
-QDeclarativeAction::QDeclarativeAction(QObject *target, const QString &propertyName,
- QDeclarativeContext *context, const QVariant &value)
-: restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false),
- property(target, propertyName, context), toValue(value),
- fromBinding(0), event(0),
- specifiedObject(target), specifiedProperty(propertyName)
-{
- if (property.isValid())
- fromValue = property.read();
-}
-
-
-QDeclarativeActionEvent::~QDeclarativeActionEvent()
-{
-}
-
-QString QDeclarativeActionEvent::typeName() const
-{
- return QString();
-}
-
-void QDeclarativeActionEvent::execute(Reason)
-{
-}
-
-bool QDeclarativeActionEvent::isReversable()
-{
- return false;
-}
-
-void QDeclarativeActionEvent::reverse(Reason)
-{
-}
-
-bool QDeclarativeActionEvent::changesBindings()
-{
- return false;
-}
-
-void QDeclarativeActionEvent::clearBindings()
-{
-}
-
-bool QDeclarativeActionEvent::override(QDeclarativeActionEvent *other)
-{
- Q_UNUSED(other);
- return false;
-}
-
-QDeclarativeStateOperation::QDeclarativeStateOperation(QObjectPrivate &dd, QObject *parent)
- : QObject(dd, parent)
-{
-}
-
-/*!
- \qmlclass State QDeclarativeState
- \inqmlmodule QtQuick 2
- \ingroup qml-state-elements
- \brief The State element defines configurations of objects and properties.
-
- A \e state is a set of batched changes from the default configuration.
-
- All items have a default state that defines the default configuration of objects
- and property values. New states can be defined by adding State items to the \l {Item::states}{states} property to
- allow items to switch between different configurations. These configurations
- can, for example, be used to apply different sets of property values or execute
- different scripts.
-
- The following example displays a single \l Rectangle. In the default state, the rectangle
- is colored black. In the "clicked" state, a PropertyChanges element changes the
- rectangle's color to red. Clicking within the MouseArea toggles the rectangle's state
- between the default state and the "clicked" state, thus toggling the color of the
- rectangle between black and red.
-
- \snippet doc/src/snippets/declarative/state.qml 0
-
- Notice the default state is referred to using an empty string ("").
-
- States are commonly used together with \l{QML Animation and Transitions}{Transitions} to provide
- animations when state changes occur.
-
- \note Setting the state of an object from within another state of the same object is
- not allowed.
-
- \sa {declarative/animation/states}{states example}, {qmlstates}{States},
- {QML Animation and Transitions}{Transitions}, QtDeclarative
-*/
-QDeclarativeState::QDeclarativeState(QObject *parent)
-: QObject(*(new QDeclarativeStatePrivate), parent)
-{
- Q_D(QDeclarativeState);
- d->transitionManager.setState(this);
-}
-
-QDeclarativeState::~QDeclarativeState()
-{
- Q_D(QDeclarativeState);
- if (d->group)
- d->group->removeState(this);
-}
-
-/*!
- \qmlproperty string QtQuick2::State::name
- This property holds the name of the state.
-
- Each state should have a unique name within its item.
-*/
-QString QDeclarativeState::name() const
-{
- Q_D(const QDeclarativeState);
- return d->name;
-}
-
-void QDeclarativeState::setName(const QString &n)
-{
- Q_D(QDeclarativeState);
- d->name = n;
- d->named = true;
-}
-
-bool QDeclarativeState::isNamed() const
-{
- Q_D(const QDeclarativeState);
- return d->named;
-}
-
-bool QDeclarativeState::isWhenKnown() const
-{
- Q_D(const QDeclarativeState);
- return d->when != 0;
-}
-
-/*!
- \qmlproperty bool QtQuick2::State::when
- This property holds when the state should be applied.
-
- This should be set to an expression that evaluates to \c true when you want the state to
- be applied. For example, the following \l Rectangle changes in and out of the "hidden"
- state when the \l MouseArea is pressed:
-
- \snippet doc/src/snippets/declarative/state-when.qml 0
-
- If multiple states in a group have \c when clauses that evaluate to \c true
- at the same time, the first matching state will be applied. For example, in
- the following snippet \c state1 will always be selected rather than
- \c state2 when sharedCondition becomes \c true.
- \qml
- Item {
- states: [
- State { name: "state1"; when: sharedCondition },
- State { name: "state2"; when: sharedCondition }
- ]
- // ...
- }
- \endqml
-*/
-QDeclarativeBinding *QDeclarativeState::when() const
-{
- Q_D(const QDeclarativeState);
- return d->when;
-}
-
-void QDeclarativeState::setWhen(QDeclarativeBinding *when)
-{
- Q_D(QDeclarativeState);
- d->when = when;
- if (d->group)
- d->group->updateAutoState();
-}
-
-/*!
- \qmlproperty string QtQuick2::State::extend
- This property holds the state that this state extends.
-
- When a state extends another state, it inherits all the changes of that state.
-
- The state being extended is treated as the base state in regards to
- the changes specified by the extending state.
-*/
-QString QDeclarativeState::extends() const
-{
- Q_D(const QDeclarativeState);
- return d->extends;
-}
-
-void QDeclarativeState::setExtends(const QString &extends)
-{
- Q_D(QDeclarativeState);
- d->extends = extends;
-}
-
-/*!
- \qmlproperty list<Change> QtQuick2::State::changes
- This property holds the changes to apply for this state
- \default
-
- By default these changes are applied against the default state. If the state
- extends another state, then the changes are applied against the state being
- extended.
-*/
-QDeclarativeListProperty<QDeclarativeStateOperation> QDeclarativeState::changes()
-{
- Q_D(QDeclarativeState);
- return QDeclarativeListProperty<QDeclarativeStateOperation>(this, &d->operations, QDeclarativeStatePrivate::operations_append,
- QDeclarativeStatePrivate::operations_count, QDeclarativeStatePrivate::operations_at,
- QDeclarativeStatePrivate::operations_clear);
-}
-
-int QDeclarativeState::operationCount() const
-{
- Q_D(const QDeclarativeState);
- return d->operations.count();
-}
-
-QDeclarativeStateOperation *QDeclarativeState::operationAt(int index) const
-{
- Q_D(const QDeclarativeState);
- return d->operations.at(index);
-}
-
-QDeclarativeState &QDeclarativeState::operator<<(QDeclarativeStateOperation *op)
-{
- Q_D(QDeclarativeState);
- d->operations.append(QDeclarativeStatePrivate::OperationGuard(op, &d->operations));
- return *this;
-}
-
-void QDeclarativeStatePrivate::complete()
-{
- Q_Q(QDeclarativeState);
-
- for (int ii = 0; ii < reverting.count(); ++ii) {
- for (int jj = 0; jj < revertList.count(); ++jj) {
- const QDeclarativeRevertAction &revert = reverting.at(ii);
- const QDeclarativeSimpleAction &simple = revertList.at(jj);
- if ((revert.event && simple.event() == revert.event) ||
- simple.property() == revert.property) {
- revertList.removeAt(jj);
- break;
- }
- }
- }
- reverting.clear();
-
- if (group)
- group->stateAboutToComplete();
- emit q->completed();
-}
-
-// Generate a list of actions for this state. This includes coelescing state
-// actions that this state "extends"
-QDeclarativeStateOperation::ActionList
-QDeclarativeStatePrivate::generateActionList() const
-{
- QDeclarativeStateOperation::ActionList applyList;
- if (inState)
- return applyList;
-
- // Prevent "extends" recursion
- inState = true;
-
- if (!extends.isEmpty()) {
- QList<QDeclarativeState *> states = group ? group->states() : QList<QDeclarativeState *>();
- for (int ii = 0; ii < states.count(); ++ii)
- if (states.at(ii)->name() == extends) {
- qmlExecuteDeferred(states.at(ii));
- applyList = static_cast<QDeclarativeStatePrivate*>(states.at(ii)->d_func())->generateActionList();
- }
- }
-
- foreach(QDeclarativeStateOperation *op, operations)
- applyList << op->actions();
-
- inState = false;
- return applyList;
-}
-
-QDeclarativeStateGroup *QDeclarativeState::stateGroup() const
-{
- Q_D(const QDeclarativeState);
- return d->group;
-}
-
-void QDeclarativeState::setStateGroup(QDeclarativeStateGroup *group)
-{
- Q_D(QDeclarativeState);
- d->group = group;
-}
-
-void QDeclarativeState::cancel()
-{
- Q_D(QDeclarativeState);
- d->transitionManager.cancel();
-}
-
-void QDeclarativeAction::deleteFromBinding()
-{
- if (fromBinding) {
- QDeclarativePropertyPrivate::setBinding(property, 0);
- fromBinding->destroy();
- fromBinding = 0;
- }
-}
-
-bool QDeclarativeState::containsPropertyInRevertList(QObject *target, const QString &name) const
-{
- Q_D(const QDeclarativeState);
-
- if (isStateActive()) {
- QListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList);
-
- while (revertListIterator.hasNext()) {
- const QDeclarativeSimpleAction &simpleAction = revertListIterator.next();
- if (simpleAction.specifiedObject() == target && simpleAction.specifiedProperty() == name)
- return true;
- }
- }
-
- return false;
-}
-
-bool QDeclarativeState::changeValueInRevertList(QObject *target, const QString &name, const QVariant &revertValue)
-{
- Q_D(QDeclarativeState);
-
- if (isStateActive()) {
- QMutableListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList);
-
- while (revertListIterator.hasNext()) {
- QDeclarativeSimpleAction &simpleAction = revertListIterator.next();
- if (simpleAction.specifiedObject() == target && simpleAction.specifiedProperty() == name) {
- simpleAction.setValue(revertValue);
- return true;
- }
- }
- }
-
- return false;
-}
-
-bool QDeclarativeState::changeBindingInRevertList(QObject *target, const QString &name, QDeclarativeAbstractBinding *binding)
-{
- Q_D(QDeclarativeState);
-
- if (isStateActive()) {
- QMutableListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList);
-
- while (revertListIterator.hasNext()) {
- QDeclarativeSimpleAction &simpleAction = revertListIterator.next();
- if (simpleAction.specifiedObject() == target && simpleAction.specifiedProperty() == name) {
- if (simpleAction.binding())
- simpleAction.binding()->destroy();
-
- simpleAction.setBinding(binding);
- return true;
- }
- }
- }
-
- return false;
-}
-
-bool QDeclarativeState::removeEntryFromRevertList(QObject *target, const QString &name)
-{
- Q_D(QDeclarativeState);
-
- if (isStateActive()) {
- QMutableListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList);
-
- while (revertListIterator.hasNext()) {
- QDeclarativeSimpleAction &simpleAction = revertListIterator.next();
- if (simpleAction.property().object() == target && simpleAction.property().name() == name) {
- QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(simpleAction.property());
- if (oldBinding) {
- QDeclarativePropertyPrivate::setBinding(simpleAction.property(), 0);
- oldBinding->destroy();
- }
-
- simpleAction.property().write(simpleAction.value());
- if (simpleAction.binding())
- QDeclarativePropertyPrivate::setBinding(simpleAction.property(), simpleAction.binding());
-
- revertListIterator.remove();
- return true;
- }
- }
- }
-
- return false;
-}
-
-void QDeclarativeState::addEntryToRevertList(const QDeclarativeAction &action)
-{
- Q_D(QDeclarativeState);
-
- QDeclarativeSimpleAction simpleAction(action);
-
- d->revertList.append(simpleAction);
-}
-
-void QDeclarativeState::removeAllEntriesFromRevertList(QObject *target)
-{
- Q_D(QDeclarativeState);
-
- if (isStateActive()) {
- QMutableListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList);
-
- while (revertListIterator.hasNext()) {
- QDeclarativeSimpleAction &simpleAction = revertListIterator.next();
- if (simpleAction.property().object() == target) {
- QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(simpleAction.property());
- if (oldBinding) {
- QDeclarativePropertyPrivate::setBinding(simpleAction.property(), 0);
- oldBinding->destroy();
- }
-
- simpleAction.property().write(simpleAction.value());
- if (simpleAction.binding())
- QDeclarativePropertyPrivate::setBinding(simpleAction.property(), simpleAction.binding());
-
- revertListIterator.remove();
- }
- }
- }
-}
-
-void QDeclarativeState::addEntriesToRevertList(const QList<QDeclarativeAction> &actionList)
-{
- Q_D(QDeclarativeState);
- if (isStateActive()) {
- QList<QDeclarativeSimpleAction> simpleActionList;
-
- QListIterator<QDeclarativeAction> actionListIterator(actionList);
- while(actionListIterator.hasNext()) {
- const QDeclarativeAction &action = actionListIterator.next();
- QDeclarativeSimpleAction simpleAction(action);
- action.property.write(action.toValue);
- if (!action.toBinding.isNull()) {
- QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(simpleAction.property());
- if (oldBinding)
- QDeclarativePropertyPrivate::setBinding(simpleAction.property(), 0);
- QDeclarativePropertyPrivate::setBinding(simpleAction.property(), action.toBinding.data(), QDeclarativePropertyPrivate::DontRemoveBinding);
- }
-
- simpleActionList.append(simpleAction);
- }
-
- d->revertList.append(simpleActionList);
- }
-}
-
-QVariant QDeclarativeState::valueInRevertList(QObject *target, const QString &name) const
-{
- Q_D(const QDeclarativeState);
-
- if (isStateActive()) {
- QListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList);
-
- while (revertListIterator.hasNext()) {
- const QDeclarativeSimpleAction &simpleAction = revertListIterator.next();
- if (simpleAction.specifiedObject() == target && simpleAction.specifiedProperty() == name)
- return simpleAction.value();
- }
- }
-
- return QVariant();
-}
-
-QDeclarativeAbstractBinding *QDeclarativeState::bindingInRevertList(QObject *target, const QString &name) const
-{
- Q_D(const QDeclarativeState);
-
- if (isStateActive()) {
- QListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList);
-
- while (revertListIterator.hasNext()) {
- const QDeclarativeSimpleAction &simpleAction = revertListIterator.next();
- if (simpleAction.specifiedObject() == target && simpleAction.specifiedProperty() == name)
- return simpleAction.binding();
- }
- }
-
- return 0;
-}
-
-bool QDeclarativeState::isStateActive() const
-{
- return stateGroup() && stateGroup()->state() == name();
-}
-
-void QDeclarativeState::apply(QDeclarativeTransition *trans, QDeclarativeState *revert)
-{
- Q_D(QDeclarativeState);
-
- qmlExecuteDeferred(this);
-
- cancel();
- if (revert)
- revert->cancel();
- d->revertList.clear();
- d->reverting.clear();
-
- if (revert) {
- QDeclarativeStatePrivate *revertPrivate =
- static_cast<QDeclarativeStatePrivate*>(revert->d_func());
- d->revertList = revertPrivate->revertList;
- revertPrivate->revertList.clear();
- }
-
- // List of actions caused by this state
- QDeclarativeStateOperation::ActionList applyList = d->generateActionList();
-
- // List of actions that need to be reverted to roll back (just) this state
- QDeclarativeStatePrivate::SimpleActionList additionalReverts;
- // First add the reverse of all the applyList actions
- for (int ii = 0; ii < applyList.count(); ++ii) {
- QDeclarativeAction &action = applyList[ii];
-
- if (action.event) {
- if (!action.event->isReversable())
- continue;
- bool found = false;
- for (int jj = 0; jj < d->revertList.count(); ++jj) {
- QDeclarativeActionEvent *event = d->revertList.at(jj).event();
- if (event && event->typeName() == action.event->typeName()) {
- if (action.event->override(event)) {
- found = true;
-
- if (action.event != d->revertList.at(jj).event() && action.event->needsCopy()) {
- action.event->copyOriginals(d->revertList.at(jj).event());
-
- QDeclarativeSimpleAction r(action);
- additionalReverts << r;
- d->revertList.removeAt(jj);
- --jj;
- } else if (action.event->isRewindable()) //###why needed?
- action.event->saveCurrentValues();
-
- break;
- }
- }
- }
- if (!found) {
- action.event->saveOriginals();
- // Only need to revert the applyList action if the previous
- // state doesn't have a higher priority revert already
- QDeclarativeSimpleAction r(action);
- additionalReverts << r;
- }
- } else {
- bool found = false;
- action.fromBinding = QDeclarativePropertyPrivate::binding(action.property);
-
- for (int jj = 0; jj < d->revertList.count(); ++jj) {
- if (d->revertList.at(jj).property() == action.property) {
- found = true;
- if (d->revertList.at(jj).binding() != action.fromBinding) {
- action.deleteFromBinding();
- }
- break;
- }
- }
-
- if (!found) {
- if (!action.restore) {
- action.deleteFromBinding();;
- } else {
- // Only need to revert the applyList action if the previous
- // state doesn't have a higher priority revert already
- QDeclarativeSimpleAction r(action);
- additionalReverts << r;
- }
- }
- }
- }
-
- // Any reverts from a previous state that aren't carried forth
- // into this state need to be translated into apply actions
- for (int ii = 0; ii < d->revertList.count(); ++ii) {
- bool found = false;
- if (d->revertList.at(ii).event()) {
- QDeclarativeActionEvent *event = d->revertList.at(ii).event();
- if (!event->isReversable())
- continue;
- for (int jj = 0; !found && jj < applyList.count(); ++jj) {
- const QDeclarativeAction &action = applyList.at(jj);
- if (action.event && action.event->typeName() == event->typeName()) {
- if (action.event->override(event))
- found = true;
- }
- }
- } else {
- for (int jj = 0; !found && jj < applyList.count(); ++jj) {
- const QDeclarativeAction &action = applyList.at(jj);
- if (action.property == d->revertList.at(ii).property())
- found = true;
- }
- }
- if (!found) {
- QVariant cur = d->revertList.at(ii).property().read();
- QDeclarativeAbstractBinding *delBinding =
- QDeclarativePropertyPrivate::setBinding(d->revertList.at(ii).property(), 0);
- if (delBinding)
- delBinding->destroy();
-
- QDeclarativeAction a;
- a.property = d->revertList.at(ii).property();
- a.fromValue = cur;
- a.toValue = d->revertList.at(ii).value();
- a.toBinding = QDeclarativeAbstractBinding::getPointer(d->revertList.at(ii).binding());
- a.specifiedObject = d->revertList.at(ii).specifiedObject();
- a.specifiedProperty = d->revertList.at(ii).specifiedProperty();
- a.event = d->revertList.at(ii).event();
- a.reverseEvent = d->revertList.at(ii).reverseEvent();
- if (a.event && a.event->isRewindable())
- a.event->saveCurrentValues();
- applyList << a;
- // Store these special reverts in the reverting list
- if (a.event)
- d->reverting << a.event;
- else
- d->reverting << a.property;
- }
- }
- // All the local reverts now become part of the ongoing revertList
- d->revertList << additionalReverts;
-
-#ifndef QT_NO_DEBUG_STREAM
- // Output for debugging
- if (stateChangeDebug()) {
- foreach(const QDeclarativeAction &action, applyList) {
- if (action.event)
- qWarning() << " QDeclarativeAction event:" << action.event->typeName();
- else
- qWarning() << " QDeclarativeAction:" << action.property.object()
- << action.property.name() << "From:" << action.fromValue
- << "To:" << action.toValue;
- }
- }
-#endif
-
- d->transitionManager.transition(applyList, trans);
-}
-
-QDeclarativeStateOperation::ActionList QDeclarativeStateOperation::actions()
-{
- return ActionList();
-}
-
-QDeclarativeState *QDeclarativeStateOperation::state() const
-{
- Q_D(const QDeclarativeStateOperation);
- return d->m_state;
-}
-
-void QDeclarativeStateOperation::setState(QDeclarativeState *state)
-{
- Q_D(QDeclarativeStateOperation);
- d->m_state = state;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativestate_p.h b/src/declarative/util/qdeclarativestate_p.h
deleted file mode 100644
index a7aafe32fe..0000000000
--- a/src/declarative/util/qdeclarativestate_p.h
+++ /dev/null
@@ -1,210 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVESTATE_H
-#define QDECLARATIVESTATE_H
-
-#include <qdeclarative.h>
-#include <qdeclarativeproperty.h>
-#include <QtCore/qobject.h>
-#include <QtCore/qsharedpointer.h>
-#include <private/qdeclarativeglobal_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeActionEvent;
-class QDeclarativeAbstractBinding;
-class QDeclarativeBinding;
-class QDeclarativeExpression;
-class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativeAction
-{
-public:
- QDeclarativeAction();
- QDeclarativeAction(QObject *, const QString &, const QVariant &);
- QDeclarativeAction(QObject *, const QString &,
- QDeclarativeContext *, const QVariant &);
-
- bool restore:1;
- bool actionDone:1;
- bool reverseEvent:1;
- bool deletableToBinding:1;
-
- QDeclarativeProperty property;
- QVariant fromValue;
- QVariant toValue;
-
- QDeclarativeAbstractBinding *fromBinding;
- QWeakPointer<QDeclarativeAbstractBinding> toBinding;
- QDeclarativeActionEvent *event;
-
- //strictly for matching
- QObject *specifiedObject;
- QString specifiedProperty;
-
- void deleteFromBinding();
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativeActionEvent
-{
-public:
- virtual ~QDeclarativeActionEvent();
- virtual QString typeName() const;
-
- enum Reason { ActualChange, FastForward };
-
- virtual void execute(Reason reason = ActualChange);
- virtual bool isReversable();
- virtual void reverse(Reason reason = ActualChange);
- virtual void saveOriginals() {}
- virtual bool needsCopy() { return false; }
- virtual void copyOriginals(QDeclarativeActionEvent *) {}
-
- virtual bool isRewindable() { return isReversable(); }
- virtual void rewind() {}
- virtual void saveCurrentValues() {}
- virtual void saveTargetValues() {}
-
- virtual bool changesBindings();
- virtual void clearBindings();
- virtual bool override(QDeclarativeActionEvent*other);
-};
-
-//### rename to QDeclarativeStateChange?
-class QDeclarativeStateGroup;
-class QDeclarativeState;
-class QDeclarativeStateOperationPrivate;
-class Q_DECLARATIVE_EXPORT QDeclarativeStateOperation : public QObject
-{
- Q_OBJECT
-public:
- QDeclarativeStateOperation(QObject *parent = 0)
- : QObject(parent) {}
- typedef QList<QDeclarativeAction> ActionList;
-
- virtual ActionList actions();
-
- QDeclarativeState *state() const;
- void setState(QDeclarativeState *state);
-
-protected:
- QDeclarativeStateOperation(QObjectPrivate &dd, QObject *parent = 0);
-
-private:
- Q_DECLARE_PRIVATE(QDeclarativeStateOperation)
- Q_DISABLE_COPY(QDeclarativeStateOperation)
-};
-
-typedef QDeclarativeStateOperation::ActionList QDeclarativeStateActions;
-
-class QDeclarativeTransition;
-class QDeclarativeStatePrivate;
-class Q_DECLARATIVE_EXPORT QDeclarativeState : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QString name READ name WRITE setName)
- Q_PROPERTY(QDeclarativeBinding *when READ when WRITE setWhen)
- Q_PROPERTY(QString extend READ extends WRITE setExtends)
- Q_PROPERTY(QDeclarativeListProperty<QDeclarativeStateOperation> changes READ changes)
- Q_CLASSINFO("DefaultProperty", "changes")
- Q_CLASSINFO("DeferredPropertyNames", "changes")
-
-public:
- QDeclarativeState(QObject *parent=0);
- virtual ~QDeclarativeState();
-
- QString name() const;
- void setName(const QString &);
- bool isNamed() const;
-
- /*'when' is a QDeclarativeBinding to limit state changes oscillation
- due to the unpredictable order of evaluation of bound expressions*/
- bool isWhenKnown() const;
- QDeclarativeBinding *when() const;
- void setWhen(QDeclarativeBinding *);
-
- QString extends() const;
- void setExtends(const QString &);
-
- QDeclarativeListProperty<QDeclarativeStateOperation> changes();
- int operationCount() const;
- QDeclarativeStateOperation *operationAt(int) const;
-
- QDeclarativeState &operator<<(QDeclarativeStateOperation *);
-
- void apply(QDeclarativeTransition *, QDeclarativeState *revert);
- void cancel();
-
- QDeclarativeStateGroup *stateGroup() const;
- void setStateGroup(QDeclarativeStateGroup *);
-
- bool containsPropertyInRevertList(QObject *target, const QString &name) const;
- bool changeValueInRevertList(QObject *target, const QString &name, const QVariant &revertValue);
- bool changeBindingInRevertList(QObject *target, const QString &name, QDeclarativeAbstractBinding *binding);
- bool removeEntryFromRevertList(QObject *target, const QString &name);
- void addEntryToRevertList(const QDeclarativeAction &action);
- void removeAllEntriesFromRevertList(QObject *target);
- void addEntriesToRevertList(const QList<QDeclarativeAction> &actions);
- QVariant valueInRevertList(QObject *target, const QString &name) const;
- QDeclarativeAbstractBinding *bindingInRevertList(QObject *target, const QString &name) const;
-
- bool isStateActive() const;
-
-Q_SIGNALS:
- void completed();
-
-private:
- Q_DECLARE_PRIVATE(QDeclarativeState)
- Q_DISABLE_COPY(QDeclarativeState)
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeStateOperation)
-QML_DECLARE_TYPE(QDeclarativeState)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVESTATE_H
diff --git a/src/declarative/util/qdeclarativestate_p_p.h b/src/declarative/util/qdeclarativestate_p_p.h
deleted file mode 100644
index 55aeecde11..0000000000
--- a/src/declarative/util/qdeclarativestate_p_p.h
+++ /dev/null
@@ -1,264 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVESTATE_P_H
-#define QDECLARATIVESTATE_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 "qdeclarativestate_p.h"
-
-#include "qdeclarativetransitionmanager_p_p.h"
-
-#include <private/qdeclarativeproperty_p.h>
-#include <private/qdeclarativeguard_p.h>
-
-#include <private/qdeclarativebinding_p.h>
-
-#include <private/qobject_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeSimpleAction
-{
-public:
- enum State { StartState, EndState };
- QDeclarativeSimpleAction(const QDeclarativeAction &a, State state = StartState)
- {
- m_property = a.property;
- m_specifiedObject = a.specifiedObject;
- m_specifiedProperty = a.specifiedProperty;
- m_event = a.event;
- if (state == StartState) {
- m_value = a.fromValue;
- if (QDeclarativePropertyPrivate::binding(m_property)) {
- m_binding = QDeclarativeAbstractBinding::getPointer(QDeclarativePropertyPrivate::binding(m_property));
- }
- m_reverseEvent = true;
- } else {
- m_value = a.toValue;
- m_binding = a.toBinding;
- m_reverseEvent = false;
- }
- }
-
- ~QDeclarativeSimpleAction()
- {
- }
-
- QDeclarativeSimpleAction(const QDeclarativeSimpleAction &other)
- : m_property(other.m_property),
- m_value(other.m_value),
- m_binding(QDeclarativeAbstractBinding::getPointer(other.binding())),
- m_specifiedObject(other.m_specifiedObject),
- m_specifiedProperty(other.m_specifiedProperty),
- m_event(other.m_event),
- m_reverseEvent(other.m_reverseEvent)
- {
- }
-
- QDeclarativeSimpleAction &operator =(const QDeclarativeSimpleAction &other)
- {
- m_property = other.m_property;
- m_value = other.m_value;
- m_binding = QDeclarativeAbstractBinding::getPointer(other.binding());
- m_specifiedObject = other.m_specifiedObject;
- m_specifiedProperty = other.m_specifiedProperty;
- m_event = other.m_event;
- m_reverseEvent = other.m_reverseEvent;
-
- return *this;
- }
-
- void setProperty(const QDeclarativeProperty &property)
- {
- m_property = property;
- }
-
- const QDeclarativeProperty &property() const
- {
- return m_property;
- }
-
- void setValue(const QVariant &value)
- {
- m_value = value;
- }
-
- const QVariant &value() const
- {
- return m_value;
- }
-
- void setBinding(QDeclarativeAbstractBinding *binding)
- {
- m_binding = QDeclarativeAbstractBinding::getPointer(binding);
- }
-
- QDeclarativeAbstractBinding *binding() const
- {
- return m_binding.data();
- }
-
- QObject *specifiedObject() const
- {
- return m_specifiedObject;
- }
-
- const QString &specifiedProperty() const
- {
- return m_specifiedProperty;
- }
-
- QDeclarativeActionEvent *event() const
- {
- return m_event;
- }
-
- bool reverseEvent() const
- {
- return m_reverseEvent;
- }
-
-private:
- QDeclarativeProperty m_property;
- QVariant m_value;
- QDeclarativeAbstractBinding::Pointer m_binding;
- QObject *m_specifiedObject;
- QString m_specifiedProperty;
- QDeclarativeActionEvent *m_event;
- bool m_reverseEvent;
-};
-
-class QDeclarativeRevertAction
-{
-public:
- QDeclarativeRevertAction() : event(0) {}
- QDeclarativeRevertAction(const QDeclarativeProperty &prop) : property(prop), event(0) {}
- QDeclarativeRevertAction(QDeclarativeActionEvent *e) : event(e) {}
- QDeclarativeProperty property;
- QDeclarativeActionEvent *event;
-};
-
-class QDeclarativeStateOperationPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeStateOperation)
-
-public:
-
- QDeclarativeStateOperationPrivate()
- : m_state(0) {}
-
- QDeclarativeState *m_state;
-};
-
-class QDeclarativeStatePrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeState)
-
-public:
- QDeclarativeStatePrivate()
- : when(0), named(false), inState(false), group(0) {}
-
- typedef QList<QDeclarativeSimpleAction> SimpleActionList;
-
- QString name;
- QDeclarativeBinding *when;
- bool named;
-
- struct OperationGuard : public QDeclarativeGuard<QDeclarativeStateOperation>
- {
- OperationGuard(QObject *obj, QList<OperationGuard> *l) : list(l) {
- setObject(static_cast<QDeclarativeStateOperation *>(obj));
- }
- QList<OperationGuard> *list;
- void objectDestroyed(QDeclarativeStateOperation *) {
- // we assume priv will always be destroyed after objectDestroyed calls
- list->removeOne(*this);
- }
- };
- QList<OperationGuard> operations;
-
- static void operations_append(QDeclarativeListProperty<QDeclarativeStateOperation> *prop, QDeclarativeStateOperation *op) {
- QList<OperationGuard> *list = static_cast<QList<OperationGuard> *>(prop->data);
- op->setState(qobject_cast<QDeclarativeState*>(prop->object));
- list->append(OperationGuard(op, list));
- }
- static void operations_clear(QDeclarativeListProperty<QDeclarativeStateOperation> *prop) {
- QList<OperationGuard> *list = static_cast<QList<OperationGuard> *>(prop->data);
- QMutableListIterator<OperationGuard> listIterator(*list);
- while(listIterator.hasNext())
- listIterator.next()->setState(0);
- list->clear();
- }
- static int operations_count(QDeclarativeListProperty<QDeclarativeStateOperation> *prop) {
- QList<OperationGuard> *list = static_cast<QList<OperationGuard> *>(prop->data);
- return list->count();
- }
- static QDeclarativeStateOperation *operations_at(QDeclarativeListProperty<QDeclarativeStateOperation> *prop, int index) {
- QList<OperationGuard> *list = static_cast<QList<OperationGuard> *>(prop->data);
- return list->at(index);
- }
-
- QDeclarativeTransitionManager transitionManager;
-
- SimpleActionList revertList;
- QList<QDeclarativeRevertAction> reverting;
- QString extends;
- mutable bool inState;
- QDeclarativeStateGroup *group;
-
- QDeclarativeStateOperation::ActionList generateActionList() const;
- void complete();
-};
-
-QT_END_NAMESPACE
-
-#endif // QDECLARATIVESTATE_P_H
diff --git a/src/declarative/util/qdeclarativestategroup.cpp b/src/declarative/util/qdeclarativestategroup.cpp
deleted file mode 100644
index 51e27e4bf0..0000000000
--- a/src/declarative/util/qdeclarativestategroup.cpp
+++ /dev/null
@@ -1,516 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativestategroup_p.h"
-
-#include "qdeclarativetransition_p.h"
-
-#include <private/qdeclarativebinding_p.h>
-#include <private/qdeclarativeglobal_p.h>
-
-#include <QtCore/qstringbuilder.h>
-#include <QtCore/qstringlist.h>
-#include <QtCore/qdebug.h>
-
-#include <private/qobject_p.h>
-#include <qdeclarativeinfo.h>
-
-QT_BEGIN_NAMESPACE
-
-DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG);
-
-class QDeclarativeStateGroupPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeStateGroup)
-public:
- QDeclarativeStateGroupPrivate()
- : nullState(0), componentComplete(true),
- ignoreTrans(false), applyingState(false), unnamedCount(0) {}
-
- QString currentState;
- QDeclarativeState *nullState;
-
- static void append_state(QDeclarativeListProperty<QDeclarativeState> *list, QDeclarativeState *state);
- static int count_state(QDeclarativeListProperty<QDeclarativeState> *list);
- static QDeclarativeState *at_state(QDeclarativeListProperty<QDeclarativeState> *list, int index);
- static void clear_states(QDeclarativeListProperty<QDeclarativeState> *list);
-
- static void append_transition(QDeclarativeListProperty<QDeclarativeTransition> *list, QDeclarativeTransition *state);
- static int count_transitions(QDeclarativeListProperty<QDeclarativeTransition> *list);
- static QDeclarativeTransition *at_transition(QDeclarativeListProperty<QDeclarativeTransition> *list, int index);
- static void clear_transitions(QDeclarativeListProperty<QDeclarativeTransition> *list);
-
- QList<QDeclarativeState *> states;
- QList<QDeclarativeTransition *> transitions;
-
- bool componentComplete;
- bool ignoreTrans;
- bool applyingState;
- int unnamedCount;
-
- QDeclarativeTransition *findTransition(const QString &from, const QString &to);
- void setCurrentStateInternal(const QString &state, bool = false);
- bool updateAutoState();
-};
-
-/*!
- \qmlclass StateGroup QDeclarativeStateGroup
- \inqmlmodule QtQuick 2
- \ingroup qml-state-elements
- \brief The StateGroup element provides state support for non-Item elements.
-
- Item (and all derived elements) provides built in support for states and transitions
- via its \l{Item::state}{state}, \l{Item::states}{states} and \l{Item::transitions}{transitions} properties. StateGroup provides an easy way to
- use this support in other (non-Item-derived) elements.
-
- \qml
- MyCustomObject {
- StateGroup {
- id: myStateGroup
- states: State {
- name: "state1"
- // ...
- }
- transitions: Transition {
- // ...
- }
- }
-
- onSomethingHappened: myStateGroup.state = "state1";
- }
- \endqml
-
- \sa {qmlstate}{States} {QML Animation and Transitions}{Transitions}, {QtDeclarative}
-*/
-
-QDeclarativeStateGroup::QDeclarativeStateGroup(QObject *parent)
- : QObject(*(new QDeclarativeStateGroupPrivate), parent)
-{
-}
-
-QDeclarativeStateGroup::~QDeclarativeStateGroup()
-{
- Q_D(const QDeclarativeStateGroup);
- for (int i = 0; i < d->states.count(); ++i)
- d->states.at(i)->setStateGroup(0);
-}
-
-QList<QDeclarativeState *> QDeclarativeStateGroup::states() const
-{
- Q_D(const QDeclarativeStateGroup);
- return d->states;
-}
-
-/*!
- \qmlproperty list<State> QtQuick2::StateGroup::states
- This property holds a list of states defined by the state group.
-
- \qml
- StateGroup {
- states: [
- State {
- // State definition...
- },
- State {
- // ...
- }
- // Other states...
- ]
- }
- \endqml
-
- \sa {qmlstate}{States}
-*/
-QDeclarativeListProperty<QDeclarativeState> QDeclarativeStateGroup::statesProperty()
-{
- Q_D(QDeclarativeStateGroup);
- return QDeclarativeListProperty<QDeclarativeState>(this, &d->states, &QDeclarativeStateGroupPrivate::append_state,
- &QDeclarativeStateGroupPrivate::count_state,
- &QDeclarativeStateGroupPrivate::at_state,
- &QDeclarativeStateGroupPrivate::clear_states);
-}
-
-void QDeclarativeStateGroupPrivate::append_state(QDeclarativeListProperty<QDeclarativeState> *list, QDeclarativeState *state)
-{
- QDeclarativeStateGroup *_this = static_cast<QDeclarativeStateGroup *>(list->object);
- if (state) {
- _this->d_func()->states.append(state);
- state->setStateGroup(_this);
- }
-
-}
-
-int QDeclarativeStateGroupPrivate::count_state(QDeclarativeListProperty<QDeclarativeState> *list)
-{
- QDeclarativeStateGroup *_this = static_cast<QDeclarativeStateGroup *>(list->object);
- return _this->d_func()->states.count();
-}
-
-QDeclarativeState *QDeclarativeStateGroupPrivate::at_state(QDeclarativeListProperty<QDeclarativeState> *list, int index)
-{
- QDeclarativeStateGroup *_this = static_cast<QDeclarativeStateGroup *>(list->object);
- return _this->d_func()->states.at(index);
-}
-
-void QDeclarativeStateGroupPrivate::clear_states(QDeclarativeListProperty<QDeclarativeState> *list)
-{
- QDeclarativeStateGroup *_this = static_cast<QDeclarativeStateGroup *>(list->object);
- _this->d_func()->setCurrentStateInternal(QString(), true);
- for (int i = 0; i < _this->d_func()->states.count(); ++i) {
- _this->d_func()->states.at(i)->setStateGroup(0);
- }
- _this->d_func()->states.clear();
-}
-
-/*!
- \qmlproperty list<Transition> QtQuick2::StateGroup::transitions
- This property holds a list of transitions defined by the state group.
-
- \qml
- StateGroup {
- transitions: [
- Transition {
- // ...
- },
- Transition {
- // ...
- }
- // ...
- ]
- }
- \endqml
-
- \sa {QML Animation and Transitions}{Transitions}
-*/
-QDeclarativeListProperty<QDeclarativeTransition> QDeclarativeStateGroup::transitionsProperty()
-{
- Q_D(QDeclarativeStateGroup);
- return QDeclarativeListProperty<QDeclarativeTransition>(this, &d->transitions, &QDeclarativeStateGroupPrivate::append_transition,
- &QDeclarativeStateGroupPrivate::count_transitions,
- &QDeclarativeStateGroupPrivate::at_transition,
- &QDeclarativeStateGroupPrivate::clear_transitions);
-}
-
-void QDeclarativeStateGroupPrivate::append_transition(QDeclarativeListProperty<QDeclarativeTransition> *list, QDeclarativeTransition *trans)
-{
- QDeclarativeStateGroup *_this = static_cast<QDeclarativeStateGroup *>(list->object);
- if (trans)
- _this->d_func()->transitions.append(trans);
-}
-
-int QDeclarativeStateGroupPrivate::count_transitions(QDeclarativeListProperty<QDeclarativeTransition> *list)
-{
- QDeclarativeStateGroup *_this = static_cast<QDeclarativeStateGroup *>(list->object);
- return _this->d_func()->transitions.count();
-}
-
-QDeclarativeTransition *QDeclarativeStateGroupPrivate::at_transition(QDeclarativeListProperty<QDeclarativeTransition> *list, int index)
-{
- QDeclarativeStateGroup *_this = static_cast<QDeclarativeStateGroup *>(list->object);
- return _this->d_func()->transitions.at(index);
-}
-
-void QDeclarativeStateGroupPrivate::clear_transitions(QDeclarativeListProperty<QDeclarativeTransition> *list)
-{
- QDeclarativeStateGroup *_this = static_cast<QDeclarativeStateGroup *>(list->object);
- _this->d_func()->transitions.clear();
-}
-
-/*!
- \qmlproperty string QtQuick2::StateGroup::state
-
- This property holds the name of the current state of the state group.
-
- This property is often used in scripts to change between states. For
- example:
-
- \js
- function toggle() {
- if (button.state == 'On')
- button.state = 'Off';
- else
- button.state = 'On';
- }
- \endjs
-
- If the state group is in its base state (i.e. no explicit state has been
- set), \c state will be a blank string. Likewise, you can return a
- state group to its base state by setting its current state to \c ''.
-
- \sa {qmlstates}{States}
-*/
-QString QDeclarativeStateGroup::state() const
-{
- Q_D(const QDeclarativeStateGroup);
- return d->currentState;
-}
-
-void QDeclarativeStateGroup::setState(const QString &state)
-{
- Q_D(QDeclarativeStateGroup);
- if (d->currentState == state)
- return;
-
- d->setCurrentStateInternal(state);
-}
-
-void QDeclarativeStateGroup::classBegin()
-{
- Q_D(QDeclarativeStateGroup);
- d->componentComplete = false;
-}
-
-void QDeclarativeStateGroup::componentComplete()
-{
- Q_D(QDeclarativeStateGroup);
- d->componentComplete = true;
-
- for (int ii = 0; ii < d->states.count(); ++ii) {
- QDeclarativeState *state = d->states.at(ii);
- if (!state->isNamed())
- state->setName(QLatin1String("anonymousState") % QString::number(++d->unnamedCount));
- }
-
- if (d->updateAutoState()) {
- return;
- } else if (!d->currentState.isEmpty()) {
- QString cs = d->currentState;
- d->currentState.clear();
- d->setCurrentStateInternal(cs, true);
- }
-}
-
-/*!
- Returns true if the state was changed, otherwise false.
-*/
-bool QDeclarativeStateGroup::updateAutoState()
-{
- Q_D(QDeclarativeStateGroup);
- return d->updateAutoState();
-}
-
-bool QDeclarativeStateGroupPrivate::updateAutoState()
-{
- Q_Q(QDeclarativeStateGroup);
- if (!componentComplete)
- return false;
-
- bool revert = false;
- for (int ii = 0; ii < states.count(); ++ii) {
- QDeclarativeState *state = states.at(ii);
- if (state->isWhenKnown()) {
- if (state->isNamed()) {
- if (state->when() && state->when()->evaluate().toBool()) {
- if (stateChangeDebug())
- qWarning() << "Setting auto state due to:"
- << state->when()->expression();
- if (currentState != state->name()) {
- q->setState(state->name());
- return true;
- } else {
- return false;
- }
- } else if (state->name() == currentState) {
- revert = true;
- }
- }
- }
- }
- if (revert) {
- bool rv = !currentState.isEmpty();
- q->setState(QString());
- return rv;
- } else {
- return false;
- }
-}
-
-QDeclarativeTransition *QDeclarativeStateGroupPrivate::findTransition(const QString &from, const QString &to)
-{
- QDeclarativeTransition *highest = 0;
- int score = 0;
- bool reversed = false;
- bool done = false;
-
- for (int ii = 0; !done && ii < transitions.count(); ++ii) {
- QDeclarativeTransition *t = transitions.at(ii);
- if (!t->enabled())
- continue;
- for (int ii = 0; ii < 2; ++ii)
- {
- if (ii && (!t->reversible() ||
- (t->fromState() == QLatin1String("*") &&
- t->toState() == QLatin1String("*"))))
- break;
- QStringList fromState;
- QStringList toState;
-
- fromState = t->fromState().split(QLatin1Char(','));
- for (int jj = 0; jj < fromState.count(); ++jj)
- fromState[jj] = fromState.at(jj).trimmed();
- toState = t->toState().split(QLatin1Char(','));
- for (int jj = 0; jj < toState.count(); ++jj)
- toState[jj] = toState.at(jj).trimmed();
- if (ii == 1)
- qSwap(fromState, toState);
- int tScore = 0;
- if (fromState.contains(from))
- tScore += 2;
- else if (fromState.contains(QLatin1String("*")))
- tScore += 1;
- else
- continue;
-
- if (toState.contains(to))
- tScore += 2;
- else if (toState.contains(QLatin1String("*")))
- tScore += 1;
- else
- continue;
-
- if (ii == 1)
- reversed = true;
- else
- reversed = false;
-
- if (tScore == 4) {
- highest = t;
- done = true;
- break;
- } else if (tScore > score) {
- score = tScore;
- highest = t;
- }
- }
- }
-
- if (highest)
- highest->setReversed(reversed);
-
- return highest;
-}
-
-void QDeclarativeStateGroupPrivate::setCurrentStateInternal(const QString &state,
- bool ignoreTrans)
-{
- Q_Q(QDeclarativeStateGroup);
- if (!componentComplete) {
- currentState = state;
- return;
- }
-
- if (applyingState) {
- qmlInfo(q) << "Can't apply a state change as part of a state definition.";
- return;
- }
-
- applyingState = true;
-
- QDeclarativeTransition *transition = ignoreTrans ? 0 : findTransition(currentState, state);
- if (stateChangeDebug()) {
- qWarning() << this << "Changing state. From" << currentState << ". To" << state;
- if (transition)
- qWarning() << " using transition" << transition->fromState()
- << transition->toState();
- }
-
- QDeclarativeState *oldState = 0;
- if (!currentState.isEmpty()) {
- for (int ii = 0; ii < states.count(); ++ii) {
- if (states.at(ii)->name() == currentState) {
- oldState = states.at(ii);
- break;
- }
- }
- }
-
- currentState = state;
- emit q->stateChanged(currentState);
-
- QDeclarativeState *newState = 0;
- for (int ii = 0; ii < states.count(); ++ii) {
- if (states.at(ii)->name() == currentState) {
- newState = states.at(ii);
- break;
- }
- }
-
- if (oldState == 0 || newState == 0) {
- if (!nullState) {
- nullState = new QDeclarativeState;
- QDeclarative_setParent_noEvent(nullState, q);
- nullState->setStateGroup(q);
- }
- if (!oldState) oldState = nullState;
- if (!newState) newState = nullState;
- }
-
- newState->apply(transition, oldState);
- applyingState = false; //### consider removing this (don't allow state changes in transition)
-}
-
-QDeclarativeState *QDeclarativeStateGroup::findState(const QString &name) const
-{
- Q_D(const QDeclarativeStateGroup);
- for (int i = 0; i < d->states.count(); ++i) {
- QDeclarativeState *state = d->states.at(i);
- if (state->name() == name)
- return state;
- }
-
- return 0;
-}
-
-void QDeclarativeStateGroup::removeState(QDeclarativeState *state)
-{
- Q_D(QDeclarativeStateGroup);
- d->states.removeOne(state);
-}
-
-void QDeclarativeStateGroup::stateAboutToComplete()
-{
- Q_D(QDeclarativeStateGroup);
- d->applyingState = false;
-}
-
-QT_END_NAMESPACE
-
-
diff --git a/src/declarative/util/qdeclarativestategroup_p.h b/src/declarative/util/qdeclarativestategroup_p.h
deleted file mode 100644
index c59325580b..0000000000
--- a/src/declarative/util/qdeclarativestategroup_p.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVESTATEGROUP_H
-#define QDECLARATIVESTATEGROUP_H
-
-#include "qdeclarativestate_p.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeStateGroupPrivate;
-class Q_DECLARATIVE_EXPORT QDeclarativeStateGroup : public QObject, public QDeclarativeParserStatus
-{
- Q_OBJECT
- Q_INTERFACES(QDeclarativeParserStatus)
- Q_DECLARE_PRIVATE(QDeclarativeStateGroup)
-
- Q_PROPERTY(QString state READ state WRITE setState NOTIFY stateChanged)
- Q_PROPERTY(QDeclarativeListProperty<QDeclarativeState> states READ statesProperty DESIGNABLE false)
- Q_PROPERTY(QDeclarativeListProperty<QDeclarativeTransition> transitions READ transitionsProperty DESIGNABLE false)
-
-public:
- QDeclarativeStateGroup(QObject * = 0);
- virtual ~QDeclarativeStateGroup();
-
- QString state() const;
- void setState(const QString &);
-
- QDeclarativeListProperty<QDeclarativeState> statesProperty();
- QList<QDeclarativeState *> states() const;
-
- QDeclarativeListProperty<QDeclarativeTransition> transitionsProperty();
-
- QDeclarativeState *findState(const QString &name) const;
- void removeState(QDeclarativeState *state);
-
- virtual void classBegin();
- virtual void componentComplete();
-Q_SIGNALS:
- void stateChanged(const QString &);
-
-private:
- friend class QDeclarativeState;
- friend class QDeclarativeStatePrivate;
- bool updateAutoState();
- void stateAboutToComplete();
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeStateGroup)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVESTATEGROUP_H
diff --git a/src/declarative/util/qdeclarativestateoperations.cpp b/src/declarative/util/qdeclarativestateoperations.cpp
deleted file mode 100644
index d8a5369568..0000000000
--- a/src/declarative/util/qdeclarativestateoperations.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativestateoperations_p.h"
-
-#include <qdeclarative.h>
-#include <qdeclarativecontext.h>
-#include <qdeclarativeexpression.h>
-#include <qdeclarativeinfo.h>
-#include <private/qdeclarativeguard_p.h>
-#include <private/qdeclarativecontext_p.h>
-#include <private/qdeclarativeproperty_p.h>
-#include <private/qdeclarativebinding_p.h>
-#include "qdeclarativestate_p_p.h"
-
-#include <QtCore/qdebug.h>
-#include <QtCore/qmath.h>
-
-#include <private/qobject_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeStateChangeScriptPrivate : public QDeclarativeStateOperationPrivate
-{
-public:
- QDeclarativeStateChangeScriptPrivate() {}
-
- QDeclarativeScriptString script;
- QString name;
-};
-
-/*!
- \qmlclass StateChangeScript QDeclarativeStateChangeScript
- \inqmlmodule QtQuick 2
- \ingroup qml-state-elements
- \brief The StateChangeScript element allows you to run a script in a state.
-
- A StateChangeScript is run upon entering a state. You can optionally use
- ScriptAction to specify the point in the transition at which
- the StateChangeScript should to be run.
-
- \snippet snippets/declarative/states/statechangescript.qml state and transition
-
- \sa ScriptAction
-*/
-
-QDeclarativeStateChangeScript::QDeclarativeStateChangeScript(QObject *parent)
-: QDeclarativeStateOperation(*(new QDeclarativeStateChangeScriptPrivate), parent)
-{
-}
-
-QDeclarativeStateChangeScript::~QDeclarativeStateChangeScript()
-{
-}
-
-/*!
- \qmlproperty script QtQuick2::StateChangeScript::script
- This property holds the script to run when the state is current.
-*/
-QDeclarativeScriptString QDeclarativeStateChangeScript::script() const
-{
- Q_D(const QDeclarativeStateChangeScript);
- return d->script;
-}
-
-void QDeclarativeStateChangeScript::setScript(const QDeclarativeScriptString &s)
-{
- Q_D(QDeclarativeStateChangeScript);
- d->script = s;
-}
-
-/*!
- \qmlproperty string QtQuick2::StateChangeScript::name
- This property holds the name of the script. This name can be used by a
- ScriptAction to target a specific script.
-
- \sa ScriptAction::scriptName
-*/
-QString QDeclarativeStateChangeScript::name() const
-{
- Q_D(const QDeclarativeStateChangeScript);
- return d->name;
-}
-
-void QDeclarativeStateChangeScript::setName(const QString &n)
-{
- Q_D(QDeclarativeStateChangeScript);
- d->name = n;
-}
-
-void QDeclarativeStateChangeScript::execute(Reason)
-{
- Q_D(QDeclarativeStateChangeScript);
- if (!d->script.script().isEmpty()) {
- QDeclarativeExpression expr(d->script);
- expr.evaluate();
- if (expr.hasError())
- qmlInfo(this, expr.error());
- }
-}
-
-QDeclarativeStateChangeScript::ActionList QDeclarativeStateChangeScript::actions()
-{
- ActionList rv;
- QDeclarativeAction a;
- a.event = this;
- rv << a;
- return rv;
-}
-
-QString QDeclarativeStateChangeScript::typeName() const
-{
- return QLatin1String("StateChangeScript");
-}
-
-
-#include <moc_qdeclarativestateoperations_p.cpp>
-
-QT_END_NAMESPACE
-
diff --git a/src/declarative/util/qdeclarativestateoperations_p.h b/src/declarative/util/qdeclarativestateoperations_p.h
deleted file mode 100644
index 4975a5226f..0000000000
--- a/src/declarative/util/qdeclarativestateoperations_p.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVESTATEOPERATIONS_H
-#define QDECLARATIVESTATEOPERATIONS_H
-
-#include "qdeclarativestate_p.h"
-#include <qdeclarativescriptstring.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-
-class QDeclarativeStateChangeScriptPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativeStateChangeScript : public QDeclarativeStateOperation, public QDeclarativeActionEvent
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeStateChangeScript)
-
- Q_PROPERTY(QDeclarativeScriptString script READ script WRITE setScript)
- Q_PROPERTY(QString name READ name WRITE setName)
-
-public:
- QDeclarativeStateChangeScript(QObject *parent=0);
- ~QDeclarativeStateChangeScript();
-
- virtual ActionList actions();
-
- virtual QString typeName() const;
-
- QDeclarativeScriptString script() const;
- void setScript(const QDeclarativeScriptString &);
-
- QString name() const;
- void setName(const QString &);
-
- virtual void execute(Reason reason = ActualChange);
-};
-
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeStateChangeScript)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVESTATEOPERATIONS_H
diff --git a/src/declarative/util/qdeclarativestyledtext.cpp b/src/declarative/util/qdeclarativestyledtext.cpp
deleted file mode 100644
index 1c7ca5fbfd..0000000000
--- a/src/declarative/util/qdeclarativestyledtext.cpp
+++ /dev/null
@@ -1,624 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QStack>
-#include <QVector>
-#include <QPainter>
-#include <QTextLayout>
-#include <QDebug>
-#include <qmath.h>
-#include "qdeclarativestyledtext_p.h"
-
-/*
- QDeclarativeStyledText supports few tags:
-
- <b></b> - bold
- <i></i> - italic
- <br> - new line
- <p> - paragraph
- <u> - underlined text
- <font color="color_name" size="1-7"></font>
- <h1> to <h6> - headers
- <a href=""> - anchor
- <ol type="">, <ul type=""> and <li> - ordered and unordered lists
-
- The opening and closing tags must be correctly nested.
-*/
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeStyledTextPrivate
-{
-public:
- enum ListType { Ordered, Unordered };
- enum ListFormat { Bullet, Disc, Square, Decimal, LowerAlpha, UpperAlpha, LowerRoman, UpperRoman };
-
- struct List {
- int level;
- ListType type;
- ListFormat format;
- };
-
- QDeclarativeStyledTextPrivate(const QString &t, QTextLayout &l)
- : text(t), layout(l), baseFont(layout.font()), hasNewLine(false)
- {
- }
-
- void parse();
- bool parseTag(const QChar *&ch, const QString &textIn, QString &textOut, QTextCharFormat &format);
- bool parseCloseTag(const QChar *&ch, const QString &textIn, QString &textOut);
- void parseEntity(const QChar *&ch, const QString &textIn, QString &textOut);
- bool parseFontAttributes(const QChar *&ch, const QString &textIn, QTextCharFormat &format);
- bool parseOrderedListAttributes(const QChar *&ch, const QString &textIn);
- bool parseUnorderedListAttributes(const QChar *&ch, const QString &textIn);
- bool parseAnchorAttributes(const QChar *&ch, const QString &textIn, QTextCharFormat &format);
- QPair<QStringRef,QStringRef> parseAttribute(const QChar *&ch, const QString &textIn);
- QStringRef parseValue(const QChar *&ch, const QString &textIn);
-
- inline void skipSpace(const QChar *&ch) {
- while (ch->isSpace() && !ch->isNull())
- ++ch;
- }
-
- static QString toAlpha(int value, bool upper);
- static QString toRoman(int value, bool upper);
-
- QString text;
- QTextLayout &layout;
- QFont baseFont;
- QStack<List> listStack;
- bool hasNewLine;
-
- static const QChar lessThan;
- static const QChar greaterThan;
- static const QChar equals;
- static const QChar singleQuote;
- static const QChar doubleQuote;
- static const QChar slash;
- static const QChar ampersand;
- static const QChar bullet;
- static const QChar disc;
- static const QChar square;
- static const int tabsize = 6;
-};
-
-const QChar QDeclarativeStyledTextPrivate::lessThan(QLatin1Char('<'));
-const QChar QDeclarativeStyledTextPrivate::greaterThan(QLatin1Char('>'));
-const QChar QDeclarativeStyledTextPrivate::equals(QLatin1Char('='));
-const QChar QDeclarativeStyledTextPrivate::singleQuote(QLatin1Char('\''));
-const QChar QDeclarativeStyledTextPrivate::doubleQuote(QLatin1Char('\"'));
-const QChar QDeclarativeStyledTextPrivate::slash(QLatin1Char('/'));
-const QChar QDeclarativeStyledTextPrivate::ampersand(QLatin1Char('&'));
-const QChar QDeclarativeStyledTextPrivate::bullet(0x2022);
-const QChar QDeclarativeStyledTextPrivate::disc(0x25e6);
-const QChar QDeclarativeStyledTextPrivate::square(0x25a1);
-
-QDeclarativeStyledText::QDeclarativeStyledText(const QString &string, QTextLayout &layout)
-: d(new QDeclarativeStyledTextPrivate(string, layout))
-{
-}
-
-QDeclarativeStyledText::~QDeclarativeStyledText()
-{
- delete d;
-}
-
-void QDeclarativeStyledText::parse(const QString &string, QTextLayout &layout)
-{
- if (string.isEmpty())
- return;
- QDeclarativeStyledText styledText(string, layout);
- styledText.d->parse();
-}
-
-void QDeclarativeStyledTextPrivate::parse()
-{
- QList<QTextLayout::FormatRange> ranges;
- QStack<QTextCharFormat> formatStack;
-
- QString drawText;
- drawText.reserve(text.count());
-
- int textStart = 0;
- int textLength = 0;
- int rangeStart = 0;
- const QChar *ch = text.constData();
- while (!ch->isNull()) {
- if (*ch == lessThan) {
- if (textLength) {
- QStringRef ref = QStringRef(&text, textStart, textLength);
- const QChar *c = ref.constData();
- bool isWhiteSpace = true;
- for (int i = 0; isWhiteSpace && (i < textLength); ++c, ++i) {
- if (!c->isSpace())
- isWhiteSpace = false;
- }
- if (!isWhiteSpace) {
- drawText.append(ref);
- hasNewLine = false;
- }
- }
- if (rangeStart != drawText.length() && formatStack.count()) {
- QTextLayout::FormatRange formatRange;
- formatRange.format = formatStack.top();
- formatRange.start = rangeStart;
- formatRange.length = drawText.length() - rangeStart;
- ranges.append(formatRange);
- }
- rangeStart = drawText.length();
- ++ch;
- if (*ch == slash) {
- ++ch;
- if (parseCloseTag(ch, text, drawText)) {
- if (formatStack.count())
- formatStack.pop();
- }
- } else {
- QTextCharFormat format;
- if (formatStack.count())
- format = formatStack.top();
- if (parseTag(ch, text, drawText, format))
- formatStack.push(format);
- }
- textStart = ch - text.constData() + 1;
- textLength = 0;
- } else if (*ch == ampersand) {
- ++ch;
- drawText.append(QStringRef(&text, textStart, textLength));
- parseEntity(ch, text, drawText);
- textStart = ch - text.constData() + 1;
- textLength = 0;
- } else {
- ++textLength;
- }
- if (!ch->isNull())
- ++ch;
- }
- if (textLength)
- drawText.append(QStringRef(&text, textStart, textLength));
- if (rangeStart != drawText.length() && formatStack.count()) {
- QTextLayout::FormatRange formatRange;
- formatRange.format = formatStack.top();
- formatRange.start = rangeStart;
- formatRange.length = drawText.length() - rangeStart;
- ranges.append(formatRange);
- }
-
- layout.setText(drawText);
- layout.setAdditionalFormats(ranges);
-}
-
-bool QDeclarativeStyledTextPrivate::parseTag(const QChar *&ch, const QString &textIn, QString &textOut, QTextCharFormat &format)
-{
- skipSpace(ch);
-
- int tagStart = ch - textIn.constData();
- int tagLength = 0;
- while (!ch->isNull()) {
- if (*ch == greaterThan) {
- if (tagLength == 0)
- return false;
- QStringRef tag(&textIn, tagStart, tagLength);
- const QChar char0 = tag.at(0);
- if (char0 == QLatin1Char('b')) {
- if (tagLength == 1)
- format.setFontWeight(QFont::Bold);
- else if (tagLength == 2 && tag.at(1) == QLatin1Char('r')) {
- textOut.append(QChar(QChar::LineSeparator));
- return false;
- }
- } else if (char0 == QLatin1Char('i')) {
- if (tagLength == 1)
- format.setFontItalic(true);
- } else if (char0 == QLatin1Char('p')) {
- if (tagLength == 1) {
- if (!hasNewLine)
- textOut.append(QChar::LineSeparator);
- }
- } else if (char0 == QLatin1Char('u')) {
- if (tagLength == 1)
- format.setFontUnderline(true);
- else if (tag == QLatin1String("ul")) {
- List listItem;
- listItem.level = 0;
- listItem.type = Unordered;
- listItem.format = Bullet;
- listStack.push(listItem);
- }
- } else if (char0 == QLatin1Char('h') && tagLength == 2) {
- int level = tag.at(1).digitValue();
- if (level >= 1 && level <= 6) {
- static const qreal scaling[] = { 2.0, 1.5, 1.2, 1.0, 0.8, 0.7 };
- if (!hasNewLine)
- textOut.append(QChar::LineSeparator);
- format.setFontPointSize(baseFont.pointSize() * scaling[level - 1]);
- format.setFontWeight(QFont::Bold);
- }
- } else if (tag == QLatin1String("ol")) {
- List listItem;
- listItem.level = 0;
- listItem.type = Ordered;
- listItem.format = Decimal;
- listStack.push(listItem);
- } else if (tag == QLatin1String("li")) {
- if (!hasNewLine)
- textOut.append(QChar(QChar::LineSeparator));
- if (!listStack.isEmpty()) {
- int count = ++listStack.top().level;
- for (int i = 0; i < listStack.size(); ++i)
- textOut += QString(tabsize, QChar::Nbsp);
- switch (listStack.top().format) {
- case Decimal:
- textOut += QString::number(count) % QLatin1Char('.');
- break;
- case LowerAlpha:
- textOut += toAlpha(count, false) % QLatin1Char('.');
- break;
- case UpperAlpha:
- textOut += toAlpha(count, true) % QLatin1Char('.');
- break;
- case LowerRoman:
- textOut += toRoman(count, false) % QLatin1Char('.');
- break;
- case UpperRoman:
- textOut += toRoman(count, true) % QLatin1Char('.');
- break;
- case Bullet:
- textOut += bullet;
- break;
- case Disc:
- textOut += disc;
- break;
- case Square:
- textOut += square;
- break;
- }
- textOut += QString(2, QChar::Nbsp);
- }
- }
- return true;
- } else if (ch->isSpace()) {
- // may have params.
- QStringRef tag(&textIn, tagStart, tagLength);
- if (tag == QLatin1String("font"))
- return parseFontAttributes(ch, textIn, format);
- if (tag == QLatin1String("ol"))
- return parseOrderedListAttributes(ch, textIn);
- if (tag == QLatin1String("ul"))
- return parseUnorderedListAttributes(ch, textIn);
- if (tag == QLatin1String("a")) {
- return parseAnchorAttributes(ch, textIn, format);
- }
- if (*ch == greaterThan || ch->isNull())
- continue;
- } else if (*ch != slash) {
- tagLength++;
- }
- ++ch;
- }
- return false;
-}
-
-bool QDeclarativeStyledTextPrivate::parseCloseTag(const QChar *&ch, const QString &textIn, QString &textOut)
-{
- skipSpace(ch);
-
- int tagStart = ch - textIn.constData();
- int tagLength = 0;
- while (!ch->isNull()) {
- if (*ch == greaterThan) {
- if (tagLength == 0)
- return false;
- QStringRef tag(&textIn, tagStart, tagLength);
- const QChar char0 = tag.at(0);
- hasNewLine = false;
- if (char0 == QLatin1Char('b')) {
- if (tagLength == 1)
- return true;
- else if (tag.at(1) == QLatin1Char('r') && tagLength == 2)
- return true;
- } else if (char0 == QLatin1Char('i')) {
- if (tagLength == 1)
- return true;
- } else if (char0 == QLatin1Char('a')) {
- if (tagLength == 1)
- return true;
- } else if (char0 == QLatin1Char('p')) {
- if (tagLength == 1) {
- textOut.append(QChar::LineSeparator);
- hasNewLine = true;
- return true;
- }
- } else if (char0 == QLatin1Char('u')) {
- if (tagLength == 1)
- return true;
- else if (tag == QLatin1String("ul")) {
- if (!listStack.isEmpty()) {
- listStack.pop();
- if (!listStack.count())
- textOut.append(QChar::LineSeparator);
- }
- return true;
- }
- } else if (char0 == QLatin1Char('h') && tagLength == 2) {
- textOut.append(QChar::LineSeparator);
- hasNewLine = true;
- return true;
- } else if (tag == QLatin1String("font")) {
- return true;
- } else if (tag == QLatin1String("ol")) {
- if (!listStack.isEmpty()) {
- listStack.pop();
- if (!listStack.count())
- textOut.append(QChar::LineSeparator);
- }
- return true;
- } else if (tag == QLatin1String("li")) {
- return true;
- }
- return false;
- } else if (!ch->isSpace()){
- tagLength++;
- }
- ++ch;
- }
-
- return false;
-}
-
-void QDeclarativeStyledTextPrivate::parseEntity(const QChar *&ch, const QString &textIn, QString &textOut)
-{
- int entityStart = ch - textIn.constData();
- int entityLength = 0;
- while (!ch->isNull()) {
- if (*ch == QLatin1Char(';')) {
- QStringRef entity(&textIn, entityStart, entityLength);
- if (entity == QLatin1String("gt"))
- textOut += QChar(62);
- else if (entity == QLatin1String("lt"))
- textOut += QChar(60);
- else if (entity == QLatin1String("amp"))
- textOut += QChar(38);
- return;
- }
- ++entityLength;
- ++ch;
- }
-}
-
-bool QDeclarativeStyledTextPrivate::parseFontAttributes(const QChar *&ch, const QString &textIn, QTextCharFormat &format)
-{
- bool valid = false;
- QPair<QStringRef,QStringRef> attr;
- do {
- attr = parseAttribute(ch, textIn);
- if (attr.first == QLatin1String("color")) {
- valid = true;
- format.setForeground(QColor(attr.second.toString()));
- } else if (attr.first == QLatin1String("size")) {
- valid = true;
- int size = attr.second.toString().toInt();
- if (attr.second.at(0) == QLatin1Char('-') || attr.second.at(0) == QLatin1Char('+'))
- size += 3;
- if (size >= 1 && size <= 7) {
- static const qreal scaling[] = { 0.7, 0.8, 1.0, 1.2, 1.5, 2.0, 2.4 };
- format.setFontPointSize(baseFont.pointSize() * scaling[size-1]);
- }
- }
- } while (!ch->isNull() && !attr.first.isEmpty());
-
- return valid;
-}
-
-bool QDeclarativeStyledTextPrivate::parseOrderedListAttributes(const QChar *&ch, const QString &textIn)
-{
- bool valid = false;
-
- List listItem;
- listItem.level = 0;
- listItem.type = Ordered;
- listItem.format = Decimal;
-
- QPair<QStringRef,QStringRef> attr;
- do {
- attr = parseAttribute(ch, textIn);
- if (attr.first == QLatin1String("type")) {
- valid = true;
- if (attr.second == QLatin1String("a"))
- listItem.format = LowerAlpha;
- else if (attr.second == QLatin1String("A"))
- listItem.format = UpperAlpha;
- else if (attr.second == QLatin1String("i"))
- listItem.format = LowerRoman;
- else if (attr.second == QLatin1String("I"))
- listItem.format = UpperRoman;
- }
- } while (!ch->isNull() && !attr.first.isEmpty());
-
- listStack.push(listItem);
- return valid;
-}
-
-bool QDeclarativeStyledTextPrivate::parseUnorderedListAttributes(const QChar *&ch, const QString &textIn)
-{
- bool valid = false;
-
- List listItem;
- listItem.level = 0;
- listItem.type = Unordered;
- listItem.format = Bullet;
-
- QPair<QStringRef,QStringRef> attr;
- do {
- attr = parseAttribute(ch, textIn);
- if (attr.first == QLatin1String("type")) {
- valid = true;
- if (attr.second == QLatin1String("disc"))
- listItem.format = Disc;
- else if (attr.second == QLatin1String("square"))
- listItem.format = Square;
- }
- } while (!ch->isNull() && !attr.first.isEmpty());
-
- listStack.push(listItem);
- return valid;
-}
-
-bool QDeclarativeStyledTextPrivate::parseAnchorAttributes(const QChar *&ch, const QString &textIn, QTextCharFormat &format)
-{
- bool valid = false;
-
- QPair<QStringRef,QStringRef> attr;
- do {
- attr = parseAttribute(ch, textIn);
- if (attr.first == QLatin1String("href")) {
- format.setAnchorHref(attr.second.toString());
- format.setAnchor(true);
- format.setFontUnderline(true);
- format.setForeground(QColor("blue"));
- valid = true;
- }
- } while (!ch->isNull() && !attr.first.isEmpty());
-
- return valid;
-}
-
-QPair<QStringRef,QStringRef> QDeclarativeStyledTextPrivate::parseAttribute(const QChar *&ch, const QString &textIn)
-{
- skipSpace(ch);
-
- int attrStart = ch - textIn.constData();
- int attrLength = 0;
- while (!ch->isNull()) {
- if (*ch == greaterThan) {
- break;
- } else if (*ch == equals) {
- ++ch;
- if (*ch != singleQuote && *ch != doubleQuote) {
- while (*ch != greaterThan && !ch->isNull())
- ++ch;
- break;
- }
- ++ch;
- if (!attrLength)
- break;
- QStringRef attr(&textIn, attrStart, attrLength);
- QStringRef val = parseValue(ch, textIn);
- if (!val.isEmpty())
- return QPair<QStringRef,QStringRef>(attr,val);
- break;
- } else {
- ++attrLength;
- }
- ++ch;
- }
-
- return QPair<QStringRef,QStringRef>();
-}
-
-QStringRef QDeclarativeStyledTextPrivate::parseValue(const QChar *&ch, const QString &textIn)
-{
- int valStart = ch - textIn.constData();
- int valLength = 0;
- while (*ch != singleQuote && *ch != doubleQuote && !ch->isNull()) {
- ++valLength;
- ++ch;
- }
- if (ch->isNull())
- return QStringRef();
- ++ch; // skip quote
-
- return QStringRef(&textIn, valStart, valLength);
-}
-
-QString QDeclarativeStyledTextPrivate::toAlpha(int value, bool upper)
-{
- const char baseChar = upper ? 'A' : 'a';
-
- QString result;
- int c = value;
- while (c > 0) {
- c--;
- result.prepend(QChar(baseChar + (c % 26)));
- c /= 26;
- }
- return result;
-}
-
-QString QDeclarativeStyledTextPrivate::toRoman(int value, bool upper)
-{
- QString result = QLatin1String("?");
- // works for up to 4999 items
- if (value < 5000) {
- QByteArray romanNumeral;
-
- static const char romanSymbolsLower[] = "iiivixxxlxcccdcmmmm";
- static const char romanSymbolsUpper[] = "IIIVIXXXLXCCCDCMMMM";
- QByteArray romanSymbols;
- if (!upper)
- romanSymbols = QByteArray::fromRawData(romanSymbolsLower, sizeof(romanSymbolsLower));
- else
- romanSymbols = QByteArray::fromRawData(romanSymbolsUpper, sizeof(romanSymbolsUpper));
-
- int c[] = { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 };
- int n = value;
- for (int i = 12; i >= 0; n %= c[i], i--) {
- int q = n / c[i];
- if (q > 0) {
- int startDigit = i + (i + 3) / 4;
- int numDigits;
- if (i % 4) {
- if ((i - 2) % 4)
- numDigits = 2;
- else
- numDigits = 1;
- }
- else
- numDigits = q;
- romanNumeral.append(romanSymbols.mid(startDigit, numDigits));
- }
- }
- result = QString::fromLatin1(romanNumeral);
- }
- return result;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativestyledtext_p.h b/src/declarative/util/qdeclarativestyledtext_p.h
deleted file mode 100644
index beffb4d22a..0000000000
--- a/src/declarative/util/qdeclarativestyledtext_p.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVESTYLEDTEXT_H
-#define QDECLARATIVESTYLEDTEXT_H
-
-#include <QSizeF>
-
-QT_BEGIN_NAMESPACE
-
-class QPainter;
-class QPointF;
-class QString;
-class QDeclarativeStyledTextPrivate;
-class QTextLayout;
-
-class Q_AUTOTEST_EXPORT QDeclarativeStyledText
-{
-public:
- static void parse(const QString &string, QTextLayout &layout);
-
-private:
- QDeclarativeStyledText(const QString &string, QTextLayout &layout);
- ~QDeclarativeStyledText();
-
- QDeclarativeStyledTextPrivate *d;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/declarative/util/qdeclarativesvgparser.cpp b/src/declarative/util/qdeclarativesvgparser.cpp
deleted file mode 100644
index e8ceb2116c..0000000000
--- a/src/declarative/util/qdeclarativesvgparser.cpp
+++ /dev/null
@@ -1,614 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclaractive module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativesvgparser_p.h"
-
-#include <QtCore/qmath.h>
-#include <QtCore/qvarlengtharray.h>
-#include <QtCore/qstring.h>
-
-QT_BEGIN_NAMESPACE
-
-static const double Q_PI = 3.14159265358979323846; // pi
-
-//copied from QtSvg (qsvghandler.cpp).
-Q_CORE_EXPORT double qstrtod(const char *s00, char const **se, bool *ok);
-// '0' is 0x30 and '9' is 0x39
-static inline bool isDigit(ushort ch)
-{
- static quint16 magic = 0x3ff;
- return ((ch >> 4) == 3) && (magic >> (ch & 15));
-}
-
-static qreal toDouble(const QChar *&str)
-{
- const int maxLen = 255;//technically doubles can go til 308+ but whatever
- char temp[maxLen+1];
- int pos = 0;
-
- if (*str == QLatin1Char('-')) {
- temp[pos++] = '-';
- ++str;
- } else if (*str == QLatin1Char('+')) {
- ++str;
- }
- while (isDigit(str->unicode()) && pos < maxLen) {
- temp[pos++] = str->toLatin1();
- ++str;
- }
- if (*str == QLatin1Char('.') && pos < maxLen) {
- temp[pos++] = '.';
- ++str;
- }
- while (isDigit(str->unicode()) && pos < maxLen) {
- temp[pos++] = str->toLatin1();
- ++str;
- }
- bool exponent = false;
- if ((*str == QLatin1Char('e') || *str == QLatin1Char('E')) && pos < maxLen) {
- exponent = true;
- temp[pos++] = 'e';
- ++str;
- if ((*str == QLatin1Char('-') || *str == QLatin1Char('+')) && pos < maxLen) {
- temp[pos++] = str->toLatin1();
- ++str;
- }
- while (isDigit(str->unicode()) && pos < maxLen) {
- temp[pos++] = str->toLatin1();
- ++str;
- }
- }
-
- temp[pos] = '\0';
-
- qreal val;
- if (!exponent && pos < 10) {
- int ival = 0;
- const char *t = temp;
- bool neg = false;
- if(*t == '-') {
- neg = true;
- ++t;
- }
- while(*t && *t != '.') {
- ival *= 10;
- ival += (*t) - '0';
- ++t;
- }
- if(*t == '.') {
- ++t;
- int div = 1;
- while(*t) {
- ival *= 10;
- ival += (*t) - '0';
- div *= 10;
- ++t;
- }
- val = ((qreal)ival)/((qreal)div);
- } else {
- val = ival;
- }
- if (neg)
- val = -val;
- } else {
-#if defined(Q_WS_QWS) && !defined(Q_OS_VXWORKS)
- if(sizeof(qreal) == sizeof(float))
- val = strtof(temp, 0);
- else
-#endif
- {
- bool ok = false;
- val = qstrtod(temp, 0, &ok);
- }
- }
- return val;
-
-}
-static inline void parseNumbersArray(const QChar *&str, QVarLengthArray<qreal, 8> &points)
-{
- while (str->isSpace())
- ++str;
- while (isDigit(str->unicode()) ||
- *str == QLatin1Char('-') || *str == QLatin1Char('+') ||
- *str == QLatin1Char('.')) {
-
- points.append(toDouble(str));
-
- while (str->isSpace())
- ++str;
- if (*str == QLatin1Char(','))
- ++str;
-
- //eat the rest of space
- while (str->isSpace())
- ++str;
- }
-}
-
-static void pathArcSegment(QPainterPath &path,
- qreal xc, qreal yc,
- qreal th0, qreal th1,
- qreal rx, qreal ry, qreal xAxisRotation)
-{
- qreal sinTh, cosTh;
- qreal a00, a01, a10, a11;
- qreal x1, y1, x2, y2, x3, y3;
- qreal t;
- qreal thHalf;
-
- sinTh = qSin(xAxisRotation * (Q_PI / 180.0));
- cosTh = qCos(xAxisRotation * (Q_PI / 180.0));
-
- a00 = cosTh * rx;
- a01 = -sinTh * ry;
- a10 = sinTh * rx;
- a11 = cosTh * ry;
-
- thHalf = 0.5 * (th1 - th0);
- t = (8.0 / 3.0) * qSin(thHalf * 0.5) * qSin(thHalf * 0.5) / qSin(thHalf);
- x1 = xc + qCos(th0) - t * qSin(th0);
- y1 = yc + qSin(th0) + t * qCos(th0);
- x3 = xc + qCos(th1);
- y3 = yc + qSin(th1);
- x2 = x3 + t * qSin(th1);
- y2 = y3 - t * qCos(th1);
-
- path.cubicTo(a00 * x1 + a01 * y1, a10 * x1 + a11 * y1,
- a00 * x2 + a01 * y2, a10 * x2 + a11 * y2,
- a00 * x3 + a01 * y3, a10 * x3 + a11 * y3);
-}
-
-void QDeclarativeSvgParser::pathArc(QPainterPath &path,
- qreal rx,
- qreal ry,
- qreal x_axis_rotation,
- int large_arc_flag,
- int sweep_flag,
- qreal x,
- qreal y,
- qreal curx, qreal cury)
-{
- qreal sin_th, cos_th;
- qreal a00, a01, a10, a11;
- qreal x0, y0, x1, y1, xc, yc;
- qreal d, sfactor, sfactor_sq;
- qreal th0, th1, th_arc;
- int i, n_segs;
- qreal dx, dy, dx1, dy1, Pr1, Pr2, Px, Py, check;
-
- rx = qAbs(rx);
- ry = qAbs(ry);
-
- sin_th = qSin(x_axis_rotation * (Q_PI / 180.0));
- cos_th = qCos(x_axis_rotation * (Q_PI / 180.0));
-
- dx = (curx - x) / 2.0;
- dy = (cury - y) / 2.0;
- dx1 = cos_th * dx + sin_th * dy;
- dy1 = -sin_th * dx + cos_th * dy;
- Pr1 = rx * rx;
- Pr2 = ry * ry;
- Px = dx1 * dx1;
- Py = dy1 * dy1;
- /* Spec : check if radii are large enough */
- check = Px / Pr1 + Py / Pr2;
- if (check > 1) {
- rx = rx * qSqrt(check);
- ry = ry * qSqrt(check);
- }
-
- a00 = cos_th / rx;
- a01 = sin_th / rx;
- a10 = -sin_th / ry;
- a11 = cos_th / ry;
- x0 = a00 * curx + a01 * cury;
- y0 = a10 * curx + a11 * cury;
- x1 = a00 * x + a01 * y;
- y1 = a10 * x + a11 * y;
- /* (x0, y0) is current point in transformed coordinate space.
- (x1, y1) is new point in transformed coordinate space.
-
- The arc fits a unit-radius circle in this space.
- */
- d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
- sfactor_sq = 1.0 / d - 0.25;
- if (sfactor_sq < 0) sfactor_sq = 0;
- sfactor = qSqrt(sfactor_sq);
- if (sweep_flag == large_arc_flag) sfactor = -sfactor;
- xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
- yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
- /* (xc, yc) is center of the circle. */
-
- th0 = qAtan2(y0 - yc, x0 - xc);
- th1 = qAtan2(y1 - yc, x1 - xc);
-
- th_arc = th1 - th0;
- if (th_arc < 0 && sweep_flag)
- th_arc += 2 * Q_PI;
- else if (th_arc > 0 && !sweep_flag)
- th_arc -= 2 * Q_PI;
-
- n_segs = qCeil(qAbs(th_arc / (Q_PI * 0.5 + 0.001)));
-
- for (i = 0; i < n_segs; i++) {
- pathArcSegment(path, xc, yc,
- th0 + i * th_arc / n_segs,
- th0 + (i + 1) * th_arc / n_segs,
- rx, ry, x_axis_rotation);
- }
-}
-
-
-bool QDeclarativeSvgParser::parsePathDataFast(const QString &dataStr, QPainterPath &path)
-{
- qreal x0 = 0, y0 = 0; // starting point
- qreal x = 0, y = 0; // current point
- char lastMode = 0;
- QPointF ctrlPt;
- const QChar *str = dataStr.constData();
- const QChar *end = str + dataStr.size();
-
- while (str != end) {
- while (str->isSpace())
- ++str;
- QChar pathElem = *str;
- ++str;
- QChar endc = *end;
- *const_cast<QChar *>(end) = 0; // parseNumbersArray requires 0-termination that QStringRef cannot guarantee
- QVarLengthArray<qreal, 8> arg;
- parseNumbersArray(str, arg);
- *const_cast<QChar *>(end) = endc;
- if (pathElem == QLatin1Char('z') || pathElem == QLatin1Char('Z'))
- arg.append(0);//dummy
- const qreal *num = arg.constData();
- int count = arg.count();
- while (count > 0) {
- qreal offsetX = x; // correction offsets
- qreal offsetY = y; // for relative commands
- switch (pathElem.unicode()) {
- case 'm': {
- if (count < 2) {
- num++;
- count--;
- break;
- }
- x = x0 = num[0] + offsetX;
- y = y0 = num[1] + offsetY;
- num += 2;
- count -= 2;
- path.moveTo(x0, y0);
-
- // As per 1.2 spec 8.3.2 The "moveto" commands
- // If a 'moveto' is followed by multiple pairs of coordinates without explicit commands,
- // the subsequent pairs shall be treated as implicit 'lineto' commands.
- pathElem = QLatin1Char('l');
- }
- break;
- case 'M': {
- if (count < 2) {
- num++;
- count--;
- break;
- }
- x = x0 = num[0];
- y = y0 = num[1];
- num += 2;
- count -= 2;
- path.moveTo(x0, y0);
-
- // As per 1.2 spec 8.3.2 The "moveto" commands
- // If a 'moveto' is followed by multiple pairs of coordinates without explicit commands,
- // the subsequent pairs shall be treated as implicit 'lineto' commands.
- pathElem = QLatin1Char('L');
- }
- break;
- case 'z':
- case 'Z': {
- x = x0;
- y = y0;
- count--; // skip dummy
- num++;
- path.closeSubpath();
- }
- break;
- case 'l': {
- if (count < 2) {
- num++;
- count--;
- break;
- }
- x = num[0] + offsetX;
- y = num[1] + offsetY;
- num += 2;
- count -= 2;
- path.lineTo(x, y);
-
- }
- break;
- case 'L': {
- if (count < 2) {
- num++;
- count--;
- break;
- }
- x = num[0];
- y = num[1];
- num += 2;
- count -= 2;
- path.lineTo(x, y);
- }
- break;
- case 'h': {
- x = num[0] + offsetX;
- num++;
- count--;
- path.lineTo(x, y);
- }
- break;
- case 'H': {
- x = num[0];
- num++;
- count--;
- path.lineTo(x, y);
- }
- break;
- case 'v': {
- y = num[0] + offsetY;
- num++;
- count--;
- path.lineTo(x, y);
- }
- break;
- case 'V': {
- y = num[0];
- num++;
- count--;
- path.lineTo(x, y);
- }
- break;
- case 'c': {
- if (count < 6) {
- num += count;
- count = 0;
- break;
- }
- QPointF c1(num[0] + offsetX, num[1] + offsetY);
- QPointF c2(num[2] + offsetX, num[3] + offsetY);
- QPointF e(num[4] + offsetX, num[5] + offsetY);
- num += 6;
- count -= 6;
- path.cubicTo(c1, c2, e);
- ctrlPt = c2;
- x = e.x();
- y = e.y();
- break;
- }
- case 'C': {
- if (count < 6) {
- num += count;
- count = 0;
- break;
- }
- QPointF c1(num[0], num[1]);
- QPointF c2(num[2], num[3]);
- QPointF e(num[4], num[5]);
- num += 6;
- count -= 6;
- path.cubicTo(c1, c2, e);
- ctrlPt = c2;
- x = e.x();
- y = e.y();
- break;
- }
- case 's': {
- if (count < 4) {
- num += count;
- count = 0;
- break;
- }
- QPointF c1;
- if (lastMode == 'c' || lastMode == 'C' ||
- lastMode == 's' || lastMode == 'S')
- c1 = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y());
- else
- c1 = QPointF(x, y);
- QPointF c2(num[0] + offsetX, num[1] + offsetY);
- QPointF e(num[2] + offsetX, num[3] + offsetY);
- num += 4;
- count -= 4;
- path.cubicTo(c1, c2, e);
- ctrlPt = c2;
- x = e.x();
- y = e.y();
- break;
- }
- case 'S': {
- if (count < 4) {
- num += count;
- count = 0;
- break;
- }
- QPointF c1;
- if (lastMode == 'c' || lastMode == 'C' ||
- lastMode == 's' || lastMode == 'S')
- c1 = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y());
- else
- c1 = QPointF(x, y);
- QPointF c2(num[0], num[1]);
- QPointF e(num[2], num[3]);
- num += 4;
- count -= 4;
- path.cubicTo(c1, c2, e);
- ctrlPt = c2;
- x = e.x();
- y = e.y();
- break;
- }
- case 'q': {
- if (count < 4) {
- num += count;
- count = 0;
- break;
- }
- QPointF c(num[0] + offsetX, num[1] + offsetY);
- QPointF e(num[2] + offsetX, num[3] + offsetY);
- num += 4;
- count -= 4;
- path.quadTo(c, e);
- ctrlPt = c;
- x = e.x();
- y = e.y();
- break;
- }
- case 'Q': {
- if (count < 4) {
- num += count;
- count = 0;
- break;
- }
- QPointF c(num[0], num[1]);
- QPointF e(num[2], num[3]);
- num += 4;
- count -= 4;
- path.quadTo(c, e);
- ctrlPt = c;
- x = e.x();
- y = e.y();
- break;
- }
- case 't': {
- if (count < 2) {
- num += count;
- count = 0;
- break;
- }
- QPointF e(num[0] + offsetX, num[1] + offsetY);
- num += 2;
- count -= 2;
- QPointF c;
- if (lastMode == 'q' || lastMode == 'Q' ||
- lastMode == 't' || lastMode == 'T')
- c = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y());
- else
- c = QPointF(x, y);
- path.quadTo(c, e);
- ctrlPt = c;
- x = e.x();
- y = e.y();
- break;
- }
- case 'T': {
- if (count < 2) {
- num += count;
- count = 0;
- break;
- }
- QPointF e(num[0], num[1]);
- num += 2;
- count -= 2;
- QPointF c;
- if (lastMode == 'q' || lastMode == 'Q' ||
- lastMode == 't' || lastMode == 'T')
- c = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y());
- else
- c = QPointF(x, y);
- path.quadTo(c, e);
- ctrlPt = c;
- x = e.x();
- y = e.y();
- break;
- }
- case 'a': {
- if (count < 7) {
- num += count;
- count = 0;
- break;
- }
- qreal rx = (*num++);
- qreal ry = (*num++);
- qreal xAxisRotation = (*num++);
- qreal largeArcFlag = (*num++);
- qreal sweepFlag = (*num++);
- qreal ex = (*num++) + offsetX;
- qreal ey = (*num++) + offsetY;
- count -= 7;
- qreal curx = x;
- qreal cury = y;
- pathArc(path, rx, ry, xAxisRotation, int(largeArcFlag),
- int(sweepFlag), ex, ey, curx, cury);
-
- x = ex;
- y = ey;
- }
- break;
- case 'A': {
- if (count < 7) {
- num += count;
- count = 0;
- break;
- }
- qreal rx = (*num++);
- qreal ry = (*num++);
- qreal xAxisRotation = (*num++);
- qreal largeArcFlag = (*num++);
- qreal sweepFlag = (*num++);
- qreal ex = (*num++);
- qreal ey = (*num++);
- count -= 7;
- qreal curx = x;
- qreal cury = y;
- pathArc(path, rx, ry, xAxisRotation, int(largeArcFlag),
- int(sweepFlag), ex, ey, curx, cury);
-
- x = ex;
- y = ey;
- }
- break;
- default:
- return false;
- }
- lastMode = pathElem.toLatin1();
- }
- }
- return true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativesvgparser_p.h b/src/declarative/util/qdeclarativesvgparser_p.h
deleted file mode 100644
index 0d7be10761..0000000000
--- a/src/declarative/util/qdeclarativesvgparser_p.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclaractive module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVESVGPARSER_P_H
-#define QDECLARATIVESVGPARSER_P_H
-
-#include <QtCore/qstring.h>
-#include <QtGui/qpainterpath.h>
-
-QT_BEGIN_NAMESPACE
-
-namespace QDeclarativeSvgParser
-{
- bool parsePathDataFast(const QString &dataStr, QPainterPath &path);
- void pathArc(QPainterPath &path, qreal rx, qreal ry, qreal x_axis_rotation,
- int large_arc_flag, int sweep_flag, qreal x, qreal y, qreal curx,
- qreal cury);
-}
-
-QT_END_NAMESPACE
-
-#endif // QDECLARATIVESVGPARSER_P_H
diff --git a/src/declarative/util/qdeclarativesystempalette.cpp b/src/declarative/util/qdeclarativesystempalette.cpp
deleted file mode 100644
index 61d8406141..0000000000
--- a/src/declarative/util/qdeclarativesystempalette.cpp
+++ /dev/null
@@ -1,312 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativesystempalette_p.h"
-
-#include <QGuiApplication>
-
-#include <private/qobject_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeSystemPalettePrivate : public QObjectPrivate
-{
-public:
- QPalette palette;
- QPalette::ColorGroup group;
-};
-
-
-
-/*!
- \qmlclass SystemPalette QDeclarativeSystemPalette
- \inqmlmodule QtQuick 2
- \ingroup qml-utility-elements
- \brief The SystemPalette element provides access to the Qt palettes.
-
- The SystemPalette element provides access to the Qt application
- palettes. This provides information about the standard colors used
- for application windows, buttons and other features. These colors
- are grouped into three \e {color groups}: \c Active, \c Inactive,
- and \c Disabled. See the QPalette documentation for details about
- color groups and the properties provided by SystemPalette.
-
- This can be used to color items in a way that provides a more
- native look and feel.
-
- The following example creates a palette from the \c Active color
- group and uses this to color the window and text items
- appropriately:
-
- \snippet doc/src/snippets/declarative/systempalette.qml 0
-
- \sa QPalette
-*/
-QDeclarativeSystemPalette::QDeclarativeSystemPalette(QObject *parent)
- : QObject(*(new QDeclarativeSystemPalettePrivate), parent)
-{
- Q_D(QDeclarativeSystemPalette);
- d->palette = QGuiApplication::palette();
- d->group = QPalette::Active;
- qApp->installEventFilter(this);
-}
-
-QDeclarativeSystemPalette::~QDeclarativeSystemPalette()
-{
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::window
- The window (general background) color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::window() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::Window);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::windowText
- The window text (general foreground) color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::windowText() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::WindowText);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::base
- The base color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::base() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::Base);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::text
- The text color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::text() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::Text);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::alternateBase
- The alternate base color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::alternateBase() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::AlternateBase);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::button
- The button color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::button() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::Button);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::buttonText
- The button text foreground color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::buttonText() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::ButtonText);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::light
- The light color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::light() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::Light);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::midlight
- The midlight color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::midlight() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::Midlight);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::dark
- The dark color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::dark() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::Dark);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::mid
- The mid color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::mid() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::Mid);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::shadow
- The shadow color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::shadow() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::Shadow);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::highlight
- The highlight color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::highlight() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::Highlight);
-}
-
-/*!
- \qmlproperty color QtQuick2::SystemPalette::highlightedText
- The highlighted text color of the current color group.
-
- \sa QPalette::ColorRole
-*/
-QColor QDeclarativeSystemPalette::highlightedText() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return d->palette.color(d->group, QPalette::HighlightedText);
-}
-
-/*!
- \qmlproperty enumeration QtQuick2::SystemPalette::colorGroup
-
- The color group of the palette. This can be one of:
-
- \list
- \o SystemPalette.Active (default)
- \o SystemPalette.Inactive
- \o SystemPalette.Disabled
- \endlist
-
- \sa QPalette::ColorGroup
-*/
-QDeclarativeSystemPalette::ColorGroup QDeclarativeSystemPalette::colorGroup() const
-{
- Q_D(const QDeclarativeSystemPalette);
- return (QDeclarativeSystemPalette::ColorGroup)d->group;
-}
-
-void QDeclarativeSystemPalette::setColorGroup(QDeclarativeSystemPalette::ColorGroup colorGroup)
-{
- Q_D(QDeclarativeSystemPalette);
- d->group = (QPalette::ColorGroup)colorGroup;
- emit paletteChanged();
-}
-
-bool QDeclarativeSystemPalette::eventFilter(QObject *watched, QEvent *event)
-{
- if (watched == qApp) {
- if (event->type() == QEvent::ApplicationPaletteChange) {
- QGuiApplication::postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
- return false;
- }
- }
- return QObject::eventFilter(watched, event);
-}
-
-bool QDeclarativeSystemPalette::event(QEvent *event)
-{
- Q_D(QDeclarativeSystemPalette);
- if (event->type() == QEvent::ApplicationPaletteChange) {
- d->palette = QGuiApplication::palette();
- emit paletteChanged();
- return true;
- }
- return QObject::event(event);
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativesystempalette_p.h b/src/declarative/util/qdeclarativesystempalette_p.h
deleted file mode 100644
index e92dc514d5..0000000000
--- a/src/declarative/util/qdeclarativesystempalette_p.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVESYSTEMPALETTE_H
-#define QDECLARATIVESYSTEMPALETTE_H
-
-#include <qdeclarative.h>
-
-#include <QtCore/qobject.h>
-#include <QPalette>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeSystemPalettePrivate;
-class Q_AUTOTEST_EXPORT QDeclarativeSystemPalette : public QObject
-{
- Q_OBJECT
- Q_ENUMS(ColorGroup)
- Q_DECLARE_PRIVATE(QDeclarativeSystemPalette)
-
- Q_PROPERTY(QDeclarativeSystemPalette::ColorGroup colorGroup READ colorGroup WRITE setColorGroup NOTIFY paletteChanged)
- Q_PROPERTY(QColor window READ window NOTIFY paletteChanged)
- Q_PROPERTY(QColor windowText READ windowText NOTIFY paletteChanged)
- Q_PROPERTY(QColor base READ base NOTIFY paletteChanged)
- Q_PROPERTY(QColor text READ text NOTIFY paletteChanged)
- Q_PROPERTY(QColor alternateBase READ alternateBase NOTIFY paletteChanged)
- Q_PROPERTY(QColor button READ button NOTIFY paletteChanged)
- Q_PROPERTY(QColor buttonText READ buttonText NOTIFY paletteChanged)
- Q_PROPERTY(QColor light READ light NOTIFY paletteChanged)
- Q_PROPERTY(QColor midlight READ midlight NOTIFY paletteChanged)
- Q_PROPERTY(QColor dark READ dark NOTIFY paletteChanged)
- Q_PROPERTY(QColor mid READ mid NOTIFY paletteChanged)
- Q_PROPERTY(QColor shadow READ shadow NOTIFY paletteChanged)
- Q_PROPERTY(QColor highlight READ highlight NOTIFY paletteChanged)
- Q_PROPERTY(QColor highlightedText READ highlightedText NOTIFY paletteChanged)
-
-public:
- QDeclarativeSystemPalette(QObject *parent=0);
- ~QDeclarativeSystemPalette();
-
- enum ColorGroup { Active = QPalette::Active, Inactive = QPalette::Inactive, Disabled = QPalette::Disabled };
-
- QColor window() const;
- QColor windowText() const;
-
- QColor base() const;
- QColor text() const;
- QColor alternateBase() const;
-
- QColor button() const;
- QColor buttonText() const;
-
- QColor light() const;
- QColor midlight() const;
- QColor dark() const;
- QColor mid() const;
- QColor shadow() const;
-
- QColor highlight() const;
- QColor highlightedText() const;
-
- QDeclarativeSystemPalette::ColorGroup colorGroup() const;
- void setColorGroup(QDeclarativeSystemPalette::ColorGroup);
-
-Q_SIGNALS:
- void paletteChanged();
-
-private:
- bool eventFilter(QObject *watched, QEvent *event);
- bool event(QEvent *event);
-
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeSystemPalette)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVESYSTEMPALETTE_H
diff --git a/src/declarative/util/qdeclarativetimeline.cpp b/src/declarative/util/qdeclarativetimeline.cpp
deleted file mode 100644
index 7066d3d062..0000000000
--- a/src/declarative/util/qdeclarativetimeline.cpp
+++ /dev/null
@@ -1,947 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativetimeline_p_p.h"
-
-#include <QDebug>
-#include <QMutex>
-#include <QThread>
-#include <QWaitCondition>
-#include <QEvent>
-#include <QCoreApplication>
-#include <QEasingCurve>
-#include <QTime>
-
-QT_BEGIN_NAMESPACE
-
-struct Update {
- Update(QDeclarativeTimeLineValue *_g, qreal _v)
- : g(_g), v(_v) {}
- Update(const QDeclarativeTimeLineCallback &_e)
- : g(0), v(0), e(_e) {}
-
- QDeclarativeTimeLineValue *g;
- qreal v;
- QDeclarativeTimeLineCallback e;
-};
-
-struct QDeclarativeTimeLinePrivate
-{
- QDeclarativeTimeLinePrivate(QDeclarativeTimeLine *);
-
- struct Op {
- enum Type {
- Pause,
- Set,
- Move,
- MoveBy,
- Accel,
- AccelDistance,
- Execute
- };
- Op() {}
- Op(Type t, int l, qreal v, qreal v2, int o,
- const QDeclarativeTimeLineCallback &ev = QDeclarativeTimeLineCallback(), const QEasingCurve &es = QEasingCurve())
- : type(t), length(l), value(v), value2(v2), order(o), event(ev),
- easing(es) {}
- Op(const Op &o)
- : type(o.type), length(o.length), value(o.value), value2(o.value2),
- order(o.order), event(o.event), easing(o.easing) {}
- Op &operator=(const Op &o) {
- type = o.type; length = o.length; value = o.value;
- value2 = o.value2; order = o.order; event = o.event;
- easing = o.easing;
- return *this;
- }
-
- Type type;
- int length;
- qreal value;
- qreal value2;
-
- int order;
- QDeclarativeTimeLineCallback event;
- QEasingCurve easing;
- };
- struct TimeLine
- {
- TimeLine() : length(0), consumedOpLength(0), base(0.) {}
- QList<Op> ops;
- int length;
- int consumedOpLength;
- qreal base;
- };
-
- int length;
- int syncPoint;
- typedef QHash<QDeclarativeTimeLineObject *, TimeLine> Ops;
- Ops ops;
- QDeclarativeTimeLine *q;
-
- void add(QDeclarativeTimeLineObject &, const Op &);
- qreal value(const Op &op, int time, qreal base, bool *) const;
-
- int advance(int);
-
- bool clockRunning;
- int prevTime;
-
- int order;
-
- QDeclarativeTimeLine::SyncMode syncMode;
- int syncAdj;
- QList<QPair<int, Update> > *updateQueue;
-};
-
-QDeclarativeTimeLinePrivate::QDeclarativeTimeLinePrivate(QDeclarativeTimeLine *parent)
-: length(0), syncPoint(0), q(parent), clockRunning(false), prevTime(0), order(0), syncMode(QDeclarativeTimeLine::LocalSync), syncAdj(0), updateQueue(0)
-{
-}
-
-void QDeclarativeTimeLinePrivate::add(QDeclarativeTimeLineObject &g, const Op &o)
-{
- if (g._t && g._t != q) {
- qWarning() << "QDeclarativeTimeLine: Cannot modify a QDeclarativeTimeLineValue owned by"
- << "another timeline.";
- return;
- }
- g._t = q;
-
- Ops::Iterator iter = ops.find(&g);
- if (iter == ops.end()) {
- iter = ops.insert(&g, TimeLine());
- if (syncPoint > 0)
- q->pause(g, syncPoint);
- }
- if (!iter->ops.isEmpty() &&
- o.type == Op::Pause &&
- iter->ops.last().type == Op::Pause) {
- iter->ops.last().length += o.length;
- iter->length += o.length;
- } else {
- iter->ops.append(o);
- iter->length += o.length;
- }
-
- if (iter->length > length)
- length = iter->length;
-
- if (!clockRunning) {
- q->stop();
- prevTime = 0;
- clockRunning = true;
-
- if (syncMode == QDeclarativeTimeLine::LocalSync) {
- syncAdj = -1;
- } else {
- syncAdj = 0;
- }
- q->start();
-/* q->tick(0);
- if (syncMode == QDeclarativeTimeLine::LocalSync) {
- syncAdj = -1;
- } else {
- syncAdj = 0;
- }
- */
- }
-}
-
-qreal QDeclarativeTimeLinePrivate::value(const Op &op, int time, qreal base, bool *changed) const
-{
- Q_ASSERT(time >= 0);
- Q_ASSERT(time <= op.length);
- *changed = true;
-
- switch(op.type) {
- case Op::Pause:
- *changed = false;
- return base;
- case Op::Set:
- return op.value;
- case Op::Move:
- if (time == 0) {
- return base;
- } else if (time == (op.length)) {
- return op.value;
- } else {
- qreal delta = op.value - base;
- qreal pTime = (qreal)(time) / (qreal)op.length;
- if (op.easing.type() == QEasingCurve::Linear)
- return base + delta * pTime;
- else
- return base + delta * op.easing.valueForProgress(pTime);
- }
- case Op::MoveBy:
- if (time == 0) {
- return base;
- } else if (time == (op.length)) {
- return base + op.value;
- } else {
- qreal delta = op.value;
- qreal pTime = (qreal)(time) / (qreal)op.length;
- if (op.easing.type() == QEasingCurve::Linear)
- return base + delta * pTime;
- else
- return base + delta * op.easing.valueForProgress(pTime);
- }
- case Op::Accel:
- if (time == 0) {
- return base;
- } else {
- qreal t = (qreal)(time) / 1000.0f;
- qreal delta = op.value * t + 0.5f * op.value2 * t * t;
- return base + delta;
- }
- case Op::AccelDistance:
- if (time == 0) {
- return base;
- } else if (time == (op.length)) {
- return base + op.value2;
- } else {
- qreal t = (qreal)(time) / 1000.0f;
- qreal accel = -1.0f * 1000.0f * op.value / (qreal)op.length;
- qreal delta = op.value * t + 0.5f * accel * t * t;
- return base + delta;
-
- }
- case Op::Execute:
- op.event.d0(op.event.d1);
- *changed = false;
- return -1;
- }
-
- return base;
-}
-
-/*!
- \internal
- \class QDeclarativeTimeLine
- \brief The QDeclarativeTimeLine class provides a timeline for controlling animations.
-
- QDeclarativeTimeLine is similar to QTimeLine except:
- \list
- \i It updates QDeclarativeTimeLineValue instances directly, rather than maintaining a single
- current value.
-
- For example, the following animates a simple value over 200 milliseconds:
- \code
- QDeclarativeTimeLineValue v(<starting value>);
- QDeclarativeTimeLine tl;
- tl.move(v, 100., 200);
- tl.start()
- \endcode
-
- If your program needs to know when values are changed, it can either
- connect to the QDeclarativeTimeLine's updated() signal, or inherit from QDeclarativeTimeLineValue
- and reimplement the QDeclarativeTimeLineValue::setValue() method.
-
- \i Supports multiple QDeclarativeTimeLineValue, arbitrary start and end values and allows
- animations to be strung together for more complex effects.
-
- For example, the following animation moves the x and y coordinates of
- an object from wherever they are to the position (100, 100) in 50
- milliseconds and then further animates them to (100, 200) in 50
- milliseconds:
-
- \code
- QDeclarativeTimeLineValue x(<starting value>);
- QDeclarativeTimeLineValue y(<starting value>);
-
- QDeclarativeTimeLine tl;
- tl.start();
-
- tl.move(x, 100., 50);
- tl.move(y, 100., 50);
- tl.move(y, 200., 50);
- \endcode
-
- \i All QDeclarativeTimeLine instances share a single, synchronized clock.
-
- Actions scheduled within the same event loop tick are scheduled
- synchronously against each other, regardless of the wall time between the
- scheduling. Synchronized scheduling applies both to within the same
- QDeclarativeTimeLine and across separate QDeclarativeTimeLine's within the same process.
-
- \endlist
-
- Currently easing functions are not supported.
-*/
-
-
-/*!
- Construct a new QDeclarativeTimeLine with the specified \a parent.
-*/
-QDeclarativeTimeLine::QDeclarativeTimeLine(QObject *parent)
-: QAbstractAnimation(parent)
-{
- d = new QDeclarativeTimeLinePrivate(this);
-}
-
-/*!
- Destroys the time line. Any inprogress animations are canceled, but not
- completed.
-*/
-QDeclarativeTimeLine::~QDeclarativeTimeLine()
-{
- for (QDeclarativeTimeLinePrivate::Ops::Iterator iter = d->ops.begin();
- iter != d->ops.end();
- ++iter)
- iter.key()->_t = 0;
-
- delete d; d = 0;
-}
-
-/*!
- \enum QDeclarativeTimeLine::SyncMode
- */
-
-/*!
- Return the timeline's synchronization mode.
- */
-QDeclarativeTimeLine::SyncMode QDeclarativeTimeLine::syncMode() const
-{
- return d->syncMode;
-}
-
-/*!
- Set the timeline's synchronization mode to \a syncMode.
- */
-void QDeclarativeTimeLine::setSyncMode(SyncMode syncMode)
-{
- d->syncMode = syncMode;
-}
-
-/*!
- Pause \a obj for \a time milliseconds.
-*/
-void QDeclarativeTimeLine::pause(QDeclarativeTimeLineObject &obj, int time)
-{
- if (time <= 0) return;
- QDeclarativeTimeLinePrivate::Op op(QDeclarativeTimeLinePrivate::Op::Pause, time, 0., 0., d->order++);
- d->add(obj, op);
-}
-
-/*!
- Execute the \a event.
- */
-void QDeclarativeTimeLine::callback(const QDeclarativeTimeLineCallback &callback)
-{
- QDeclarativeTimeLinePrivate::Op op(QDeclarativeTimeLinePrivate::Op::Execute, 0, 0, 0., d->order++, callback);
- d->add(*callback.callbackObject(), op);
-}
-
-/*!
- Set the \a value of \a timeLineValue.
-*/
-void QDeclarativeTimeLine::set(QDeclarativeTimeLineValue &timeLineValue, qreal value)
-{
- QDeclarativeTimeLinePrivate::Op op(QDeclarativeTimeLinePrivate::Op::Set, 0, value, 0., d->order++);
- d->add(timeLineValue, op);
-}
-
-/*!
- Decelerate \a timeLineValue from the starting \a velocity to zero at the
- given \a acceleration rate. Although the \a acceleration is technically
- a deceleration, it should always be positive. The QDeclarativeTimeLine will ensure
- that the deceleration is in the opposite direction to the initial velocity.
-*/
-int QDeclarativeTimeLine::accel(QDeclarativeTimeLineValue &timeLineValue, qreal velocity, qreal acceleration)
-{
- if (acceleration == 0.0f)
- return -1;
-
- if ((velocity > 0.0f) == (acceleration > 0.0f))
- acceleration = acceleration * -1.0f;
-
- int time = static_cast<int>(-1000 * velocity / acceleration);
-
- QDeclarativeTimeLinePrivate::Op op(QDeclarativeTimeLinePrivate::Op::Accel, time, velocity, acceleration, d->order++);
- d->add(timeLineValue, op);
-
- return time;
-}
-
-/*!
- \overload
-
- Decelerate \a timeLineValue from the starting \a velocity to zero at the
- given \a acceleration rate over a maximum distance of maxDistance.
-
- If necessary, QDeclarativeTimeLine will reduce the acceleration to ensure that the
- entire operation does not require a move of more than \a maxDistance.
- \a maxDistance should always be positive.
-*/
-int QDeclarativeTimeLine::accel(QDeclarativeTimeLineValue &timeLineValue, qreal velocity, qreal acceleration, qreal maxDistance)
-{
- if (maxDistance == 0.0f || acceleration == 0.0f)
- return -1;
-
- Q_ASSERT(acceleration > 0.0f && maxDistance > 0.0f);
-
- qreal maxAccel = (velocity * velocity) / (2.0f * maxDistance);
- if (maxAccel > acceleration)
- acceleration = maxAccel;
-
- if ((velocity > 0.0f) == (acceleration > 0.0f))
- acceleration = acceleration * -1.0f;
-
- int time = static_cast<int>(-1000 * velocity / acceleration);
-
- QDeclarativeTimeLinePrivate::Op op(QDeclarativeTimeLinePrivate::Op::Accel, time, velocity, acceleration, d->order++);
- d->add(timeLineValue, op);
-
- return time;
-}
-
-/*!
- Decelerate \a timeLineValue from the starting \a velocity to zero over the given
- \a distance. This is like accel(), but the QDeclarativeTimeLine calculates the exact
- deceleration to use.
-
- \a distance should be positive.
-*/
-int QDeclarativeTimeLine::accelDistance(QDeclarativeTimeLineValue &timeLineValue, qreal velocity, qreal distance)
-{
- if (distance == 0.0f || velocity == 0.0f)
- return -1;
-
- Q_ASSERT((distance >= 0.0f) == (velocity >= 0.0f));
-
- int time = static_cast<int>(1000 * (2.0f * distance) / velocity);
-
- QDeclarativeTimeLinePrivate::Op op(QDeclarativeTimeLinePrivate::Op::AccelDistance, time, velocity, distance, d->order++);
- d->add(timeLineValue, op);
-
- return time;
-}
-
-/*!
- Linearly change the \a timeLineValue from its current value to the given
- \a destination value over \a time milliseconds.
-*/
-void QDeclarativeTimeLine::move(QDeclarativeTimeLineValue &timeLineValue, qreal destination, int time)
-{
- if (time <= 0) return;
- QDeclarativeTimeLinePrivate::Op op(QDeclarativeTimeLinePrivate::Op::Move, time, destination, 0.0f, d->order++);
- d->add(timeLineValue, op);
-}
-
-/*!
- Change the \a timeLineValue from its current value to the given \a destination
- value over \a time milliseconds using the \a easing curve.
- */
-void QDeclarativeTimeLine::move(QDeclarativeTimeLineValue &timeLineValue, qreal destination, const QEasingCurve &easing, int time)
-{
- if (time <= 0) return;
- QDeclarativeTimeLinePrivate::Op op(QDeclarativeTimeLinePrivate::Op::Move, time, destination, 0.0f, d->order++, QDeclarativeTimeLineCallback(), easing);
- d->add(timeLineValue, op);
-}
-
-/*!
- Linearly change the \a timeLineValue from its current value by the \a change amount
- over \a time milliseconds.
-*/
-void QDeclarativeTimeLine::moveBy(QDeclarativeTimeLineValue &timeLineValue, qreal change, int time)
-{
- if (time <= 0) return;
- QDeclarativeTimeLinePrivate::Op op(QDeclarativeTimeLinePrivate::Op::MoveBy, time, change, 0.0f, d->order++);
- d->add(timeLineValue, op);
-}
-
-/*!
- Change the \a timeLineValue from its current value by the \a change amount over
- \a time milliseconds using the \a easing curve.
- */
-void QDeclarativeTimeLine::moveBy(QDeclarativeTimeLineValue &timeLineValue, qreal change, const QEasingCurve &easing, int time)
-{
- if (time <= 0) return;
- QDeclarativeTimeLinePrivate::Op op(QDeclarativeTimeLinePrivate::Op::MoveBy, time, change, 0.0f, d->order++, QDeclarativeTimeLineCallback(), easing);
- d->add(timeLineValue, op);
-}
-
-/*!
- Cancel (but don't complete) all scheduled actions for \a timeLineValue.
-*/
-void QDeclarativeTimeLine::reset(QDeclarativeTimeLineValue &timeLineValue)
-{
- if (!timeLineValue._t)
- return;
- if (timeLineValue._t != this) {
- qWarning() << "QDeclarativeTimeLine: Cannot reset a QDeclarativeTimeLineValue owned by another timeline.";
- return;
- }
- remove(&timeLineValue);
- timeLineValue._t = 0;
-}
-
-int QDeclarativeTimeLine::duration() const
-{
- return -1;
-}
-
-/*!
- Synchronize the end point of \a timeLineValue to the endpoint of \a syncTo
- within this timeline.
-
- Following operations on \a timeLineValue in this timeline will be scheduled after
- all the currently scheduled actions on \a syncTo are complete. In
- pseudo-code this is equivalent to:
- \code
- QDeclarativeTimeLine::pause(timeLineValue, min(0, length_of(syncTo) - length_of(timeLineValue)))
- \endcode
-*/
-void QDeclarativeTimeLine::sync(QDeclarativeTimeLineValue &timeLineValue, QDeclarativeTimeLineValue &syncTo)
-{
- QDeclarativeTimeLinePrivate::Ops::Iterator iter = d->ops.find(&syncTo);
- if (iter == d->ops.end())
- return;
- int length = iter->length;
-
- iter = d->ops.find(&timeLineValue);
- if (iter == d->ops.end()) {
- pause(timeLineValue, length);
- } else {
- int glength = iter->length;
- pause(timeLineValue, length - glength);
- }
-}
-
-/*!
- Synchronize the end point of \a timeLineValue to the endpoint of the longest
- action cursrently scheduled in the timeline.
-
- In pseudo-code, this is equivalent to:
- \code
- QDeclarativeTimeLine::pause(timeLineValue, length_of(timeline) - length_of(timeLineValue))
- \endcode
-*/
-void QDeclarativeTimeLine::sync(QDeclarativeTimeLineValue &timeLineValue)
-{
- QDeclarativeTimeLinePrivate::Ops::Iterator iter = d->ops.find(&timeLineValue);
- if (iter == d->ops.end()) {
- pause(timeLineValue, d->length);
- } else {
- pause(timeLineValue, d->length - iter->length);
- }
-}
-
-/*
- Synchronize all currently and future scheduled values in this timeline to
- the longest action currently scheduled.
-
- For example:
- \code
- value1->setValue(0.);
- value2->setValue(0.);
- value3->setValue(0.);
- QDeclarativeTimeLine tl;
- ...
- tl.move(value1, 10, 200);
- tl.move(value2, 10, 100);
- tl.sync();
- tl.move(value2, 20, 100);
- tl.move(value3, 20, 100);
- \endcode
-
- will result in:
-
- \table
- \header \o \o 0ms \o 50ms \o 100ms \o 150ms \o 200ms \o 250ms \o 300ms
- \row \o value1 \o 0 \o 2.5 \o 5.0 \o 7.5 \o 10 \o 10 \o 10
- \row \o value2 \o 0 \o 5.0 \o 10.0 \o 10.0 \o 10.0 \o 15.0 \o 20.0
- \row \o value2 \o 0 \o 0 \o 0 \o 0 \o 0 \o 10.0 \o 20.0
- \endtable
-*/
-
-/*void QDeclarativeTimeLine::sync()
-{
- for (QDeclarativeTimeLinePrivate::Ops::Iterator iter = d->ops.begin();
- iter != d->ops.end();
- ++iter)
- pause(*iter.key(), d->length - iter->length);
- d->syncPoint = d->length;
-}*/
-
-/*!
- \internal
-
- Temporary hack.
- */
-void QDeclarativeTimeLine::setSyncPoint(int sp)
-{
- d->syncPoint = sp;
-}
-
-/*!
- \internal
-
- Temporary hack.
- */
-int QDeclarativeTimeLine::syncPoint() const
-{
- return d->syncPoint;
-}
-
-/*!
- Returns true if the timeline is active. An active timeline is one where
- QDeclarativeTimeLineValue actions are still pending.
-*/
-bool QDeclarativeTimeLine::isActive() const
-{
- return !d->ops.isEmpty();
-}
-
-/*!
- Completes the timeline. All queued actions are played to completion, and then discarded. For example,
- \code
- QDeclarativeTimeLineValue v(0.);
- QDeclarativeTimeLine tl;
- tl.move(v, 100., 1000.);
- // 500 ms passes
- // v.value() == 50.
- tl.complete();
- // v.value() == 100.
- \endcode
-*/
-void QDeclarativeTimeLine::complete()
-{
- d->advance(d->length);
-}
-
-/*!
- Resets the timeline. All queued actions are discarded and QDeclarativeTimeLineValue's retain their current value. For example,
- \code
- QDeclarativeTimeLineValue v(0.);
- QDeclarativeTimeLine tl;
- tl.move(v, 100., 1000.);
- // 500 ms passes
- // v.value() == 50.
- tl.clear();
- // v.value() == 50.
- \endcode
-*/
-void QDeclarativeTimeLine::clear()
-{
- for (QDeclarativeTimeLinePrivate::Ops::ConstIterator iter = d->ops.begin(); iter != d->ops.end(); ++iter)
- iter.key()->_t = 0;
- d->ops.clear();
- d->length = 0;
- d->syncPoint = 0;
- //XXX need stop here?
-}
-
-int QDeclarativeTimeLine::time() const
-{
- return d->prevTime;
-}
-
-/*!
- \fn void QDeclarativeTimeLine::updated()
-
- Emitted each time the timeline modifies QDeclarativeTimeLineValues. Even if multiple
- QDeclarativeTimeLineValues are changed, this signal is only emitted once for each clock tick.
-*/
-
-void QDeclarativeTimeLine::updateCurrentTime(int v)
-{
- if (d->syncAdj == -1)
- d->syncAdj = v;
- v -= d->syncAdj;
-
- int timeChanged = v - d->prevTime;
-#if 0
- if (!timeChanged)
- return;
-#endif
- d->prevTime = v;
- d->advance(timeChanged);
- emit updated();
-
- // Do we need to stop the clock?
- if (d->ops.isEmpty()) {
- stop();
- d->prevTime = 0;
- d->clockRunning = false;
- emit completed();
- } /*else if (pauseTime > 0) {
- GfxClock::cancelClock();
- d->prevTime = 0;
- GfxClock::pauseFor(pauseTime);
- d->syncAdj = 0;
- d->clockRunning = false;
- }*/ else if (/*!GfxClock::isActive()*/ state() != Running) {
- stop();
- d->prevTime = 0;
- d->clockRunning = true;
- d->syncAdj = 0;
- start();
- }
-}
-
-bool operator<(const QPair<int, Update> &lhs,
- const QPair<int, Update> &rhs)
-{
- return lhs.first < rhs.first;
-}
-
-int QDeclarativeTimeLinePrivate::advance(int t)
-{
- int pauseTime = -1;
-
- // XXX - surely there is a more efficient way?
- do {
- pauseTime = -1;
- // Minimal advance time
- int advanceTime = t;
- for (Ops::Iterator iter = ops.begin(); iter != ops.end(); ++iter) {
- TimeLine &tl = *iter;
- Op &op = tl.ops.first();
- int length = op.length - tl.consumedOpLength;
-
- if (length < advanceTime) {
- advanceTime = length;
- if (advanceTime == 0)
- break;
- }
- }
- t -= advanceTime;
-
- // Process until then. A zero length advance time will only process
- // sets.
- QList<QPair<int, Update> > updates;
-
- for (Ops::Iterator iter = ops.begin(); iter != ops.end(); ) {
- QDeclarativeTimeLineValue *v = static_cast<QDeclarativeTimeLineValue *>(iter.key());
- TimeLine &tl = *iter;
- Q_ASSERT(!tl.ops.isEmpty());
-
- do {
- Op &op = tl.ops.first();
- if (advanceTime == 0 && op.length != 0)
- continue;
-
- if (tl.consumedOpLength == 0 &&
- op.type != Op::Pause &&
- op.type != Op::Execute)
- tl.base = v->value();
-
- if ((tl.consumedOpLength + advanceTime) == op.length) {
- if (op.type == Op::Execute) {
- updates << qMakePair(op.order, Update(op.event));
- } else {
- bool changed = false;
- qreal val = value(op, op.length, tl.base, &changed);
- if (changed)
- updates << qMakePair(op.order, Update(v, val));
- }
- tl.length -= qMin(advanceTime, tl.length);
- tl.consumedOpLength = 0;
- tl.ops.removeFirst();
- } else {
- tl.consumedOpLength += advanceTime;
- bool changed = false;
- qreal val = value(op, tl.consumedOpLength, tl.base, &changed);
- if (changed)
- updates << qMakePair(op.order, Update(v, val));
- tl.length -= qMin(advanceTime, tl.length);
- break;
- }
-
- } while(!tl.ops.isEmpty() && advanceTime == 0 && tl.ops.first().length == 0);
-
-
- if (tl.ops.isEmpty()) {
- iter = ops.erase(iter);
- v->_t = 0;
- } else {
- if (tl.ops.first().type == Op::Pause && pauseTime != 0) {
- int opPauseTime = tl.ops.first().length - tl.consumedOpLength;
- if (pauseTime == -1 || opPauseTime < pauseTime)
- pauseTime = opPauseTime;
- } else {
- pauseTime = 0;
- }
- ++iter;
- }
- }
-
- length -= qMin(length, advanceTime);
- syncPoint -= advanceTime;
-
- qSort(updates.begin(), updates.end());
- updateQueue = &updates;
- for (int ii = 0; ii < updates.count(); ++ii) {
- const Update &v = updates.at(ii).second;
- if (v.g) {
- v.g->setValue(v.v);
- } else {
- v.e.d0(v.e.d1);
- }
- }
- updateQueue = 0;
- } while(t);
-
- return pauseTime;
-}
-
-void QDeclarativeTimeLine::remove(QDeclarativeTimeLineObject *v)
-{
- QDeclarativeTimeLinePrivate::Ops::Iterator iter = d->ops.find(v);
- Q_ASSERT(iter != d->ops.end());
-
- int len = iter->length;
- d->ops.erase(iter);
- if (len == d->length) {
- // We need to recalculate the length
- d->length = 0;
- for (QDeclarativeTimeLinePrivate::Ops::Iterator iter = d->ops.begin();
- iter != d->ops.end();
- ++iter) {
-
- if (iter->length > d->length)
- d->length = iter->length;
-
- }
- }
- if (d->ops.isEmpty()) {
- stop();
- d->clockRunning = false;
- } else if (/*!GfxClock::isActive()*/ state() != Running) {
- stop();
- d->prevTime = 0;
- d->clockRunning = true;
-
- if (d->syncMode == QDeclarativeTimeLine::LocalSync) {
- d->syncAdj = -1;
- } else {
- d->syncAdj = 0;
- }
- start();
- }
-
- if (d->updateQueue) {
- for (int ii = 0; ii < d->updateQueue->count(); ++ii) {
- if (d->updateQueue->at(ii).second.g == v ||
- d->updateQueue->at(ii).second.e.callbackObject() == v) {
- d->updateQueue->removeAt(ii);
- --ii;
- }
- }
- }
-
-
-}
-
-/*!
- \internal
- \class QDeclarativeTimeLineValue
- \brief The QDeclarativeTimeLineValue class provides a value that can be modified by QDeclarativeTimeLine.
-*/
-
-/*!
- \fn QDeclarativeTimeLineValue::QDeclarativeTimeLineValue(qreal value = 0)
-
- Construct a new QDeclarativeTimeLineValue with an initial \a value.
-*/
-
-/*!
- \fn qreal QDeclarativeTimeLineValue::value() const
-
- Return the current value.
-*/
-
-/*!
- \fn void QDeclarativeTimeLineValue::setValue(qreal value)
-
- Set the current \a value.
-*/
-
-/*!
- \fn QDeclarativeTimeLine *QDeclarativeTimeLineValue::timeLine() const
-
- If a QDeclarativeTimeLine is operating on this value, return a pointer to it,
- otherwise return null.
-*/
-
-
-QDeclarativeTimeLineObject::QDeclarativeTimeLineObject()
-: _t(0)
-{
-}
-
-QDeclarativeTimeLineObject::~QDeclarativeTimeLineObject()
-{
- if (_t) {
- _t->remove(this);
- _t = 0;
- }
-}
-
-QDeclarativeTimeLineCallback::QDeclarativeTimeLineCallback()
-: d0(0), d1(0), d2(0)
-{
-}
-
-QDeclarativeTimeLineCallback::QDeclarativeTimeLineCallback(QDeclarativeTimeLineObject *b, Callback f, void *d)
-: d0(f), d1(d), d2(b)
-{
-}
-
-QDeclarativeTimeLineCallback::QDeclarativeTimeLineCallback(const QDeclarativeTimeLineCallback &o)
-: d0(o.d0), d1(o.d1), d2(o.d2)
-{
-}
-
-QDeclarativeTimeLineCallback &QDeclarativeTimeLineCallback::operator=(const QDeclarativeTimeLineCallback &o)
-{
- d0 = o.d0;
- d1 = o.d1;
- d2 = o.d2;
- return *this;
-}
-
-QDeclarativeTimeLineObject *QDeclarativeTimeLineCallback::callbackObject() const
-{
- return d2;
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativetimeline_p_p.h b/src/declarative/util/qdeclarativetimeline_p_p.h
deleted file mode 100644
index d84053903f..0000000000
--- a/src/declarative/util/qdeclarativetimeline_p_p.h
+++ /dev/null
@@ -1,200 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVETIMELINE_H
-#define QDECLARATIVETIMELINE_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 <QtCore/QObject>
-#include <QtCore/QAbstractAnimation>
-
-QT_BEGIN_NAMESPACE
-
-class QEasingCurve;
-class QDeclarativeTimeLineValue;
-class QDeclarativeTimeLineCallback;
-struct QDeclarativeTimeLinePrivate;
-class QDeclarativeTimeLineObject;
-class Q_AUTOTEST_EXPORT QDeclarativeTimeLine : public QAbstractAnimation
-{
-Q_OBJECT
-public:
- QDeclarativeTimeLine(QObject *parent = 0);
- ~QDeclarativeTimeLine();
-
- enum SyncMode { LocalSync, GlobalSync };
- SyncMode syncMode() const;
- void setSyncMode(SyncMode);
-
- void pause(QDeclarativeTimeLineObject &, int);
- void callback(const QDeclarativeTimeLineCallback &);
- void set(QDeclarativeTimeLineValue &, qreal);
-
- int accel(QDeclarativeTimeLineValue &, qreal velocity, qreal accel);
- int accel(QDeclarativeTimeLineValue &, qreal velocity, qreal accel, qreal maxDistance);
- int accelDistance(QDeclarativeTimeLineValue &, qreal velocity, qreal distance);
-
- void move(QDeclarativeTimeLineValue &, qreal destination, int time = 500);
- void move(QDeclarativeTimeLineValue &, qreal destination, const QEasingCurve &, int time = 500);
- void moveBy(QDeclarativeTimeLineValue &, qreal change, int time = 500);
- void moveBy(QDeclarativeTimeLineValue &, qreal change, const QEasingCurve &, int time = 500);
-
- void sync();
- void setSyncPoint(int);
- int syncPoint() const;
-
- void sync(QDeclarativeTimeLineValue &);
- void sync(QDeclarativeTimeLineValue &, QDeclarativeTimeLineValue &);
-
- void reset(QDeclarativeTimeLineValue &);
-
- void complete();
- void clear();
- bool isActive() const;
-
- int time() const;
-
- virtual int duration() const;
-Q_SIGNALS:
- void updated();
- void completed();
-
-protected:
- virtual void updateCurrentTime(int);
-
-private:
- void remove(QDeclarativeTimeLineObject *);
- friend class QDeclarativeTimeLineObject;
- friend struct QDeclarativeTimeLinePrivate;
- QDeclarativeTimeLinePrivate *d;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativeTimeLineObject
-{
-public:
- QDeclarativeTimeLineObject();
- virtual ~QDeclarativeTimeLineObject();
-
-protected:
- friend class QDeclarativeTimeLine;
- friend struct QDeclarativeTimeLinePrivate;
- QDeclarativeTimeLine *_t;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativeTimeLineValue : public QDeclarativeTimeLineObject
-{
-public:
- QDeclarativeTimeLineValue(qreal v = 0.) : _v(v) {}
-
- virtual qreal value() const { return _v; }
- virtual void setValue(qreal v) { _v = v; }
-
- QDeclarativeTimeLine *timeLine() const { return _t; }
-
- operator qreal() const { return _v; }
- QDeclarativeTimeLineValue &operator=(qreal v) { setValue(v); return *this; }
-private:
- friend class QDeclarativeTimeLine;
- friend struct QDeclarativeTimeLinePrivate;
- qreal _v;
-};
-
-class Q_AUTOTEST_EXPORT QDeclarativeTimeLineCallback
-{
-public:
- typedef void (*Callback)(void *);
-
- QDeclarativeTimeLineCallback();
- QDeclarativeTimeLineCallback(QDeclarativeTimeLineObject *b, Callback, void * = 0);
- QDeclarativeTimeLineCallback(const QDeclarativeTimeLineCallback &o);
-
- QDeclarativeTimeLineCallback &operator=(const QDeclarativeTimeLineCallback &o);
- QDeclarativeTimeLineObject *callbackObject() const;
-
-private:
- friend struct QDeclarativeTimeLinePrivate;
- Callback d0;
- void *d1;
- QDeclarativeTimeLineObject *d2;
-};
-
-template<class T>
-class QDeclarativeTimeLineValueProxy : public QDeclarativeTimeLineValue
-{
-public:
- QDeclarativeTimeLineValueProxy(T *cls, void (T::*func)(qreal), qreal v = 0.)
- : QDeclarativeTimeLineValue(v), _class(cls), _setFunctionReal(func), _setFunctionInt(0)
- {
- Q_ASSERT(_class);
- }
-
- QDeclarativeTimeLineValueProxy(T *cls, void (T::*func)(int), qreal v = 0.)
- : QDeclarativeTimeLineValue(v), _class(cls), _setFunctionReal(0), _setFunctionInt(func)
- {
- Q_ASSERT(_class);
- }
-
- virtual void setValue(qreal v)
- {
- QDeclarativeTimeLineValue::setValue(v);
- if (_setFunctionReal) (_class->*_setFunctionReal)(v);
- else if (_setFunctionInt) (_class->*_setFunctionInt)((int)v);
- }
-
-private:
- T *_class;
- void (T::*_setFunctionReal)(qreal);
- void (T::*_setFunctionInt)(int);
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/declarative/util/qdeclarativetimer.cpp b/src/declarative/util/qdeclarativetimer.cpp
deleted file mode 100644
index a4a2362680..0000000000
--- a/src/declarative/util/qdeclarativetimer.cpp
+++ /dev/null
@@ -1,324 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativetimer_p.h"
-
-#include <QtCore/qcoreapplication.h>
-#include <QtCore/qpauseanimation.h>
-#include <qdebug.h>
-
-#include <private/qobject_p.h>
-
-QT_BEGIN_NAMESPACE
-
-
-
-class QDeclarativeTimerPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeTimer)
-public:
- QDeclarativeTimerPrivate()
- : interval(1000), running(false), repeating(false), triggeredOnStart(false)
- , classBegun(false), componentComplete(false), firstTick(true) {}
- int interval;
- QPauseAnimation pause;
- bool running : 1;
- bool repeating : 1;
- bool triggeredOnStart : 1;
- bool classBegun : 1;
- bool componentComplete : 1;
- bool firstTick : 1;
-};
-
-/*!
- \qmlclass Timer QDeclarativeTimer
- \inqmlmodule QtQuick 2
- \ingroup qml-utility-elements
- \brief The Timer item triggers a handler at a specified interval.
-
- A Timer can be used to trigger an action either once, or repeatedly
- at a given interval.
-
- Here is a Timer that shows the current date and time, and updates
- the text every 500 milliseconds. It uses the JavaScript \c Date
- object to access the current time.
-
- \qml
- import QtQuick 1.0
-
- Item {
- Timer {
- interval: 500; running: true; repeat: true
- onTriggered: time.text = Date().toString()
- }
-
- Text { id: time }
- }
- \endqml
-
- The Timer element is synchronized with the animation timer. Since the animation
- timer is usually set to 60fps, the resolution of Timer will be
- at best 16ms.
-
- If the Timer is running and one of its properties is changed, the
- elapsed time will be reset. For example, if a Timer with interval of
- 1000ms has its \e repeat property changed 500ms after starting, the
- elapsed time will be reset to 0, and the Timer will be triggered
- 1000ms later.
-
- \sa {declarative/toys/clocks}{Clocks example}
-*/
-
-QDeclarativeTimer::QDeclarativeTimer(QObject *parent)
- : QObject(*(new QDeclarativeTimerPrivate), parent)
-{
- Q_D(QDeclarativeTimer);
- connect(&d->pause, SIGNAL(currentLoopChanged(int)), this, SLOT(ticked()));
- connect(&d->pause, SIGNAL(finished()), this, SLOT(finished()));
- d->pause.setLoopCount(1);
- d->pause.setDuration(d->interval);
-}
-
-/*!
- \qmlproperty int QtQuick2::Timer::interval
-
- Sets the \a interval between triggers, in milliseconds.
-
- The default interval is 1000 milliseconds.
-*/
-void QDeclarativeTimer::setInterval(int interval)
-{
- Q_D(QDeclarativeTimer);
- if (interval != d->interval) {
- d->interval = interval;
- update();
- emit intervalChanged();
- }
-}
-
-int QDeclarativeTimer::interval() const
-{
- Q_D(const QDeclarativeTimer);
- return d->interval;
-}
-
-/*!
- \qmlproperty bool QtQuick2::Timer::running
-
- If set to true, starts the timer; otherwise stops the timer.
- For a non-repeating timer, \a running is set to false after the
- timer has been triggered.
-
- \a running defaults to false.
-
- \sa repeat
-*/
-bool QDeclarativeTimer::isRunning() const
-{
- Q_D(const QDeclarativeTimer);
- return d->running;
-}
-
-void QDeclarativeTimer::setRunning(bool running)
-{
- Q_D(QDeclarativeTimer);
- if (d->running != running) {
- d->running = running;
- d->firstTick = true;
- emit runningChanged();
- update();
- }
-}
-
-/*!
- \qmlproperty bool QtQuick2::Timer::repeat
-
- If \a repeat is true the timer is triggered repeatedly at the
- specified interval; otherwise, the timer will trigger once at the
- specified interval and then stop (i.e. running will be set to false).
-
- \a repeat defaults to false.
-
- \sa running
-*/
-bool QDeclarativeTimer::isRepeating() const
-{
- Q_D(const QDeclarativeTimer);
- return d->repeating;
-}
-
-void QDeclarativeTimer::setRepeating(bool repeating)
-{
- Q_D(QDeclarativeTimer);
- if (repeating != d->repeating) {
- d->repeating = repeating;
- update();
- emit repeatChanged();
- }
-}
-
-/*!
- \qmlproperty bool QtQuick2::Timer::triggeredOnStart
-
- When a timer is started, the first trigger is usually after the specified
- interval has elapsed. It is sometimes desirable to trigger immediately
- when the timer is started; for example, to establish an initial
- state.
-
- If \a triggeredOnStart is true, the timer is triggered immediately
- when started, and subsequently at the specified interval. Note that if
- \e repeat is set to false, the timer is triggered twice; once on start,
- and again at the interval.
-
- \a triggeredOnStart defaults to false.
-
- \sa running
-*/
-bool QDeclarativeTimer::triggeredOnStart() const
-{
- Q_D(const QDeclarativeTimer);
- return d->triggeredOnStart;
-}
-
-void QDeclarativeTimer::setTriggeredOnStart(bool triggeredOnStart)
-{
- Q_D(QDeclarativeTimer);
- if (d->triggeredOnStart != triggeredOnStart) {
- d->triggeredOnStart = triggeredOnStart;
- update();
- emit triggeredOnStartChanged();
- }
-}
-
-/*!
- \qmlmethod QtQuick2::Timer::start()
- \brief Starts the timer.
-
- If the timer is already running, calling this method has no effect. The
- \c running property will be true following a call to \c start().
-*/
-void QDeclarativeTimer::start()
-{
- setRunning(true);
-}
-
-/*!
- \qmlmethod QtQuick2::Timer::stop()
- \brief Stops the timer.
-
- If the timer is not running, calling this method has no effect. The
- \c running property will be false following a call to \c stop().
-*/
-void QDeclarativeTimer::stop()
-{
- setRunning(false);
-}
-
-/*!
- \qmlmethod QtQuick2::Timer::restart()
- \brief Restarts the timer.
-
- If the Timer is not running it will be started, otherwise it will be
- stopped, reset to initial state and started. The \c running property
- will be true following a call to \c restart().
-*/
-void QDeclarativeTimer::restart()
-{
- setRunning(false);
- setRunning(true);
-}
-
-void QDeclarativeTimer::update()
-{
- Q_D(QDeclarativeTimer);
- if (d->classBegun && !d->componentComplete)
- return;
- d->pause.stop();
- if (d->running) {
- d->pause.setCurrentTime(0);
- d->pause.setLoopCount(d->repeating ? -1 : 1);
- d->pause.setDuration(d->interval);
- d->pause.start();
- if (d->triggeredOnStart && d->firstTick) {
- QCoreApplication::removePostedEvents(this, QEvent::MetaCall);
- QMetaObject::invokeMethod(this, "ticked", Qt::QueuedConnection);
- }
- }
-}
-
-void QDeclarativeTimer::classBegin()
-{
- Q_D(QDeclarativeTimer);
- d->classBegun = true;
-}
-
-void QDeclarativeTimer::componentComplete()
-{
- Q_D(QDeclarativeTimer);
- d->componentComplete = true;
- update();
-}
-
-/*!
- \qmlsignal QtQuick2::Timer::onTriggered()
-
- This handler is called when the Timer is triggered.
-*/
-void QDeclarativeTimer::ticked()
-{
- Q_D(QDeclarativeTimer);
- if (d->running && (d->pause.currentTime() > 0 || (d->triggeredOnStart && d->firstTick)))
- emit triggered();
- d->firstTick = false;
-}
-
-void QDeclarativeTimer::finished()
-{
- Q_D(QDeclarativeTimer);
- if (d->repeating || !d->running)
- return;
- emit triggered();
- d->running = false;
- d->firstTick = false;
- emit runningChanged();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativetimer_p.h b/src/declarative/util/qdeclarativetimer_p.h
deleted file mode 100644
index 7de56068dd..0000000000
--- a/src/declarative/util/qdeclarativetimer_p.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVETIMER_H
-#define QDECLARATIVETIMER_H
-
-#include <qdeclarative.h>
-
-#include <QtCore/qobject.h>
-#include <QtCore/qabstractanimation.h>
-
-#include <private/qdeclarativeglobal_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeTimerPrivate;
-class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativeTimer : public QObject, public QDeclarativeParserStatus
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeTimer)
- Q_INTERFACES(QDeclarativeParserStatus)
- Q_PROPERTY(int interval READ interval WRITE setInterval NOTIFY intervalChanged)
- Q_PROPERTY(bool running READ isRunning WRITE setRunning NOTIFY runningChanged)
- Q_PROPERTY(bool repeat READ isRepeating WRITE setRepeating NOTIFY repeatChanged)
- Q_PROPERTY(bool triggeredOnStart READ triggeredOnStart WRITE setTriggeredOnStart NOTIFY triggeredOnStartChanged)
- Q_PROPERTY(QObject *parent READ parent CONSTANT)
-
-public:
- QDeclarativeTimer(QObject *parent=0);
-
- void setInterval(int interval);
- int interval() const;
-
- bool isRunning() const;
- void setRunning(bool running);
-
- bool isRepeating() const;
- void setRepeating(bool repeating);
-
- bool triggeredOnStart() const;
- void setTriggeredOnStart(bool triggeredOnStart);
-
-protected:
- void classBegin();
- void componentComplete();
-
-public Q_SLOTS:
- void start();
- void stop();
- void restart();
-
-Q_SIGNALS:
- void triggered();
- void runningChanged();
- void intervalChanged();
- void repeatChanged();
- void triggeredOnStartChanged();
-
-private:
- void update();
-
-private Q_SLOTS:
- void ticked();
- void finished();
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeTimer)
-
-QT_END_HEADER
-
-#endif
diff --git a/src/declarative/util/qdeclarativetransition.cpp b/src/declarative/util/qdeclarativetransition.cpp
deleted file mode 100644
index 916e599cc6..0000000000
--- a/src/declarative/util/qdeclarativetransition.cpp
+++ /dev/null
@@ -1,392 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativetransition_p.h"
-
-#include "qdeclarativestate_p.h"
-#include "qdeclarativestate_p_p.h"
-#include "qdeclarativestateoperations_p.h"
-#include "qdeclarativeanimation_p.h"
-#include "qdeclarativeanimation_p_p.h"
-#include "qdeclarativetransitionmanager_p_p.h"
-
-#include <QParallelAnimationGroup>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \qmlclass Transition QDeclarativeTransition
- \inqmlmodule QtQuick 2
- \ingroup qml-animation-transition
- \brief The Transition element defines animated transitions that occur on state changes.
-
- A Transition defines the animations to be applied when a \l State change occurs.
-
- For example, the following \l Rectangle has two states: the default state, and
- an added "moved" state. In the "moved state, the rectangle's position changes
- to (50, 50). The added Transition specifies that when the rectangle
- changes between the default and the "moved" state, any changes
- to the \c x and \c y properties should be animated, using an \c Easing.InOutQuad.
-
- \snippet doc/src/snippets/declarative/transition.qml 0
-
- Notice the example does not require \l{PropertyAnimation::}{to} and
- \l{PropertyAnimation::}{from} values for the NumberAnimation. As a convenience,
- these properties are automatically set to the values of \c x and \c y before
- and after the state change; the \c from values are provided by
- the current values of \c x and \c y, and the \c to values are provided by
- the PropertyChanges object. If you wish, you can provide \l{PropertyAnimation::}{to} and
- \l{PropertyAnimation::}{from} values anyway to override the default values.
-
- By default, a Transition's animations are applied for any state change in the
- parent item. The Transition \l {Transition::}{from} and \l {Transition::}{to}
- values can be set to restrict the animations to only be applied when changing
- from one particular state to another.
-
- To define multiple transitions, specify \l Item::transitions as a list:
-
- \snippet doc/src/snippets/declarative/transitions-list.qml list of transitions
-
- If multiple Transitions are specified, only a single (best-matching) Transition will be applied for any particular
- state change. In the example above, when changing to \c state1, the first transition will be used, rather
- than the more generic second transition.
-
- If a state change has a Transition that matches the same property as a
- \l Behavior, the Transition animation overrides the \l Behavior for that
- state change.
-
- \sa {QML Animation and Transitions}, {declarative/animation/states}{states example}, {qmlstates}{States}, {QtDeclarative}
-*/
-
-//ParallelAnimationWrapper allows us to do a "callback" when the animation finishes, rather than connecting
-//and disconnecting signals and slots frequently
-class ParallelAnimationWrapper : public QParallelAnimationGroup
-{
- Q_OBJECT
-public:
- ParallelAnimationWrapper(QObject *parent = 0) : QParallelAnimationGroup(parent) {}
- QDeclarativeTransitionPrivate *trans;
-protected:
- virtual void updateState(QAbstractAnimation::State newState, QAbstractAnimation::State oldState);
-};
-
-class QDeclarativeTransitionPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QDeclarativeTransition)
-public:
- QDeclarativeTransitionPrivate()
- : fromState(QLatin1String("*")), toState(QLatin1String("*")),
- reversed(false), reversible(false), enabled(true), manager(0)
- {
- group.trans = this;
- }
-
- QString fromState;
- QString toState;
- bool reversed;
- bool reversible;
- bool enabled;
- ParallelAnimationWrapper group;
- QDeclarativeTransitionManager *manager;
-
- void complete()
- {
- manager->complete();
- }
- static void append_animation(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list, QDeclarativeAbstractAnimation *a);
- static int animation_count(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list);
- static QDeclarativeAbstractAnimation* animation_at(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list, int pos);
- static void clear_animations(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list);
- QList<QDeclarativeAbstractAnimation *> animations;
-};
-
-void QDeclarativeTransitionPrivate::append_animation(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list, QDeclarativeAbstractAnimation *a)
-{
- QDeclarativeTransition *q = static_cast<QDeclarativeTransition *>(list->object);
- q->d_func()->animations.append(a);
- q->d_func()->group.addAnimation(a->qtAnimation());
- a->setDisableUserControl();
-}
-
-int QDeclarativeTransitionPrivate::animation_count(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list)
-{
- QDeclarativeTransition *q = static_cast<QDeclarativeTransition *>(list->object);
- return q->d_func()->animations.count();
-}
-
-QDeclarativeAbstractAnimation* QDeclarativeTransitionPrivate::animation_at(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list, int pos)
-{
- QDeclarativeTransition *q = static_cast<QDeclarativeTransition *>(list->object);
- return q->d_func()->animations.at(pos);
-}
-
-void QDeclarativeTransitionPrivate::clear_animations(QDeclarativeListProperty<QDeclarativeAbstractAnimation> *list)
-{
- QDeclarativeTransition *q = static_cast<QDeclarativeTransition *>(list->object);
- while (q->d_func()->animations.count()) {
- QDeclarativeAbstractAnimation *firstAnim = q->d_func()->animations.at(0);
- q->d_func()->group.removeAnimation(firstAnim->qtAnimation());
- q->d_func()->animations.removeAll(firstAnim);
- }
-}
-
-void ParallelAnimationWrapper::updateState(QAbstractAnimation::State newState, QAbstractAnimation::State oldState)
-{
- QParallelAnimationGroup::updateState(newState, oldState);
- if (newState == Stopped && (duration() == -1
- || (direction() == QAbstractAnimation::Forward && currentLoopTime() == duration())
- || (direction() == QAbstractAnimation::Backward && currentLoopTime() == 0)))
- {
- trans->complete();
- }
-}
-
-
-
-QDeclarativeTransition::QDeclarativeTransition(QObject *parent)
- : QObject(*(new QDeclarativeTransitionPrivate), parent)
-{
-}
-
-QDeclarativeTransition::~QDeclarativeTransition()
-{
-}
-
-void QDeclarativeTransition::stop()
-{
- Q_D(QDeclarativeTransition);
- d->group.stop();
-}
-
-void QDeclarativeTransition::setReversed(bool r)
-{
- Q_D(QDeclarativeTransition);
- d->reversed = r;
-}
-
-void QDeclarativeTransition::prepare(QDeclarativeStateOperation::ActionList &actions,
- QList<QDeclarativeProperty> &after,
- QDeclarativeTransitionManager *manager)
-{
- Q_D(QDeclarativeTransition);
-
- qmlExecuteDeferred(this);
-
- if (d->reversed) {
- for (int ii = d->animations.count() - 1; ii >= 0; --ii) {
- d->animations.at(ii)->transition(actions, after, QDeclarativeAbstractAnimation::Backward);
- }
- } else {
- for (int ii = 0; ii < d->animations.count(); ++ii) {
- d->animations.at(ii)->transition(actions, after, QDeclarativeAbstractAnimation::Forward);
- }
- }
-
- d->manager = manager;
- d->group.setDirection(d->reversed ? QAbstractAnimation::Backward : QAbstractAnimation::Forward);
- d->group.start();
-}
-
-/*!
- \qmlproperty string QtQuick2::Transition::from
- \qmlproperty string QtQuick2::Transition::to
-
- These properties indicate the state changes that trigger the transition.
-
- The default values for these properties is "*" (that is, any state).
-
- For example, the following transition has not set the \c to and \c from
- properties, so the animation is always applied when changing between
- the two states (i.e. when the mouse is pressed and released).
-
- \snippet doc/src/snippets/declarative/transition-from-to.qml 0
-
- If the transition was changed to this:
-
- \snippet doc/src/snippets/declarative/transition-from-to-modified.qml modified transition
-
- The animation would only be applied when changing from the default state to
- the "brighter" state (i.e. when the mouse is pressed, but not on release).
-
- Multiple \c to and \from values can be set by using a comma-separated string.
-
- \sa reversible
-*/
-QString QDeclarativeTransition::fromState() const
-{
- Q_D(const QDeclarativeTransition);
- return d->fromState;
-}
-
-void QDeclarativeTransition::setFromState(const QString &f)
-{
- Q_D(QDeclarativeTransition);
- if (f == d->fromState)
- return;
-
- d->fromState = f;
- emit fromChanged();
-}
-
-/*!
- \qmlproperty bool QtQuick2::Transition::reversible
- This property holds whether the transition should be automatically reversed when the conditions that triggered this transition are reversed.
-
- The default value is false.
-
- By default, transitions run in parallel and are applied to all state
- changes if the \l from and \l to states have not been set. In this
- situation, the transition is automatically applied when a state change
- is reversed, and it is not necessary to set this property to reverse
- the transition.
-
- However, if a SequentialAnimation is used, or if the \l from or \l to
- properties have been set, this property will need to be set to reverse
- a transition when a state change is reverted. For example, the following
- transition applies a sequential animation when the mouse is pressed,
- and reverses the sequence of the animation when the mouse is released:
-
- \snippet doc/src/snippets/declarative/transition-reversible.qml 0
-
- If the transition did not set the \c to and \c reversible values, then
- on the mouse release, the transition would play the PropertyAnimation
- before the ColorAnimation instead of reversing the sequence.
-*/
-bool QDeclarativeTransition::reversible() const
-{
- Q_D(const QDeclarativeTransition);
- return d->reversible;
-}
-
-void QDeclarativeTransition::setReversible(bool r)
-{
- Q_D(QDeclarativeTransition);
- if (r == d->reversible)
- return;
-
- d->reversible = r;
- emit reversibleChanged();
-}
-
-QString QDeclarativeTransition::toState() const
-{
- Q_D(const QDeclarativeTransition);
- return d->toState;
-}
-
-void QDeclarativeTransition::setToState(const QString &t)
-{
- Q_D(QDeclarativeTransition);
- if (t == d->toState)
- return;
-
- d->toState = t;
- emit toChanged();
-}
-
-/*!
- \qmlproperty bool QtQuick2::Transition::enabled
-
- This property holds whether the Transition will be run when moving
- from the \c from state to the \c to state.
-
- By default a Transition is enabled.
-
- Note that in some circumstances disabling a Transition may cause an
- alternative Transition to be used in its place. In the following
- example, the generic Transition will be used to animate the change
- from \c state1 to \c state2, as the more specific Transition has
- been disabled.
-
- \qml
- Item {
- states: [
- State { name: "state1" ... }
- State { name: "state2" ... }
- ]
- transitions: [
- Transition { from: "state1"; to: "state2"; enabled: false ... }
- Transition { ... }
- ]
- }
- \endqml
-*/
-
-bool QDeclarativeTransition::enabled() const
-{
- Q_D(const QDeclarativeTransition);
- return d->enabled;
-}
-
-void QDeclarativeTransition::setEnabled(bool enabled)
-{
- Q_D(QDeclarativeTransition);
- if (d->enabled == enabled)
- return;
- d->enabled = enabled;
- emit enabledChanged();
-}
-
-/*!
- \qmlproperty list<Animation> QtQuick2::Transition::animations
- \default
-
- This property holds a list of the animations to be run for this transition.
-
- \snippet examples/declarative/toys/dynamicscene/dynamicscene.qml top-level transitions
-
- The top-level animations are run in parallel. To run them sequentially,
- define them within a SequentialAnimation:
-
- \snippet doc/src/snippets/declarative/transition-reversible.qml sequential animations
-*/
-QDeclarativeListProperty<QDeclarativeAbstractAnimation> QDeclarativeTransition::animations()
-{
- Q_D(QDeclarativeTransition);
- return QDeclarativeListProperty<QDeclarativeAbstractAnimation>(this, &d->animations, QDeclarativeTransitionPrivate::append_animation,
- QDeclarativeTransitionPrivate::animation_count,
- QDeclarativeTransitionPrivate::animation_at,
- QDeclarativeTransitionPrivate::clear_animations);
-}
-
-QT_END_NAMESPACE
-
-#include <qdeclarativetransition.moc>
diff --git a/src/declarative/util/qdeclarativetransition_p.h b/src/declarative/util/qdeclarativetransition_p.h
deleted file mode 100644
index a53346e148..0000000000
--- a/src/declarative/util/qdeclarativetransition_p.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVETRANSITION_H
-#define QDECLARATIVETRANSITION_H
-
-#include "qdeclarativestate_p.h"
-
-#include <qdeclarative.h>
-
-#include <QtCore/qobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeAbstractAnimation;
-class QDeclarativeTransitionPrivate;
-class QDeclarativeTransitionManager;
-class Q_DECLARATIVE_EXPORT QDeclarativeTransition : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDeclarativeTransition)
-
- Q_PROPERTY(QString from READ fromState WRITE setFromState NOTIFY fromChanged)
- Q_PROPERTY(QString to READ toState WRITE setToState NOTIFY toChanged)
- Q_PROPERTY(bool reversible READ reversible WRITE setReversible NOTIFY reversibleChanged)
- Q_PROPERTY(QDeclarativeListProperty<QDeclarativeAbstractAnimation> animations READ animations)
- Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
- Q_CLASSINFO("DefaultProperty", "animations")
- Q_CLASSINFO("DeferredPropertyNames", "animations")
-
-public:
- QDeclarativeTransition(QObject *parent=0);
- ~QDeclarativeTransition();
-
- QString fromState() const;
- void setFromState(const QString &);
-
- QString toState() const;
- void setToState(const QString &);
-
- bool reversible() const;
- void setReversible(bool);
-
- bool enabled() const;
- void setEnabled(bool enabled);
-
- QDeclarativeListProperty<QDeclarativeAbstractAnimation> animations();
-
- void prepare(QDeclarativeStateOperation::ActionList &actions,
- QList<QDeclarativeProperty> &after,
- QDeclarativeTransitionManager *end);
-
- void setReversed(bool r);
- void stop();
-
-Q_SIGNALS:
- void fromChanged();
- void toChanged();
- void reversibleChanged();
- void enabledChanged();
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QDeclarativeTransition)
-
-QT_END_HEADER
-
-#endif // QDECLARATIVETRANSITION_H
diff --git a/src/declarative/util/qdeclarativetransitionmanager.cpp b/src/declarative/util/qdeclarativetransitionmanager.cpp
deleted file mode 100644
index 2dd1da70ed..0000000000
--- a/src/declarative/util/qdeclarativetransitionmanager.cpp
+++ /dev/null
@@ -1,282 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativetransitionmanager_p_p.h"
-
-#include "qdeclarativetransition_p.h"
-#include "qdeclarativestate_p_p.h"
-#include "qdeclarativestate_p.h"
-
-#include <private/qdeclarativebinding_p.h>
-#include <private/qdeclarativeglobal_p.h>
-#include <private/qdeclarativeproperty_p.h>
-
-#include <QtCore/qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG);
-
-class QDeclarativeTransitionManagerPrivate
-{
-public:
- QDeclarativeTransitionManagerPrivate()
- : state(0) {}
-
- void applyBindings();
- typedef QList<QDeclarativeSimpleAction> SimpleActionList;
- QDeclarativeState *state;
- QDeclarativeGuard<QDeclarativeTransition> transition;
- QDeclarativeStateOperation::ActionList bindingsList;
- SimpleActionList completeList;
-};
-
-QDeclarativeTransitionManager::QDeclarativeTransitionManager()
-: d(new QDeclarativeTransitionManagerPrivate)
-{
-}
-
-void QDeclarativeTransitionManager::setState(QDeclarativeState *s)
-{
- d->state = s;
-}
-
-QDeclarativeTransitionManager::~QDeclarativeTransitionManager()
-{
- delete d; d = 0;
-}
-
-void QDeclarativeTransitionManager::complete()
-{
- d->applyBindings();
-
- for (int ii = 0; ii < d->completeList.count(); ++ii) {
- const QDeclarativeProperty &prop = d->completeList.at(ii).property();
- prop.write(d->completeList.at(ii).value());
- }
-
- d->completeList.clear();
-
- if (d->state)
- static_cast<QDeclarativeStatePrivate*>(QObjectPrivate::get(d->state))->complete();
-}
-
-void QDeclarativeTransitionManagerPrivate::applyBindings()
-{
- foreach(const QDeclarativeAction &action, bindingsList) {
- if (!action.toBinding.isNull()) {
- QDeclarativePropertyPrivate::setBinding(action.property, action.toBinding.data());
- } else if (action.event) {
- if (action.reverseEvent)
- action.event->reverse();
- else
- action.event->execute();
- }
-
- }
-
- bindingsList.clear();
-}
-
-void QDeclarativeTransitionManager::transition(const QList<QDeclarativeAction> &list,
- QDeclarativeTransition *transition)
-{
- cancel();
-
- QDeclarativeStateOperation::ActionList applyList = list;
- // Determine which actions are binding changes and disable any current bindings
- foreach(const QDeclarativeAction &action, applyList) {
- if (action.toBinding)
- d->bindingsList << action;
- if (action.fromBinding)
- QDeclarativePropertyPrivate::setBinding(action.property, 0); // Disable current binding
- if (action.event && action.event->changesBindings()) { //### assume isReversable()?
- d->bindingsList << action;
- action.event->clearBindings();
- }
- }
-
- // Animated transitions need both the start and the end value for
- // each property change. In the presence of bindings, the end values
- // are non-trivial to calculate. As a "best effort" attempt, we first
- // apply all the property and binding changes, then read all the actual
- // final values, then roll back the changes and proceed as normal.
- //
- // This doesn't catch everything, and it might be a little fragile in
- // some cases - but whatcha going to do?
- //
- // Note that we only fast forward if both a transition and bindings are
- // present, as it is unneccessary (and potentially expensive) otherwise.
-
- if (transition && !d->bindingsList.isEmpty()) {
-
- // Apply all the property and binding changes
- for (int ii = 0; ii < applyList.size(); ++ii) {
- const QDeclarativeAction &action = applyList.at(ii);
- if (!action.toBinding.isNull()) {
- QDeclarativePropertyPrivate::setBinding(action.property, action.toBinding.data(), QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
- } else if (!action.event) {
- QDeclarativePropertyPrivate::write(action.property, action.toValue, QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
- } else if (action.event->isReversable()) {
- if (action.reverseEvent)
- action.event->reverse(QDeclarativeActionEvent::FastForward);
- else
- action.event->execute(QDeclarativeActionEvent::FastForward);
- }
- }
-
- // Read all the end values for binding changes
- for (int ii = 0; ii < applyList.size(); ++ii) {
- QDeclarativeAction *action = &applyList[ii];
- if (action->event) {
- action->event->saveTargetValues();
- continue;
- }
- const QDeclarativeProperty &prop = action->property;
- if (!action->toBinding.isNull() || !action->toValue.isValid()) {
- action->toValue = prop.read();
- }
- }
-
- // Revert back to the original values
- foreach(const QDeclarativeAction &action, applyList) {
- if (action.event) {
- if (action.event->isReversable()) {
- action.event->clearBindings();
- action.event->rewind();
- action.event->clearBindings(); //### shouldn't be needed
- }
- continue;
- }
-
- if (action.toBinding)
- QDeclarativePropertyPrivate::setBinding(action.property, 0); // Make sure this is disabled during the transition
-
- QDeclarativePropertyPrivate::write(action.property, action.fromValue, QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding);
- }
- }
-
- if (transition) {
- QList<QDeclarativeProperty> touched;
- d->transition = transition;
- d->transition->prepare(applyList, touched, this);
-
- // Modify the action list to remove actions handled in the transition
- for (int ii = 0; ii < applyList.count(); ++ii) {
- const QDeclarativeAction &action = applyList.at(ii);
-
- if (action.event) {
-
- if (action.actionDone) {
- applyList.removeAt(ii);
- --ii;
- }
-
- } else {
-
- if (touched.contains(action.property)) {
- if (action.toValue != action.fromValue)
- d->completeList <<
- QDeclarativeSimpleAction(action, QDeclarativeSimpleAction::EndState);
-
- applyList.removeAt(ii);
- --ii;
- }
-
- }
- }
- }
-
- // Any actions remaining have not been handled by the transition and should
- // be applied immediately. We skip applying bindings, as they are all
- // applied at the end in applyBindings() to avoid any nastiness mid
- // transition
- foreach(const QDeclarativeAction &action, applyList) {
- if (action.event && !action.event->changesBindings()) {
- if (action.event->isReversable() && action.reverseEvent)
- action.event->reverse();
- else
- action.event->execute();
- } else if (!action.event && !action.toBinding) {
- action.property.write(action.toValue);
- }
- }
-#ifndef QT_NO_DEBUG_STREAM
- if (stateChangeDebug()) {
- foreach(const QDeclarativeAction &action, applyList) {
- if (action.event)
- qWarning() << " No transition for event:" << action.event->typeName();
- else
- qWarning() << " No transition for:" << action.property.object()
- << action.property.name() << "From:" << action.fromValue
- << "To:" << action.toValue;
- }
- }
-#endif
- if (!transition)
- complete();
-}
-
-void QDeclarativeTransitionManager::cancel()
-{
- if (d->transition) {
- // ### this could potentially trigger a complete in rare circumstances
- d->transition->stop();
- d->transition = 0;
- }
-
- for(int i = 0; i < d->bindingsList.count(); ++i) {
- QDeclarativeAction action = d->bindingsList[i];
- if (!action.toBinding.isNull() && action.deletableToBinding) {
- QDeclarativePropertyPrivate::setBinding(action.property, 0);
- action.toBinding.data()->destroy();
- action.toBinding.clear();
- action.deletableToBinding = false;
- } else if (action.event) {
- //### what do we do here?
- }
-
- }
- d->bindingsList.clear();
- d->completeList.clear();
-}
-
-QT_END_NAMESPACE
diff --git a/src/declarative/util/qdeclarativetransitionmanager_p_p.h b/src/declarative/util/qdeclarativetransitionmanager_p_p.h
deleted file mode 100644
index 94a2dd1539..0000000000
--- a/src/declarative/util/qdeclarativetransitionmanager_p_p.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVETRANSITIONMANAGER_P_H
-#define QDECLARATIVETRANSITIONMANAGER_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 "qdeclarativestateoperations_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QDeclarativeStatePrivate;
-class QDeclarativeTransitionManagerPrivate;
-class Q_AUTOTEST_EXPORT QDeclarativeTransitionManager
-{
-public:
- QDeclarativeTransitionManager();
- ~QDeclarativeTransitionManager();
-
- void transition(const QList<QDeclarativeAction> &, QDeclarativeTransition *transition);
-
- void cancel();
-
-private:
- Q_DISABLE_COPY(QDeclarativeTransitionManager)
- QDeclarativeTransitionManagerPrivate *d;
-
- void complete();
- void setState(QDeclarativeState *);
-
- friend class QDeclarativeState;
- friend class QDeclarativeTransitionPrivate;
-};
-
-QT_END_NAMESPACE
-
-#endif // QDECLARATIVETRANSITIONMANAGER_P_H
diff --git a/src/declarative/util/qdeclarativeutilmodule.cpp b/src/declarative/util/qdeclarativeutilmodule.cpp
deleted file mode 100644
index 2e82364a42..0000000000
--- a/src/declarative/util/qdeclarativeutilmodule.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdeclarativeutilmodule_p.h"
-#include "qdeclarativeanimation_p.h"
-#include "qdeclarativeanimation_p_p.h"
-#include "qdeclarativebehavior_p.h"
-#include "qdeclarativebind_p.h"
-#include "qdeclarativeconnections_p.h"
-#include "qdeclarativesmoothedanimation_p.h"
-#include "qdeclarativefontloader_p.h"
-#include "qdeclarativepackage_p.h"
-#include "qdeclarativepropertychanges_p.h"
-#include "qdeclarativespringanimation_p.h"
-#include "qdeclarativestategroup_p.h"
-#include "qdeclarativestateoperations_p.h"
-#include "qdeclarativestate_p.h"
-#include "qdeclarativestate_p_p.h"
-#include "qdeclarativesystempalette_p.h"
-#include "qdeclarativetimer_p.h"
-#include "qdeclarativetransition_p.h"
-#include <qdeclarativeinfo.h>
-#include <private/qdeclarativetypenotavailable_p.h>
-#include <QtCore/qcoreapplication.h>
-#include <QtGui/QInputPanel>
-
-void QDeclarativeUtilModule::defineModule()
-{
- qmlRegisterUncreatableType<QInputPanel>("QtQuick",2,0,"InputPanel", QInputPanel::tr("InputPanel is an abstract class"));
- qmlRegisterUncreatableType<QDeclarativeAbstractAnimation>("QtQuick",2,0,"Animation",QDeclarativeAbstractAnimation::tr("Animation is an abstract class"));
-
- qmlRegisterType<QDeclarativeBehavior>("QtQuick",2,0,"Behavior");
- qmlRegisterType<QDeclarativeBind>("QtQuick",2,0,"Binding");
- qmlRegisterType<QDeclarativeColorAnimation>("QtQuick",2,0,"ColorAnimation");
- qmlRegisterType<QDeclarativeConnections>("QtQuick",2,0,"Connections");
- qmlRegisterType<QDeclarativeSmoothedAnimation>("QtQuick",2,0,"SmoothedAnimation");
- qmlRegisterType<QDeclarativeFontLoader>("QtQuick",2,0,"FontLoader");
- qmlRegisterType<QDeclarativeNumberAnimation>("QtQuick",2,0,"NumberAnimation");
- qmlRegisterType<QDeclarativePackage>("QtQuick",2,0,"Package");
- qmlRegisterType<QDeclarativeParallelAnimation>("QtQuick",2,0,"ParallelAnimation");
- qmlRegisterType<QDeclarativePauseAnimation>("QtQuick",2,0,"PauseAnimation");
- qmlRegisterType<QDeclarativePropertyAction>("QtQuick",2,0,"PropertyAction");
- qmlRegisterType<QDeclarativePropertyAnimation>("QtQuick",2,0,"PropertyAnimation");
- qmlRegisterType<QDeclarativeRotationAnimation>("QtQuick",2,0,"RotationAnimation");
- qmlRegisterType<QDeclarativeScriptAction>("QtQuick",2,0,"ScriptAction");
- qmlRegisterType<QDeclarativeSequentialAnimation>("QtQuick",2,0,"SequentialAnimation");
- qmlRegisterType<QDeclarativeSpringAnimation>("QtQuick",2,0,"SpringAnimation");
- qmlRegisterType<QDeclarativeStateChangeScript>("QtQuick",2,0,"StateChangeScript");
- qmlRegisterType<QDeclarativeStateGroup>("QtQuick",2,0,"StateGroup");
- qmlRegisterType<QDeclarativeState>("QtQuick",2,0,"State");
- qmlRegisterType<QDeclarativeSystemPalette>("QtQuick",2,0,"SystemPalette");
- qmlRegisterType<QDeclarativeTimer>("QtQuick",2,0,"Timer");
- qmlRegisterType<QDeclarativeTransition>("QtQuick",2,0,"Transition");
- qmlRegisterType<QDeclarativeVector3dAnimation>("QtQuick",2,0,"Vector3dAnimation");
-
- qmlRegisterType<QDeclarativeStateOperation>();
-
- qmlRegisterCustomType<QDeclarativePropertyChanges>("QtQuick",2,0,"PropertyChanges", new QDeclarativePropertyChangesParser);
- qmlRegisterCustomType<QDeclarativeConnections>("QtQuick",2,0,"Connections", new QDeclarativeConnectionsParser);
-}
diff --git a/src/declarative/util/qdeclarativeutilmodule_p.h b/src/declarative/util/qdeclarativeutilmodule_p.h
deleted file mode 100644
index 7304f6fd77..0000000000
--- a/src/declarative/util/qdeclarativeutilmodule_p.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-** All rights reserved.
-** Contact: Nokia Corporation (qt-info@nokia.com)
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** GNU Lesser General Public License Usage
-** This file may be used under the terms of the GNU Lesser General Public
-** License version 2.1 as published by the Free Software Foundation and
-** appearing in the file LICENSE.LGPL included in the packaging of this
-** file. Please review the following information to ensure the GNU Lesser
-** General Public License version 2.1 requirements will be met:
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU General
-** Public License version 3.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of this
-** file. Please review the following information to ensure the GNU General
-** Public License version 3.0 requirements will be met:
-** http://www.gnu.org/copyleft/gpl.html.
-**
-** Other Usage
-** Alternatively, this file may be used in accordance with the terms and
-** conditions contained in a signed written agreement between you and Nokia.
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDECLARATIVEUTILMODULE_H
-#define QDECLARATIVEUTILMODULE_H
-
-#include <qdeclarative.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-
-class QDeclarativeUtilModule
-{
-public:
- static void defineModule();
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDECLARATIVEUTILMODULE_H
diff --git a/src/declarative/util/util.pri b/src/declarative/util/util.pri
index 3122cd24bb..01d4247ff8 100644
--- a/src/declarative/util/util.pri
+++ b/src/declarative/util/util.pri
@@ -1,61 +1,5 @@
SOURCES += \
- $$PWD/qdeclarativeutilmodule.cpp\
- $$PWD/qdeclarativeconnections.cpp \
- $$PWD/qdeclarativepackage.cpp \
- $$PWD/qdeclarativeanimation.cpp \
- $$PWD/qdeclarativesystempalette.cpp \
- $$PWD/qdeclarativespringanimation.cpp \
- $$PWD/qdeclarativesmoothedanimation.cpp \
- $$PWD/qdeclarativestate.cpp\
- $$PWD/qdeclarativetransitionmanager.cpp \
- $$PWD/qdeclarativestateoperations.cpp \
- $$PWD/qdeclarativepropertychanges.cpp \
- $$PWD/qdeclarativestategroup.cpp \
- $$PWD/qdeclarativetransition.cpp \
- $$PWD/qdeclarativelistaccessor.cpp \
- $$PWD/qdeclarativetimeline.cpp \
- $$PWD/qdeclarativetimer.cpp \
- $$PWD/qdeclarativebind.cpp \
- $$PWD/qdeclarativepropertymap.cpp \
- $$PWD/qdeclarativepixmapcache.cpp \
- $$PWD/qdeclarativebehavior.cpp \
- $$PWD/qdeclarativefontloader.cpp \
- $$PWD/qdeclarativestyledtext.cpp \
- $$PWD/qdeclarativepath.cpp \
- $$PWD/qdeclarativechangeset.cpp \
- $$PWD/qdeclarativelistcompositor.cpp \
- $$PWD/qdeclarativepathinterpolator.cpp \
- $$PWD/qdeclarativesvgparser.cpp
+ $$PWD/qdeclarativepropertymap.cpp
HEADERS += \
- $$PWD/qdeclarativeutilmodule_p.h\
- $$PWD/qdeclarativeconnections_p.h \
- $$PWD/qdeclarativepackage_p.h \
- $$PWD/qdeclarativeanimation_p.h \
- $$PWD/qdeclarativeanimation_p_p.h \
- $$PWD/qdeclarativesystempalette_p.h \
- $$PWD/qdeclarativespringanimation_p.h \
- $$PWD/qdeclarativesmoothedanimation_p.h \
- $$PWD/qdeclarativesmoothedanimation_p_p.h \
- $$PWD/qdeclarativestate_p.h\
- $$PWD/qdeclarativestateoperations_p.h \
- $$PWD/qdeclarativepropertychanges_p.h \
- $$PWD/qdeclarativestate_p_p.h\
- $$PWD/qdeclarativetransitionmanager_p_p.h \
- $$PWD/qdeclarativestategroup_p.h \
- $$PWD/qdeclarativetransition_p.h \
- $$PWD/qdeclarativelistaccessor_p.h \
- $$PWD/qdeclarativetimeline_p_p.h \
- $$PWD/qdeclarativetimer_p.h \
- $$PWD/qdeclarativebind_p.h \
- $$PWD/qdeclarativepropertymap.h \
- $$PWD/qdeclarativepixmapcache_p.h \
- $$PWD/qdeclarativebehavior_p.h \
- $$PWD/qdeclarativefontloader_p.h \
- $$PWD/qdeclarativestyledtext_p.h \
- $$PWD/qdeclarativepath_p.h \
- $$PWD/qdeclarativepath_p_p.h \
- $$PWD/qdeclarativechangeset_p.h \
- $$PWD/qdeclarativelistcompositor_p.h \
- $$PWD/qdeclarativepathinterpolator_p.h \
- $$PWD/qdeclarativesvgparser_p.h \ No newline at end of file
+ $$PWD/qdeclarativepropertymap.h