summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/3rdparty/clucene/src/CLucene/index/SegmentTermDocs.cpp72
-rw-r--r--src/3rdparty/clucene/src/CLucene/index/Term.cpp5
-rw-r--r--src/3rdparty/clucene/src/CLucene/queryParser/MultiFieldQueryParser.cpp61
-rw-r--r--src/3rdparty/clucene/src/CLucene/store/FSDirectory.cpp33
-rw-r--r--src/3rdparty/clucene/src/CLucene/store/FSDirectory.h4
-rw-r--r--src/3rdparty/clucene/src/CLucene/util/bufferedstream.h2
-rw-r--r--src/3rdparty/phonon/ds9/qevr9.h143
-rw-r--r--src/3rdparty/phonon/ds9/videorenderer_default.cpp153
-rw-r--r--src/3rdparty/phonon/ds9/videorenderer_default.h55
-rw-r--r--src/3rdparty/phonon/ds9/videorenderer_evr.cpp215
-rw-r--r--src/3rdparty/phonon/ds9/videorenderer_evr.h56
-rw-r--r--src/3rdparty/phonon/ds9/videorenderer_vmr9.cpp112
-rw-r--r--src/3rdparty/phonon/ds9/videorenderer_vmr9.h1
-rw-r--r--src/3rdparty/phonon/ds9/videowidget.cpp26
-rw-r--r--src/3rdparty/phonon/phonon/objectdescriptionmodel.cpp7
-rw-r--r--src/3rdparty/phonon/phonon/objectdescriptionmodel.h8
-rw-r--r--src/corelib/animation/qabstractanimation.cpp9
-rw-r--r--src/corelib/animation/qabstractanimation_p.h62
-rw-r--r--src/corelib/animation/qpropertyanimation.cpp6
-rw-r--r--src/corelib/animation/qvariantanimation.cpp4
-rw-r--r--src/corelib/codecs/qtextcodec.cpp49
-rw-r--r--src/corelib/codecs/qtextcodec.h11
-rw-r--r--src/corelib/global/qglobal.h12
-rw-r--r--src/corelib/global/qnamespace.h5
-rw-r--r--src/corelib/global/qnamespace.qdoc15
-rw-r--r--src/corelib/io/io.pri2
-rw-r--r--src/corelib/io/qdatastream.cpp232
-rw-r--r--src/corelib/io/qdatastream.h7
-rw-r--r--src/corelib/io/qdataurl.cpp101
-rw-r--r--src/corelib/io/qdataurl_p.h67
-rw-r--r--src/corelib/io/qdir.cpp369
-rw-r--r--src/corelib/io/qdir.h5
-rw-r--r--src/corelib/io/qfileinfo.cpp303
-rw-r--r--src/corelib/io/qfileinfo_p.h21
-rw-r--r--src/corelib/io/qfilesystemwatcher.cpp2
-rw-r--r--src/corelib/io/qfilesystemwatcher_dnotify.cpp13
-rw-r--r--src/corelib/io/qfilesystemwatcher_fsevents.cpp10
-rw-r--r--src/corelib/io/qfilesystemwatcher_inotify.cpp2
-rw-r--r--src/corelib/io/qfilesystemwatcher_kqueue.cpp2
-rw-r--r--src/corelib/io/qfsfileengine.cpp27
-rw-r--r--src/corelib/io/qfsfileengine_iterator_unix.cpp20
-rw-r--r--src/corelib/io/qfsfileengine_win.cpp20
-rw-r--r--src/corelib/io/qurl.h7
-rw-r--r--src/corelib/kernel/qabstractitemmodel.cpp2
-rw-r--r--src/corelib/kernel/qcoreevent.cpp3
-rw-r--r--src/corelib/kernel/qcoreevent.h1
-rw-r--r--src/corelib/kernel/qeventdispatcher_win.cpp25
-rw-r--r--src/corelib/kernel/qmetaobject.cpp105
-rw-r--r--src/corelib/kernel/qmetaobject_p.h27
-rw-r--r--src/corelib/kernel/qmetatype.cpp7
-rw-r--r--src/corelib/kernel/qmetatype.h20
-rw-r--r--src/corelib/kernel/qobject.cpp48
-rw-r--r--src/corelib/kernel/qobject_p.h4
-rw-r--r--src/corelib/plugin/qlibrary.cpp16
-rw-r--r--src/corelib/thread/qorderedmutexlocker_p.h8
-rw-r--r--src/corelib/tools/qbytearray.cpp5
-rw-r--r--src/corelib/tools/qbytearray.h1
-rw-r--r--src/corelib/tools/qhash.cpp5
-rw-r--r--src/corelib/tools/qhash.h1
-rw-r--r--src/corelib/tools/qlinkedlist.cpp5
-rw-r--r--src/corelib/tools/qlinkedlist.h1
-rw-r--r--src/corelib/tools/qlist.cpp5
-rw-r--r--src/corelib/tools/qlist.h1
-rw-r--r--src/corelib/tools/qlocale.cpp11
-rw-r--r--src/corelib/tools/qmap.cpp5
-rw-r--r--src/corelib/tools/qmap.h1
-rw-r--r--src/corelib/tools/qpoint.cpp2
-rw-r--r--src/corelib/tools/qstring.cpp10
-rw-r--r--src/corelib/tools/qstring.h1
-rw-r--r--src/corelib/tools/qstringlist.cpp10
-rw-r--r--src/corelib/tools/qvector.cpp5
-rw-r--r--src/corelib/tools/qvector.h1
-rw-r--r--src/corelib/xml/qxmlstream.cpp7
-rw-r--r--src/declarative/3rdparty/3rdparty.pri7
-rw-r--r--src/declarative/3rdparty/qlistmodelinterface.cpp109
-rw-r--r--src/declarative/3rdparty/qlistmodelinterface_p.h85
-rw-r--r--src/declarative/QmlChanges.txt122
-rw-r--r--src/declarative/debugger/debugger.pri15
-rw-r--r--src/declarative/debugger/qmldebug.cpp934
-rw-r--r--src/declarative/debugger/qmldebug_p.h366
-rw-r--r--src/declarative/debugger/qmldebugclient.cpp207
-rw-r--r--src/declarative/debugger/qmldebugclient_p.h99
-rw-r--r--src/declarative/debugger/qmldebuggerstatus.cpp54
-rw-r--r--src/declarative/debugger/qmldebuggerstatus_p.h66
-rw-r--r--src/declarative/debugger/qmldebugservice.cpp393
-rw-r--r--src/declarative/debugger/qmldebugservice_p.h90
-rw-r--r--src/declarative/debugger/qpacketprotocol.cpp498
-rw-r--r--src/declarative/debugger/qpacketprotocol_p.h122
-rw-r--r--src/declarative/declarative.pro30
-rw-r--r--src/declarative/graphicsitems/graphicsitems.pri90
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsanchors.cpp1060
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsanchors_p.h196
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsanchors_p_p.h174
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsanimatedimage.cpp305
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsanimatedimage_p.h106
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsanimatedimage_p_p.h82
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsborderimage.cpp409
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsborderimage_p.h103
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsborderimage_p_p.h97
-rw-r--r--src/declarative/graphicsitems/qmlgraphicseffects.cpp183
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsevents.cpp195
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsevents_p_p.h137
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsflickable.cpp1374
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsflickable_p.h210
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsflickable_p_p.h164
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsflipable.cpp239
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsflipable_p.h95
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsfocuspanel.cpp90
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsfocuspanel_p.h77
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsfocusscope.cpp71
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsfocusscope_p.h68
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsgraphicsobjectcontainer.cpp271
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsgraphicsobjectcontainer_p.h90
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsgridview.cpp1761
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsgridview_p.h164
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsimage.cpp369
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsimage_p.h102
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsimage_p_p.h79
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsimagebase.cpp191
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsimagebase_p.h92
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsimagebase_p_p.h84
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsitem.cpp3099
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsitem.h239
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsitem_p.h287
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsitemchangelistener_p.h76
-rw-r--r--src/declarative/graphicsitems/qmlgraphicslayoutitem.cpp108
-rw-r--r--src/declarative/graphicsitems/qmlgraphicslayoutitem_p.h94
-rw-r--r--src/declarative/graphicsitems/qmlgraphicslistview.cpp2748
-rw-r--r--src/declarative/graphicsitems/qmlgraphicslistview_p.h238
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsloader.cpp488
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsloader_p.h109
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsloader_p_p.h88
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsmouseregion.cpp653
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsmouseregion_p.h177
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsmouseregion_p_p.h117
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspainteditem.cpp466
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspainteditem_p.h114
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspainteditem_p_p.h90
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsparticles.cpp1241
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsparticles_p.h247
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspath.cpp850
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspath_p.h262
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspath_p_p.h81
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspathview.cpp971
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspathview_p.h134
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspathview_p_p.h144
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspositioners.cpp851
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspositioners_p.h192
-rw-r--r--src/declarative/graphicsitems/qmlgraphicspositioners_p_p.h136
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsrectangle.cpp467
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsrectangle_p.h186
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsrectangle_p_p.h109
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsrepeater.cpp320
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsrepeater_p.h102
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsrepeater_p_p.h82
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsscalegrid.cpp213
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsscalegrid_p_p.h133
-rw-r--r--src/declarative/graphicsitems/qmlgraphicstext.cpp927
-rw-r--r--src/declarative/graphicsitems/qmlgraphicstext_p.h160
-rw-r--r--src/declarative/graphicsitems/qmlgraphicstext_p_p.h127
-rw-r--r--src/declarative/graphicsitems/qmlgraphicstextedit.cpp1035
-rw-r--r--src/declarative/graphicsitems/qmlgraphicstextedit_p.h240
-rw-r--r--src/declarative/graphicsitems/qmlgraphicstextedit_p_p.h113
-rw-r--r--src/declarative/graphicsitems/qmlgraphicstextinput.cpp916
-rw-r--r--src/declarative/graphicsitems/qmlgraphicstextinput_p.h230
-rw-r--r--src/declarative/graphicsitems/qmlgraphicstextinput_p_p.h114
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsvisualitemmodel.cpp1155
-rw-r--r--src/declarative/graphicsitems/qmlgraphicsvisualitemmodel_p.h207
-rw-r--r--src/declarative/graphicsitems/qmlgraphicswebview.cpp1351
-rw-r--r--src/declarative/graphicsitems/qmlgraphicswebview_p.h257
-rw-r--r--src/declarative/graphicsitems/qmlgraphicswebview_p_p.h151
-rw-r--r--src/declarative/qml/parser/parser.pri21
-rw-r--r--src/declarative/qml/parser/qmljs.g3075
-rw-r--r--src/declarative/qml/parser/qmljsast.cpp955
-rw-r--r--src/declarative/qml/parser/qmljsast_p.h2678
-rw-r--r--src/declarative/qml/parser/qmljsastfwd_p.h189
-rw-r--r--src/declarative/qml/parser/qmljsastvisitor.cpp58
-rw-r--r--src/declarative/qml/parser/qmljsastvisitor_p.h335
-rw-r--r--src/declarative/qml/parser/qmljsengine_p.cpp212
-rw-r--r--src/declarative/qml/parser/qmljsengine_p.h173
-rw-r--r--src/declarative/qml/parser/qmljsglobal_p.h64
-rw-r--r--src/declarative/qml/parser/qmljsgrammar.cpp939
-rw-r--r--src/declarative/qml/parser/qmljsgrammar_p.h209
-rw-r--r--src/declarative/qml/parser/qmljslexer.cpp1161
-rw-r--r--src/declarative/qml/parser/qmljslexer_p.h249
-rw-r--r--src/declarative/qml/parser/qmljsmemorypool_p.h133
-rw-r--r--src/declarative/qml/parser/qmljsnodepool_p.h139
-rw-r--r--src/declarative/qml/parser/qmljsparser.cpp1843
-rw-r--r--src/declarative/qml/parser/qmljsparser_p.h246
-rw-r--r--src/declarative/qml/qbitfield_p.h165
-rw-r--r--src/declarative/qml/qmetaobjectbuilder.cpp2575
-rw-r--r--src/declarative/qml/qmetaobjectbuilder_p.h321
-rw-r--r--src/declarative/qml/qml.h155
-rw-r--r--src/declarative/qml/qml.pri123
-rw-r--r--src/declarative/qml/qmlbinding.cpp304
-rw-r--r--src/declarative/qml/qmlbinding.h129
-rw-r--r--src/declarative/qml/qmlbinding_p.h89
-rw-r--r--src/declarative/qml/qmlboundsignal.cpp264
-rw-r--r--src/declarative/qml/qmlboundsignal_p.h100
-rw-r--r--src/declarative/qml/qmlclassfactory.cpp50
-rw-r--r--src/declarative/qml/qmlclassfactory_p.h74
-rw-r--r--src/declarative/qml/qmlcleanup.cpp85
-rw-r--r--src/declarative/qml/qmlcleanup_p.h79
-rw-r--r--src/declarative/qml/qmlcompiledbindings.cpp2720
-rw-r--r--src/declarative/qml/qmlcompiledbindings_p.h116
-rw-r--r--src/declarative/qml/qmlcompileddata.cpp239
-rw-r--r--src/declarative/qml/qmlcompiler.cpp2815
-rw-r--r--src/declarative/qml/qmlcompiler_p.h337
-rw-r--r--src/declarative/qml/qmlcomponent.cpp798
-rw-r--r--src/declarative/qml/qmlcomponent.h134
-rw-r--r--src/declarative/qml/qmlcomponent_p.h147
-rw-r--r--src/declarative/qml/qmlcompositetypedata_p.h150
-rw-r--r--src/declarative/qml/qmlcompositetypemanager.cpp670
-rw-r--r--src/declarative/qml/qmlcompositetypemanager_p.h117
-rw-r--r--src/declarative/qml/qmlcontext.cpp544
-rw-r--r--src/declarative/qml/qmlcontext.h105
-rw-r--r--src/declarative/qml/qmlcontext_p.h192
-rw-r--r--src/declarative/qml/qmlcontextscriptclass.cpp270
-rw-r--r--src/declarative/qml/qmlcontextscriptclass_p.h101
-rw-r--r--src/declarative/qml/qmlcustomparser.cpp263
-rw-r--r--src/declarative/qml/qmlcustomparser_p.h146
-rw-r--r--src/declarative/qml/qmlcustomparser_p_p.h89
-rw-r--r--src/declarative/qml/qmldeclarativedata_p.h138
-rw-r--r--src/declarative/qml/qmldom.cpp1837
-rw-r--r--src/declarative/qml/qmldom.h349
-rw-r--r--src/declarative/qml/qmldom_p.h157
-rw-r--r--src/declarative/qml/qmlengine.cpp1659
-rw-r--r--src/declarative/qml/qmlengine.h106
-rw-r--r--src/declarative/qml/qmlengine_p.h320
-rw-r--r--src/declarative/qml/qmlenginedebug.cpp457
-rw-r--r--src/declarative/qml/qmlenginedebug_p.h121
-rw-r--r--src/declarative/qml/qmlerror.cpp257
-rw-r--r--src/declarative/qml/qmlerror.h86
-rw-r--r--src/declarative/qml/qmlexpression.cpp831
-rw-r--r--src/declarative/qml/qmlexpression.h118
-rw-r--r--src/declarative/qml/qmlexpression_p.h187
-rw-r--r--src/declarative/qml/qmlglobal_p.h91
-rw-r--r--src/declarative/qml/qmlglobalscriptclass.cpp121
-rw-r--r--src/declarative/qml/qmlglobalscriptclass_p.h83
-rw-r--r--src/declarative/qml/qmlguard_p.h156
-rw-r--r--src/declarative/qml/qmlinfo.cpp127
-rw-r--r--src/declarative/qml/qmlinfo.h92
-rw-r--r--src/declarative/qml/qmlinstruction.cpp216
-rw-r--r--src/declarative/qml/qmlinstruction_p.h321
-rw-r--r--src/declarative/qml/qmlintegercache.cpp86
-rw-r--r--src/declarative/qml/qmlintegercache_p.h111
-rw-r--r--src/declarative/qml/qmllist.h126
-rw-r--r--src/declarative/qml/qmllistscriptclass.cpp173
-rw-r--r--src/declarative/qml/qmllistscriptclass_p.h86
-rw-r--r--src/declarative/qml/qmlmetaproperty.cpp1245
-rw-r--r--src/declarative/qml/qmlmetaproperty.h148
-rw-r--r--src/declarative/qml/qmlmetaproperty_p.h124
-rw-r--r--src/declarative/qml/qmlmetatype.cpp1301
-rw-r--r--src/declarative/qml/qmlmetatype.h301
-rw-r--r--src/declarative/qml/qmlmoduleplugin.cpp111
-rw-r--r--src/declarative/qml/qmlmoduleplugin.h86
-rw-r--r--src/declarative/qml/qmlnetworkaccessmanagerfactory.cpp79
-rw-r--r--src/declarative/qml/qmlnetworkaccessmanagerfactory.h66
-rw-r--r--src/declarative/qml/qmlobjectscriptclass.cpp675
-rw-r--r--src/declarative/qml/qmlobjectscriptclass_p.h144
-rw-r--r--src/declarative/qml/qmlparser.cpp387
-rw-r--r--src/declarative/qml/qmlparser_p.h357
-rw-r--r--src/declarative/qml/qmlparserstatus.cpp80
-rw-r--r--src/declarative/qml/qmlparserstatus.h75
-rw-r--r--src/declarative/qml/qmlprivate.cpp48
-rw-r--r--src/declarative/qml/qmlprivate.h386
-rw-r--r--src/declarative/qml/qmlpropertycache.cpp415
-rw-r--r--src/declarative/qml/qmlpropertycache_p.h194
-rw-r--r--src/declarative/qml/qmlpropertyvalueinterceptor.cpp79
-rw-r--r--src/declarative/qml/qmlpropertyvalueinterceptor.h68
-rw-r--r--src/declarative/qml/qmlpropertyvaluesource.cpp71
-rw-r--r--src/declarative/qml/qmlpropertyvaluesource.h67
-rw-r--r--src/declarative/qml/qmlproxymetaobject.cpp138
-rw-r--r--src/declarative/qml/qmlproxymetaobject_p.h100
-rw-r--r--src/declarative/qml/qmlrefcount.cpp70
-rw-r--r--src/declarative/qml/qmlrefcount_p.h80
-rw-r--r--src/declarative/qml/qmlrewrite.cpp215
-rw-r--r--src/declarative/qml/qmlrewrite_p.h121
-rw-r--r--src/declarative/qml/qmlscript.cpp87
-rw-r--r--src/declarative/qml/qmlscriptclass_p.h89
-rw-r--r--src/declarative/qml/qmlscriptparser.cpp952
-rw-r--r--src/declarative/qml/qmlscriptparser_p.h137
-rw-r--r--src/declarative/qml/qmlscriptstring.cpp154
-rw-r--r--src/declarative/qml/qmlscriptstring.h87
-rw-r--r--src/declarative/qml/qmlsqldatabase.cpp425
-rw-r--r--src/declarative/qml/qmlsqldatabase_p.h60
-rw-r--r--src/declarative/qml/qmlstringconverters.cpp276
-rw-r--r--src/declarative/qml/qmlstringconverters_p.h87
-rw-r--r--src/declarative/qml/qmltypenamecache.cpp103
-rw-r--r--src/declarative/qml/qmltypenamecache_p.h117
-rw-r--r--src/declarative/qml/qmltypenamescriptclass.cpp166
-rw-r--r--src/declarative/qml/qmltypenamescriptclass_p.h93
-rw-r--r--src/declarative/qml/qmlvaluetype.cpp636
-rw-r--r--src/declarative/qml/qmlvaluetype_p.h340
-rw-r--r--src/declarative/qml/qmlvaluetypescriptclass.cpp148
-rw-r--r--src/declarative/qml/qmlvaluetypescriptclass_p.h86
-rw-r--r--src/declarative/qml/qmlvme.cpp891
-rw-r--r--src/declarative/qml/qmlvme_p.h119
-rw-r--r--src/declarative/qml/qmlvmemetaobject.cpp340
-rw-r--r--src/declarative/qml/qmlvmemetaobject_p.h172
-rw-r--r--src/declarative/qml/qmlwatcher.cpp185
-rw-r--r--src/declarative/qml/qmlwatcher_p.h94
-rw-r--r--src/declarative/qml/qmlworkerscript.cpp1037
-rw-r--r--src/declarative/qml/qmlworkerscript_p.h160
-rw-r--r--src/declarative/qml/qmlxmlhttprequest.cpp1627
-rw-r--r--src/declarative/qml/qmlxmlhttprequest_p.h60
-rw-r--r--src/declarative/qml/qpodvector_p.h173
-rw-r--r--src/declarative/qml/rewriter/rewriter.cpp102
-rw-r--r--src/declarative/qml/rewriter/rewriter.pri9
-rw-r--r--src/declarative/qml/rewriter/rewriter_p.h153
-rw-r--r--src/declarative/qml/rewriter/textwriter.cpp217
-rw-r--r--src/declarative/qml/rewriter/textwriter_p.h101
-rw-r--r--src/declarative/util/qfxperf.cpp67
-rw-r--r--src/declarative/util/qfxperf_p_p.h90
-rw-r--r--src/declarative/util/qmlanimation.cpp2337
-rw-r--r--src/declarative/util/qmlanimation_p.h440
-rw-r--r--src/declarative/util/qmlanimation_p_p.h384
-rw-r--r--src/declarative/util/qmlbehavior.cpp189
-rw-r--r--src/declarative/util/qmlbehavior_p.h92
-rw-r--r--src/declarative/util/qmlbind.cpp201
-rw-r--r--src/declarative/util/qmlbind_p.h95
-rw-r--r--src/declarative/util/qmlconnection.cpp287
-rw-r--r--src/declarative/util/qmlconnection_p.h93
-rw-r--r--src/declarative/util/qmldatetimeformatter.cpp372
-rw-r--r--src/declarative/util/qmldatetimeformatter_p.h117
-rw-r--r--src/declarative/util/qmleasefollow.cpp527
-rw-r--r--src/declarative/util/qmleasefollow_p.h114
-rw-r--r--src/declarative/util/qmlfontloader.cpp229
-rw-r--r--src/declarative/util/qmlfontloader_p.h95
-rw-r--r--src/declarative/util/qmllistaccessor.cpp260
-rw-r--r--src/declarative/util/qmllistaccessor_p.h85
-rw-r--r--src/declarative/util/qmllistmodel.cpp990
-rw-r--r--src/declarative/util/qmllistmodel_p.h107
-rw-r--r--src/declarative/util/qmlnullablevalue_p_p.h81
-rw-r--r--src/declarative/util/qmlnumberformatter.cpp260
-rw-r--r--src/declarative/util/qmlnumberformatter_p.h93
-rw-r--r--src/declarative/util/qmlopenmetaobject.cpp355
-rw-r--r--src/declarative/util/qmlopenmetaobject_p.h125
-rw-r--r--src/declarative/util/qmlpackage.cpp177
-rw-r--r--src/declarative/util/qmlpackage_p.h88
-rw-r--r--src/declarative/util/qmlpixmapcache.cpp605
-rw-r--r--src/declarative/util/qmlpixmapcache_p.h107
-rw-r--r--src/declarative/util/qmlpropertychanges.cpp468
-rw-r--r--src/declarative/util/qmlpropertychanges_p.h84
-rw-r--r--src/declarative/util/qmlpropertymap.cpp278
-rw-r--r--src/declarative/util/qmlpropertymap.h90
-rw-r--r--src/declarative/util/qmlspringfollow.cpp464
-rw-r--r--src/declarative/util/qmlspringfollow_p.h112
-rw-r--r--src/declarative/util/qmlstate.cpp468
-rw-r--r--src/declarative/util/qmlstate_p.h178
-rw-r--r--src/declarative/util/qmlstate_p_p.h147
-rw-r--r--src/declarative/util/qmlstategroup.cpp423
-rw-r--r--src/declarative/util/qmlstategroup_p.h95
-rw-r--r--src/declarative/util/qmlstateoperations.cpp834
-rw-r--r--src/declarative/util/qmlstateoperations_p.h184
-rw-r--r--src/declarative/util/qmlstyledtext.cpp343
-rw-r--r--src/declarative/util/qmlstyledtext_p.h63
-rw-r--r--src/declarative/util/qmlsystempalette.cpp303
-rw-r--r--src/declarative/util/qmlsystempalette_p.h122
-rw-r--r--src/declarative/util/qmltimeline.cpp941
-rw-r--r--src/declarative/util/qmltimeline_p_p.h223
-rw-r--r--src/declarative/util/qmltimer.cpp313
-rw-r--r--src/declarative/util/qmltimer_p.h109
-rw-r--r--src/declarative/util/qmltransition.cpp261
-rw-r--r--src/declarative/util/qmltransition_p.h101
-rw-r--r--src/declarative/util/qmltransitionmanager.cpp282
-rw-r--r--src/declarative/util/qmltransitionmanager_p_p.h85
-rw-r--r--src/declarative/util/qmlview.cpp586
-rw-r--r--src/declarative/util/qmlview.h113
-rw-r--r--src/declarative/util/qmlxmllistmodel.cpp728
-rw-r--r--src/declarative/util/qmlxmllistmodel_p.h136
-rw-r--r--src/declarative/util/qnumberformat.cpp225
-rw-r--r--src/declarative/util/qnumberformat_p.h174
-rw-r--r--src/declarative/util/qperformancelog.cpp181
-rw-r--r--src/declarative/util/qperformancelog_p_p.h141
-rw-r--r--src/declarative/util/util.pri72
-rw-r--r--src/declarative/widgets/graphicslayouts.cpp319
-rw-r--r--src/declarative/widgets/graphicslayouts_p.h183
-rw-r--r--src/declarative/widgets/graphicswidgets.cpp163
-rw-r--r--src/declarative/widgets/graphicswidgets_p.h68
-rw-r--r--src/declarative/widgets/widgets.pri9
-rw-r--r--src/gui/dialogs/dialogs.pri3
-rw-r--r--src/gui/dialogs/qdialog.cpp7
-rw-r--r--src/gui/dialogs/qfiledialog_win.cpp78
-rw-r--r--src/gui/dialogs/qfiledialog_win_p.h243
-rw-r--r--src/gui/dialogs/qfileinfogatherer.cpp1
-rw-r--r--src/gui/dialogs/qfileinfogatherer_p.h1
-rw-r--r--src/gui/dialogs/qfilesystemmodel.cpp122
-rw-r--r--src/gui/dialogs/qfilesystemmodel.h1
-rw-r--r--src/gui/dialogs/qfilesystemmodel_p.h4
-rw-r--r--src/gui/dialogs/qmessagebox.cpp4
-rw-r--r--src/gui/dialogs/qprintdialog_win.cpp2
-rw-r--r--src/gui/embedded/qscreen_qws.cpp21
-rw-r--r--src/gui/graphicsview/qgraphicsitem.cpp9
-rw-r--r--src/gui/graphicsview/qgraphicsscene.cpp2
-rw-r--r--src/gui/graphicsview/qgraphicswidget.cpp30
-rw-r--r--src/gui/graphicsview/qgraphicswidget.h4
-rw-r--r--src/gui/graphicsview/qgraphicswidget_p.h2
-rw-r--r--src/gui/image/qimage.cpp40
-rw-r--r--src/gui/image/qimage.h2
-rw-r--r--src/gui/image/qpicture.cpp49
-rw-r--r--src/gui/image/qpixmap.cpp28
-rw-r--r--src/gui/image/qpixmap.h4
-rw-r--r--src/gui/image/qpixmap_x11.cpp26
-rw-r--r--src/gui/image/qpixmap_x11_p.h2
-rw-r--r--src/gui/image/qpnghandler.cpp137
-rw-r--r--src/gui/inputmethod/qwininputcontext_p.h2
-rw-r--r--src/gui/itemviews/qdirmodel.cpp4
-rw-r--r--src/gui/itemviews/qfileiconprovider.cpp2
-rw-r--r--src/gui/itemviews/qheaderview.cpp14
-rw-r--r--src/gui/itemviews/qsortfilterproxymodel.cpp17
-rw-r--r--src/gui/kernel/kernel.pri1
-rw-r--r--src/gui/kernel/qaction.h3
-rw-r--r--src/gui/kernel/qapplication.cpp256
-rw-r--r--src/gui/kernel/qapplication_mac.mm57
-rw-r--r--src/gui/kernel/qapplication_p.h13
-rw-r--r--src/gui/kernel/qapplication_x11.cpp5
-rw-r--r--src/gui/kernel/qcocoaapplicationdelegate_mac.mm7
-rw-r--r--src/gui/kernel/qcocoapanel_mac.mm1
-rw-r--r--src/gui/kernel/qcocoapanel_mac_p.h6
-rw-r--r--src/gui/kernel/qcocoasharedwindowmethods_mac_p.h188
-rw-r--r--src/gui/kernel/qcocoaview_mac.mm76
-rw-r--r--src/gui/kernel/qcocoaview_mac_p.h2
-rw-r--r--src/gui/kernel/qcocoawindow_mac.mm1
-rw-r--r--src/gui/kernel/qcocoawindow_mac_p.h3
-rw-r--r--src/gui/kernel/qcocoawindowdelegate_mac.mm7
-rw-r--r--src/gui/kernel/qcursor.cpp6
-rw-r--r--src/gui/kernel/qcursor_mac.mm24
-rw-r--r--src/gui/kernel/qcursor_win.cpp7
-rw-r--r--src/gui/kernel/qcursor_x11.cpp50
-rw-r--r--src/gui/kernel/qdnd.cpp218
-rw-r--r--src/gui/kernel/qdnd_p.h2
-rw-r--r--src/gui/kernel/qdnd_x11.cpp6
-rw-r--r--src/gui/kernel/qeventdispatcher_mac.mm415
-rw-r--r--src/gui/kernel/qeventdispatcher_mac_p.h11
-rw-r--r--src/gui/kernel/qguieventdispatcher_glib.cpp5
-rw-r--r--src/gui/kernel/qguieventdispatcher_glib_p.h1
-rw-r--r--src/gui/kernel/qkeysequence.cpp36
-rw-r--r--src/gui/kernel/qkeysequence.h12
-rw-r--r--src/gui/kernel/qmime_mac.cpp57
-rw-r--r--src/gui/kernel/qnsthemeframe_mac_p.h2
-rw-r--r--src/gui/kernel/qsoftkeymanager_s60.cpp16
-rw-r--r--src/gui/kernel/qsoftkeymanager_s60_p.h1
-rw-r--r--src/gui/kernel/qt_cocoa_helpers_mac.mm15
-rw-r--r--src/gui/kernel/qt_cocoa_helpers_mac_p.h4
-rw-r--r--src/gui/kernel/qt_x11_p.h2
-rw-r--r--src/gui/kernel/qwidget.cpp198
-rw-r--r--src/gui/kernel/qwidget_mac.mm180
-rw-r--r--src/gui/kernel/qwidget_p.h5
-rw-r--r--src/gui/kernel/qwidget_win.cpp21
-rw-r--r--src/gui/mac/qt_menu.nib/classes.nib16
-rw-r--r--src/gui/mac/qt_menu.nib/info.nib4
-rw-r--r--src/gui/mac/qt_menu.nib/keyedobjects.nibbin5567 -> 5560 bytes
-rw-r--r--src/gui/math3d/qmatrix4x4.h2
-rw-r--r--src/gui/math3d/qquaternion.h2
-rw-r--r--src/gui/math3d/qvector2d.h2
-rw-r--r--src/gui/math3d/qvector3d.h2
-rw-r--r--src/gui/math3d/qvector4d.h2
-rw-r--r--src/gui/painting/qbrush.cpp36
-rw-r--r--src/gui/painting/qdatabuffer_p.h7
-rw-r--r--src/gui/painting/qemulationpaintengine.cpp30
-rw-r--r--src/gui/painting/qpainterpath.cpp2
-rw-r--r--src/gui/painting/qwindowsurface_s60.cpp10
-rw-r--r--src/gui/statemachine/qguistatemachine.cpp6
-rw-r--r--src/gui/styles/qcommonstyle.cpp198
-rw-r--r--src/gui/styles/qmacstyle_mac.mm13
-rw-r--r--src/gui/styles/qs60style.cpp45
-rw-r--r--src/gui/styles/qs60style_p.h2
-rw-r--r--src/gui/styles/qs60style_s60.cpp6
-rw-r--r--src/gui/styles/qs60style_simulated.cpp12
-rw-r--r--src/gui/styles/qstylesheetstyle.cpp8
-rw-r--r--src/gui/text/qfontdatabase_win.cpp1
-rw-r--r--src/gui/text/qtextcontrol.cpp12
-rw-r--r--src/gui/text/qtextdocument.cpp22
-rw-r--r--src/gui/text/qtextdocument.h7
-rw-r--r--src/gui/text/qtextdocument_p.cpp63
-rw-r--r--src/gui/text/qtextdocument_p.h3
-rw-r--r--src/gui/text/qzipreader_p.h4
-rw-r--r--src/gui/util/qcompleter.cpp77
-rw-r--r--src/gui/util/qcompleter.h1
-rw-r--r--src/gui/util/qcompleter_p.h1
-rw-r--r--src/gui/util/qdesktopservices_win.cpp16
-rw-r--r--src/gui/util/qsystemtrayicon_win.cpp3
-rw-r--r--src/gui/widgets/qcocoamenu_mac.mm33
-rw-r--r--src/gui/widgets/qcocoamenu_mac_p.h4
-rw-r--r--src/gui/widgets/qcombobox.cpp5
-rw-r--r--src/gui/widgets/qdatetimeedit.cpp2
-rw-r--r--src/gui/widgets/qdockarealayout.cpp62
-rw-r--r--src/gui/widgets/qdockarealayout_p.h5
-rw-r--r--src/gui/widgets/qfocusframe.cpp91
-rw-r--r--src/gui/widgets/qlabel.cpp93
-rw-r--r--src/gui/widgets/qlabel.h7
-rw-r--r--src/gui/widgets/qlineedit.cpp18
-rw-r--r--src/gui/widgets/qmainwindow.cpp13
-rw-r--r--src/gui/widgets/qmenu.cpp4
-rw-r--r--src/gui/widgets/qmenu.h1
-rw-r--r--src/gui/widgets/qmenu_mac.mm190
-rw-r--r--src/gui/widgets/qplaintextedit.cpp1
-rw-r--r--src/gui/widgets/qtabbar.cpp4
-rw-r--r--src/gui/widgets/qtabbar_p.h3
-rw-r--r--src/gui/widgets/qtextedit.cpp13
-rw-r--r--src/gui/widgets/qtoolbar.cpp9
-rw-r--r--src/gui/widgets/qtoolbar.h1
-rw-r--r--src/gui/widgets/qvalidator.cpp20
-rw-r--r--src/gui/widgets/qvalidator.h6
-rw-r--r--src/multimedia/audio/qaudiodeviceinfo.cpp34
-rw-r--r--src/multimedia/audio/qaudiodeviceinfo.h2
-rw-r--r--src/multimedia/audio/qaudiodeviceinfo_win32_p.cpp4
-rw-r--r--src/multimedia/audio/qaudioformat.cpp66
-rw-r--r--src/multimedia/audio/qaudioformat.h4
-rw-r--r--src/multimedia/audio/qaudioinput_win32_p.cpp5
-rw-r--r--src/multimedia/video/qabstractvideobuffer.cpp1
-rw-r--r--src/multimedia/video/qabstractvideosurface.cpp1
-rw-r--r--src/multimedia/video/qvideoframe.cpp1
-rw-r--r--src/multimedia/video/qvideosurfaceformat.cpp1
-rw-r--r--src/network/access/qnetworkaccessdatabackend.cpp62
-rw-r--r--src/network/access/qnetworkaccesshttpbackend.cpp14
-rw-r--r--src/network/access/qnetworkaccessmanager.cpp2
-rw-r--r--src/network/access/qnetworkreply.cpp15
-rw-r--r--src/network/access/qnetworkreply.h3
-rw-r--r--src/network/access/qnetworkrequest.cpp45
-rw-r--r--src/network/access/qnetworkrequest.h9
-rw-r--r--src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp2
-rw-r--r--src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp186
-rw-r--r--src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h2
-rw-r--r--src/opengl/gl2paintengineex/qtriangulator.cpp2983
-rw-r--r--src/opengl/gl2paintengineex/qtriangulator_p.h98
-rw-r--r--src/opengl/opengl.pro12
-rw-r--r--src/opengl/qgl.cpp226
-rw-r--r--src/opengl/qgl.h25
-rw-r--r--src/opengl/qgl_cl_p.h141
-rw-r--r--src/opengl/qgl_p.h34
-rw-r--r--src/opengl/qgl_win.cpp158
-rw-r--r--src/opengl/qglbuffer.cpp454
-rw-r--r--src/opengl/qglbuffer.h124
-rw-r--r--src/opengl/qglextensions.cpp32
-rw-r--r--src/opengl/qglextensions_p.h94
-rw-r--r--src/opengl/qglframebufferobject.cpp10
-rw-r--r--src/opengl/qglpaintdevice.cpp8
-rw-r--r--src/opengl/qglpixelbuffer.cpp6
-rw-r--r--src/opengl/qglpixelbuffer_egl.cpp4
-rw-r--r--src/opengl/qglshaderprogram.cpp393
-rw-r--r--src/opengl/qglshaderprogram.h50
-rw-r--r--src/opengl/qgraphicsshadereffect.cpp2
-rw-r--r--src/opengl/qpaintengine_opengl.cpp197
-rw-r--r--src/opengl/qpixmapdata_x11gl_egl.cpp8
-rw-r--r--src/opengl/qwindowsurface_gl.cpp22
-rw-r--r--src/openvg/qpaintengine_vg.cpp21
-rw-r--r--src/openvg/qpixmapdata_vg.cpp12
-rw-r--r--src/plugins/accessible/widgets/qaccessiblewidgets.cpp2
-rw-r--r--src/plugins/graphicssystems/opengl/main.cpp4
-rw-r--r--src/plugins/imageformats/jpeg/qjpeghandler.cpp574
-rw-r--r--src/plugins/phonon/ds9/ds9.pro10
-rw-r--r--src/plugins/qpluginbase.pri2
-rw-r--r--src/qbase.pri2
-rw-r--r--src/s60installs/qt.iby3
-rw-r--r--src/script/api/qscriptprogram.cpp9
-rw-r--r--src/script/api/qscriptprogram_p.h4
-rw-r--r--src/script/bridge/qscriptdeclarativeclass.cpp192
-rw-r--r--src/script/bridge/qscriptdeclarativeclass_p.h37
-rw-r--r--src/script/bridge/qscriptdeclarativeobject.cpp35
-rw-r--r--src/script/bridge/qscriptdeclarativeobject_p.h6
-rw-r--r--src/scripttools/debugging/qscriptdebuggerconsole.cpp221
-rw-r--r--src/scripttools/debugging/qscriptdebuggerlocalsmodel.cpp55
-rw-r--r--src/scripttools/debugging/qscriptdebuggerlocalswidget.cpp5
-rw-r--r--src/scripttools/debugging/qscriptdebuggerscriptedconsolecommand.cpp237
-rw-r--r--src/scripttools/debugging/qscriptdebuggerscriptedconsolecommand_p.h4
-rw-r--r--src/sql/drivers/odbc/qsql_odbc.cpp20
-rw-r--r--src/sql/drivers/odbc/qsql_odbc.h10
-rw-r--r--src/testlib/qbenchmark.cpp53
-rw-r--r--src/testlib/qbenchmark.h10
-rw-r--r--src/testlib/qbenchmark_p.h26
-rw-r--r--src/testlib/qbenchmarkevent.cpp10
-rw-r--r--src/testlib/qbenchmarkevent_p.h3
-rw-r--r--src/testlib/qbenchmarkmeasurement.cpp20
-rw-r--r--src/testlib/qbenchmarkmeasurement_p.h10
-rw-r--r--src/testlib/qbenchmarkmetric.cpp115
-rw-r--r--src/testlib/qbenchmarkmetric.h71
-rw-r--r--src/testlib/qbenchmarkmetric_p.h63
-rw-r--r--src/testlib/qbenchmarkvalgrind.cpp9
-rw-r--r--src/testlib/qbenchmarkvalgrind_p.h4
-rw-r--r--src/testlib/qplaintestlogger.cpp33
-rw-r--r--src/testlib/qtestcase.cpp14
-rw-r--r--src/testlib/qtestcoreelement.h5
-rw-r--r--src/testlib/qtestlogger.cpp4
-rw-r--r--src/testlib/qxmltestlogger.cpp3
-rw-r--r--src/testlib/testlib.pro1
-rw-r--r--src/tools/moc/generator.cpp2
-rw-r--r--src/xmlpatterns/type/qprimitives_p.h14
589 files changed, 116710 insertions, 3647 deletions
diff --git a/src/3rdparty/clucene/src/CLucene/index/SegmentTermDocs.cpp b/src/3rdparty/clucene/src/CLucene/index/SegmentTermDocs.cpp
index f4c5e3a..50951e9 100644
--- a/src/3rdparty/clucene/src/CLucene/index/SegmentTermDocs.cpp
+++ b/src/3rdparty/clucene/src/CLucene/index/SegmentTermDocs.cpp
@@ -112,47 +112,51 @@ CL_NS_DEF(index)
return _freq;
}
- bool SegmentTermDocs::next() {
- while (true) {
- if (count == df)
- return false;
- uint32_t docCode = freqStream->readVInt();
- _doc += docCode >> 1; //unsigned shift
- if ((docCode & 1) != 0) // if low bit is set
- _freq = 1; // _freq is one
- else
- _freq = freqStream->readVInt(); // else read _freq
- count++;
-
- if ( (deletedDocs == NULL) || (deletedDocs->get(_doc) == false ) )
- break;
- skippingDoc();
+bool SegmentTermDocs::next()
+{
+ while (true) {
+ if (count == df)
+ return false;
+
+ uint32_t docCode = freqStream->readVInt();
+ _doc += docCode >> 1; //unsigned shift
+ if ((docCode & 1) != 0) // if low bit is set
+ _freq = 1; // _freq is one
+ else
+ _freq = freqStream->readVInt(); // else read _freq
+ count++;
+
+ if (deletedDocs == NULL || (_doc >= 0 && !deletedDocs->get(_doc)))
+ break;
+ skippingDoc();
}
return true;
- }
+}
- int32_t SegmentTermDocs::read(int32_t* docs, int32_t* freqs, int32_t length) {
+
+int32_t SegmentTermDocs::read(int32_t* docs, int32_t* freqs, int32_t length)
+{
int32_t i = 0;
-//todo: one optimization would be to get the pointer buffer for ram or mmap dirs
-//and iterate over them instead of using readByte() intensive functions.
- while (i<length && count < df) {
- uint32_t docCode = freqStream->readVInt();
- _doc += docCode >> 1;
- if ((docCode & 1) != 0) // if low bit is set
- _freq = 1; // _freq is one
- else
- _freq = freqStream->readVInt(); // else read _freq
- count++;
-
- if (deletedDocs == NULL || !deletedDocs->get(_doc)) {
- docs[i] = _doc;
- freqs[i] = _freq;
- i++;
- }
+ // TODO: one optimization would be to get the pointer buffer for ram or mmap
+ // dirs and iterate over them instead of using readByte() intensive functions.
+ while (i < length && count < df) {
+ uint32_t docCode = freqStream->readVInt();
+ _doc += docCode >> 1;
+ if ((docCode & 1) != 0) // if low bit is set
+ _freq = 1; // _freq is one
+ else
+ _freq = freqStream->readVInt(); // else read _freq
+ count++;
+
+ if (deletedDocs == NULL || (_doc >= 0 && !deletedDocs->get(_doc))) {
+ docs[i] = _doc;
+ freqs[i] = _freq;
+ i++;
+ }
}
return i;
- }
+}
bool SegmentTermDocs::skipTo(const int32_t target){
if (df >= skipInterval) { // optimized case
diff --git a/src/3rdparty/clucene/src/CLucene/index/Term.cpp b/src/3rdparty/clucene/src/CLucene/index/Term.cpp
index fc32e44..5ff7bb2 100644
--- a/src/3rdparty/clucene/src/CLucene/index/Term.cpp
+++ b/src/3rdparty/clucene/src/CLucene/index/Term.cpp
@@ -153,7 +153,10 @@ int32_t Term::compareTo(const Term* other) const
if (_field == other->_field)
return _tcscmp(_text, other->_text);
- return _tcscmp(_field, other->_field);
+ int32_t ret = _tcscmp(_field, other->_field);
+ if (ret == 0)
+ ret = _tcscmp(_text, other->_text);
+ return ret;
}
TCHAR* Term::toString() const
diff --git a/src/3rdparty/clucene/src/CLucene/queryParser/MultiFieldQueryParser.cpp b/src/3rdparty/clucene/src/CLucene/queryParser/MultiFieldQueryParser.cpp
index ea93ec4..b57896b 100644
--- a/src/3rdparty/clucene/src/CLucene/queryParser/MultiFieldQueryParser.cpp
+++ b/src/3rdparty/clucene/src/CLucene/queryParser/MultiFieldQueryParser.cpp
@@ -21,51 +21,62 @@ CL_NS_USE(analysis)
CL_NS_DEF(queryParser)
-MultiFieldQueryParser::MultiFieldQueryParser(const TCHAR** fields, CL_NS(analysis)::Analyzer* a, BoostMap* boosts):
- QueryParser(NULL,a)
+MultiFieldQueryParser::MultiFieldQueryParser(const TCHAR** fields,
+ CL_NS(analysis)::Analyzer* analyzer, BoostMap* boosts)
+ : QueryParser(NULL, analyzer)
{
this->fields = fields;
this->boosts = boosts;
}
-MultiFieldQueryParser::~MultiFieldQueryParser(){
+
+MultiFieldQueryParser::~MultiFieldQueryParser()
+{
}
//static
-Query* MultiFieldQueryParser::parse(const TCHAR* query, const TCHAR** fields, Analyzer* analyzer)
+Query* MultiFieldQueryParser::parse(const TCHAR* query, const TCHAR** fields,
+ Analyzer* analyzer)
{
BooleanQuery* bQuery = _CLNEW BooleanQuery();
int32_t i = 0;
- while ( fields[i] != NULL ){
- Query* q = QueryParser::parse(query, fields[i], analyzer);
- bQuery->add(q, true, false, false);
-
+ while (fields[i] != NULL){
+ Query* q = QueryParser::parse(query, fields[i], analyzer);
+ if (q && (q->getQueryName() != _T("BooleanQuery")
+ || ((BooleanQuery*)q)->getClauseCount() > 0)) {
+ bQuery->add(q , true, false, false);
+ } else {
+ _CLDELETE(q);
+ }
i++;
}
return bQuery;
}
//static
-Query* MultiFieldQueryParser::parse(const TCHAR* query, const TCHAR** fields, const uint8_t* flags, Analyzer* analyzer)
+Query* MultiFieldQueryParser::parse(const TCHAR* query, const TCHAR** fields,
+ const uint8_t* flags, Analyzer* analyzer)
{
BooleanQuery* bQuery = _CLNEW BooleanQuery();
int32_t i = 0;
- while ( fields[i] != NULL )
- {
- Query* q = QueryParser::parse(query, fields[i], analyzer);
- uint8_t flag = flags[i];
- switch (flag)
- {
- case MultiFieldQueryParser::REQUIRED_FIELD:
- bQuery->add(q, true, true, false);
- break;
- case MultiFieldQueryParser::PROHIBITED_FIELD:
- bQuery->add(q, true, false, true);
- break;
- default:
- bQuery->add(q, true, false, false);
- break;
+ while ( fields[i] != NULL ) {
+ Query* q = QueryParser::parse(query, fields[i], analyzer);
+ if (q && (q->getQueryName() != _T("BooleanQuery")
+ || ((BooleanQuery*)q)->getClauseCount() > 0)) {
+ uint8_t flag = flags[i];
+ switch (flag) {
+ case MultiFieldQueryParser::REQUIRED_FIELD:
+ bQuery->add(q, true, true, false);
+ break;
+ case MultiFieldQueryParser::PROHIBITED_FIELD:
+ bQuery->add(q, true, false, true);
+ break;
+ default:
+ bQuery->add(q, true, false, false);
+ break;
+ }
+ } else {
+ _CLDELETE(q);
}
-
i++;
}
return bQuery;
diff --git a/src/3rdparty/clucene/src/CLucene/store/FSDirectory.cpp b/src/3rdparty/clucene/src/CLucene/store/FSDirectory.cpp
index e9659cf..5f96e91 100644
--- a/src/3rdparty/clucene/src/CLucene/store/FSDirectory.cpp
+++ b/src/3rdparty/clucene/src/CLucene/store/FSDirectory.cpp
@@ -91,7 +91,7 @@ QString FSDirectory::FSLock::toString() const
// # pragma mark -- FSDirectory::FSIndexInput
FSDirectory::FSIndexInput::FSIndexInput(const QString& path, int32_t bufferSize)
- : BufferedIndexInput(bufferSize)
+ : BufferedIndexInput(bufferSize)
{
CND_PRECONDITION(!path.isEmpty(), "path is NULL");
@@ -155,7 +155,7 @@ FSDirectory::FSIndexInput::FSIndexInput(const FSIndexInput& other)
if (other.handle == NULL)
_CLTHROWA(CL_ERR_NullPointer, "other handle is null");
- SCOPED_LOCK_MUTEX(other.handle->THIS_LOCK)
+ SCOPED_LOCK_MUTEX(*other.handle->THIS_LOCK)
_pos = other.handle->_fpos;
handle = _CL_POINTER(other.handle);
@@ -169,7 +169,30 @@ FSDirectory::FSIndexInput::~FSIndexInput()
void FSDirectory::FSIndexInput::close()
{
BufferedIndexInput::close();
+#ifdef _LUCENE_THREADMUTEX
+ if (handle != NULL) {
+ // Here we have a bit of a problem... We need to lock the handle to
+ // ensure that we can safely delete the handle... But if we delete the
+ // handle, then the scoped unlock, won't be able to unlock the mutex...
+
+ // take a reference of the lock object...
+ _LUCENE_THREADMUTEX* mutex = handle->THIS_LOCK;
+ //lock the mutex
+ mutex->lock();
+
+ // determine if we are about to delete the handle...
+ bool doUnlock = (handle->__cl_refcount > 1);
+ // decdelete (deletes if refcount is down to 0)
+ _CLDECDELETE(handle);
+
+ if (doUnlock)
+ mutex->unlock();
+ else
+ delete mutex;
+ }
+#else
_CLDECDELETE(handle);
+#endif
}
IndexInput* FSDirectory::FSIndexInput::clone() const
@@ -186,7 +209,7 @@ void FSDirectory::FSIndexInput::seekInternal(const int64_t position)
void FSDirectory::FSIndexInput::readInternal(uint8_t* b, const int32_t len)
{
- SCOPED_LOCK_MUTEX(handle->THIS_LOCK)
+ SCOPED_LOCK_MUTEX(*handle->THIS_LOCK)
CND_PRECONDITION(handle != NULL, "shared file handle has closed");
CND_PRECONDITION(handle->fhandle.isOpen(), "file is not open");
@@ -214,8 +237,10 @@ void FSDirectory::FSIndexInput::readInternal(uint8_t* b, const int32_t len)
FSDirectory::FSIndexInput::SharedHandle::SharedHandle()
: _fpos(0)
, _length(0)
-
{
+#ifdef _LUCENE_THREADMUTEX
+ THIS_LOCK = new _LUCENE_THREADMUTEX;
+#endif
}
FSDirectory::FSIndexInput::SharedHandle::~SharedHandle()
diff --git a/src/3rdparty/clucene/src/CLucene/store/FSDirectory.h b/src/3rdparty/clucene/src/CLucene/store/FSDirectory.h
index 1302edf..e967380 100644
--- a/src/3rdparty/clucene/src/CLucene/store/FSDirectory.h
+++ b/src/3rdparty/clucene/src/CLucene/store/FSDirectory.h
@@ -147,7 +147,7 @@ private:
void close();
IndexInput* clone() const;
-
+
int64_t length()
{ return handle->_length; }
@@ -174,7 +174,7 @@ private:
int64_t _length;
QFile fhandle;
- DEFINE_MUTEX(THIS_LOCK)
+ DEFINE_MUTEX(*THIS_LOCK)
};
SharedHandle* handle;
int64_t _pos;
diff --git a/src/3rdparty/clucene/src/CLucene/util/bufferedstream.h b/src/3rdparty/clucene/src/CLucene/util/bufferedstream.h
index 2455d5e..b73ad98 100644
--- a/src/3rdparty/clucene/src/CLucene/util/bufferedstream.h
+++ b/src/3rdparty/clucene/src/CLucene/util/bufferedstream.h
@@ -28,7 +28,9 @@
#include "streambase.h"
#include "inputstreambuffer.h"
+
#include <cassert>
+#include <stdio.h>
namespace jstreams {
diff --git a/src/3rdparty/phonon/ds9/qevr9.h b/src/3rdparty/phonon/ds9/qevr9.h
new file mode 100644
index 0000000..8599fce
--- /dev/null
+++ b/src/3rdparty/phonon/ds9/qevr9.h
@@ -0,0 +1,143 @@
+/* This file is part of the KDE project.
+
+Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+
+This library is free software: you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation, either version 2.1 or 3 of the License.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <d3d9.h>
+
+#define DXVA2_ProcAmp_Brightness 1
+#define DXVA2_ProcAmp_Contrast 2
+#define DXVA2_ProcAmp_Hue 4
+#define DXVA2_ProcAmp_Saturation 8
+
+typedef enum {
+ MFVideoARMode_None = 0x00000000,
+ MFVideoARMode_PreservePicture = 0x00000001,
+ MFVideoARMode_PreservePixel = 0x00000002,
+ MFVideoARMode_NonLinearStretch = 0x00000004,
+ MFVideoARMode_Mask = 0x00000007
+} MFVideoAspectRatioMode;
+
+typedef struct {
+ float left;
+ float top;
+ float right;
+ float bottom;
+} MFVideoNormalizedRect;
+
+typedef struct {
+ UINT DeviceCaps;
+ D3DPOOL InputPool;
+ UINT NumForwardRefSamples;
+ UINT NumBackwardRefSamples;
+ UINT Reserved;
+ UINT DeinterlaceTechnology;
+ UINT ProcAmpControlCaps;
+ UINT VideoProcessorOperations;
+ UINT NoiseFilterTechnology;
+ UINT DetailFilterTechnology;
+} DXVA2_VideoProcessorCaps;
+
+typedef struct {
+ union {
+ struct {
+ USHORT Fraction;
+ SHORT Value;
+ };
+ LONG ll;
+ };
+} DXVA2_Fixed32;
+
+typedef struct {
+ DXVA2_Fixed32 MinValue;
+ DXVA2_Fixed32 MaxValue;
+ DXVA2_Fixed32 DefaultValue;
+ DXVA2_Fixed32 StepSize;
+} DXVA2_ValueRange;
+
+typedef struct {
+ DXVA2_Fixed32 Brightness;
+ DXVA2_Fixed32 Contrast;
+ DXVA2_Fixed32 Hue;
+ DXVA2_Fixed32 Saturation;
+} DXVA2_ProcAmpValues;
+
+DXVA2_Fixed32 DXVA2FloatToFixed(const float _float_)
+{
+ DXVA2_Fixed32 _fixed_;
+ _fixed_.Fraction = LOWORD(_float_ * 0x10000);
+ _fixed_.Value = HIWORD(_float_ * 0x10000);
+ return _fixed_;
+}
+
+float DXVA2FixedToFloat(const DXVA2_Fixed32 _fixed_)
+{
+ return (FLOAT)_fixed_.Value + (FLOAT)_fixed_.Fraction / 0x10000;
+}
+
+#undef INTERFACE
+#define INTERFACE IMFVideoDisplayControl
+DECLARE_INTERFACE_(IMFVideoDisplayControl, IUnknown)
+{
+ STDMETHOD(GetNativeVideoSize)(THIS_ SIZE* pszVideo, SIZE* pszARVideo) PURE;
+ STDMETHOD(GetIdealVideoSize)(THIS_ SIZE* pszMin, SIZE* pszMax) PURE;
+ STDMETHOD(SetVideoPosition)(THIS_ const MFVideoNormalizedRect* pnrcSource, const LPRECT prcDest) PURE;
+ STDMETHOD(GetVideoPosition)(THIS_ MFVideoNormalizedRect* pnrcSource, LPRECT prcDest) PURE;
+ STDMETHOD(SetAspectRatioMode)(THIS_ DWORD dwAspectRatioMode) PURE;
+ STDMETHOD(GetAspectRatioMode)(THIS_ DWORD* pdwAspectRatioMode) PURE;
+ STDMETHOD(SetVideoWindow)(THIS_ HWND hwndVideo) PURE;
+ STDMETHOD(GetVideoWindow)(THIS_ HWND* phwndVideo) PURE;
+ STDMETHOD(RepaintVideo)(THIS_) PURE;
+ STDMETHOD(GetCurrentImage)(THIS_ BITMAPINFOHEADER* pBih, BYTE** pDib, DWORD* pcbDib, LONGLONG* pTimeStamp) PURE;
+ STDMETHOD(SetBorderColor)(THIS_ COLORREF Clr) PURE;
+ STDMETHOD(GetBorderColor)(THIS_ COLORREF* pClr) PURE;
+ STDMETHOD(SetRenderingPrefs)(THIS_ DWORD dwRenderFlags) PURE;
+ STDMETHOD(GetRenderingPrefs)(THIS_ DWORD* pdwRenderFlags) PURE;
+ STDMETHOD(SetFullScreen)(THIS_ BOOL fFullscreen) PURE;
+ STDMETHOD(GetFullScreen)(THIS_ BOOL* pfFullscreen) PURE;
+};
+#undef INTERFACE
+#define INTERFACE IMFVideoMixerControl
+DECLARE_INTERFACE_(IMFVideoMixerControl, IUnknown)
+{
+ STDMETHOD(SetStreamZOrder)(THIS_ DWORD dwStreamID, DWORD dwZ) PURE;
+ STDMETHOD(GetStreamZOrder)(THIS_ DWORD dwStreamID, DWORD* pdwZ) PURE;
+ STDMETHOD(SetStreamOutputRect)(THIS_ DWORD dwStreamID, const MFVideoNormalizedRect* pnrcOutput) PURE;
+ STDMETHOD(GetStreamOutputRect)(THIS_ DWORD dwStreamID, MFVideoNormalizedRect* pnrcOutput) PURE;
+};
+#undef INTERFACE
+#define INTERFACE IMFVideoProcessor
+DECLARE_INTERFACE_(IMFVideoProcessor, IUnknown)
+{
+ STDMETHOD(GetAvailableVideoProcessorModes)(THIS_ UINT* lpdwNumProcessingModes, GUID** ppVideoProcessingModes) PURE;
+ STDMETHOD(GetVideoProcessorCaps)(THIS_ LPGUID lpVideoProcessorMode, DXVA2_VideoProcessorCaps* lpVideoProcessorCaps) PURE;
+ STDMETHOD(GetVideoProcessorMode)(THIS_ LPGUID lpMode) PURE;
+ STDMETHOD(SetVideoProcessorMode)(THIS_ LPGUID lpMode) PURE;
+ STDMETHOD(GetProcAmpRange)(THIS_ DWORD dwProperty, DXVA2_ValueRange* pPropRange) PURE;
+ STDMETHOD(GetProcAmpValues)(THIS_ DWORD dwFlags, DXVA2_ProcAmpValues* Values) PURE;
+ STDMETHOD(SetProcAmpValues)(THIS_ DWORD dwFlags, DXVA2_ProcAmpValues* pValues) PURE;
+ STDMETHOD(GetFilteringRange)(THIS_ DWORD dwProperty, DXVA2_ValueRange* pPropRange) PURE;
+ STDMETHOD(GetFilteringValue)(THIS_ DWORD dwProperty, DXVA2_Fixed32* pValue) PURE;
+ STDMETHOD(SetFilteringValue)(THIS_ DWORD dwProperty, DXVA2_Fixed32* pValue) PURE;
+ STDMETHOD(GetBackgroundColor)(THIS_ COLORREF* lpClrBkg) PURE;
+ STDMETHOD(SetBackgroundColor)(THIS_ COLORREF ClrBkg) PURE;
+};
+#undef INTERFACE
+#define INTERFACE IMFGetService
+DECLARE_INTERFACE_(IMFGetService, IUnknown)
+{
+ STDMETHOD(GetService)(THIS_ REFGUID guidService, REFIID riid, LPVOID* ppvObject) PURE;
+};
+#undef INTERFACE
diff --git a/src/3rdparty/phonon/ds9/videorenderer_default.cpp b/src/3rdparty/phonon/ds9/videorenderer_default.cpp
new file mode 100644
index 0000000..0045a49
--- /dev/null
+++ b/src/3rdparty/phonon/ds9/videorenderer_default.cpp
@@ -0,0 +1,153 @@
+/* This file is part of the KDE project.
+
+Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+
+This library is free software: you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation, either version 2.1 or 3 of the License.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+
+#include "videorenderer_default.h"
+
+#ifndef QT_NO_PHONON_VIDEO
+
+#include <QtGui/QWidget>
+#include <QtGui/QPainter>
+
+#include <uuids.h>
+
+QT_BEGIN_NAMESPACE
+
+
+namespace Phonon
+{
+ namespace DS9
+ {
+ VideoRendererDefault::~VideoRendererDefault()
+ {
+ }
+
+ bool VideoRendererDefault::isNative() const
+ {
+ return true;
+ }
+
+
+ VideoRendererDefault::VideoRendererDefault(QWidget *target) : m_target(target)
+ {
+ m_target->setAttribute(Qt::WA_PaintOnScreen, true);
+ m_filter = Filter(CLSID_VideoRenderer, IID_IBaseFilter);
+ }
+
+ QSize VideoRendererDefault::videoSize() const
+ {
+ LONG w = 0,
+ h = 0;
+ ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);
+ if (basic) {
+ basic->GetVideoSize( &w, &h);
+ }
+ return QSize(w, h);
+ }
+
+ void VideoRendererDefault::repaintCurrentFrame(QWidget * /*target*/, const QRect & /*rect*/)
+ {
+ //nothing to do here: the renderer paints everything
+ }
+
+ void VideoRendererDefault::notifyResize(const QSize &size, Phonon::VideoWidget::AspectRatio aspectRatio,
+ Phonon::VideoWidget::ScaleMode scaleMode)
+ {
+ if (!isActive()) {
+ ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);
+ if (basic) {
+ basic->SetDestinationPosition(0, 0, 0, 0);
+ }
+ return;
+ }
+
+ ComPointer<IVideoWindow> video(m_filter, IID_IVideoWindow);
+
+ OAHWND owner;
+ HRESULT hr = video->get_Owner(&owner);
+ if (FAILED(hr)) {
+ return;
+ }
+
+ const OAHWND newOwner = reinterpret_cast<OAHWND>(m_target->winId());
+ if (owner != newOwner) {
+ video->put_Owner(newOwner);
+ video->put_MessageDrain(newOwner);
+ video->put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
+ }
+
+ //make sure the widget takes the whole size of the parent
+ video->SetWindowPosition(0, 0, size.width(), size.height());
+
+ const QSize vsize = videoSize();
+ internalNotifyResize(size, vsize, aspectRatio, scaleMode);
+
+ ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);
+ if (basic) {
+ basic->SetDestinationPosition(m_dstX, m_dstY, m_dstWidth, m_dstHeight);
+ }
+ }
+
+ void VideoRendererDefault::applyMixerSettings(qreal /*brightness*/, qreal /*contrast*/, qreal /*m_hue*/, qreal /*saturation*/)
+ {
+ //this can't be supported for the default renderer
+ }
+
+ QImage VideoRendererDefault::snapshot() const
+ {
+ ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);
+ if (basic) {
+ LONG bufferSize = 0;
+ //1st we get the buffer size
+ basic->GetCurrentImage(&bufferSize, 0);
+
+ QByteArray buffer;
+ buffer.resize(bufferSize);
+ HRESULT hr = basic->GetCurrentImage(&bufferSize, reinterpret_cast<long*>(buffer.data()));
+
+ if (SUCCEEDED(hr)) {
+
+ const BITMAPINFOHEADER *bmi = reinterpret_cast<const BITMAPINFOHEADER*>(buffer.constData());
+
+ const int w = qAbs(bmi->biWidth),
+ h = qAbs(bmi->biHeight);
+
+ // Create image and copy data into image.
+ QImage ret(w, h, QImage::Format_RGB32);
+
+ if (!ret.isNull()) {
+ const char *data = buffer.constData() + bmi->biSize;
+ const int bytes_per_line = w * sizeof(QRgb);
+ for (int y = h - 1; y >= 0; --y) {
+ qMemCopy(ret.scanLine(y), //destination
+ data, //source
+ bytes_per_line);
+ data += bytes_per_line;
+ }
+ }
+ return ret;
+ }
+ }
+ return QImage();
+ }
+
+ }
+}
+
+QT_END_NAMESPACE
+
+#endif //QT_NO_PHONON_VIDEO
diff --git a/src/3rdparty/phonon/ds9/videorenderer_default.h b/src/3rdparty/phonon/ds9/videorenderer_default.h
new file mode 100644
index 0000000..43768d9
--- /dev/null
+++ b/src/3rdparty/phonon/ds9/videorenderer_default.h
@@ -0,0 +1,55 @@
+/* This file is part of the KDE project.
+
+Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+
+This library is free software: you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation, either version 2.1 or 3 of the License.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PHONON_VIDEORENDERER_DEFAULT_H
+#define PHONON_VIDEORENDERER_DEFAULT_H
+
+#include "abstractvideorenderer.h"
+
+QT_BEGIN_NAMESPACE
+
+#ifndef QT_NO_PHONON_VIDEO
+
+namespace Phonon
+{
+ namespace DS9
+ {
+ class VideoRendererDefault : public AbstractVideoRenderer
+ {
+ public:
+ VideoRendererDefault(QWidget *target);
+ ~VideoRendererDefault();
+
+ //Implementation from AbstractVideoRenderer
+ void repaintCurrentFrame(QWidget *target, const QRect &rect);
+ void notifyResize(const QSize&, Phonon::VideoWidget::AspectRatio, Phonon::VideoWidget::ScaleMode);
+ QSize videoSize() const;
+ QImage snapshot() const;
+ void applyMixerSettings(qreal brightness, qreal contrast, qreal m_hue, qreal saturation);
+ bool isNative() const;
+ private:
+ QWidget *m_target;
+ };
+ }
+}
+
+#endif //QT_NO_PHONON_VIDEO
+
+QT_END_NAMESPACE
+
+#endif
+
diff --git a/src/3rdparty/phonon/ds9/videorenderer_evr.cpp b/src/3rdparty/phonon/ds9/videorenderer_evr.cpp
new file mode 100644
index 0000000..d23d9ce
--- /dev/null
+++ b/src/3rdparty/phonon/ds9/videorenderer_evr.cpp
@@ -0,0 +1,215 @@
+/* This file is part of the KDE project.
+
+Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+
+This library is free software: you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation, either version 2.1 or 3 of the License.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+
+#include "videorenderer_evr.h"
+#include "qevr9.h"
+
+#ifndef QT_NO_PHONON_VIDEO
+
+#include <QtGui/QWidget>
+#include <QtGui/QPainter>
+
+QT_BEGIN_NAMESPACE
+
+namespace Phonon
+{
+ namespace DS9
+ {
+ //we have to define them here because not all compilers/sdk have them
+ static const GUID MR_VIDEO_RENDER_SERVICE = {0x1092a86c, 0xab1a, 0x459a, {0xa3, 0x36, 0x83, 0x1f, 0xbc, 0x4d, 0x11, 0xff} };
+ static const GUID MR_VIDEO_MIXER_SERVICE = { 0x73cd2fc, 0x6cf4, 0x40b7, {0x88, 0x59, 0xe8, 0x95, 0x52, 0xc8, 0x41, 0xf8} };
+ static const IID IID_IMFVideoDisplayControl = {0xa490b1e4, 0xab84, 0x4d31, {0xa1, 0xb2, 0x18, 0x1e, 0x03, 0xb1, 0x07, 0x7a} };
+ static const IID IID_IMFVideoMixerControl = {0xA5C6C53F, 0xC202, 0x4aa5, {0x96, 0x95, 0x17, 0x5B, 0xA8, 0xC5, 0x08, 0xA5} };
+ static const IID IID_IMFVideoProcessor = {0x6AB0000C, 0xFECE, 0x4d1f, {0xA2, 0xAC, 0xA9, 0x57, 0x35, 0x30, 0x65, 0x6E} };
+ static const IID IID_IMFGetService = {0xFA993888, 0x4383, 0x415A, {0xA9, 0x30, 0xDD, 0x47, 0x2A, 0x8C, 0xF6, 0xF7} };
+ static const GUID CLSID_EnhancedVideoRenderer = {0xfa10746c, 0x9b63, 0x4b6c, {0xbc, 0x49, 0xfc, 0x30, 0xe, 0xa5, 0xf2, 0x56} };
+
+ template <typename T> ComPointer<T> getService(const Filter &filter, REFGUID guidService, REFIID riid)
+ {
+ //normally we should use IID_IMFGetService but this introduces another dependency
+ //so here we simply define our own IId with the same value
+ ComPointer<IMFGetService> getService(filter, IID_IMFGetService);
+ Q_ASSERT(getService);
+ T *ptr = 0;
+ HRESULT hr = getService->GetService(guidService, riid, reinterpret_cast<void **>(&ptr));
+ if (!SUCCEEDED(hr) || ptr == 0)
+ Q_ASSERT(!SUCCEEDED(hr) && ptr != 0);
+ ComPointer<T> service(ptr);
+ return service;
+ }
+
+ VideoRendererEVR::~VideoRendererEVR()
+ {
+ }
+
+ bool VideoRendererEVR::isNative() const
+ {
+ return true;
+ }
+
+ VideoRendererEVR::VideoRendererEVR(QWidget *target) : m_target(target)
+ {
+ m_filter = Filter(CLSID_EnhancedVideoRenderer, IID_IBaseFilter);
+ if (!m_filter) {
+ return;
+ }
+
+ ComPointer<IMFVideoDisplayControl> filterControl = getService<IMFVideoDisplayControl>(m_filter, MR_VIDEO_RENDER_SERVICE, IID_IMFVideoDisplayControl);
+
+ filterControl->SetVideoWindow(reinterpret_cast<HWND>(target->winId()));
+ filterControl->SetAspectRatioMode(MFVideoARMode_None); // We're in control of the size
+ }
+
+ QImage VideoRendererEVR::snapshot() const
+ {
+ // This will always capture black areas where no video is drawn, if any are present.
+ // Due to the hack in notifyResize()
+ ComPointer<IMFVideoDisplayControl> filterControl = getService<IMFVideoDisplayControl>(m_filter, MR_VIDEO_RENDER_SERVICE, IID_IMFVideoDisplayControl);
+ if (filterControl) {
+ BITMAPINFOHEADER bmi;
+ BYTE *buffer = 0;
+ DWORD bufferSize;
+ LONGLONG timeStamp;
+
+ bmi.biSize = sizeof(BITMAPINFOHEADER);
+
+ HRESULT hr = filterControl->GetCurrentImage(&bmi, &buffer, &bufferSize, &timeStamp);
+ if (SUCCEEDED(hr)) {
+
+ const int w = qAbs(bmi.biWidth),
+ h = qAbs(bmi.biHeight);
+
+ // Create image and copy data into image.
+ QImage ret(w, h, QImage::Format_RGB32);
+
+ if (!ret.isNull()) {
+ uchar *data = buffer;
+ const int bytes_per_line = w * sizeof(QRgb);
+ for (int y = h - 1; y >= 0; --y) {
+ qMemCopy(ret.scanLine(y), //destination
+ data, //source
+ bytes_per_line);
+ data += bytes_per_line;
+ }
+ }
+ ::CoTaskMemFree(buffer);
+ return ret;
+ }
+ }
+ return QImage();
+ }
+
+ QSize VideoRendererEVR::videoSize() const
+ {
+ SIZE nativeSize;
+ SIZE aspectRatioSize;
+
+ ComPointer<IMFVideoDisplayControl> filterControl = getService<IMFVideoDisplayControl>(m_filter, MR_VIDEO_RENDER_SERVICE, IID_IMFVideoDisplayControl);
+
+ filterControl->GetNativeVideoSize(&nativeSize, &aspectRatioSize);
+
+ return QSize(nativeSize.cx, nativeSize.cy);
+ }
+
+ void VideoRendererEVR::repaintCurrentFrame(QWidget *target, const QRect &rect)
+ {
+ // repaint the video
+ ComPointer<IMFVideoDisplayControl> filterControl = getService<IMFVideoDisplayControl>(m_filter, MR_VIDEO_RENDER_SERVICE, IID_IMFVideoDisplayControl);
+ // All failed results can be safely ignored
+ filterControl->RepaintVideo();
+ }
+
+ void VideoRendererEVR::notifyResize(const QSize &size, Phonon::VideoWidget::AspectRatio aspectRatio,
+ Phonon::VideoWidget::ScaleMode scaleMode)
+ {
+ if (!isActive()) {
+ RECT dummyRect = { 0, 0, 0, 0};
+ ComPointer<IMFVideoDisplayControl> filterControl = getService<IMFVideoDisplayControl>(m_filter, MR_VIDEO_RENDER_SERVICE, IID_IMFVideoDisplayControl);
+ filterControl->SetVideoPosition(0, &dummyRect);
+ return;
+ }
+
+ const QSize vsize = videoSize();
+ internalNotifyResize(size, vsize, aspectRatio, scaleMode);
+
+ RECT dstRectWin = { 0, 0, size.width(), size.height()};
+
+ // Resize the Stream output rect instead of the destination rect.
+ // Hacky workaround for flicker in the areas outside of the destination rect
+ // This way these areas don't exist
+ MFVideoNormalizedRect streamOutputRect = { float(m_dstX) / float(size.width()), float(m_dstY) / float(size.height()),
+ float(m_dstWidth + m_dstX) / float(size.width()), float(m_dstHeight + m_dstY) / float(size.height())};
+
+ ComPointer<IMFVideoMixerControl> filterMixer = getService<IMFVideoMixerControl>(m_filter, MR_VIDEO_MIXER_SERVICE, IID_IMFVideoMixerControl);
+ ComPointer<IMFVideoDisplayControl> filterControl = getService<IMFVideoDisplayControl>(m_filter, MR_VIDEO_RENDER_SERVICE, IID_IMFVideoDisplayControl);
+
+ filterMixer->SetStreamOutputRect(0, &streamOutputRect);
+ filterControl->SetVideoPosition(0, &dstRectWin);
+ }
+
+ void VideoRendererEVR::applyMixerSettings(qreal brightness, qreal contrast, qreal hue, qreal saturation)
+ {
+ InputPin sink = BackendNode::pins(m_filter, PINDIR_INPUT).first();
+ OutputPin source;
+ if (FAILED(sink->ConnectedTo(source.pparam()))) {
+ return; //it must be connected to work
+ }
+
+ // Get the "Video Processor" (used for brightness/contrast/saturation/hue)
+ ComPointer<IMFVideoProcessor> processor = getService<IMFVideoProcessor>(m_filter, MR_VIDEO_MIXER_SERVICE, IID_IMFVideoProcessor);
+ Q_ASSERT(processor);
+
+ DXVA2_ValueRange contrastRange;
+ DXVA2_ValueRange brightnessRange;
+ DXVA2_ValueRange saturationRange;
+ DXVA2_ValueRange hueRange;
+
+ if (FAILED(processor->GetProcAmpRange(DXVA2_ProcAmp_Contrast, &contrastRange)))
+ return;
+ if (FAILED(processor->GetProcAmpRange(DXVA2_ProcAmp_Brightness, &brightnessRange)))
+ return;
+ if (FAILED(processor->GetProcAmpRange(DXVA2_ProcAmp_Saturation, &saturationRange)))
+ return;
+ if (FAILED(processor->GetProcAmpRange(DXVA2_ProcAmp_Hue, &hueRange)))
+ return;
+
+ DXVA2_ProcAmpValues values;
+
+ values.Contrast = DXVA2FloatToFixed(((contrast < 0
+ ? DXVA2FixedToFloat(contrastRange.MinValue) : DXVA2FixedToFloat(contrastRange.MaxValue))
+ - DXVA2FixedToFloat(contrastRange.DefaultValue)) * qAbs(contrast) + DXVA2FixedToFloat(contrastRange.DefaultValue));
+ values.Brightness = DXVA2FloatToFixed(((brightness < 0
+ ? DXVA2FixedToFloat(brightnessRange.MinValue) : DXVA2FixedToFloat(brightnessRange.MaxValue))
+ - DXVA2FixedToFloat(brightnessRange.DefaultValue)) * qAbs(brightness) + DXVA2FixedToFloat(brightnessRange.DefaultValue));
+ values.Saturation = DXVA2FloatToFixed(((saturation < 0
+ ? DXVA2FixedToFloat(saturationRange.MinValue) : DXVA2FixedToFloat(saturationRange.MaxValue))
+ - DXVA2FixedToFloat(saturationRange.DefaultValue)) * qAbs(saturation) + DXVA2FixedToFloat(saturationRange.DefaultValue));
+ values.Hue = DXVA2FloatToFixed(((hue < 0
+ ? DXVA2FixedToFloat(hueRange.MinValue) : DXVA2FixedToFloat(hueRange.MaxValue))
+ - DXVA2FixedToFloat(hueRange.DefaultValue)) * qAbs(hue) + DXVA2FixedToFloat(hueRange.DefaultValue));
+
+ //finally set the settings
+ processor->SetProcAmpValues(DXVA2_ProcAmp_Contrast | DXVA2_ProcAmp_Brightness | DXVA2_ProcAmp_Saturation | DXVA2_ProcAmp_Hue, &values);
+
+ }
+ }
+}
+
+QT_END_NAMESPACE
+
+#endif //QT_NO_PHONON_VIDEO
diff --git a/src/3rdparty/phonon/ds9/videorenderer_evr.h b/src/3rdparty/phonon/ds9/videorenderer_evr.h
new file mode 100644
index 0000000..229c36d
--- /dev/null
+++ b/src/3rdparty/phonon/ds9/videorenderer_evr.h
@@ -0,0 +1,56 @@
+/* This file is part of the KDE project.
+
+Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+
+This library is free software: you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation, either version 2.1 or 3 of the License.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PHONON_VIDEORENDERER_EVR_H
+#define PHONON_VIDEORENDERER_EVR_H
+
+#include "abstractvideorenderer.h"
+#include "compointer.h"
+
+QT_BEGIN_NAMESPACE
+
+#ifndef QT_NO_PHONON_VIDEO
+
+namespace Phonon
+{
+ namespace DS9
+ {
+ class VideoRendererEVR : public AbstractVideoRenderer
+ {
+ public:
+ VideoRendererEVR(QWidget *target);
+ ~VideoRendererEVR();
+
+ //Implementation from AbstractVideoRenderer
+ void repaintCurrentFrame(QWidget *target, const QRect &rect);
+ void notifyResize(const QSize&, Phonon::VideoWidget::AspectRatio, Phonon::VideoWidget::ScaleMode);
+ QSize videoSize() const;
+ QImage snapshot() const;
+ void applyMixerSettings(qreal brightness, qreal contrast, qreal m_hue, qreal saturation);
+ bool isNative() const;
+ private:
+ QWidget *m_target;
+ };
+ }
+}
+
+#endif //QT_NO_PHONON_VIDEO
+
+QT_END_NAMESPACE
+
+#endif
+
diff --git a/src/3rdparty/phonon/ds9/videorenderer_vmr9.cpp b/src/3rdparty/phonon/ds9/videorenderer_vmr9.cpp
index 81ebb8b..545b31e 100644
--- a/src/3rdparty/phonon/ds9/videorenderer_vmr9.cpp
+++ b/src/3rdparty/phonon/ds9/videorenderer_vmr9.cpp
@@ -22,14 +22,9 @@ along with this library. If not, see <http://www.gnu.org/licenses/>.
#include <QtGui/QWidget>
#include <QtGui/QPainter>
-#include <QtCore/QTimerEvent>
-#ifndef Q_OS_WINCE
#include <d3d9.h>
#include <vmr9.h>
-#else
-#include <uuids.h>
-#endif
QT_BEGIN_NAMESPACE
@@ -48,116 +43,10 @@ namespace Phonon
}
-#ifdef Q_OS_WINCE
- VideoRendererVMR9::VideoRendererVMR9(QWidget *target) : m_target(target)
- {
- m_target->setAttribute(Qt::WA_PaintOnScreen, true);
- m_filter = Filter(CLSID_VideoRenderer, IID_IBaseFilter);
- }
-
- QSize VideoRendererVMR9::videoSize() const
- {
- LONG w = 0,
- h = 0;
- ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);
- if (basic) {
- basic->GetVideoSize( &w, &h);
- }
- return QSize(w, h);
- }
-
- void VideoRendererVMR9::repaintCurrentFrame(QWidget * /*target*/, const QRect & /*rect*/)
- {
- //nothing to do here: the renderer paints everything
- }
-
- void VideoRendererVMR9::notifyResize(const QSize &size, Phonon::VideoWidget::AspectRatio aspectRatio,
- Phonon::VideoWidget::ScaleMode scaleMode)
- {
- if (!isActive()) {
- ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);
- if (basic) {
- basic->SetDestinationPosition(0, 0, 0, 0);
- }
- return;
- }
-
- ComPointer<IVideoWindow> video(m_filter, IID_IVideoWindow);
-
- OAHWND owner;
- HRESULT hr = video->get_Owner(&owner);
- if (FAILED(hr)) {
- return;
- }
-
- const OAHWND newOwner = reinterpret_cast<OAHWND>(m_target->winId());
- if (owner != newOwner) {
- video->put_Owner(newOwner);
- video->put_MessageDrain(newOwner);
- video->put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
- }
-
- //make sure the widget takes the whole size of the parent
- video->SetWindowPosition(0, 0, size.width(), size.height());
-
- const QSize vsize = videoSize();
- internalNotifyResize(size, vsize, aspectRatio, scaleMode);
-
- ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);
- if (basic) {
- basic->SetDestinationPosition(m_dstX, m_dstY, m_dstWidth, m_dstHeight);
- }
- }
-
- void VideoRendererVMR9::applyMixerSettings(qreal /*brightness*/, qreal /*contrast*/, qreal /*m_hue*/, qreal /*saturation*/)
- {
- //this can't be supported for WinCE
- }
-
- QImage VideoRendererVMR9::snapshot() const
- {
- ComPointer<IBasicVideo> basic(m_filter, IID_IBasicVideo);
- if (basic) {
- LONG bufferSize = 0;
- //1st we get the buffer size
- basic->GetCurrentImage(&bufferSize, 0);
-
- QByteArray buffer;
- buffer.resize(bufferSize);
- HRESULT hr = basic->GetCurrentImage(&bufferSize, reinterpret_cast<long*>(buffer.data()));
-
- if (SUCCEEDED(hr)) {
-
- const BITMAPINFOHEADER *bmi = reinterpret_cast<const BITMAPINFOHEADER*>(buffer.constData());
-
- const int w = qAbs(bmi->biWidth),
- h = qAbs(bmi->biHeight);
-
- // Create image and copy data into image.
- QImage ret(w, h, QImage::Format_RGB32);
-
- if (!ret.isNull()) {
- const char *data = buffer.constData() + bmi->biSize;
- const int bytes_per_line = w * sizeof(QRgb);
- for (int y = h - 1; y >= 0; --y) {
- qMemCopy(ret.scanLine(y), //destination
- data, //source
- bytes_per_line);
- data += bytes_per_line;
- }
- }
- return ret;
- }
- }
- return QImage();
- }
-
-#else
VideoRendererVMR9::VideoRendererVMR9(QWidget *target) : m_target(target)
{
m_filter = Filter(CLSID_VideoMixingRenderer9, IID_IBaseFilter);
if (!m_filter) {
- qWarning("the video widget could not be initialized correctly");
return;
}
@@ -325,7 +214,6 @@ namespace Phonon
//finally set the settings
mixer->SetProcAmpControl(0, &ctrl);
}
-#endif
}
}
diff --git a/src/3rdparty/phonon/ds9/videorenderer_vmr9.h b/src/3rdparty/phonon/ds9/videorenderer_vmr9.h
index 4eb237e..516d79d 100644
--- a/src/3rdparty/phonon/ds9/videorenderer_vmr9.h
+++ b/src/3rdparty/phonon/ds9/videorenderer_vmr9.h
@@ -19,7 +19,6 @@ along with this library. If not, see <http://www.gnu.org/licenses/>.
#define PHONON_VIDEORENDERER_VMR9_H
#include "abstractvideorenderer.h"
-#include "compointer.h"
QT_BEGIN_NAMESPACE
diff --git a/src/3rdparty/phonon/ds9/videowidget.cpp b/src/3rdparty/phonon/ds9/videowidget.cpp
index 95423c6..09d42a4 100644
--- a/src/3rdparty/phonon/ds9/videowidget.cpp
+++ b/src/3rdparty/phonon/ds9/videowidget.cpp
@@ -24,7 +24,12 @@ along with this library. If not, see <http://www.gnu.org/licenses/>.
#include "mediaobject.h"
+#ifndef Q_OS_WINCE
+#include "videorenderer_evr.h"
#include "videorenderer_vmr9.h"
+#else
+#include "videorenderer_default.h"
+#endif
#include "videorenderer_soft.h"
QT_BEGIN_NAMESPACE
@@ -352,14 +357,29 @@ namespace Phonon
int index = graphIndex * 2 + type;
if (m_renderers[index] == 0 && autoCreate) {
AbstractVideoRenderer *renderer = 0;
- if (type == Native) {
- renderer = new VideoRendererVMR9(m_widget);
+ if (type == Native) {
+#ifndef Q_OS_WINCE
+ renderer = new VideoRendererEVR(m_widget);
if (renderer->getFilter() == 0) {
- //instanciating the renderer might fail with error VFW_E_DDRAW_CAPS_NOT_SUITABLE (0x80040273)
+ delete renderer;
+ //EVR not present, let's try VMR
+ renderer = new VideoRendererVMR9(m_widget);
+ if (renderer->getFilter() == 0) {
+ //instanciating the renderer might fail
+ m_noNativeRendererSupported = true;
+ delete renderer;
+ renderer = 0;
+ }
+ }
+#else
+ renderer = new VideoRendererDefault(m_widget);
+ if (renderer->getFilter() == 0) {
+ //instanciating the renderer might fail
m_noNativeRendererSupported = true;
delete renderer;
renderer = 0;
}
+#endif
}
if (renderer == 0) {
diff --git a/src/3rdparty/phonon/phonon/objectdescriptionmodel.cpp b/src/3rdparty/phonon/phonon/objectdescriptionmodel.cpp
index 7237e91..bf5be6d 100644
--- a/src/3rdparty/phonon/phonon/objectdescriptionmodel.cpp
+++ b/src/3rdparty/phonon/phonon/objectdescriptionmodel.cpp
@@ -67,8 +67,6 @@ static const char qt_meta_stringdata_Phonon__ObjectDescriptionModel_Visualizatio
namespace Phonon
{
-#if !defined(Q_CC_MINGW) || __MINGW32_MAJOR_VERSION >= 4
-
template<> const QMetaObject ObjectDescriptionModel<AudioOutputDeviceType>::staticMetaObject = {
{ &QAbstractListModel::staticMetaObject, qt_meta_stringdata_Phonon__ObjectDescriptionModel_AudioOutputDeviceType,
qt_meta_data_Phonon__ObjectDescriptionModel, 0 }
@@ -139,7 +137,6 @@ int ObjectDescriptionModel<type>::qt_metacall(QMetaObject::Call _c, int _id, voi
return QAbstractListModel::qt_metacall(_c, _id, _a);
}
*/
-#endif
int ObjectDescriptionModelData::rowCount(const QModelIndex &parent) const
{
@@ -365,8 +362,6 @@ QStringList ObjectDescriptionModelData::mimeTypes(ObjectDescriptionType type) co
return QStringList(QLatin1String("application/x-phonon-objectdescription") + QString::number(static_cast<int>(type)));
}
-#if !defined(Q_CC_MINGW) || __MINGW32_MAJOR_VERSION >= 4
-#if !defined(Q_CC_MSVC) || _MSC_VER > 1300 || defined(Q_CC_INTEL)
#define INSTANTIATE_META_FUNCTIONS(type) \
template const QMetaObject *ObjectDescriptionModel<type>::metaObject() const; \
template void *ObjectDescriptionModel<type>::qt_metacast(const char *)
@@ -376,7 +371,6 @@ INSTANTIATE_META_FUNCTIONS(AudioCaptureDeviceType);
INSTANTIATE_META_FUNCTIONS(EffectType);
INSTANTIATE_META_FUNCTIONS(AudioChannelType);
INSTANTIATE_META_FUNCTIONS(SubtitleType);
-#endif
/*INSTANTIATE_META_FUNCTIONS(VideoOutputDeviceType);
INSTANTIATE_META_FUNCTIONS(VideoCaptureDeviceType);
INSTANTIATE_META_FUNCTIONS(AudioCodecType);
@@ -384,7 +378,6 @@ INSTANTIATE_META_FUNCTIONS(VideoCodecType);
INSTANTIATE_META_FUNCTIONS(ContainerFormatType);
INSTANTIATE_META_FUNCTIONS(VisualizationType);
*/
-#endif //Q_CC_MINGW
} // namespace Phonon
#endif //QT_NO_PHONON_OBJECTDESCRIPTIONMODEL
diff --git a/src/3rdparty/phonon/phonon/objectdescriptionmodel.h b/src/3rdparty/phonon/phonon/objectdescriptionmodel.h
index 96187c3..8fd622f 100644
--- a/src/3rdparty/phonon/phonon/objectdescriptionmodel.h
+++ b/src/3rdparty/phonon/phonon/objectdescriptionmodel.h
@@ -195,13 +195,6 @@ and existing builds. */
public:
Q_OBJECT_CHECK
-/* MinGW 3.4.x gives an ICE when trying to instantiate one of the
- ObjectDescriptionModel<foo> classes because it can't handle
- half exported classes correct. gcc 4.3.x has a fix for this but
- we currently there's no official gcc 4.3 on windows available.
- Because of this we need this little hack
- */
-#if !defined(Q_CC_MINGW) || __MINGW32_MAJOR_VERSION >= 4
/** \internal */
static PHONON_TEMPLATE_CLASS_MEMBER_EXPORT const QMetaObject staticMetaObject;
/** \internal */
@@ -209,7 +202,6 @@ and existing builds. */
/** \internal */
PHONON_TEMPLATE_CLASS_MEMBER_EXPORT void *qt_metacast(const char *_clname);
//int qt_metacall(QMetaObject::Call _c, int _id, void **_a);
-#endif
/**
* Returns the number of rows in the model. This value corresponds
diff --git a/src/corelib/animation/qabstractanimation.cpp b/src/corelib/animation/qabstractanimation.cpp
index cedb43f..f834a80 100644
--- a/src/corelib/animation/qabstractanimation.cpp
+++ b/src/corelib/animation/qabstractanimation.cpp
@@ -161,7 +161,9 @@
QT_BEGIN_NAMESPACE
+#ifndef QT_NO_THREAD
Q_GLOBAL_STATIC(QThreadStorage<QUnifiedTimer *>, unifiedTimer)
+#endif
QUnifiedTimer::QUnifiedTimer() :
QObject(), lastTick(0), timingInterval(DEFAULT_TIMER_INTERVAL),
@@ -173,12 +175,17 @@ QUnifiedTimer::QUnifiedTimer() :
QUnifiedTimer *QUnifiedTimer::instance()
{
QUnifiedTimer *inst;
+#ifndef QT_NO_THREAD
if (!unifiedTimer()->hasLocalData()) {
inst = new QUnifiedTimer;
unifiedTimer()->setLocalData(inst);
} else {
inst = unifiedTimer()->localData();
}
+#else
+ static QUnifiedTimer unifiedTimer;
+ inst = &unifiedTimer;
+#endif
return inst;
}
@@ -242,7 +249,7 @@ void QUnifiedTimer::timerEvent(QTimerEvent *event)
animationTimer.stop();
isPauseTimerActive = false;
// invalidate the start reference time
- time = QTime();
+ time.invalidate();
} else {
restartAnimationTimer();
if (!time.isValid()) {
diff --git a/src/corelib/animation/qabstractanimation_p.h b/src/corelib/animation/qabstractanimation_p.h
index ad35d89..8bc3224 100644
--- a/src/corelib/animation/qabstractanimation_p.h
+++ b/src/corelib/animation/qabstractanimation_p.h
@@ -58,6 +58,10 @@
#include <QtCore/qtimer.h>
#include <private/qobject_p.h>
+#ifdef Q_OS_WIN
+#include <qt_windows.h>
+#endif
+
#ifndef QT_NO_ANIMATION
QT_BEGIN_NAMESPACE
@@ -109,6 +113,61 @@ private:
Q_DECLARE_PUBLIC(QAbstractAnimation)
};
+class ElapsedTimer
+{
+public:
+ ElapsedTimer() {
+ invalidate();
+ }
+
+ void invalidate() {
+ m_started = -1;
+ }
+
+ bool isValid() const {
+ return m_started >= 0;
+ }
+
+ void start() {
+ m_started = getTickCount_sys();
+ }
+
+ qint64 elapsed() const {
+ qint64 current = getTickCount_sys();
+ qint64 delta = current - m_started;
+ if (delta < 0)
+ delta += getPeriod_sys(); //we wrapped around
+ return delta;
+ }
+
+private:
+ enum {
+ MSECS_PER_HOUR = 3600000,
+ MSECS_PER_MIN = 60000
+ };
+
+ qint64 m_started;
+
+ quint64 getPeriod_sys() const {
+#ifdef Q_OS_WIN
+ return Q_UINT64_C(0x100000000);
+#else
+ // fallback
+ return 86400 * 1000;
+#endif
+ }
+
+ qint64 getTickCount_sys() const {
+#ifdef Q_OS_WIN
+ return ::GetTickCount();
+#else
+ // fallback
+ const QTime t = QTime::currentTime();
+ return MSECS_PER_HOUR * t.hour() + MSECS_PER_MIN * t.minute() + 1000 * t.second() + t.msec();
+#endif
+ }
+};
+
class QUnifiedTimer : public QObject
{
@@ -162,7 +221,8 @@ private:
// timer used to delay the check if we should start/stop the animation timer
QBasicTimer startStopAnimationTimer;
- QTime time;
+ ElapsedTimer time;
+
int lastTick;
int timingInterval;
int currentAnimationIdx;
diff --git a/src/corelib/animation/qpropertyanimation.cpp b/src/corelib/animation/qpropertyanimation.cpp
index cfd7cc2..37b79ba 100644
--- a/src/corelib/animation/qpropertyanimation.cpp
+++ b/src/corelib/animation/qpropertyanimation.cpp
@@ -118,7 +118,9 @@ void QPropertyAnimationPrivate::updateMetaProperty()
propertyType = QVariant::Invalid;
if (!targetValue->dynamicPropertyNames().contains(propertyName))
qWarning("QPropertyAnimation: you're trying to animate a non-existing property %s of your QObject", propertyName.constData());
- }
+ } else if (!targetValue->metaObject()->property(propertyIndex).isWritable()) {
+ qWarning("QPropertyAnimation: you're trying to animate the non-writable property %s of your QObject", propertyName.constData());
+ }
}
void QPropertyAnimationPrivate::updateProperty(const QVariant &newValue)
@@ -265,7 +267,9 @@ void QPropertyAnimation::updateState(QAbstractAnimation::State newState,
QPropertyAnimation *animToStop = 0;
{
+#ifndef QT_NO_THREAD
QMutexLocker locker(QMutexPool::globalInstanceGet(&staticMetaObject));
+#endif
typedef QPair<QObject *, QByteArray> QPropertyAnimationPair;
typedef QHash<QPropertyAnimationPair, QPropertyAnimation*> QPropertyAnimationHash;
static QPropertyAnimationHash hash;
diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp
index 115edbe..173802d 100644
--- a/src/corelib/animation/qvariantanimation.cpp
+++ b/src/corelib/animation/qvariantanimation.cpp
@@ -431,7 +431,9 @@ void QVariantAnimation::registerInterpolator(QVariantAnimation::Interpolator fun
{
// will override any existing interpolators
QInterpolatorVector *interpolators = registeredInterpolators();
+#ifndef QT_NO_THREAD
QMutexLocker locker(QMutexPool::globalInstanceGet(interpolators));
+#endif
if (int(interpolationType) >= interpolators->count())
interpolators->resize(int(interpolationType) + 1);
interpolators->replace(interpolationType, func);
@@ -446,7 +448,9 @@ template<typename T> static inline QVariantAnimation::Interpolator castToInterpo
QVariantAnimation::Interpolator QVariantAnimationPrivate::getInterpolator(int interpolationType)
{
QInterpolatorVector *interpolators = registeredInterpolators();
+#ifndef QT_NO_THREAD
QMutexLocker locker(QMutexPool::globalInstanceGet(interpolators));
+#endif
QVariantAnimation::Interpolator ret = 0;
if (interpolationType < interpolators->count()) {
ret = interpolators->at(interpolationType);
diff --git a/src/corelib/codecs/qtextcodec.cpp b/src/corelib/codecs/qtextcodec.cpp
index ff40af5..1c607a6 100644
--- a/src/corelib/codecs/qtextcodec.cpp
+++ b/src/corelib/codecs/qtextcodec.cpp
@@ -1193,6 +1193,19 @@ QTextDecoder* QTextCodec::makeDecoder() const
return new QTextDecoder(this);
}
+/*!
+ Creates a QTextDecoder with a specified \a flags to decode chunks
+ of \c{char *} data to create chunks of Unicode data.
+
+ The caller is responsible for deleting the returned object.
+
+ \since 4.7
+*/
+QTextDecoder* QTextCodec::makeDecoder(QTextCodec::ConversionFlags flags) const
+{
+ return new QTextDecoder(this, flags);
+}
+
/*!
Creates a QTextEncoder which stores enough state to encode chunks
@@ -1206,6 +1219,19 @@ QTextEncoder* QTextCodec::makeEncoder() const
}
/*!
+ Creates a QTextEncoder with a specified \a flags to encode chunks
+ of Unicode data as \c{char *} data.
+
+ The caller is responsible for deleting the returned object.
+
+ \since 4.7
+*/
+QTextEncoder* QTextCodec::makeEncoder(QTextCodec::ConversionFlags flags) const
+{
+ return new QTextEncoder(this, flags);
+}
+
+/*!
\fn QByteArray QTextCodec::fromUnicode(const QChar *input, int number,
ConverterState *state) const
@@ -1346,6 +1372,17 @@ QString QTextCodec::toUnicode(const char *chars) const
*/
/*!
+ Constructs a text encoder for the given \a codec and conversion \a flags.
+
+ \since 4.7
+*/
+QTextEncoder::QTextEncoder(const QTextCodec *codec, QTextCodec::ConversionFlags flags)
+ : c(codec), state()
+{
+ state.flags = flags;
+}
+
+/*!
Destroys the encoder.
*/
QTextEncoder::~QTextEncoder()
@@ -1422,6 +1459,18 @@ QByteArray QTextEncoder::fromUnicode(const QString& uc, int& lenInOut)
*/
/*!
+ Constructs a text decoder for the given \a codec and conversion \a flags.
+
+ \since 4.7
+*/
+
+QTextDecoder::QTextDecoder(const QTextCodec *codec, QTextCodec::ConversionFlags flags)
+ : c(codec), state()
+{
+ state.flags = flags;
+}
+
+/*!
Destroys the decoder.
*/
QTextDecoder::~QTextDecoder()
diff --git a/src/corelib/codecs/qtextcodec.h b/src/corelib/codecs/qtextcodec.h
index a099dd9..5012b42 100644
--- a/src/corelib/codecs/qtextcodec.h
+++ b/src/corelib/codecs/qtextcodec.h
@@ -85,9 +85,6 @@ public:
static QTextCodec *codecForUtfText(const QByteArray &ba);
static QTextCodec *codecForUtfText(const QByteArray &ba, QTextCodec *defaultCodec);
- QTextDecoder* makeDecoder() const;
- QTextEncoder* makeEncoder() const;
-
bool canEncode(QChar) const;
bool canEncode(const QString&) const;
@@ -120,6 +117,12 @@ public:
QByteArray fromUnicode(const QChar *in, int length, ConverterState *state = 0) const
{ return convertFromUnicode(in, length, state); }
+ // ### Qt 5: merge these functions.
+ QTextDecoder* makeDecoder() const;
+ QTextDecoder* makeDecoder(ConversionFlags flags) const;
+ QTextEncoder* makeEncoder() const;
+ QTextEncoder* makeEncoder(ConversionFlags flags) const;
+
virtual QByteArray name() const = 0;
virtual QList<QByteArray> aliases() const;
virtual int mibEnum() const = 0;
@@ -157,6 +160,7 @@ class Q_CORE_EXPORT QTextEncoder {
Q_DISABLE_COPY(QTextEncoder)
public:
explicit QTextEncoder(const QTextCodec *codec) : c(codec), state() {}
+ QTextEncoder(const QTextCodec *codec, QTextCodec::ConversionFlags flags);
~QTextEncoder();
QByteArray fromUnicode(const QString& str);
QByteArray fromUnicode(const QChar *uc, int len);
@@ -178,6 +182,7 @@ class Q_CORE_EXPORT QTextDecoder {
Q_DISABLE_COPY(QTextDecoder)
public:
explicit QTextDecoder(const QTextCodec *codec) : c(codec), state() {}
+ QTextDecoder(const QTextCodec *codec, QTextCodec::ConversionFlags flags);
~QTextDecoder();
QString toUnicode(const char* chars, int len);
QString toUnicode(const QByteArray &ba);
diff --git a/src/corelib/global/qglobal.h b/src/corelib/global/qglobal.h
index f51849b..99bbe42 100644
--- a/src/corelib/global/qglobal.h
+++ b/src/corelib/global/qglobal.h
@@ -44,11 +44,11 @@
#include <stddef.h>
-#define QT_VERSION_STR "4.6.2"
+#define QT_VERSION_STR "4.7.0"
/*
QT_VERSION is (major << 16) + (minor << 8) + patch.
*/
-#define QT_VERSION 0x040602
+#define QT_VERSION 0x040700
/*
can be used like #if (QT_VERSION >= QT_VERSION_CHECK(4, 4, 0))
*/
@@ -275,7 +275,7 @@ namespace QT_NAMESPACE {}
# endif
#endif
-#ifdef AUTODETECT_COCOA
+#ifdef QT_AUTODETECT_COCOA
# ifdef Q_OS_MAC64
# define QT_MAC_USE_COCOA 1
# define QT_BUILD_KEY QT_BUILD_KEY_COCOA
@@ -672,8 +672,9 @@ namespace QT_NAMESPACE {}
# define Q_ALIGNOF(type) __alignof__(type)
# define Q_TYPEOF(expr) __typeof__(expr)
# define Q_DECL_ALIGN(n) __attribute__((__aligned__(n)))
-// using CC 5.9: Warning: attribute visibility is unsupported and will be skipped..
-//# define Q_DECL_EXPORT __attribute__((__visibility__("default")))
+# endif
+# if __SUNPRO_CC >= 0x550
+# define Q_DECL_EXPORT __global
# endif
# if __SUNPRO_CC < 0x5a0
# define Q_NO_TEMPLATE_FRIENDS
@@ -1540,6 +1541,7 @@ inline QT3_SUPPORT bool qt_winUnicode() { return true; }
inline QT3_SUPPORT int qWinVersion() { return QSysInfo::WindowsVersion; }
#endif
+// ### Qt 5: remove Win9x support macros QT_WA and QT_WA_INLINE.
#define QT_WA(unicode, ansi) unicode
#define QT_WA_INLINE(unicode, ansi) (unicode)
diff --git a/src/corelib/global/qnamespace.h b/src/corelib/global/qnamespace.h
index 177bee4..35ff8e7 100644
--- a/src/corelib/global/qnamespace.h
+++ b/src/corelib/global/qnamespace.h
@@ -1235,7 +1235,10 @@ public:
BusyCursor,
OpenHandCursor,
ClosedHandCursor,
- LastCursor = ClosedHandCursor,
+ DragCopyCursor,
+ DragMoveCursor,
+ DragLinkCursor,
+ LastCursor = DragLinkCursor,
BitmapCursor = 24,
CustomCursor = 25
diff --git a/src/corelib/global/qnamespace.qdoc b/src/corelib/global/qnamespace.qdoc
index 6627c76..1f1c8f7 100644
--- a/src/corelib/global/qnamespace.qdoc
+++ b/src/corelib/global/qnamespace.qdoc
@@ -157,7 +157,7 @@
\value AA_MacDontSwapCtrlAndMeta On Mac OS X by default, Qt swaps the
Control and Meta (Command) keys (i.e., whenever Control is pressed, Qt
- sends Meta and whenever Meta is pressed Control is sent. When this
+ sends Meta, and whenever Meta is pressed Control is sent). When this
attribute is true, Qt will not do the flip. QKeySequence::StandardShortcuts
will also flip accordingly (i.e., QKeySequence::Copy will be
Command+C on the keyboard regardless of the value set, though what is output for
@@ -493,7 +493,7 @@
\omitvalue WordBreak
\omitvalue TextForceLeftToRight
\omitvalue TextForceRightToLeft
- \omitvalue TextLongestVariant Always use the longest variant when computing the size of a multi-variant string
+ \omitvalue TextLongestVariant Always use the longest variant when computing the size of a multi-variant string.
You can use as many modifier flags as you want, except that
Qt::TextSingleLine and Qt::TextWordWrap cannot be combined.
@@ -2115,7 +2115,7 @@
On some platforms this implies Qt::WindowSystemMenuHint for it to work.
\value MacWindowToolBarButtonHint On Mac OS X adds a tool bar button (i.e.,
- the oblong button that is on the top right of windows that have toolbars.
+ the oblong button that is on the top right of windows that have toolbars).
\value BypassGraphicsProxyWidget Prevents the window and its children from
automatically embedding themselves into a QGraphicsProxyWidget if the
@@ -2508,6 +2508,15 @@
operations that allow the user to interact with
the application while they are performed in the
background.
+ \value DragMoveCursor
+ A cursor that is usually used when dragging an item.
+ \value DragCopyCursor
+ A cursor that is usually used when dragging an item
+ to copy it.
+ \value DragLinkCursor
+ A cursor that is usually used when dragging an item
+ to make a link to it.
+
\value BitmapCursor
\omitvalue LastCursor
\omitvalue CustomCursor
diff --git a/src/corelib/io/io.pri b/src/corelib/io/io.pri
index 9178a2e..ef448b1 100644
--- a/src/corelib/io/io.pri
+++ b/src/corelib/io/io.pri
@@ -6,6 +6,7 @@ HEADERS += \
io/qbuffer.h \
io/qdatastream.h \
io/qdatastream_p.h \
+ io/qdataurl_p.h \
io/qdebug.h \
io/qdir.h \
io/qdiriterator.h \
@@ -34,6 +35,7 @@ SOURCES += \
io/qabstractfileengine.cpp \
io/qbuffer.cpp \
io/qdatastream.cpp \
+ io/qdataurl.cpp \
io/qdebug.cpp \
io/qdir.cpp \
io/qdiriterator.cpp \
diff --git a/src/corelib/io/qdatastream.cpp b/src/corelib/io/qdatastream.cpp
index 82d3b79..7c1887e 100644
--- a/src/corelib/io/qdatastream.cpp
+++ b/src/corelib/io/qdatastream.cpp
@@ -48,6 +48,7 @@
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
+#include "qendian.h"
QT_BEGIN_NAMESPACE
@@ -570,6 +571,7 @@ void QDataStream::setByteOrder(ByteOrder bo)
\value Qt_4_4 Version 10 (Qt 4.4)
\value Qt_4_5 Version 11 (Qt 4.5)
\value Qt_4_6 Version 12 (Qt 4.6)
+ \value Qt_4_7 Same as Qt_4_6.
\sa setVersion(), version()
*/
@@ -672,24 +674,12 @@ QDataStream &QDataStream::operator>>(qint16 &i)
{
i = 0;
CHECK_STREAM_PRECOND(*this)
- if (noswap) {
- if (dev->read((char *)&i, 2) != 2) {
- i = 0;
- setStatus(ReadPastEnd);
- }
+ if (dev->read((char *)&i, 2) != 2) {
+ i = 0;
+ setStatus(ReadPastEnd);
} else {
- union {
- qint16 val1;
- char val2[2];
- } x;
- char *p = x.val2;
- char b[2];
- if (dev->read(b, 2) == 2) {
- *p++ = b[1];
- *p = b[0];
- i = x.val1;
- } else {
- setStatus(ReadPastEnd);
+ if (!noswap) {
+ i = qbswap(i);
}
}
return *this;
@@ -715,26 +705,12 @@ QDataStream &QDataStream::operator>>(qint32 &i)
{
i = 0;
CHECK_STREAM_PRECOND(*this)
- if (noswap) {
- if (dev->read((char *)&i, 4) != 4) {
- i = 0;
- setStatus(ReadPastEnd);
- }
- } else { // swap bytes
- union {
- qint32 val1;
- char val2[4];
- } x;
- char *p = x.val2;
- char b[4];
- if (dev->read(b, 4) == 4) {
- *p++ = b[3];
- *p++ = b[2];
- *p++ = b[1];
- *p = b[0];
- i = x.val1;
- } else {
- setStatus(ReadPastEnd);
+ if (dev->read((char *)&i, 4) != 4) {
+ i = 0;
+ setStatus(ReadPastEnd);
+ } else {
+ if (!noswap) {
+ i = qbswap(i);
}
}
return *this;
@@ -763,31 +739,14 @@ QDataStream &QDataStream::operator>>(qint64 &i)
quint32 i1, i2;
*this >> i2 >> i1;
i = ((quint64)i1 << 32) + i2;
- } else if (noswap) { // no conversion needed
+ } else {
if (dev->read((char *)&i, 8) != 8) {
i = qint64(0);
setStatus(ReadPastEnd);
- }
- } else { // swap bytes
- union {
- qint64 val1;
- char val2[8];
- } x;
-
- char *p = x.val2;
- char b[8];
- if (dev->read(b, 8) == 8) {
- *p++ = b[7];
- *p++ = b[6];
- *p++ = b[5];
- *p++ = b[4];
- *p++ = b[3];
- *p++ = b[2];
- *p++ = b[1];
- *p = b[0];
- i = x.val1;
} else {
- setStatus(ReadPastEnd);
+ if (!noswap) {
+ i = qbswap(i);
+ }
}
}
return *this;
@@ -827,27 +786,17 @@ QDataStream &QDataStream::operator>>(float &f)
f = 0.0f;
CHECK_STREAM_PRECOND(*this)
- if (noswap) {
- if (dev->read((char *)&f, 4) != 4) {
- f = 0.0f;
- setStatus(ReadPastEnd);
- }
- } else { // swap bytes
- union {
- float val1;
- char val2[4];
- } x;
-
- char *p = x.val2;
- char b[4];
- if (dev->read(b, 4) == 4) {
- *p++ = b[3];
- *p++ = b[2];
- *p++ = b[1];
- *p = b[0];
+ if (dev->read((char *)&f, 4) != 4) {
+ f = 0.0f;
+ setStatus(ReadPastEnd);
+ } else {
+ if (!noswap) {
+ union {
+ float val1;
+ quint32 val2;
+ } x;
+ x.val2 = qbswap(*reinterpret_cast<quint32 *>(&f));
f = x.val1;
- } else {
- setStatus(ReadPastEnd);
}
}
return *this;
@@ -880,30 +829,17 @@ QDataStream &QDataStream::operator>>(double &f)
f = 0.0;
CHECK_STREAM_PRECOND(*this)
#ifndef Q_DOUBLE_FORMAT
- if (noswap) {
- if (dev->read((char *)&f, 8) != 8) {
- f = 0.0;
- setStatus(ReadPastEnd);
- }
- } else { // swap bytes
- union {
- double val1;
- char val2[8];
- } x;
- char *p = x.val2;
- char b[8];
- if (dev->read(b, 8) == 8) {
- *p++ = b[7];
- *p++ = b[6];
- *p++ = b[5];
- *p++ = b[4];
- *p++ = b[3];
- *p++ = b[2];
- *p++ = b[1];
- *p = b[0];
+ if (dev->read((char *)&f, 8) != 8) {
+ f = 0.0;
+ setStatus(ReadPastEnd);
+ } else {
+ if (!noswap) {
+ union {
+ double val1;
+ quint64 val2;
+ } x;
+ x.val2 = qbswap(*reinterpret_cast<quint64 *>(&f));
f = x.val1;
- } else {
- setStatus(ReadPastEnd);
}
}
#else
@@ -1075,20 +1011,10 @@ QDataStream &QDataStream::operator<<(qint8 i)
QDataStream &QDataStream::operator<<(qint16 i)
{
CHECK_STREAM_PRECOND(*this)
- if (noswap) {
- dev->write((char *)&i, sizeof(qint16));
- } else { // swap bytes
- union {
- qint16 val1;
- char val2[2];
- } x;
- x.val1 = i;
- char *p = x.val2;
- char b[2];
- b[1] = *p++;
- b[0] = *p;
- dev->write(b, 2);
+ if (!noswap) {
+ i = qbswap(i);
}
+ dev->write((char *)&i, sizeof(qint16));
return *this;
}
@@ -1102,22 +1028,10 @@ QDataStream &QDataStream::operator<<(qint16 i)
QDataStream &QDataStream::operator<<(qint32 i)
{
CHECK_STREAM_PRECOND(*this)
- if (noswap) {
- dev->write((char *)&i, sizeof(qint32));
- } else { // swap bytes
- union {
- qint32 val1;
- char val2[4];
- } x;
- x.val1 = i;
- char *p = x.val2;
- char b[4];
- b[3] = *p++;
- b[2] = *p++;
- b[1] = *p++;
- b[0] = *p;
- dev->write(b, 4);
+ if (!noswap) {
+ i = qbswap(i);
}
+ dev->write((char *)&i, sizeof(qint32));
return *this;
}
@@ -1143,25 +1057,11 @@ QDataStream &QDataStream::operator<<(qint64 i)
quint32 i1 = i & 0xffffffff;
quint32 i2 = i >> 32;
*this << i2 << i1;
- } else if (noswap) { // no conversion needed
+ } else {
+ if (!noswap) {
+ i = qbswap(i);
+ }
dev->write((char *)&i, sizeof(qint64));
- } else { // swap bytes
- union {
- qint64 val1;
- char val2[8];
- } x;
- x.val1 = i;
- char *p = x.val2;
- char b[8];
- b[7] = *p++;
- b[6] = *p++;
- b[5] = *p++;
- b[4] = *p++;
- b[3] = *p++;
- b[2] = *p++;
- b[1] = *p++;
- b[0] = *p;
- dev->write(b, 8);
}
return *this;
}
@@ -1205,22 +1105,16 @@ QDataStream &QDataStream::operator<<(float f)
CHECK_STREAM_PRECOND(*this)
float g = f; // fixes float-on-stack problem
- if (noswap) { // no conversion needed
- dev->write((char *)&g, sizeof(float));
- } else { // swap bytes
+ if (!noswap) {
union {
float val1;
- char val2[4];
+ quint32 val2;
} x;
- x.val1 = f;
- char *p = x.val2;
- char b[4];
- b[3] = *p++;
- b[2] = *p++;
- b[1] = *p++;
- b[0] = *p;
- dev->write(b, 4);
+ x.val1 = g;
+ x.val2 = qbswap(x.val2);
+ g = x.val1;
}
+ dev->write((char *)&g, sizeof(float));
return *this;
}
@@ -1244,26 +1138,16 @@ QDataStream &QDataStream::operator<<(double f)
CHECK_STREAM_PRECOND(*this)
#ifndef Q_DOUBLE_FORMAT
- if (noswap) {
- dev->write((char *)&f, sizeof(double));
- } else {
+ if (!noswap) {
union {
double val1;
- char val2[8];
+ quint64 val2;
} x;
x.val1 = f;
- char *p = x.val2;
- char b[8];
- b[7] = *p++;
- b[6] = *p++;
- b[5] = *p++;
- b[4] = *p++;
- b[3] = *p++;
- b[2] = *p++;
- b[1] = *p++;
- b[0] = *p;
- dev->write(b, 8);
+ x.val2 = qbswap(x.val2);
+ f = x.val1;
}
+ dev->write((char *)&f, sizeof(double));
#else
union {
double val1;
diff --git a/src/corelib/io/qdatastream.h b/src/corelib/io/qdatastream.h
index afc16bc..ec4ba2f 100644
--- a/src/corelib/io/qdatastream.h
+++ b/src/corelib/io/qdatastream.h
@@ -84,10 +84,11 @@ public:
Qt_4_3 = 9,
Qt_4_4 = 10,
Qt_4_5 = 11,
- Qt_4_6 = 12
-#if QT_VERSION >= 0x040700
-#error Add the datastream version for this Qt version
+ Qt_4_6 = 12,
Qt_4_7 = Qt_4_6
+#if QT_VERSION >= 0x040800
+#error Add the datastream version for this Qt version
+ Qt_4_8 = Qt_4_7
#endif
};
diff --git a/src/corelib/io/qdataurl.cpp b/src/corelib/io/qdataurl.cpp
new file mode 100644
index 0000000..9bb896e
--- /dev/null
+++ b/src/corelib/io/qdataurl.cpp
@@ -0,0 +1,101 @@
+/****************************************************************************
+**
+** 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 QtCore module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qplatformdefs.h"
+#include "qurl.h"
+#include "private/qdataurl_p.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \internal
+
+ Decode a data: URL into its mimetype and payload. Returns a null string if
+ the URL could not be decoded.
+*/
+Q_CORE_EXPORT QPair<QString, QByteArray> qDecodeDataUrl(const QUrl &uri)
+{
+ QString mimeType;
+ QByteArray payload;
+
+ if (uri.scheme() == QLatin1String("data") && uri.host().isEmpty()) {
+ mimeType = QLatin1String("text/plain;charset=US-ASCII");
+
+ // the following would have been the correct thing, but
+ // reality often differs from the specification. People have
+ // data: URIs with ? and #
+ //QByteArray data = QByteArray::fromPercentEncoding(uri.encodedPath());
+ QByteArray data = QByteArray::fromPercentEncoding(uri.toEncoded());
+
+ // remove the data: scheme
+ data.remove(0, 5);
+
+ // parse it:
+ int pos = data.indexOf(',');
+ if (pos != -1) {
+ payload = data.mid(pos + 1);
+ data.truncate(pos);
+ data = data.trimmed();
+
+ // find out if the payload is encoded in Base64
+ if (data.endsWith(";base64")) {
+ payload = QByteArray::fromBase64(payload);
+ data.chop(7);
+ }
+
+ if (data.toLower().startsWith("charset")) {
+ int i = 7; // strlen("charset")
+ while (data.at(i) == ' ')
+ ++i;
+ if (data.at(i) == '=')
+ data.prepend("text/plain;");
+ }
+
+ if (!data.isEmpty())
+ mimeType = QLatin1String(data.trimmed());
+
+ }
+ }
+
+ return QPair<QString,QByteArray>(mimeType,payload);
+}
+
+QT_END_NAMESPACE
diff --git a/src/corelib/io/qdataurl_p.h b/src/corelib/io/qdataurl_p.h
new file mode 100644
index 0000000..be5b10d
--- /dev/null
+++ b/src/corelib/io/qdataurl_p.h
@@ -0,0 +1,67 @@
+/****************************************************************************
+**
+** 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 QtCore module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QDATAURL_P_H
+#define QDATAURL_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of qDecodeDataUrl. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "QtCore/qurl.h"
+#include "QtCore/qbytearray.h"
+#include "QtCore/qstring.h"
+#include "QtCore/qpair.h"
+
+QT_BEGIN_NAMESPACE
+
+Q_CORE_EXPORT QPair<QString, QByteArray> qDecodeDataUrl(const QUrl &url);
+
+QT_END_NAMESPACE
+
+#endif // QDATAURL_P_H
diff --git a/src/corelib/io/qdir.cpp b/src/corelib/io/qdir.cpp
index dc7f17e..f5d803e 100644
--- a/src/corelib/io/qdir.cpp
+++ b/src/corelib/io/qdir.cpp
@@ -52,13 +52,13 @@
#include "qregexp.h"
#include "qvector.h"
#include "qalgorithms.h"
+#include "qvarlengtharray.h"
+
#ifdef QT_BUILD_CORE_LIB
-# include "qresource.h"
+# include "qresource.h"
+# include "private/qcoreglobaldata_p.h"
#endif
-#include "qvarlengtharray.h"
-
-#include "private/qcoreglobaldata_p.h"
#include <stdlib.h>
QT_BEGIN_NAMESPACE
@@ -83,12 +83,10 @@ static QString driveSpec(const QString &path)
//************* QDirPrivate
class QDirPrivate
{
- QDir *q_ptr;
- Q_DECLARE_PUBLIC(QDir)
-
friend struct QScopedPointerDeleter<QDirPrivate>;
-protected:
- QDirPrivate(QDir*, const QDir *copy=0);
+
+public:
+ QDirPrivate(const QDir *copy = 0);
~QDirPrivate();
QString initFileEngine(const QString &file);
@@ -96,7 +94,6 @@ protected:
void updateFileLists() const;
void sortFileList(QDir::SortFlags, QFileInfoList &, QStringList *, QFileInfoList *) const;
-private:
#ifdef QT3_SUPPORT
QChar filterSepChar;
bool matchAllDirs;
@@ -109,28 +106,30 @@ private:
sep = QChar(QLatin1Char(' '));
return sep;
}
- static inline QStringList splitFilters(const QString &nameFilter, QChar sep=0) {
- if(sep == 0)
+ static inline QStringList splitFilters(const QString &nameFilter, QChar sep = 0) {
+ if (sep == 0)
sep = getFilterSepChar(nameFilter);
QStringList ret = nameFilter.split(sep);
- for(int i = 0; i < ret.count(); i++)
+ for (int i = 0; i < ret.count(); ++i)
ret[i] = ret[i].trimmed();
return ret;
}
struct Data {
inline Data()
- : ref(1), fileEngine(0)
- { clear(); }
+ : ref(1), fileEngine(0), listsDirty(1)
+ {}
inline Data(const Data &copy)
: ref(1), path(copy.path), nameFilters(copy.nameFilters), sort(copy.sort),
- filters(copy.filters), fileEngine(0)
- { clear(); }
+ filters(copy.filters), fileEngine(0), listsDirty(1)
+ {}
inline ~Data()
{ delete fileEngine; }
inline void clear() {
listsDirty = 1;
+ files.clear();
+ fileInfos.clear();
}
mutable QAtomicInt ref;
@@ -147,7 +146,6 @@ private:
} *data;
inline void setPath(const QString &p)
{
- detach(false);
QString path = p;
if ((path.endsWith(QLatin1Char('/')) || path.endsWith(QLatin1Char('\\')))
&& path.length() > 1) {
@@ -156,12 +154,9 @@ private:
#endif
path.truncate(path.length() - 1);
}
- if(!data->fileEngine || !QDir::isRelativePath(path))
- path = initFileEngine(path);
- data->fileEngine->setFileName(path);
+
// set the path to be the qt friendly version so then we can operate on it using just /
- data->path = data->fileEngine->fileName(QAbstractFileEngine::DefaultName);
- data->clear();
+ data->path = initFileEngine(path);
}
inline void reset() {
detach();
@@ -170,18 +165,16 @@ private:
void detach(bool createFileEngine = true);
};
-QDirPrivate::QDirPrivate(QDir *qq, const QDir *copy) : q_ptr(qq)
+QDirPrivate::QDirPrivate(const QDir *copy)
#ifdef QT3_SUPPORT
- , filterSepChar(0)
- , matchAllDirs(false)
+ : filterSepChar(0), matchAllDirs(false)
#endif
{
- if(copy) {
+ if (copy) {
copy->d_func()->data->ref.ref();
data = copy->d_func()->data;
} else {
data = new QDirPrivate::Data;
- data->clear();
}
}
@@ -190,18 +183,19 @@ QDirPrivate::~QDirPrivate()
if (!data->ref.deref())
delete data;
data = 0;
- q_ptr = 0;
}
/* For sorting */
-struct QDirSortItem {
+struct QDirSortItem
+{
mutable QString filename_cache;
mutable QString suffix_cache;
QFileInfo item;
};
-class QDirSortItemComparator {
+class QDirSortItemComparator
+{
int qt_cmp_si_sort_flags;
public:
QDirSortItemComparator(int flags) : qt_cmp_si_sort_flags(flags) {}
@@ -240,7 +234,7 @@ bool QDirSortItemComparator::operator()(const QDirSortItem &n1, const QDirSortIt
f2->suffix_cache = ic ? f2->item.suffix().toLower()
: f2->item.suffix();
- r = qt_cmp_si_sort_flags & QDir::LocaleAware
+ r = qt_cmp_si_sort_flags & QDir::LocaleAware
? f1->suffix_cache.localeAwareCompare(f2->suffix_cache)
: f1->suffix_cache.compare(f2->suffix_cache);
}
@@ -260,7 +254,7 @@ bool QDirSortItemComparator::operator()(const QDirSortItem &n1, const QDirSortIt
f2->filename_cache = ic ? f2->item.fileName().toLower()
: f2->item.fileName();
- r = qt_cmp_si_sort_flags & QDir::LocaleAware
+ r = qt_cmp_si_sort_flags & QDir::LocaleAware
? f1->filename_cache.localeAwareCompare(f2->filename_cache)
: f1->filename_cache.compare(f2->filename_cache);
}
@@ -274,16 +268,13 @@ bool QDirSortItemComparator::operator()(const QDirSortItem &n1, const QDirSortIt
inline void QDirPrivate::sortFileList(QDir::SortFlags sort, QFileInfoList &l,
QStringList *names, QFileInfoList *infos) const
{
- if(names)
- names->clear();
- if(infos)
- infos->clear();
+ // names and infos are always empty lists or 0 here
int n = l.size();
- if(n > 0) {
+ if (n > 0) {
if (n == 1 || (sort & QDir::SortByMask) == QDir::Unsorted) {
- if(infos)
+ if (infos)
*infos = l;
- if(names) {
+ if (names) {
for (int i = 0; i < n; ++i)
names->append(l.at(i).fileName());
}
@@ -291,13 +282,13 @@ inline void QDirPrivate::sortFileList(QDir::SortFlags sort, QFileInfoList &l,
QScopedArrayPointer<QDirSortItem> si(new QDirSortItem[n]);
for (int i = 0; i < n; ++i)
si[i].item = l.at(i);
- qSort(si.data(), si.data()+n, QDirSortItemComparator(sort));
+ qSort(si.data(), si.data() + n, QDirSortItemComparator(sort));
// put them back in the list(s)
- if(infos) {
+ if (infos) {
for (int i = 0; i < n; ++i)
infos->append(si[i].item);
}
- if(names) {
+ if (names) {
for (int i = 0; i < n; ++i)
names->append(si[i].item.fileName());
}
@@ -307,7 +298,7 @@ inline void QDirPrivate::sortFileList(QDir::SortFlags sort, QFileInfoList &l,
inline void QDirPrivate::updateFileLists() const
{
- if(data->listsDirty) {
+ if (data->listsDirty) {
QFileInfoList l;
QDirIterator it(data->path, data->nameFilters, data->filters);
while (it.hasNext()) {
@@ -319,12 +310,11 @@ inline void QDirPrivate::updateFileLists() const
}
}
-QString QDirPrivate::initFileEngine(const QString &path)
+inline QString QDirPrivate::initFileEngine(const QString &path)
{
detach(false);
- delete data->fileEngine;
- data->fileEngine = 0;
data->clear();
+ delete data->fileEngine;
data->fileEngine = QAbstractFileEngine::create(path);
return data->fileEngine->fileName(QAbstractFileEngine::DefaultName);
}
@@ -520,8 +510,7 @@ void QDirPrivate::detach(bool createFileEngine)
\sa currentPath()
*/
-
-QDir::QDir(const QString &path) : d_ptr(new QDirPrivate(this))
+QDir::QDir(const QString &path) : d_ptr(new QDirPrivate)
{
Q_D(QDir);
d->setPath(path.isEmpty() ? QString::fromLatin1(".") : path);
@@ -548,18 +537,17 @@ QDir::QDir(const QString &path) : d_ptr(new QDirPrivate(this))
\sa exists(), setPath(), setNameFilter(), setFilter(), setSorting()
*/
-
QDir::QDir(const QString &path, const QString &nameFilter,
- SortFlags sort, Filters filters) : d_ptr(new QDirPrivate(this))
+ SortFlags sort, Filters filters) : d_ptr(new QDirPrivate)
{
Q_D(QDir);
d->setPath(path.isEmpty() ? QString::fromLatin1(".") : path);
d->data->nameFilters = QDir::nameFiltersFromString(nameFilter);
bool empty = d->data->nameFilters.isEmpty();
- if(!empty) {
+ if (!empty) {
empty = true;
- for(int i = 0; i < d->data->nameFilters.size(); ++i) {
- if(!d->data->nameFilters.at(i).isEmpty()) {
+ for (int i = 0; i < d->data->nameFilters.size(); ++i) {
+ if (!d->data->nameFilters.at(i).isEmpty()) {
empty = false;
break;
}
@@ -577,8 +565,7 @@ QDir::QDir(const QString &path, const QString &nameFilter,
\sa operator=()
*/
-
-QDir::QDir(const QDir &dir) : d_ptr(new QDirPrivate(this, &dir))
+QDir::QDir(const QDir &dir) : d_ptr(new QDirPrivate(&dir))
{
}
@@ -586,7 +573,6 @@ QDir::QDir(const QDir &dir) : d_ptr(new QDirPrivate(this, &dir))
Destroys the QDir object frees up its resources. This has no
effect on the underlying directory in the file system.
*/
-
QDir::~QDir()
{
}
@@ -607,7 +593,6 @@ QDir::~QDir()
\sa path(), absolutePath(), exists(), cleanPath(), dirName(),
absoluteFilePath(), isRelative(), makeAbsolute()
*/
-
void QDir::setPath(const QString &path)
{
Q_D(QDir);
@@ -624,7 +609,6 @@ void QDir::setPath(const QString &path)
\sa setPath(), absolutePath(), exists(), cleanPath(), dirName(),
absoluteFilePath(), toNativeSeparators(), makeAbsolute()
*/
-
QString QDir::path() const
{
Q_D(const QDir);
@@ -639,7 +623,6 @@ QString QDir::path() const
\sa setPath(), canonicalPath(), exists(), cleanPath(),
dirName(), absoluteFilePath()
*/
-
QString QDir::absolutePath() const
{
Q_D(const QDir);
@@ -649,7 +632,6 @@ QString QDir::absolutePath() const
return cleanPath(ret);
}
-
/*!
Returns the canonical path, i.e. a path without symbolic links or
redundant "." or ".." elements.
@@ -666,12 +648,11 @@ QString QDir::absolutePath() const
\sa path(), absolutePath(), exists(), cleanPath(), dirName(),
absoluteFilePath()
*/
-
QString QDir::canonicalPath() const
{
Q_D(const QDir);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
return cleanPath(d->data->fileEngine->fileName(QAbstractFileEngine::CanonicalName));
}
@@ -687,7 +668,6 @@ QString QDir::canonicalPath() const
\sa path(), filePath(), absolutePath(), absoluteFilePath()
*/
-
QString QDir::dirName() const
{
Q_D(const QDir);
@@ -706,7 +686,6 @@ QString QDir::dirName() const
\sa dirName() absoluteFilePath(), isRelative(), canonicalPath()
*/
-
QString QDir::filePath(const QString &fileName) const
{
Q_D(const QDir);
@@ -714,7 +693,7 @@ QString QDir::filePath(const QString &fileName) const
return QString(fileName);
QString ret = d->data->path;
- if(!fileName.isEmpty()) {
+ if (!fileName.isEmpty()) {
if (!ret.isEmpty() && ret[(int)ret.length()-1] != QLatin1Char('/') && fileName[0] != QLatin1Char('/'))
ret += QLatin1Char('/');
ret += fileName;
@@ -730,13 +709,12 @@ QString QDir::filePath(const QString &fileName) const
\sa relativeFilePath() filePath() canonicalPath()
*/
-
QString QDir::absoluteFilePath(const QString &fileName) const
{
Q_D(const QDir);
if (isAbsolutePath(fileName))
return fileName;
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return fileName;
QString ret;
@@ -744,7 +722,7 @@ QString QDir::absoluteFilePath(const QString &fileName) const
if (isRelativePath(d->data->path)) //get pwd
ret = QFSFileEngine::currentPath(fileName);
#endif
- if(!d->data->path.isEmpty() && d->data->path != QLatin1String(".")) {
+ if (!d->data->path.isEmpty() && d->data->path != QLatin1String(".")) {
if (!ret.isEmpty() && !ret.endsWith(QLatin1Char('/')))
ret += QLatin1Char('/');
ret += d->data->path;
@@ -764,7 +742,6 @@ QString QDir::absoluteFilePath(const QString &fileName) const
\sa absoluteFilePath() filePath() canonicalPath()
*/
-
QString QDir::relativeFilePath(const QString &fileName) const
{
QString dir = absolutePath();
@@ -851,7 +828,7 @@ QString QDir::toNativeSeparators(const QString &pathName)
{
QString n(pathName);
#if defined(Q_FS_FAT) || defined(Q_OS_OS2EMX) || defined(Q_OS_SYMBIAN)
- for (int i=0; i<(int)n.length(); i++) {
+ for (int i = 0; i < (int)n.length(); ++i) {
if (n[i] == QLatin1Char('/'))
n[i] = QLatin1Char('\\');
}
@@ -875,7 +852,7 @@ QString QDir::fromNativeSeparators(const QString &pathName)
{
QString n(pathName);
#if defined(Q_FS_FAT) || defined(Q_OS_OS2EMX) || defined(Q_OS_SYMBIAN)
- for (int i=0; i<(int)n.length(); i++) {
+ for (int i = 0; i < (int)n.length(); ++i) {
if (n[i] == QLatin1Char('\\'))
n[i] = QLatin1Char('/');
}
@@ -894,7 +871,6 @@ QString QDir::fromNativeSeparators(const QString &pathName)
\sa cdUp(), isReadable(), exists(), path()
*/
-
bool QDir::cd(const QString &dirName)
{
Q_D(QDir);
@@ -930,14 +906,13 @@ bool QDir::cd(const QString &dirName)
}
}
}
- {
- QFileInfo fi(newPath);
- if (!(fi.exists() && fi.isDir()))
- return false;
- }
- d->setPath(newPath);
- refresh();
+ QDir dir(*this);
+ dir.setPath(newPath);
+ if (!dir.exists())
+ return false;
+
+ *this = dir;
return true;
}
@@ -951,7 +926,6 @@ bool QDir::cd(const QString &dirName)
\sa cd(), isReadable(), exists(), path()
*/
-
bool QDir::cdUp()
{
return cd(QString::fromLatin1(".."));
@@ -960,7 +934,6 @@ bool QDir::cdUp()
/*!
Returns the string list set by setNameFilters()
*/
-
QStringList QDir::nameFilters() const
{
Q_D(const QDir);
@@ -983,11 +956,11 @@ QStringList QDir::nameFilters() const
\sa nameFilters(), setFilter()
*/
-
void QDir::setNameFilters(const QStringList &nameFilters)
{
Q_D(QDir);
- d->detach();
+
+ d->reset();
d->data->nameFilters = nameFilters;
}
@@ -1001,7 +974,6 @@ void QDir::setNameFilters(const QStringList &nameFilters)
\sa {The Qt Resource System}, QResource::addSearchPath()
*/
-
void QDir::addResourceSearchPath(const QString &path)
{
#ifdef QT_BUILD_CORE_LIB
@@ -1039,7 +1011,7 @@ void QDir::setSearchPaths(const QString &prefix, const QStringList &searchPaths)
return;
}
- for (int i = 0; i < prefix.count(); i++) {
+ for (int i = 0; i < prefix.count(); ++i) {
if (!prefix.at(i).isLetterOrNumber()) {
qWarning("QDir::setSearchPaths: Prefix can only contain letters or numbers");
return;
@@ -1089,7 +1061,6 @@ QStringList QDir::searchPaths(const QString &prefix)
/*!
Returns the value set by setFilter()
*/
-
QDir::Filters QDir::filter() const
{
Q_D(const QDir);
@@ -1171,12 +1142,11 @@ QDir::Filters QDir::filter() const
\sa filter(), setNameFilters()
*/
-
void QDir::setFilter(Filters filters)
{
Q_D(QDir);
- d->detach();
+ d->reset();
d->data->filters = filters;
}
@@ -1185,7 +1155,6 @@ void QDir::setFilter(Filters filters)
\sa setSorting() SortFlag
*/
-
QDir::SortFlags QDir::sorting() const
{
Q_D(const QDir);
@@ -1231,16 +1200,14 @@ QDir::SortFlags QDir::sorting() const
\sa sorting() SortFlag
*/
-
void QDir::setSorting(SortFlags sort)
{
Q_D(QDir);
- d->detach();
+ d->reset();
d->data->sort = sort;
}
-
/*!
Returns the total number of directories and files in the directory.
@@ -1248,7 +1215,6 @@ void QDir::setSorting(SortFlags sort)
\sa operator[](), entryList()
*/
-
uint QDir::count() const
{
Q_D(const QDir);
@@ -1260,13 +1226,10 @@ uint QDir::count() const
/*!
Returns the file name at position \a pos in the list of file
names. Equivalent to entryList().at(index).
-
- Returns an empty string if \a pos is out of range or if the
- entryList() function failed.
+ \a pos must be a valid index position in the list (i.e., 0 <= pos < count()).
\sa count(), entryList()
*/
-
QString QDir::operator[](int pos) const
{
Q_D(const QDir);
@@ -1294,7 +1257,6 @@ QString QDir::operator[](int pos) const
\sa entryInfoList(), setNameFilters(), setSorting(), setFilter()
*/
-
QStringList QDir::entryList(Filters filters, SortFlags sort) const
{
Q_D(const QDir);
@@ -1342,7 +1304,6 @@ QFileInfoList QDir::entryInfoList(Filters filters, SortFlags sort) const
\sa entryInfoList(), setNameFilters(), setSorting(), setFilter()
*/
-
QStringList QDir::entryList(const QStringList &nameFilters, Filters filters,
SortFlags sort) const
{
@@ -1356,10 +1317,12 @@ QStringList QDir::entryList(const QStringList &nameFilters, Filters filters,
#endif
if (sort == NoSort)
sort = d->data->sort;
- if (filters == NoFilter && sort == NoSort && nameFilters == d->data->nameFilters) {
+
+ if (filters == d->data->filters && sort == d->data->sort && nameFilters == d->data->nameFilters) {
d->updateFileLists();
return d->data->files;
}
+
QFileInfoList l;
QDirIterator it(d->data->path, nameFilters, filters);
while (it.hasNext()) {
@@ -1387,7 +1350,6 @@ QStringList QDir::entryList(const QStringList &nameFilters, Filters filters,
\sa entryList(), setNameFilters(), setSorting(), setFilter(), isReadable(), exists()
*/
-
QFileInfoList QDir::entryInfoList(const QStringList &nameFilters, Filters filters,
SortFlags sort) const
{
@@ -1401,10 +1363,12 @@ QFileInfoList QDir::entryInfoList(const QStringList &nameFilters, Filters filter
#endif
if (sort == NoSort)
sort = d->data->sort;
- if (filters == NoFilter && sort == NoSort && nameFilters == d->data->nameFilters) {
+
+ if (filters == d->data->filters && sort == d->data->sort && nameFilters == d->data->nameFilters) {
d->updateFileLists();
return d->data->fileInfos;
}
+
QFileInfoList l;
QDirIterator it(d->data->path, nameFilters, filters);
while (it.hasNext()) {
@@ -1423,7 +1387,6 @@ QFileInfoList QDir::entryInfoList(const QStringList &nameFilters, Filters filter
\sa rmdir()
*/
-
bool QDir::mkdir(const QString &dirName) const
{
Q_D(const QDir);
@@ -1432,7 +1395,7 @@ bool QDir::mkdir(const QString &dirName) const
qWarning("QDir::mkdir: Empty or null file name(s)");
return false;
}
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
QString fn = filePath(dirName);
@@ -1448,7 +1411,6 @@ bool QDir::mkdir(const QString &dirName) const
\sa mkdir()
*/
-
bool QDir::rmdir(const QString &dirName) const
{
Q_D(const QDir);
@@ -1457,7 +1419,7 @@ bool QDir::rmdir(const QString &dirName) const
qWarning("QDir::rmdir: Empty or null file name(s)");
return false;
}
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
QString fn = filePath(dirName);
@@ -1474,7 +1436,6 @@ bool QDir::rmdir(const QString &dirName) const
\sa rmpath()
*/
-
bool QDir::mkpath(const QString &dirPath) const
{
Q_D(const QDir);
@@ -1483,7 +1444,7 @@ bool QDir::mkpath(const QString &dirPath) const
qWarning("QDir::mkpath: Empty or null file name(s)");
return false;
}
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
QString fn = filePath(dirPath);
@@ -1509,7 +1470,7 @@ bool QDir::rmpath(const QString &dirPath) const
qWarning("QDir::rmpath: Empty or null file name(s)");
return false;
}
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
QString fn = filePath(dirPath);
@@ -1525,17 +1486,16 @@ bool QDir::rmpath(const QString &dirPath) const
\sa QFileInfo::isReadable()
*/
-
-
bool QDir::isReadable() const
{
Q_D(const QDir);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
- const QAbstractFileEngine::FileFlags info = d->data->fileEngine->fileFlags(QAbstractFileEngine::DirectoryType
- |QAbstractFileEngine::PermsMask);
- if(!(info & QAbstractFileEngine::DirectoryType))
+ const QAbstractFileEngine::FileFlags info =
+ d->data->fileEngine->fileFlags(QAbstractFileEngine::DirectoryType
+ | QAbstractFileEngine::PermsMask);
+ if (!(info & QAbstractFileEngine::DirectoryType))
return false;
return info & QAbstractFileEngine::ReadUserPerm;
}
@@ -1551,19 +1511,17 @@ bool QDir::isReadable() const
\sa QFileInfo::exists(), QFile::exists()
*/
-
bool QDir::exists() const
{
Q_D(const QDir);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
const QAbstractFileEngine::FileFlags info =
- d->data->fileEngine->fileFlags(
- QAbstractFileEngine::DirectoryType
- | QAbstractFileEngine::ExistsFlag
- | QAbstractFileEngine::Refresh);
- if(!(info & QAbstractFileEngine::DirectoryType))
+ d->data->fileEngine->fileFlags(QAbstractFileEngine::DirectoryType
+ | QAbstractFileEngine::ExistsFlag
+ | QAbstractFileEngine::Refresh);
+ if (!(info & QAbstractFileEngine::DirectoryType))
return false;
return info & QAbstractFileEngine::ExistsFlag;
}
@@ -1580,12 +1538,11 @@ bool QDir::exists() const
\sa root(), rootPath()
*/
-
bool QDir::isRoot() const
{
Q_D(const QDir);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return true;
return d->data->fileEngine->fileFlags(QAbstractFileEngine::FlagsMask) & QAbstractFileEngine::RootFlag;
}
@@ -1615,12 +1572,11 @@ bool QDir::isRoot() const
\sa makeAbsolute() isAbsolute() isAbsolutePath() cleanPath()
*/
-
bool QDir::isRelative() const
{
Q_D(const QDir);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->data->fileEngine->isRelativePath();
}
@@ -1633,20 +1589,19 @@ bool QDir::isRelative() const
\sa isAbsolute() isAbsolutePath() isRelative() cleanPath()
*/
-
bool QDir::makeAbsolute() // ### What do the return values signify?
{
Q_D(QDir);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
QString absolutePath = d->data->fileEngine->fileName(QAbstractFileEngine::AbsoluteName);
- if(QDir::isRelativePath(absolutePath))
+ if (QDir::isRelativePath(absolutePath))
return false;
d->detach();
d->data->path = absolutePath;
d->data->fileEngine->setFileName(absolutePath);
- if(!(d->data->fileEngine->fileFlags(QAbstractFileEngine::TypesMask) & QAbstractFileEngine::DirectoryType))
+ if (!(d->data->fileEngine->fileFlags(QAbstractFileEngine::TypesMask) & QAbstractFileEngine::DirectoryType))
return false;
return true;
}
@@ -1660,22 +1615,21 @@ bool QDir::makeAbsolute() // ### What do the return values signify?
\snippet doc/src/snippets/code/src_corelib_io_qdir.cpp 10
*/
-
bool QDir::operator==(const QDir &dir) const
{
const QDirPrivate *d = d_func();
const QDirPrivate *other = dir.d_func();
- if(d->data == other->data)
+ if (d->data == other->data)
return true;
Q_ASSERT(d->data->fileEngine && other->data->fileEngine);
- if(d->data->fileEngine->caseSensitive() != other->data->fileEngine->caseSensitive())
+ if (d->data->fileEngine->caseSensitive() != other->data->fileEngine->caseSensitive())
return false;
- if(d->data->filters == other->data->filters
+ if (d->data->filters == other->data->filters
&& d->data->sort == other->data->sort
&& d->data->nameFilters == other->data->nameFilters) {
QString dir1 = absolutePath(), dir2 = dir.absolutePath();
- if(!other->data->fileEngine->caseSensitive())
+ if (!other->data->fileEngine->caseSensitive())
return (dir1.toLower() == dir2.toLower());
return (dir1 == dir2);
@@ -1688,7 +1642,6 @@ bool QDir::operator==(const QDir &dir) const
Makes a copy of the \a dir object and assigns it to this QDir
object.
*/
-
QDir &QDir::operator=(const QDir &dir)
{
if (this == &dir)
@@ -1707,7 +1660,6 @@ QDir &QDir::operator=(const QDir &dir)
Use setPath() instead.
*/
-
QDir &QDir::operator=(const QString &path)
{
Q_D(QDir);
@@ -1728,22 +1680,19 @@ QDir &QDir::operator=(const QString &path)
\snippet doc/src/snippets/code/src_corelib_io_qdir.cpp 11
*/
-
/*!
Removes the file, \a fileName.
Returns true if the file is removed successfully; otherwise
returns false.
*/
-
bool QDir::remove(const QString &fileName)
{
if (fileName.isEmpty()) {
qWarning("QDir::remove: Empty or null file name");
return false;
}
- QString p = filePath(fileName);
- return QFile::remove(p);
+ return QFile::remove(filePath(fileName));
}
/*!
@@ -1757,7 +1706,6 @@ bool QDir::remove(const QString &fileName)
fail. For example, on at least one file system rename() fails if
\a newName points to an open file.
*/
-
bool QDir::rename(const QString &oldName, const QString &newName)
{
Q_D(QDir);
@@ -1766,11 +1714,11 @@ bool QDir::rename(const QString &oldName, const QString &newName)
qWarning("QDir::rename: Empty or null file name(s)");
return false;
}
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
QFile file(filePath(oldName));
- if(!file.exists())
+ if (!file.exists())
return false;
return file.rename(filePath(newName));
}
@@ -1785,15 +1733,13 @@ bool QDir::rename(const QString &oldName, const QString &newName)
\sa QFileInfo::exists(), QFile::exists()
*/
-
bool QDir::exists(const QString &name) const
{
if (name.isEmpty()) {
qWarning("QDir::exists: Empty or null file name");
return false;
}
- QString tmp = filePath(name);
- return QFile::exists(tmp);
+ return QFile::exists(filePath(name));
}
/*!
@@ -1805,7 +1751,6 @@ bool QDir::exists(const QString &name) const
\sa root(), rootPath()
*/
-
QFileInfoList QDir::drives()
{
#ifdef QT_NO_FSFILEENGINE
@@ -1825,7 +1770,6 @@ QFileInfoList QDir::drives()
user using their operating system's separator use
toNativeSeparators().
*/
-
QChar QDir::separator()
{
#if defined (Q_FS_FAT) || defined(Q_WS_WIN) || defined(Q_OS_SYMBIAN)
@@ -1844,9 +1788,8 @@ QChar QDir::separator()
Returns true if the directory was successfully changed; otherwise
returns false.
- \sa current() currentPath() home() root() temp()
+ \sa current(), currentPath(), home(), root(), temp()
*/
-
bool QDir::setCurrent(const QString &path)
{
#ifdef QT_NO_FSFILEENGINE
@@ -1865,13 +1808,13 @@ bool QDir::setCurrent(const QString &path)
The directory is constructed using the absolute path of the current directory,
ensuring that its path() will be the same as its absolutePath().
- \sa currentPath(), home(), root(), temp()
+ \sa currentPath(), setCurrent(), home(), root(), temp()
*/
/*!
Returns the absolute path of the application's current directory.
- \sa current(), homePath(), rootPath(), tempPath()
+ \sa current(), setCurrent(), homePath(), rootPath(), tempPath()
*/
QString QDir::currentPath()
{
@@ -1888,7 +1831,7 @@ QString QDir::currentPath()
Use currentPath() instead.
- \sa currentPath()
+ \sa currentPath(), setCurrent()
*/
/*!
@@ -1945,14 +1888,14 @@ QString QDir::homePath()
}
/*!
- \fn QString QDir::homeDirPath()
+ \fn QString QDir::homeDirPath()
- Returns the absolute path of the user's home directory.
+ Returns the absolute path of the user's home directory.
- Use homePath() instead.
+ Use homePath() instead.
- \sa homePath()
- */
+ \sa homePath()
+*/
/*!
\fn QDir QDir::temp()
@@ -2018,13 +1961,13 @@ QString QDir::rootPath()
}
/*!
- \fn QString QDir::rootDirPath()
+ \fn QString QDir::rootDirPath()
- Returns the absolute path of the root directory.
+ Returns the absolute path of the root directory.
- Use rootPath() instead.
+ Use rootPath() instead.
- \sa rootPath()
+ \sa rootPath()
*/
#ifndef QT_NO_REGEXP
@@ -2037,11 +1980,9 @@ QString QDir::rootPath()
\sa {QRegExp wildcard matching}, QRegExp::exactMatch() entryList() entryInfoList()
*/
-
-
bool QDir::match(const QStringList &filters, const QString &fileName)
{
- for(QStringList::ConstIterator sit = filters.begin(); sit != filters.end(); ++sit) {
+ for (QStringList::ConstIterator sit = filters.constBegin(); sit != filters.constEnd(); ++sit) {
QRegExp rx(*sit, Qt::CaseInsensitive, QRegExp::Wildcard);
if (rx.exactMatch(fileName))
return true;
@@ -2057,12 +1998,11 @@ bool QDir::match(const QStringList &filters, const QString &fileName)
\sa {QRegExp wildcard matching}, QRegExp::exactMatch() entryList() entryInfoList()
*/
-
bool QDir::match(const QString &filter, const QString &fileName)
{
return match(nameFiltersFromString(filter), fileName);
}
-#endif
+#endif // QT_NO_REGEXP
/*!
Removes all multiple directory separators "/" and resolves any
@@ -2075,15 +2015,14 @@ bool QDir::match(const QString &filter, const QString &fileName)
\sa absolutePath() canonicalPath()
*/
-
QString QDir::cleanPath(const QString &path)
{
if (path.isEmpty())
return path;
QString name = path;
QChar dir_separator = separator();
- if(dir_separator != QLatin1Char('/'))
- name.replace(dir_separator, QLatin1Char('/'));
+ if (dir_separator != QLatin1Char('/'))
+ name.replace(dir_separator, QLatin1Char('/'));
int used = 0, levels = 0;
const int len = name.length();
@@ -2091,27 +2030,27 @@ QString QDir::cleanPath(const QString &path)
QChar *out = outVector.data();
const QChar *p = name.unicode();
- for(int i = 0, last = -1, iwrite = 0; i < len; i++) {
- if(p[i] == QLatin1Char('/')) {
- while(i < len-1 && p[i+1] == QLatin1Char('/')) {
+ for (int i = 0, last = -1, iwrite = 0; i < len; ++i) {
+ if (p[i] == QLatin1Char('/')) {
+ while (i < len-1 && p[i+1] == QLatin1Char('/')) {
#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) //allow unc paths
- if(!i)
+ if (!i)
break;
#endif
i++;
}
bool eaten = false;
- if(i < len - 1 && p[i+1] == QLatin1Char('.')) {
+ if (i < len - 1 && p[i+1] == QLatin1Char('.')) {
int dotcount = 1;
- if(i < len - 2 && p[i+2] == QLatin1Char('.'))
+ if (i < len - 2 && p[i+2] == QLatin1Char('.'))
dotcount++;
- if(i == len - dotcount - 1) {
- if(dotcount == 1) {
+ if (i == len - dotcount - 1) {
+ if (dotcount == 1) {
break;
- } else if(levels) {
- if(last == -1) {
- for(int i2 = iwrite-1; i2 >= 0; i2--) {
- if(out[i2] == QLatin1Char('/')) {
+ } else if (levels) {
+ if (last == -1) {
+ for (int i2 = iwrite-1; i2 >= 0; i2--) {
+ if (out[i2] == QLatin1Char('/')) {
last = i2;
break;
}
@@ -2120,11 +2059,11 @@ QString QDir::cleanPath(const QString &path)
used -= iwrite - last - 1;
break;
}
- } else if(p[i+dotcount+1] == QLatin1Char('/')) {
- if(dotcount == 2 && levels) {
- if(last == -1 || iwrite - last == 1) {
- for(int i2 = (last == -1) ? (iwrite-1) : (last-1); i2 >= 0; i2--) {
- if(out[i2] == QLatin1Char('/')) {
+ } else if (p[i+dotcount+1] == QLatin1Char('/')) {
+ if (dotcount == 2 && levels) {
+ if (last == -1 || iwrite - last == 1) {
+ for (int i2 = (last == -1) ? (iwrite-1) : (last-1); i2 >= 0; i2--) {
+ if (out[i2] == QLatin1Char('/')) {
eaten = true;
last = i2;
break;
@@ -2133,7 +2072,7 @@ QString QDir::cleanPath(const QString &path)
} else {
eaten = true;
}
- if(eaten) {
+ if (eaten) {
levels--;
used -= iwrite - last;
iwrite = last;
@@ -2145,38 +2084,38 @@ QString QDir::cleanPath(const QString &path)
iwrite = qMax(0, last);
last = -1;
++i;
- } else if(dotcount == 1) {
+ } else if (dotcount == 1) {
eaten = true;
}
- if(eaten)
+ if (eaten)
i += dotcount;
} else {
levels++;
}
- } else if(last != -1 && iwrite - last == 1) {
+ } else if (last != -1 && iwrite - last == 1) {
#if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
eaten = (iwrite > 2);
#else
eaten = true;
#endif
last = -1;
- } else if(last != -1 && i == len-1) {
+ } else if (last != -1 && i == len-1) {
eaten = true;
} else {
levels++;
}
- if(!eaten)
+ if (!eaten)
last = i - (i - iwrite);
else
continue;
- } else if(!i && p[i] == QLatin1Char('.')) {
+ } else if (!i && p[i] == QLatin1Char('.')) {
int dotcount = 1;
- if(len >= 1 && p[1] == QLatin1Char('.'))
+ if (len >= 1 && p[1] == QLatin1Char('.'))
dotcount++;
- if(len >= dotcount && p[dotcount] == QLatin1Char('/')) {
- if(dotcount == 1) {
+ if (len >= dotcount && p[dotcount] == QLatin1Char('/')) {
+ if (dotcount == 1) {
i++;
- while(i+1 < len-1 && p[i+1] == QLatin1Char('/'))
+ while (i+1 < len-1 && p[i+1] == QLatin1Char('/'))
i++;
continue;
}
@@ -2185,16 +2124,15 @@ QString QDir::cleanPath(const QString &path)
out[iwrite++] = p[i];
used++;
}
- QString ret;
- if(used == len)
- ret = name;
- else
- ret = QString(out, used);
+ QString ret = (used == len ? name : QString(out, used));
// Strip away last slash except for root directories
- if (ret.endsWith(QLatin1Char('/'))
- && !(ret.size() == 1 || (ret.size() == 3 && ret.at(1) == QLatin1Char(':'))))
- ret = ret.left(ret.length() - 1);
+ if (ret.length() > 1 && ret.endsWith(QLatin1Char('/'))) {
+#ifdef Q_OS_WIN
+ if (!(ret.length() == 3 && ret.at(1) == QLatin1Char(':')))
+#endif
+ ret.chop(1);
+ }
return ret;
}
@@ -2205,7 +2143,6 @@ QString QDir::cleanPath(const QString &path)
\sa isRelative() isAbsolutePath() makeAbsolute()
*/
-
bool QDir::isRelativePath(const QString &path)
{
return QFileInfo(path).isRelative();
@@ -2214,12 +2151,11 @@ bool QDir::isRelativePath(const QString &path)
/*!
Refreshes the directory information.
*/
-
void QDir::refresh() const
{
Q_D(const QDir);
- d->data->clear();
+ const_cast<QDirPrivate *>(d)->reset();
}
/*!
@@ -2229,7 +2165,6 @@ void QDir::refresh() const
there is more than one filter, each pair of filters is separated
by a space or by a semicolon.)
*/
-
QStringList QDir::nameFiltersFromString(const QString &nameFilter)
{
return QDirPrivate::splitFilters(nameFilter);
@@ -2309,6 +2244,8 @@ bool QDir::matchAllDirs() const
void QDir::setMatchAllDirs(bool on)
{
Q_D(QDir);
+
+ d->reset();
d->matchAllDirs = on;
}
@@ -2421,7 +2358,8 @@ void QDir::setNameFilter(const QString &nameFilter)
Use QDir::SortFlags instead.
*/
-#endif
+#endif // QT3_SUPPORT
+
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, QDir::Filters filters)
{
@@ -2484,9 +2422,6 @@ QDebug operator<<(QDebug debug, const QDir &dir)
<< ')';
return debug.space();
}
-
-
-
-#endif
+#endif // QT_NO_DEBUG_STREAM
QT_END_NAMESPACE
diff --git a/src/corelib/io/qdir.h b/src/corelib/io/qdir.h
index 6be4922..186dd2f 100644
--- a/src/corelib/io/qdir.h
+++ b/src/corelib/io/qdir.h
@@ -83,7 +83,7 @@ public:
Modified = 0x080,
Hidden = 0x100,
System = 0x200,
-
+
AccessMask = 0x3F0,
AllDirs = 0x400,
@@ -215,6 +215,7 @@ public:
static bool match(const QStringList &filters, const QString &fileName);
static bool match(const QString &filter, const QString &fileName);
#endif
+
static QString cleanPath(const QString &path);
void refresh() const;
@@ -246,7 +247,7 @@ public:
inline QT3_SUPPORT static QString homeDirPath() { return homePath(); }
inline QT3_SUPPORT static QString rootDirPath() { return rootPath(); }
inline QT3_SUPPORT static QString cleanDirPath(const QString &name) { return cleanPath(name); }
-#endif
+#endif // QT3_SUPPORT
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QDir::Filters)
diff --git a/src/corelib/io/qfileinfo.cpp b/src/corelib/io/qfileinfo.cpp
index e90529e..625098e 100644
--- a/src/corelib/io/qfileinfo.cpp
+++ b/src/corelib/io/qfileinfo.cpp
@@ -41,12 +41,8 @@
#include "qplatformdefs.h"
#include "qfileinfo.h"
-#include "qdatetime.h"
-#include "qabstractfileengine.h"
#include "qfsfileengine_p.h"
#include "qglobal.h"
-#include "qatomic.h"
-#include "qhash.h"
#include "qdir.h"
#include "qfileinfo_p.h"
@@ -54,7 +50,7 @@ QT_BEGIN_NAMESPACE
QFileInfoPrivate::QFileInfoPrivate(const QFileInfo *copy)
{
- if(copy) {
+ if (copy) {
copy->d_func()->data->ref.ref();
data = copy->d_func()->data;
} else {
@@ -81,7 +77,8 @@ void QFileInfoPrivate::initFileEngine(const QString &file)
bool QFileInfoPrivate::hasAccess(Access access) const
{
- if (!(getFileFlags(QAbstractFileEngine::FileInfoAll) & QAbstractFileEngine::LocalDiskFlag)) {
+ if (!(getFileFlags(QAbstractFileEngine::PermsMask
+ | QAbstractFileEngine::LocalDiskFlag) & QAbstractFileEngine::LocalDiskFlag)) {
switch (access) {
case ReadAccess:
return getFileFlags(QAbstractFileEngine::ReadUserPerm);
@@ -129,86 +126,104 @@ void QFileInfoPrivate::detach()
QString QFileInfoPrivate::getFileName(QAbstractFileEngine::FileName name) const
{
- if(data->cache_enabled && !data->fileNames[(int)name].isNull())
+ if (data->cache_enabled && !data->fileNames[(int)name].isNull())
return data->fileNames[(int)name];
QString ret = data->fileEngine->fileName(name);
- if(data->cache_enabled)
+ if (ret.isNull())
+ ret = QLatin1String("");
+ if (data->cache_enabled)
data->fileNames[(int)name] = ret;
return ret;
}
+QString QFileInfoPrivate::getFileOwner(QAbstractFileEngine::FileOwner own) const
+{
+ if (data->cache_enabled && !data->fileOwners[(int)own].isNull())
+ return data->fileOwners[(int)own];
+ QString ret = data->fileEngine->owner(own);
+ if (ret.isNull())
+ ret = QLatin1String("");
+ if (data->cache_enabled)
+ data->fileOwners[(int)own] = ret;
+ return ret;
+}
+
uint QFileInfoPrivate::getFileFlags(QAbstractFileEngine::FileFlags request) const
{
- // We split the testing into tests for for LinkType, BundleType and the rest.
+ // We split the testing into tests for for LinkType, BundleType, PermsMask
+ // and the rest.
+ // Tests for file permissions on Windows can be slow, expecially on network
+ // paths and NTFS drives.
// In order to determine if a file is a symlink or not, we have to lstat().
// If we're not interested in that information, we might as well avoid one
// extra syscall. Bundle detecton on Mac can be slow, expecially on network
// paths, so we separate out that as well.
- QAbstractFileEngine::FileFlags flags;
- if (!data->getCachedFlag(CachedFileFlags)) {
- QAbstractFileEngine::FileFlags req = QAbstractFileEngine::FileInfoAll;
- req &= (~QAbstractFileEngine::LinkType);
- req &= (~QAbstractFileEngine::BundleType);
+ QAbstractFileEngine::FileFlags req = 0;
+ uint cachedFlags = 0;
- flags = data->fileEngine->fileFlags(req);
- data->setCachedFlag(CachedFileFlags);
- data->fileFlags |= uint(flags);
- } else {
- flags = QAbstractFileEngine::FileFlags(data->fileFlags & request);
- }
+ if (request & (QAbstractFileEngine::FlagsMask | QAbstractFileEngine::TypesMask)) {
+ if (!data->getCachedFlag(CachedFileFlags)) {
+ req |= QAbstractFileEngine::FlagsMask;
+ req |= QAbstractFileEngine::TypesMask;
+ req &= (~QAbstractFileEngine::LinkType);
+ req &= (~QAbstractFileEngine::BundleType);
- if (request & QAbstractFileEngine::LinkType) {
- if (!data->getCachedFlag(CachedLinkTypeFlag)) {
- QAbstractFileEngine::FileFlags linkflag;
- linkflag = data->fileEngine->fileFlags(QAbstractFileEngine::LinkType);
+ cachedFlags |= CachedFileFlags;
+ }
- data->setCachedFlag(CachedLinkTypeFlag);
- data->fileFlags |= uint(linkflag);
- flags |= linkflag;
+ if (request & QAbstractFileEngine::LinkType) {
+ if (!data->getCachedFlag(CachedLinkTypeFlag)) {
+ req |= QAbstractFileEngine::LinkType;
+ cachedFlags |= CachedLinkTypeFlag;
+ }
}
- }
- if (request & QAbstractFileEngine::BundleType) {
- if (!data->getCachedFlag(CachedBundleTypeFlag)) {
- QAbstractFileEngine::FileFlags bundleflag;
- bundleflag = data->fileEngine->fileFlags(QAbstractFileEngine::BundleType);
+ if (request & QAbstractFileEngine::BundleType) {
+ if (!data->getCachedFlag(CachedBundleTypeFlag)) {
+ req |= QAbstractFileEngine::BundleType;
+ cachedFlags |= CachedBundleTypeFlag;
+ }
+ }
+ }
- data->setCachedFlag(CachedBundleTypeFlag);
- data->fileFlags |= uint(bundleflag);
- flags |= bundleflag;
+ if (request & QAbstractFileEngine::PermsMask) {
+ if (!data->getCachedFlag(CachedPerms)) {
+ req |= QAbstractFileEngine::PermsMask;
+ cachedFlags |= CachedPerms;
}
}
- // no else branch
- // if we had it cached, it was caught in the previous else branch
+ if (req) {
+ if (data->cache_enabled)
+ req &= (~QAbstractFileEngine::Refresh);
+ else
+ req |= QAbstractFileEngine::Refresh;
- return flags & request;
+ QAbstractFileEngine::FileFlags flags = data->fileEngine->fileFlags(req);
+ data->fileFlags |= uint(flags);
+ data->setCachedFlag(cachedFlags);
+ }
+
+ return data->fileFlags & request;
}
QDateTime &QFileInfoPrivate::getFileTime(QAbstractFileEngine::FileTime request) const
{
if (!data->cache_enabled)
data->clearFlags();
- if(request == QAbstractFileEngine::CreationTime) {
- if(data->getCachedFlag(CachedCTime))
- return data->fileTimes[request];
- data->setCachedFlag(CachedCTime);
- return (data->fileTimes[request] = data->fileEngine->fileTime(request));
+ uint cf;
+ if (request == QAbstractFileEngine::CreationTime)
+ cf = CachedCTime;
+ else if (request == QAbstractFileEngine::ModificationTime)
+ cf = CachedMTime;
+ else
+ cf = CachedATime;
+ if (!data->getCachedFlag(cf)) {
+ data->fileTimes[request] = data->fileEngine->fileTime(request);
+ data->setCachedFlag(cf);
}
- if(request == QAbstractFileEngine::ModificationTime) {
- if(data->getCachedFlag(CachedMTime))
- return data->fileTimes[request];
- data->setCachedFlag(CachedMTime);
- return (data->fileTimes[request] = data->fileEngine->fileTime(request));
- }
- if(request == QAbstractFileEngine::AccessTime) {
- if(data->getCachedFlag(CachedATime))
- return data->fileTimes[request];
- data->setCachedFlag(CachedATime);
- return (data->fileTimes[request] = data->fileEngine->fileTime(request));
- }
- return data->fileTimes[0]; //cannot really happen
+ return data->fileTimes[request];
}
//************* QFileInfo
@@ -305,7 +320,6 @@ QDateTime &QFileInfoPrivate::getFileTime(QAbstractFileEngine::FileTime request)
\sa setFile()
*/
-
QFileInfo::QFileInfo() : d_ptr(new QFileInfoPrivate())
{
}
@@ -316,7 +330,6 @@ QFileInfo::QFileInfo() : d_ptr(new QFileInfoPrivate())
\sa setFile(), isRelative(), QDir::setCurrent(), QDir::isRelativePath()
*/
-
QFileInfo::QFileInfo(const QString &file) : d_ptr(new QFileInfoPrivate())
{
d_ptr->initFileEngine(file);
@@ -331,7 +344,6 @@ QFileInfo::QFileInfo(const QString &file) : d_ptr(new QFileInfoPrivate())
\sa isRelative()
*/
-
QFileInfo::QFileInfo(const QFile &file) : d_ptr(new QFileInfoPrivate())
{
d_ptr->initFileEngine(file.fileName());
@@ -349,7 +361,6 @@ QFileInfo::QFileInfo(const QFile &file) : d_ptr(new QFileInfoPrivate())
\sa isRelative()
*/
-
QFileInfo::QFileInfo(const QDir &dir, const QString &file) : d_ptr(new QFileInfoPrivate())
{
d_ptr->initFileEngine(dir.filePath(file));
@@ -358,7 +369,6 @@ QFileInfo::QFileInfo(const QDir &dir, const QString &file) : d_ptr(new QFileInfo
/*!
Constructs a new QFileInfo that is a copy of the given \a fileinfo.
*/
-
QFileInfo::QFileInfo(const QFileInfo &fileinfo) : d_ptr(new QFileInfoPrivate(&fileinfo))
{
@@ -368,7 +378,6 @@ QFileInfo::QFileInfo(const QFileInfo &fileinfo) : d_ptr(new QFileInfoPrivate(&fi
Destroys the QFileInfo and frees its resources.
*/
-
QFileInfo::~QFileInfo()
{
}
@@ -395,19 +404,19 @@ bool QFileInfo::operator==(const QFileInfo &fileinfo) const
Q_D(const QFileInfo);
// ### Qt 5: understand long and short file names on Windows
// ### (GetFullPathName()).
- if(fileinfo.d_func()->data == d->data)
+ if (fileinfo.d_func()->data == d->data)
return true;
- if(!d->data->fileEngine || !fileinfo.d_func()->data->fileEngine)
+ if (!d->data->fileEngine || !fileinfo.d_func()->data->fileEngine)
return false;
- if(d->data->fileEngine->caseSensitive() != fileinfo.d_func()->data->fileEngine->caseSensitive())
+ if (d->data->fileEngine->caseSensitive() != fileinfo.d_func()->data->fileEngine->caseSensitive())
return false;
- if(fileinfo.size() == size()) { //if the size isn't the same...
+ if (fileinfo.size() == size()) { //if the size isn't the same...
QString file1 = canonicalFilePath(),
file2 = fileinfo.canonicalFilePath();
- if(file1.length() == file2.length()) {
- if(!fileinfo.d_func()->data->fileEngine->caseSensitive()) {
- for(int i = 0; i < file1.length(); i++) {
- if(file1.at(i).toLower() != file2.at(i).toLower())
+ if (file1.length() == file2.length()) {
+ if (!fileinfo.d_func()->data->fileEngine->caseSensitive()) {
+ for (int i = 0; i < file1.length(); i++) {
+ if (file1.at(i).toLower() != file2.at(i).toLower())
return false;
}
return true;
@@ -441,7 +450,6 @@ bool QFileInfo::operator==(const QFileInfo &fileinfo)
/*!
Makes a copy of the given \a fileinfo and assigns it to this QFileInfo.
*/
-
QFileInfo &QFileInfo::operator=(const QFileInfo &fileinfo)
{
Q_D(QFileInfo);
@@ -464,7 +472,6 @@ QFileInfo &QFileInfo::operator=(const QFileInfo &fileinfo)
\sa isRelative(), QDir::setCurrent(), QDir::isRelativePath()
*/
-
void QFileInfo::setFile(const QString &file)
{
*this = QFileInfo(file);
@@ -481,7 +488,6 @@ void QFileInfo::setFile(const QString &file)
\sa isRelative()
*/
-
void QFileInfo::setFile(const QFile &file)
{
*this = QFileInfo(file.fileName());
@@ -498,7 +504,6 @@ void QFileInfo::setFile(const QFile &file)
\sa isRelative()
*/
-
void QFileInfo::setFile(const QDir &dir, const QString &file)
{
*this = QFileInfo(dir.filePath(file));
@@ -528,25 +533,24 @@ void QFileInfo::setFile(const QDir &dir, const QString &file)
QString QFileInfo::absoluteFilePath() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
return d->getFileName(QAbstractFileEngine::AbsoluteName);
}
/*!
- Returns the canonical path including the file name, i.e. an absolute
- path without symbolic links or redundant "." or ".." elements.
+ Returns the canonical path including the file name, i.e. an absolute
+ path without symbolic links or redundant "." or ".." elements.
- If the file does not exist, canonicalFilePath() returns an empty
- string.
+ If the file does not exist, canonicalFilePath() returns an empty
+ string.
- \sa filePath(), absoluteFilePath(), dir()
+ \sa filePath(), absoluteFilePath(), dir()
*/
-
QString QFileInfo::canonicalFilePath() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
return d->getFileName(QAbstractFileEngine::CanonicalName);
}
@@ -569,7 +573,6 @@ QString QFileInfo::canonicalFilePath() const
\sa absoluteFilePath(), path(), canonicalPath(), fileName(), isRelative()
*/
-
QString QFileInfo::absolutePath() const
{
Q_D(const QFileInfo);
@@ -591,16 +594,14 @@ QString QFileInfo::absolutePath() const
\sa path(), absolutePath()
*/
-
QString QFileInfo::canonicalPath() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
return d->getFileName(QAbstractFileEngine::CanonicalPathName);
}
-
/*!
Returns the file's path. This doesn't include the file name.
@@ -610,11 +611,10 @@ QString QFileInfo::canonicalPath() const
\sa filePath(), absolutePath(), canonicalPath(), dir(), fileName(), isRelative()
*/
-
QString QFileInfo::path() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
return d->getFileName(QAbstractFileEngine::PathName);
}
@@ -635,16 +635,14 @@ QString QFileInfo::path() const
\sa isAbsolute()
*/
-
bool QFileInfo::isRelative() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return true;
return d->data->fileEngine->isRelativePath();
}
-
/*!
Converts the file's path to an absolute path if it is not already in that form.
Returns true to indicate that the path was converted; otherwise returns false
@@ -652,11 +650,10 @@ bool QFileInfo::isRelative() const
\sa filePath(), isRelative()
*/
-
bool QFileInfo::makeAbsolute()
{
Q_D(QFileInfo);
- if(!d->data->fileEngine || !d->data->fileEngine->isRelativePath())
+ if (!d->data->fileEngine || !d->data->fileEngine->isRelativePath())
return false;
QString absFileName = d->getFileName(QAbstractFileEngine::AbsoluteName);
d->initFileEngine(absFileName);
@@ -669,11 +666,10 @@ bool QFileInfo::makeAbsolute()
\note If the file is a symlink that points to a non existing
file, false is returned.
*/
-
bool QFileInfo::exists() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->getFileFlags(QAbstractFileEngine::ExistsFlag);
}
@@ -685,7 +681,6 @@ bool QFileInfo::exists() const
\note On Windows CE, there might be a delay for the file system driver
to detect changes on the file.
*/
-
void QFileInfo::refresh()
{
Q_D(QFileInfo);
@@ -698,11 +693,10 @@ void QFileInfo::refresh()
\sa absoluteFilePath(), canonicalFilePath(), isRelative()
*/
-
QString QFileInfo::filePath() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
return d->getFileName(QAbstractFileEngine::DefaultName);
}
@@ -718,11 +712,10 @@ QString QFileInfo::filePath() const
\sa isRelative(), filePath(), baseName(), extension()
*/
-
QString QFileInfo::fileName() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
return d->getFileName(QAbstractFileEngine::BaseName);
}
@@ -739,11 +732,10 @@ QString QFileInfo::fileName() const
\sa isBundle(), filePath(), baseName(), extension()
*/
-
QString QFileInfo::bundleName() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
return d->getFileName(QAbstractFileEngine::BundleName);
}
@@ -764,11 +756,10 @@ QString QFileInfo::bundleName() const
\sa fileName(), suffix(), completeSuffix(), completeBaseName()
*/
-
QString QFileInfo::baseName() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
return d->getFileName(QAbstractFileEngine::BaseName).section(QLatin1Char('.'), 0, 0);
}
@@ -784,11 +775,10 @@ QString QFileInfo::baseName() const
\sa fileName(), suffix(), completeSuffix(), baseName()
*/
-
QString QFileInfo::completeBaseName() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
QString name = d->getFileName(QAbstractFileEngine::BaseName);
int index = name.lastIndexOf(QLatin1Char('.'));
@@ -806,11 +796,10 @@ QString QFileInfo::completeBaseName() const
\sa fileName(), suffix(), baseName(), completeBaseName()
*/
-
QString QFileInfo::completeSuffix() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
QString fileName = d->getFileName(QAbstractFileEngine::BaseName);
int firstDot = fileName.indexOf(QLatin1Char('.'));
@@ -834,11 +823,10 @@ QString QFileInfo::completeSuffix() const
\sa fileName(), completeSuffix(), baseName(), completeBaseName()
*/
-
QString QFileInfo::suffix() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
QString fileName = d->getFileName(QAbstractFileEngine::BaseName);
int lastDot = fileName.lastIndexOf(QLatin1Char('.'));
@@ -849,24 +837,23 @@ QString QFileInfo::suffix() const
/*!
- Returns the path of the object's parent directory as a QDir object.
+ Returns the path of the object's parent directory as a QDir object.
- \bold{Note:} The QDir returned always corresponds to the object's
- parent directory, even if the QFileInfo represents a directory.
+ \bold{Note:} The QDir returned always corresponds to the object's
+ parent directory, even if the QFileInfo represents a directory.
- For each of the follwing, dir() returns a QDir for
- \c{"~/examples/191697"}.
+ For each of the follwing, dir() returns a QDir for
+ \c{"~/examples/191697"}.
- \snippet doc/src/snippets/fileinfo/main.cpp 0
+ \snippet doc/src/snippets/fileinfo/main.cpp 0
- For each of the follwing, dir() returns a QDir for
- \c{"."}.
+ For each of the follwing, dir() returns a QDir for
+ \c{"."}.
- \snippet doc/src/snippets/fileinfo/main.cpp 1
+ \snippet doc/src/snippets/fileinfo/main.cpp 1
- \sa absolutePath(), filePath(), fileName(), isRelative(), absoluteDir()
+ \sa absolutePath(), filePath(), fileName(), isRelative(), absoluteDir()
*/
-
QDir QFileInfo::dir() const
{
// ### Qt5: Maybe rename this to parentDirectory(), considering what it actually do?
@@ -878,7 +865,6 @@ QDir QFileInfo::dir() const
\sa dir(), filePath(), fileName(), isRelative()
*/
-
QDir QFileInfo::absoluteDir() const
{
return QDir(absolutePath());
@@ -891,7 +877,7 @@ QDir QFileInfo::absoluteDir() const
*/
QDir QFileInfo::dir(bool absPath) const
{
- if(absPath)
+ if (absPath)
return absoluteDir();
return dir();
}
@@ -902,11 +888,10 @@ QDir QFileInfo::dir(bool absPath) const
\sa isWritable(), isExecutable(), permission()
*/
-
bool QFileInfo::isReadable() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->hasAccess(QFileInfoPrivate::ReadAccess);
}
@@ -916,11 +901,10 @@ bool QFileInfo::isReadable() const
\sa isReadable(), isExecutable(), permission()
*/
-
bool QFileInfo::isWritable() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->hasAccess(QFileInfoPrivate::WriteAccess);
}
@@ -930,11 +914,10 @@ bool QFileInfo::isWritable() const
\sa isReadable(), isWritable(), permission()
*/
-
bool QFileInfo::isExecutable() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->hasAccess(QFileInfoPrivate::ExecuteAccess);
}
@@ -948,7 +931,7 @@ bool QFileInfo::isExecutable() const
bool QFileInfo::isHidden() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->getFileFlags(QAbstractFileEngine::HiddenFlag);
}
@@ -960,11 +943,10 @@ bool QFileInfo::isHidden() const
\sa isDir(), isSymLink(), isBundle()
*/
-
bool QFileInfo::isFile() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->getFileFlags(QAbstractFileEngine::FileType);
}
@@ -975,11 +957,10 @@ bool QFileInfo::isFile() const
\sa isFile(), isSymLink(), isBundle()
*/
-
bool QFileInfo::isDir() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->getFileFlags(QAbstractFileEngine::DirectoryType);
}
@@ -992,11 +973,10 @@ bool QFileInfo::isDir() const
\sa isDir(), isSymLink(), isFile()
*/
-
bool QFileInfo::isBundle() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->getFileFlags(QAbstractFileEngine::BundleType);
}
@@ -1018,21 +998,19 @@ bool QFileInfo::isBundle() const
\sa isFile(), isDir(), symLinkTarget()
*/
-
bool QFileInfo::isSymLink() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->getFileFlags(QAbstractFileEngine::LinkType);
}
/*!
- Returns true if the object points to a directory or to a symbolic
- link to a directory, and that directory is the root directory; otherwise
- returns false.
+ Returns true if the object points to a directory or to a symbolic
+ link to a directory, and that directory is the root directory; otherwise
+ returns false.
*/
-
bool QFileInfo::isRoot() const
{
Q_D(const QFileInfo);
@@ -1064,7 +1042,7 @@ bool QFileInfo::isRoot() const
QString QFileInfo::readLink() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
return d->getFileName(QAbstractFileEngine::LinkName);
}
@@ -1079,13 +1057,12 @@ QString QFileInfo::readLink() const
\sa ownerId(), group(), groupId()
*/
-
QString QFileInfo::owner() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
- return d->data->fileEngine->owner(QAbstractFileEngine::OwnerUser);
+ return d->getFileOwner(QAbstractFileEngine::OwnerUser);
}
/*!
@@ -1096,11 +1073,10 @@ QString QFileInfo::owner() const
\sa owner(), group(), groupId()
*/
-
uint QFileInfo::ownerId() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return 0;
return d->data->fileEngine->ownerId(QAbstractFileEngine::OwnerUser);
}
@@ -1115,13 +1091,12 @@ uint QFileInfo::ownerId() const
\sa groupId(), owner(), ownerId()
*/
-
QString QFileInfo::group() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QLatin1String("");
- return d->data->fileEngine->owner(QAbstractFileEngine::OwnerGroup);
+ return d->getFileOwner(QAbstractFileEngine::OwnerGroup);
}
/*!
@@ -1132,11 +1107,10 @@ QString QFileInfo::group() const
\sa group(), owner(), ownerId()
*/
-
uint QFileInfo::groupId() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return 0;
return d->data->fileEngine->ownerId(QAbstractFileEngine::OwnerGroup);
}
@@ -1154,11 +1128,10 @@ uint QFileInfo::groupId() const
\sa isReadable(), isWritable(), isExecutable()
*/
-
bool QFileInfo::permission(QFile::Permissions permissions) const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return false;
return d->getFileFlags(QAbstractFileEngine::FileFlags((int)permissions)) == (uint)permissions;
}
@@ -1167,11 +1140,10 @@ bool QFileInfo::permission(QFile::Permissions permissions) const
Returns the complete OR-ed together combination of
QFile::Permissions for the file.
*/
-
QFile::Permissions QFileInfo::permissions() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return 0;
return QFile::Permissions(d->getFileFlags(QAbstractFileEngine::PermsMask) & QAbstractFileEngine::PermsMask);
}
@@ -1183,13 +1155,12 @@ QFile::Permissions QFileInfo::permissions() const
\sa exists()
*/
-
qint64 QFileInfo::size() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return 0;
- if(!d->data->getCachedFlag(QFileInfoPrivate::CachedSize)) {
+ if (!d->data->getCachedFlag(QFileInfoPrivate::CachedSize)) {
d->data->setCachedFlag(QFileInfoPrivate::CachedSize);
d->data->fileSize = d->data->fileEngine->size();
}
@@ -1209,11 +1180,10 @@ qint64 QFileInfo::size() const
\sa lastModified() lastRead()
*/
-
QDateTime QFileInfo::created() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QDateTime();
return d->getFileTime(QAbstractFileEngine::CreationTime);
}
@@ -1223,11 +1193,10 @@ QDateTime QFileInfo::created() const
\sa created() lastRead()
*/
-
QDateTime QFileInfo::lastModified() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QDateTime();
return d->getFileTime(QAbstractFileEngine::ModificationTime);
}
@@ -1240,11 +1209,10 @@ QDateTime QFileInfo::lastModified() const
\sa created() lastModified()
*/
-
QDateTime QFileInfo::lastRead() const
{
Q_D(const QFileInfo);
- if(!d->data->fileEngine)
+ if (!d->data->fileEngine)
return QDateTime();
return d->getFileTime(QAbstractFileEngine::AccessTime);
}
@@ -1252,7 +1220,6 @@ QDateTime QFileInfo::lastRead() const
/*! \internal
Detaches all internal data.
*/
-
void QFileInfo::detach()
{
Q_D(QFileInfo);
@@ -1264,7 +1231,6 @@ void QFileInfo::detach()
\sa setCaching(), refresh()
*/
-
bool QFileInfo::caching() const
{
Q_D(const QFileInfo);
@@ -1283,7 +1249,6 @@ bool QFileInfo::caching() const
\sa refresh(), caching()
*/
-
void QFileInfo::setCaching(bool enable)
{
Q_D(QFileInfo);
diff --git a/src/corelib/io/qfileinfo_p.h b/src/corelib/io/qfileinfo_p.h
index 065f860..d97a0cf 100644
--- a/src/corelib/io/qfileinfo_p.h
+++ b/src/corelib/io/qfileinfo_p.h
@@ -54,6 +54,9 @@
//
#include "qfileinfo.h"
+#include "qabstractfileengine.h"
+#include "qdatetime.h"
+#include "qatomic.h"
QT_BEGIN_NAMESPACE
@@ -75,35 +78,41 @@ public:
uint getFileFlags(QAbstractFileEngine::FileFlags) const;
QDateTime &getFileTime(QAbstractFileEngine::FileTime) const;
QString getFileName(QAbstractFileEngine::FileName) const;
+ QString getFileOwner(QAbstractFileEngine::FileOwner own) const;
enum { CachedFileFlags=0x01, CachedLinkTypeFlag=0x02, CachedBundleTypeFlag=0x04,
CachedMTime=0x10, CachedCTime=0x20, CachedATime=0x40,
- CachedSize =0x08 };
+ CachedSize =0x08, CachedPerms=0x80 };
struct Data {
inline Data()
- : ref(1), fileEngine(0), cache_enabled(1), fileSize(0)
- { clear(); }
+ : ref(1), fileEngine(0),
+ cachedFlags(0), cache_enabled(1), fileFlags(0), fileSize(0)
+ {}
inline Data(const Data &copy)
: ref(1), fileEngine(QAbstractFileEngine::create(copy.fileName)),
- fileName(copy.fileName), cache_enabled(copy.cache_enabled), fileSize(copy.fileSize)
- { clear(); }
+ fileName(copy.fileName),
+ cachedFlags(0), cache_enabled(copy.cache_enabled), fileFlags(0), fileSize(0)
+ {}
inline ~Data() { delete fileEngine; }
inline void clearFlags() {
fileFlags = 0;
cachedFlags = 0;
if (fileEngine)
- (void)fileEngine->fileFlags(QFSFileEngine::Refresh);
+ (void)fileEngine->fileFlags(QAbstractFileEngine::Refresh);
}
inline void clear() {
clearFlags();
for (int i = QAbstractFileEngine::NFileNames - 1 ; i >= 0 ; --i)
fileNames[i].clear();
+ fileOwners[1].clear();
+ fileOwners[0].clear();
}
mutable QAtomicInt ref;
QAbstractFileEngine *fileEngine;
mutable QString fileName;
mutable QString fileNames[QAbstractFileEngine::NFileNames];
+ mutable QString fileOwners[2];
mutable uint cachedFlags : 31;
mutable uint cache_enabled : 1;
diff --git a/src/corelib/io/qfilesystemwatcher.cpp b/src/corelib/io/qfilesystemwatcher.cpp
index 451fbd4..7223e49 100644
--- a/src/corelib/io/qfilesystemwatcher.cpp
+++ b/src/corelib/io/qfilesystemwatcher.cpp
@@ -248,7 +248,7 @@ QFileSystemWatcherEngine *QFileSystemWatcherPrivate::createNativeEngine()
eng = QDnotifyFileSystemWatcherEngine::create();
return eng;
#elif defined(Q_OS_FREEBSD) || defined(Q_OS_MAC)
-# if 0 && (defined Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
+# if defined(Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5)
return QFSEventsFileSystemWatcherEngine::create();
else
diff --git a/src/corelib/io/qfilesystemwatcher_dnotify.cpp b/src/corelib/io/qfilesystemwatcher_dnotify.cpp
index 1a218c7..82470c8 100644
--- a/src/corelib/io/qfilesystemwatcher_dnotify.cpp
+++ b/src/corelib/io/qfilesystemwatcher_dnotify.cpp
@@ -39,6 +39,7 @@
**
****************************************************************************/
+#include "qplatformdefs.h"
#include "qfilesystemwatcher.h"
#include "qfilesystemwatcher_dnotify_p.h"
@@ -255,16 +256,16 @@ QStringList QDnotifyFileSystemWatcherEngine::addPaths(const QStringList &paths,
if(fd == 0) {
- DIR *d = ::opendir(path.toUtf8().constData());
+ QT_DIR *d = QT_OPENDIR(path.toUtf8().constData());
if(!d) continue; // Could not open directory
- DIR *parent = 0;
+ QT_DIR *parent = 0;
QDir parentDir(path);
if(!parentDir.isRoot()) {
parentDir.cdUp();
- parent = ::opendir(parentDir.path().toUtf8().constData());
+ parent = QT_OPENDIR(parentDir.path().toUtf8().constData());
if(!parent) {
- ::closedir(d);
+ QT_CLOSEDIR(d);
continue;
}
}
@@ -272,8 +273,8 @@ QStringList QDnotifyFileSystemWatcherEngine::addPaths(const QStringList &paths,
fd = qt_safe_dup(::dirfd(d));
int parentFd = parent ? qt_safe_dup(::dirfd(parent)) : 0;
- ::closedir(d);
- if(parent) ::closedir(parent);
+ QT_CLOSEDIR(d);
+ if(parent) QT_CLOSEDIR(parent);
Q_ASSERT(fd);
if(::fcntl(fd, F_SETSIG, SIGIO) ||
diff --git a/src/corelib/io/qfilesystemwatcher_fsevents.cpp b/src/corelib/io/qfilesystemwatcher_fsevents.cpp
index 046377e..54ae24e 100644
--- a/src/corelib/io/qfilesystemwatcher_fsevents.cpp
+++ b/src/corelib/io/qfilesystemwatcher_fsevents.cpp
@@ -94,7 +94,7 @@ static void addPathToHash(PathHash &pathHash, const QString &key, const QFileInf
{
PathInfoList &list = pathHash[key];
list.push_back(PathInfo(path,
- fileInfo.absoluteFilePath().normalized(QString::NormalizationForm_D).toUtf8()));
+ fileInfo.canonicalFilePath().normalized(QString::NormalizationForm_D).toUtf8()));
pathHash.insert(key, list);
}
@@ -206,7 +206,7 @@ QStringList QFSEventsFileSystemWatcherEngine::addPaths(const QStringList &paths,
} else {
directories->append(path);
// Full file path for dirs.
- QCFString cfpath(createFSStreamPath(fileInfo.absoluteFilePath()));
+ QCFString cfpath(createFSStreamPath(fileInfo.canonicalFilePath()));
addPathToHash(dirPathInfoHash, cfpath, fileInfo, path);
CFArrayAppendValue(tmpArray, cfpath);
}
@@ -216,7 +216,7 @@ QStringList QFSEventsFileSystemWatcherEngine::addPaths(const QStringList &paths,
continue;
} else {
// Just the absolute path (minus it's filename) for files.
- QCFString cfpath(createFSStreamPath(fileInfo.absolutePath()));
+ QCFString cfpath(createFSStreamPath(fileInfo.canonicalPath()));
files->append(path);
addPathToHash(filePathInfoHash, cfpath, fileInfo, path);
CFArrayAppendValue(tmpArray, cfpath);
@@ -293,7 +293,7 @@ QStringList QFSEventsFileSystemWatcherEngine::removePaths(const QStringList &pat
itemCount = CFArrayGetCount(tmpArray);
const QString &path = paths.at(i);
QFileInfo fi(path);
- QCFString cfpath(createFSStreamPath(fi.absolutePath()));
+ QCFString cfpath(createFSStreamPath(fi.canonicalPath()));
CFIndex index = CFArrayGetFirstIndexOfValue(tmpArray, CFRangeMake(0, itemCount), cfpath);
if (index != -1) {
@@ -302,7 +302,7 @@ QStringList QFSEventsFileSystemWatcherEngine::removePaths(const QStringList &pat
removePathFromHash(filePathInfoHash, cfpath, path);
} else {
// Could be a directory we are watching instead.
- QCFString cfdirpath(createFSStreamPath(fi.absoluteFilePath()));
+ QCFString cfdirpath(createFSStreamPath(fi.canonicalFilePath()));
index = CFArrayGetFirstIndexOfValue(tmpArray, CFRangeMake(0, itemCount), cfdirpath);
if (index != -1) {
CFArrayRemoveValueAtIndex(tmpArray, index);
diff --git a/src/corelib/io/qfilesystemwatcher_inotify.cpp b/src/corelib/io/qfilesystemwatcher_inotify.cpp
index a7dc8fa..4740a89 100644
--- a/src/corelib/io/qfilesystemwatcher_inotify.cpp
+++ b/src/corelib/io/qfilesystemwatcher_inotify.cpp
@@ -235,7 +235,7 @@ QInotifyFileSystemWatcherEngine::QInotifyFileSystemWatcherEngine(int fd)
QInotifyFileSystemWatcherEngine::~QInotifyFileSystemWatcherEngine()
{
- foreach (int id, pathToID.values())
+ foreach (int id, pathToID)
inotify_rm_watch(inotifyFd, id < 0 ? -id : id);
::close(inotifyFd);
diff --git a/src/corelib/io/qfilesystemwatcher_kqueue.cpp b/src/corelib/io/qfilesystemwatcher_kqueue.cpp
index f088ded..8396481 100644
--- a/src/corelib/io/qfilesystemwatcher_kqueue.cpp
+++ b/src/corelib/io/qfilesystemwatcher_kqueue.cpp
@@ -109,7 +109,7 @@ QKqueueFileSystemWatcherEngine::~QKqueueFileSystemWatcherEngine()
close(kqpipe[0]);
close(kqpipe[1]);
- foreach (int id, pathToID.values())
+ foreach (int id, pathToID)
::close(id < 0 ? -id : id);
}
diff --git a/src/corelib/io/qfsfileengine.cpp b/src/corelib/io/qfsfileengine.cpp
index c842e49..1672dfc 100644
--- a/src/corelib/io/qfsfileengine.cpp
+++ b/src/corelib/io/qfsfileengine.cpp
@@ -56,6 +56,9 @@
#endif
#include <stdio.h>
#include <stdlib.h>
+#if defined(Q_OS_MAC)
+# include <private/qcore_mac_p.h>
+#endif
QT_BEGIN_NAMESPACE
@@ -143,9 +146,27 @@ QString QFSFileEnginePrivate::canonicalized(const QString &path)
if (path.size() == 1 && path.at(0) == QLatin1Char('/'))
return path;
#endif
- // Mac OS X 10.5.x doesn't support the realpath(X,0) extenstion we use here.
-#if defined(Q_OS_LINUX) || defined(Q_OS_SYMBIAN)
- char *ret = realpath(path.toLocal8Bit().constData(), (char*)0);
+#if defined(Q_OS_LINUX) || defined(Q_OS_SYMBIAN) || defined(Q_OS_MAC)
+ char *ret = 0;
+#if defined(Q_OS_MAC)
+ // Mac OS X 10.5.x doesn't support the realpath(X,0) extension we use here.
+ if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_6) {
+ ret = realpath(path.toLocal8Bit().constData(), (char*)0);
+ } else {
+ // on 10.5 we can use FSRef to resolve the file path.
+ FSRef fsref;
+ if (FSPathMakeRef((const UInt8 *)QDir::cleanPath(path).toUtf8().data(), &fsref, 0) == noErr) {
+ CFURLRef urlref = CFURLCreateFromFSRef(NULL, &fsref);
+ CFStringRef canonicalPath = CFURLCopyFileSystemPath(urlref, kCFURLPOSIXPathStyle);
+ QString ret = QCFString::toQString(canonicalPath);
+ CFRelease(canonicalPath);
+ CFRelease(urlref);
+ return ret;
+ }
+ }
+#else
+ ret = realpath(path.toLocal8Bit().constData(), (char*)0);
+#endif
if (ret) {
QString canonicalPath = QDir::cleanPath(QString::fromLocal8Bit(ret));
free(ret);
diff --git a/src/corelib/io/qfsfileengine_iterator_unix.cpp b/src/corelib/io/qfsfileengine_iterator_unix.cpp
index b68b1a1..bfdb03e 100644
--- a/src/corelib/io/qfsfileengine_iterator_unix.cpp
+++ b/src/corelib/io/qfsfileengine_iterator_unix.cpp
@@ -58,13 +58,13 @@ public:
#endif
{}
- DIR *dir;
- dirent *dirEntry;
+ QT_DIR *dir;
+ QT_DIRENT *dirEntry;
bool done;
#if defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_CYGWIN) && !defined(Q_OS_SYMBIAN)
// for readdir_r
- dirent *mt_file;
+ QT_DIRENT *mt_file;
#endif
};
@@ -76,14 +76,14 @@ void QFSFileEngineIterator::advance()
return;
#if defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_CYGWIN) && !defined(Q_OS_SYMBIAN)
- if (::readdir_r(platform->dir, platform->mt_file, &platform->dirEntry) != 0)
+ if (QT_READDIR_R(platform->dir, platform->mt_file, &platform->dirEntry) != 0)
platform->done = true;
#else
// ### add local lock to prevent breaking reentrancy
- platform->dirEntry = ::readdir(platform->dir);
+ platform->dirEntry = QT_READDIR(platform->dir);
#endif // _POSIX_THREAD_SAFE_FUNCTIONS
if (!platform->dirEntry) {
- ::closedir(platform->dir);
+ QT_CLOSEDIR(platform->dir);
platform->dir = 0;
platform->done = true;
#if defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_CYGWIN) && !defined(Q_OS_SYMBIAN)
@@ -101,7 +101,7 @@ void QFSFileEngineIterator::newPlatformSpecifics()
void QFSFileEngineIterator::deletePlatformSpecifics()
{
if (platform->dir) {
- ::closedir(platform->dir);
+ QT_CLOSEDIR(platform->dir);
#if defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_CYGWIN) && !defined(Q_OS_SYMBIAN)
delete [] platform->mt_file;
platform->mt_file = 0;
@@ -115,18 +115,18 @@ bool QFSFileEngineIterator::hasNext() const
{
if (!platform->done && !platform->dir) {
QFSFileEngineIterator *that = const_cast<QFSFileEngineIterator *>(this);
- if ((that->platform->dir = ::opendir(QFile::encodeName(path()).data())) == 0) {
+ if ((that->platform->dir = QT_OPENDIR(QFile::encodeName(path()).data())) == 0) {
that->platform->done = true;
} else {
// ### Race condition; we should use fpathconf and dirfd().
long maxPathName = ::pathconf(QFile::encodeName(path()).data(), _PC_NAME_MAX);
if ((int) maxPathName == -1)
maxPathName = FILENAME_MAX;
- maxPathName += sizeof(dirent) + 1;
+ maxPathName += sizeof(QT_DIRENT) + 1;
#if defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_CYGWIN) && !defined(Q_OS_SYMBIAN)
if (that->platform->mt_file)
delete [] that->platform->mt_file;
- that->platform->mt_file = (dirent *)new char[maxPathName];
+ that->platform->mt_file = (QT_DIRENT *)new char[maxPathName];
#endif
that->advance();
diff --git a/src/corelib/io/qfsfileengine_win.cpp b/src/corelib/io/qfsfileengine_win.cpp
index bec0075..eb99f27 100644
--- a/src/corelib/io/qfsfileengine_win.cpp
+++ b/src/corelib/io/qfsfileengine_win.cpp
@@ -66,10 +66,6 @@
#include <ctype.h>
#include <limits.h>
#define SECURITY_WIN32
-#ifdef Q_CC_MINGW
-// A workaround for a certain version of MinGW, the define UNICODE_STRING.
-#include <subauth.h>
-#endif
#include <security.h>
#ifndef _INTPTR_T_DEFINED
@@ -181,7 +177,7 @@ void QFSFileEnginePrivate::resolveLibs()
triedResolve = true;
#if !defined(Q_OS_WINCE)
- HINSTANCE advapiHnd = LoadLibraryW(L"advapi32");
+ HINSTANCE advapiHnd = LoadLibrary(L"advapi32");
if (advapiHnd) {
ptrGetNamedSecurityInfoW = (PtrGetNamedSecurityInfoW)GetProcAddress(advapiHnd, "GetNamedSecurityInfoW");
ptrLookupAccountSidW = (PtrLookupAccountSidW)GetProcAddress(advapiHnd, "LookupAccountSidW");
@@ -213,7 +209,7 @@ void QFSFileEnginePrivate::resolveLibs()
ptrFreeSid(pWorld);
}
}
- HINSTANCE userenvHnd = LoadLibraryW(L"userenv");
+ HINSTANCE userenvHnd = LoadLibrary(L"userenv");
if (userenvHnd)
ptrGetUserProfileDirectoryW = (PtrGetUserProfileDirectoryW)GetProcAddress(userenvHnd, "GetUserProfileDirectoryW");
#endif
@@ -221,7 +217,6 @@ void QFSFileEnginePrivate::resolveLibs()
}
#endif // QT_NO_LIBRARY
-// UNC functions NT
typedef DWORD (WINAPI *PtrNetShareEnum)(LPWSTR, DWORD, LPBYTE*, DWORD, LPDWORD, LPDWORD, LPDWORD);
static PtrNetShareEnum ptrNetShareEnum = 0;
typedef DWORD (WINAPI *PtrNetApiBufferFree)(LPVOID);
@@ -245,7 +240,7 @@ bool QFSFileEnginePrivate::resolveUNCLibs()
#endif
triedResolve = true;
#if !defined(Q_OS_WINCE)
- HINSTANCE hLib = LoadLibraryW(L"Netapi32");
+ HINSTANCE hLib = LoadLibrary(L"netapi32");
if (hLib) {
ptrNetShareEnum = (PtrNetShareEnum)GetProcAddress(hLib, "NetShareEnum");
if (ptrNetShareEnum)
@@ -1042,11 +1037,11 @@ QString QFSFileEngine::homePath()
if (ok) {
DWORD dwBufferSize = 0;
// First call, to determine size of the strings (with '\0').
- ok = ::ptrGetUserProfileDirectoryW(token, NULL, &dwBufferSize);
+ ok = ptrGetUserProfileDirectoryW(token, NULL, &dwBufferSize);
if (!ok && dwBufferSize != 0) { // We got the required buffer size
wchar_t *userDirectory = new wchar_t[dwBufferSize];
// Second call, now we can fill the allocated buffer.
- ok = ::ptrGetUserProfileDirectoryW(token, userDirectory, &dwBufferSize);
+ ok = ptrGetUserProfileDirectoryW(token, userDirectory, &dwBufferSize);
if (ok)
ret = QString::fromWCharArray(userDirectory);
@@ -1418,7 +1413,7 @@ QAbstractFileEngine::FileFlags QFSFileEnginePrivate::getPermissions() const
QAbstractFileEngine::FileFlags ret = 0;
#if !defined(QT_NO_LIBRARY)
- if((qt_ntfs_permission_lookup > 0) && ((QSysInfo::WindowsVersion&QSysInfo::WV_NT_based) > QSysInfo::WV_NT)) {
+ if((qt_ntfs_permission_lookup > 0) && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)) {
resolveLibs();
if(ptrGetNamedSecurityInfoW && ptrBuildTrusteeWithSidW && ptrGetEffectiveRightsFromAclW) {
enum { ReadMask = 0x00000001, WriteMask = 0x00000002, ExecMask = 0x00000020 };
@@ -1721,8 +1716,7 @@ QString QFSFileEngine::owner(FileOwner own) const
QString name;
#if !defined(QT_NO_LIBRARY)
Q_D(const QFSFileEngine);
-
- if ((qt_ntfs_permission_lookup > 0) && ((QSysInfo::WindowsVersion&QSysInfo::WV_NT_based) > QSysInfo::WV_NT)) {
+ if((qt_ntfs_permission_lookup > 0) && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)) {
QFSFileEnginePrivate::resolveLibs();
if (ptrGetNamedSecurityInfoW && ptrLookupAccountSidW) {
PSID pOwner = 0;
diff --git a/src/corelib/io/qurl.h b/src/corelib/io/qurl.h
index 0aa534a..906979c 100644
--- a/src/corelib/io/qurl.h
+++ b/src/corelib/io/qurl.h
@@ -46,6 +46,7 @@
#include <QtCore/qobjectdefs.h>
#include <QtCore/qpair.h>
#include <QtCore/qstring.h>
+#include <QtCore/qhash.h>
QT_BEGIN_HEADER
@@ -75,6 +76,7 @@ public:
RemovePath = 0x20,
RemoveQuery = 0x40,
RemoveFragment = 0x80,
+ // 0x100: private: normalized
StripTrailingSlash = 0x10000
};
@@ -268,6 +270,11 @@ public:
inline DataPtr &data_ptr() { return d; }
};
+inline uint qHash(const QUrl &uri)
+{
+ return qHash(uri.toEncoded(QUrl::FormattingOption(0x100)));
+}
+
Q_DECLARE_TYPEINFO(QUrl, Q_MOVABLE_TYPE);
Q_DECLARE_SHARED(QUrl)
Q_DECLARE_OPERATORS_FOR_FLAGS(QUrl::FormattingOptions)
diff --git a/src/corelib/kernel/qabstractitemmodel.cpp b/src/corelib/kernel/qabstractitemmodel.cpp
index 36e4af9..b0503be 100644
--- a/src/corelib/kernel/qabstractitemmodel.cpp
+++ b/src/corelib/kernel/qabstractitemmodel.cpp
@@ -1248,7 +1248,7 @@ void QAbstractItemModelPrivate::columnsRemoved(const QModelIndex &parent,
/*!
\fn QModelIndex QAbstractItemModel::parent(const QModelIndex &index) const = 0
- Returns the parent of the model item with the given \a index. If the model
+ Returns the parent of the model item with the given \a index. If the item
has no parent, an invalid QModelIndex is returned.
A common convention used in models that expose tree data structures is that
diff --git a/src/corelib/kernel/qcoreevent.cpp b/src/corelib/kernel/qcoreevent.cpp
index 3500b63..d23ea4c 100644
--- a/src/corelib/kernel/qcoreevent.cpp
+++ b/src/corelib/kernel/qcoreevent.cpp
@@ -272,7 +272,6 @@ QT_BEGIN_NAMESPACE
\omitvalue MacGLClearDrawable
\omitvalue NetworkReplyUpdated
\omitvalue FutureCallOut
- \omitvalue CocoaRequestModal
\omitvalue UpdateSoftKeys
\omitvalue NativeGesture
*/
@@ -331,7 +330,7 @@ QEvent::~QEvent()
equivalent of calling setAccepted(false).
Clearing the accept parameter indicates that the event receiver
- does not want the event. Unwanted events might be propgated to the
+ does not want the event. Unwanted events might be propagated to the
parent widget.
\sa accept()
diff --git a/src/corelib/kernel/qcoreevent.h b/src/corelib/kernel/qcoreevent.h
index c76e81b..a20d171 100644
--- a/src/corelib/kernel/qcoreevent.h
+++ b/src/corelib/kernel/qcoreevent.h
@@ -266,7 +266,6 @@ public:
UngrabMouse = 187,
GrabKeyboard = 188,
UngrabKeyboard = 189,
- CocoaRequestModal = 190, // Internal for requesting an application modal Cocoa Window
MacGLClearDrawable = 191, // Internal Cocoa, the window has changed, so we must clear
StateMachineSignal = 192,
diff --git a/src/corelib/kernel/qeventdispatcher_win.cpp b/src/corelib/kernel/qeventdispatcher_win.cpp
index cbc87f3..7c8fb3d 100644
--- a/src/corelib/kernel/qeventdispatcher_win.cpp
+++ b/src/corelib/kernel/qeventdispatcher_win.cpp
@@ -341,6 +341,9 @@ public:
// for controlling when to send posted events
QAtomicInt serialNumber;
int lastSerialNumber;
+#ifndef Q_OS_WINCE
+ int lastMessageTime;
+#endif
QAtomicInt wakeUps;
// timers
@@ -364,7 +367,12 @@ public:
};
QEventDispatcherWin32Private::QEventDispatcherWin32Private()
- : threadId(GetCurrentThreadId()), interrupt(false), internalHwnd(0), getMessageHook(0), serialNumber(0), lastSerialNumber(0), wakeUps(0)
+ : threadId(GetCurrentThreadId()), interrupt(false), internalHwnd(0), getMessageHook(0),
+ serialNumber(0), lastSerialNumber(0),
+#ifndef Q_OS_WINCE
+ lastMessageTime(0),
+#endif
+ wakeUps(0)
{
resolveTimerAPI();
}
@@ -479,6 +487,9 @@ LRESULT CALLBACK qt_internal_proc(HWND hwnd, UINT message, WPARAM wp, LPARAM lp)
int localSerialNumber = d->serialNumber;
if (localSerialNumber != d->lastSerialNumber) {
d->lastSerialNumber = localSerialNumber;
+#ifndef Q_OS_WINCE
+ d->lastMessageTime = GetMessageTime();
+#endif
QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
}
return 0;
@@ -495,9 +506,13 @@ LRESULT CALLBACK qt_GetMessageHook(int code, WPARAM wp, LPARAM lp)
if (q) {
QEventDispatcherWin32Private *d = q->d_func();
int localSerialNumber = d->serialNumber;
- if (HIWORD(GetQueueStatus(QS_INPUT | QS_RAWINPUT | QS_TIMER)) == 0) {
- // no more input or timer events in the message queue, we can allow posted events to be
- // sent now
+ if (HIWORD(GetQueueStatus(QS_INPUT | QS_RAWINPUT | QS_TIMER)) == 0
+#ifndef Q_OS_WINCE
+ || GetMessageTime() - d->lastMessageTime >= 10
+#endif
+ ) {
+ // no more input or timer events in the message queue or more than 10ms has elapsed since
+ // we send posted events, we can allow posted events to be sent now
(void) d->wakeUps.fetchAndStoreRelease(0);
MSG *msg = (MSG *) lp;
if (localSerialNumber != d->lastSerialNumber
@@ -744,6 +759,8 @@ bool QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags)
if (d->internalHwnd == msg.hwnd && msg.message == WM_QT_SENDPOSTEDEVENTS) {
if (seenWM_QT_SENDPOSTEDEVENTS) {
+ // when calling processEvents() "manually", we only want to send posted
+ // events once
needWM_QT_SENDPOSTEDEVENTS = true;
continue;
}
diff --git a/src/corelib/kernel/qmetaobject.cpp b/src/corelib/kernel/qmetaobject.cpp
index cd7418a..be1b2ae 100644
--- a/src/corelib/kernel/qmetaobject.cpp
+++ b/src/corelib/kernel/qmetaobject.cpp
@@ -482,6 +482,46 @@ int QMetaObject::classInfoCount() const
return n;
}
+/** \internal
+* helper class for indexOf{Method,Slot,Signal}, returns the relative index of the method within
+* the baseObject
+* \a MethodType might be MethodSignal or MethodSlot, or 0 to match everything.
+*/
+template<int MethodType>
+static inline int indexOfMethodRelative(const QMetaObject **baseObject,
+ const char *method,
+ bool normalizeStringData)
+{
+ const QMetaObject *m;
+ for (m = *baseObject; m; m = *baseObject = m->d.superdata) {
+ const QMetaObject *const m = *baseObject;
+ int i = (MethodType == MethodSignal && priv(m->d.data)->revision >= 4)
+ ? (priv(m->d.data)->signalCount - 1) : (priv(m->d.data)->methodCount - 1);
+ if (i < 0)
+ continue;
+
+ const int end = (MethodType == MethodSlot && priv(m->d.data)->revision >= 4)
+ ? (priv(m->d.data)->signalCount) : 0;
+ if (!normalizeStringData) {
+ for (; i >= end; --i) {
+ if ((MethodType == 0 || (m->d.data[priv(m->d.data)->methodData + 5*i + 4] & MethodTypeMask) == MethodType)
+ && strcmp(method, m->d.stringdata + m->d.data[priv(m->d.data)->methodData + 5*i]) == 0)
+ return i;
+ }
+ } else if (priv(m->d.data)->revision < 5) {
+ const char *stringdata = (m->d.stringdata + m->d.data[priv(m->d.data)->methodData + 5 * i]);
+ const QByteArray normalizedSignature = QMetaObject::normalizedSignature(stringdata);
+ for (; i >= end; --i) {
+ if ((MethodType == 0|| (m->d.data[priv(m->d.data)->methodData + 5*i + 4] & MethodTypeMask) == MethodType)
+ && normalizedSignature == method)
+ return i;
+ }
+ }
+ }
+ return -1;
+}
+
+
/*!
\since 4.5
@@ -515,17 +555,14 @@ int QMetaObject::indexOfConstructor(const char *constructor) const
*/
int QMetaObject::indexOfMethod(const char *method) const
{
- int i = -1;
const QMetaObject *m = this;
- while (m && i < 0) {
- for (i = priv(m->d.data)->methodCount-1; i >= 0; --i)
- if (strcmp(method, m->d.stringdata
- + m->d.data[priv(m->d.data)->methodData + 5*i]) == 0) {
- i += m->methodOffset();
- break;
- }
- m = m->d.superdata;
+ int i = indexOfMethodRelative<0>(&m, method, false);
+ if (i < 0) {
+ m = this;
+ i = indexOfMethodRelative<0>(&m, method, true);
}
+ if (i >= 0)
+ i += m->methodOffset();
return i;
}
@@ -543,7 +580,11 @@ int QMetaObject::indexOfMethod(const char *method) const
int QMetaObject::indexOfSignal(const char *signal) const
{
const QMetaObject *m = this;
- int i = QMetaObjectPrivate::indexOfSignalRelative(&m, signal);
+ int i = QMetaObjectPrivate::indexOfSignalRelative(&m, signal, false);
+ if (i < 0) {
+ m = this;
+ i = QMetaObjectPrivate::indexOfSignalRelative(&m, signal, true);
+ }
if (i >= 0)
i += m->methodOffset();
return i;
@@ -554,21 +595,11 @@ int QMetaObject::indexOfSignal(const char *signal) const
\a baseObject will be adjusted to the enclosing QMetaObject, or 0 if the signal is not found
*/
-int QMetaObjectPrivate::indexOfSignalRelative(const QMetaObject **baseObject, const char *signal)
+int QMetaObjectPrivate::indexOfSignalRelative(const QMetaObject **baseObject,
+ const char *signal,
+ bool normalizeStringData)
{
- int i = -1;
- while (*baseObject) {
- const QMetaObject *const m = *baseObject;
- for (i = priv(m->d.data)->methodCount-1; i >= 0; --i)
- if ((m->d.data[priv(m->d.data)->methodData + 5*i + 4] & MethodTypeMask) == MethodSignal
- && strcmp(signal, m->d.stringdata
- + m->d.data[priv(m->d.data)->methodData + 5*i]) == 0) {
- break;
- }
- if (i >= 0)
- break;
- *baseObject = m->d.superdata;
- }
+ int i = indexOfMethodRelative<MethodSignal>(baseObject, signal, normalizeStringData);
#ifndef QT_NO_DEBUG
const QMetaObject *m = *baseObject;
if (i >= 0 && m && m->d.superdata) {
@@ -581,7 +612,6 @@ int QMetaObjectPrivate::indexOfSignalRelative(const QMetaObject **baseObject, co
return i;
}
-
/*!
Finds \a slot and returns its index; otherwise returns -1.
@@ -592,18 +622,19 @@ int QMetaObjectPrivate::indexOfSignalRelative(const QMetaObject **baseObject, co
*/
int QMetaObject::indexOfSlot(const char *slot) const
{
- int i = -1;
- const QMetaObject *m = this;
- while (m && i < 0) {
- for (i = priv(m->d.data)->methodCount-1; i >= 0; --i)
- if ((m->d.data[priv(m->d.data)->methodData + 5*i + 4] & MethodTypeMask) == MethodSlot
- && strcmp(slot, m->d.stringdata
- + m->d.data[priv(m->d.data)->methodData + 5*i]) == 0) {
- i += m->methodOffset();
- break;
- }
- m = m->d.superdata;
- }
+ int i = QMetaObjectPrivate::indexOfSlot(this, slot, false);
+ if (i < 0)
+ i = QMetaObjectPrivate::indexOfSlot(this, slot, true);
+ return i;
+}
+
+int QMetaObjectPrivate::indexOfSlot(const QMetaObject *m,
+ const char *slot,
+ bool normalizeStringData)
+{
+ int i = indexOfMethodRelative<MethodSlot>(&m, slot, normalizeStringData);
+ if (i >= 0)
+ i += m->methodOffset();
return i;
}
diff --git a/src/corelib/kernel/qmetaobject_p.h b/src/corelib/kernel/qmetaobject_p.h
index 3bbb050..a176149 100644
--- a/src/corelib/kernel/qmetaobject_p.h
+++ b/src/corelib/kernel/qmetaobject_p.h
@@ -115,11 +115,17 @@ struct QMetaObjectPrivate
int constructorCount, constructorData; //since revision 2
int flags; //since revision 3
int signalCount; //since revision 4
+ // revision 5 introduces changes in normalized signatures, no new members
static inline const QMetaObjectPrivate *get(const QMetaObject *metaobject)
{ return reinterpret_cast<const QMetaObjectPrivate*>(metaobject->d.data); }
- static int indexOfSignalRelative(const QMetaObject **baseObject, const char* name);
+ static int indexOfSignalRelative(const QMetaObject **baseObject,
+ const char* name,
+ bool normalizeStringData);
+ static int indexOfSlot(const QMetaObject *m,
+ const char *slot,
+ bool normalizeStringData);
static int originalClone(const QMetaObject *obj, int local_method_index);
#ifndef QT_NO_QOBJECT
@@ -247,6 +253,7 @@ static QByteArray normalizeTypeInternal(const char *t, const char *e, bool fixSc
} while (optional[++i].keyword != 0);
}
+ bool star = false;
while (t != e) {
char c = *t++;
if (fixScope && c == ':' && *t == ':' ) {
@@ -257,6 +264,7 @@ static QByteArray normalizeTypeInternal(const char *t, const char *e, bool fixSc
--i;
result.resize(i + 1);
}
+ star = star || c == '*';
result += c;
if (c == '<') {
//template recursion
@@ -277,6 +285,23 @@ static QByteArray normalizeTypeInternal(const char *t, const char *e, bool fixSc
}
}
}
+
+ // cv qualifers can appear after the type as well
+ if (t != e && (e - t >= 5 && strncmp("const", t, 5) == 0)) {
+ t += 5;
+ while (t != e && is_space(*t))
+ ++t;
+ if (adjustConst && t != e && *t == '&') {
+ // treat const ref as value
+ ++t;
+ } else if (!star) {
+ // move const to the front (but not if const comes after a *)
+ result.prepend("const ");
+ } else {
+ // keep const after a *
+ result += "const";
+ }
+ }
}
return result;
diff --git a/src/corelib/kernel/qmetatype.cpp b/src/corelib/kernel/qmetatype.cpp
index e304290..870baab 100644
--- a/src/corelib/kernel/qmetatype.cpp
+++ b/src/corelib/kernel/qmetatype.cpp
@@ -361,7 +361,14 @@ void QMetaType::registerStreamOperators(const char *typeName, SaveOperator saveO
int idx = type(typeName);
if (!idx)
return;
+ registerStreamOperators(idx, saveOp, loadOp);
+}
+/*! \internal
+*/
+void QMetaType::registerStreamOperators(int idx, SaveOperator saveOp,
+ LoadOperator loadOp)
+{
QVector<QCustomTypeInfo> *ct = customTypes();
if (!ct)
return;
diff --git a/src/corelib/kernel/qmetatype.h b/src/corelib/kernel/qmetatype.h
index c0dd288..c23caed 100644
--- a/src/corelib/kernel/qmetatype.h
+++ b/src/corelib/kernel/qmetatype.h
@@ -108,6 +108,8 @@ public:
typedef void (*LoadOperator)(QDataStream &, void *);
static void registerStreamOperators(const char *typeName, SaveOperator saveOp,
LoadOperator loadOp);
+ static void registerStreamOperators(int type, SaveOperator saveOp,
+ LoadOperator loadOp);
#endif
static int registerType(const char *typeName, Destructor destructor,
Constructor constructor);
@@ -224,6 +226,24 @@ inline int qRegisterMetaType(
#endif
}
+#ifndef QT_NO_DATASTREAM
+template <typename T>
+inline int qRegisterMetaTypeStreamOperators()
+{
+ typedef void(*SavePtr)(QDataStream &, const T *);
+ typedef void(*LoadPtr)(QDataStream &, T *);
+ SavePtr sptr = qMetaTypeSaveHelper<T>;
+ LoadPtr lptr = qMetaTypeLoadHelper<T>;
+
+ register int id = qMetaTypeId<T>();
+ QMetaType::registerStreamOperators(id,
+ reinterpret_cast<QMetaType::SaveOperator>(sptr),
+ reinterpret_cast<QMetaType::LoadOperator>(lptr));
+
+ return id;
+}
+#endif
+
#define Q_DECLARE_METATYPE(TYPE) \
QT_BEGIN_NAMESPACE \
template <> \
diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp
index 5298fff..761b31f 100644
--- a/src/corelib/kernel/qobject.cpp
+++ b/src/corelib/kernel/qobject.cpp
@@ -871,7 +871,7 @@ QObject::~QObject()
// all the signal/slots connections are still in place - if we don't
// quit now, we will crash pretty soon.
qWarning("Detected an unexpected exception in ~QObject while emitting destroyed().");
-#if defined(Q_AUTOTEST_EXPORT) && !defined(QT_NO_EXCEPTIONS)
+#if defined(Q_BUILD_INTERNAL) && !defined(QT_NO_EXCEPTIONS)
struct AutotestException : public std::exception
{
const char *what() const throw() { return "autotest swallow"; }
@@ -903,7 +903,8 @@ QObject::~QObject()
// disconnect all receivers
if (d->connectionLists) {
++d->connectionLists->inUse;
- for (int signal = -1; signal < d->connectionLists->count(); ++signal) {
+ int connectionListsCount = d->connectionLists->count();
+ for (int signal = -1; signal < connectionListsCount; ++signal) {
QObjectPrivate::ConnectionList &connectionList =
(*d->connectionLists)[signal];
@@ -940,16 +941,17 @@ QObject::~QObject()
// disconnect all senders
QObjectPrivate::Connection *node = d->senders;
while (node) {
- QMutex *m = signalSlotLock(node->sender);
+ QObject *sender = node->sender;
+ QMutex *m = signalSlotLock(sender);
node->prev = &node;
bool needToUnlock = QOrderedMutexLocker::relock(locker.mutex(), m);
//the node has maybe been removed while the mutex was unlocked in relock?
- if (!node || signalSlotLock(node->sender) != m) {
+ if (!node || node->sender != sender) {
m->unlock();
continue;
}
node->receiver = 0;
- QObjectConnectionListVector *senderLists = node->sender->d_func()->connectionLists;
+ QObjectConnectionListVector *senderLists = sender->d_func()->connectionLists;
if (senderLists)
senderLists->dirty = true;
@@ -2510,20 +2512,25 @@ bool QObject::connect(const QObject *sender, const char *signal,
const QMetaObject *smeta = sender->metaObject();
const char *signal_arg = signal;
++signal; //skip code
- int signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal);
+ int signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal, false);
if (signal_index < 0) {
// check for normalized signatures
tmp_signal_name = QMetaObject::normalizedSignature(signal - 1);
signal = tmp_signal_name.constData() + 1;
smeta = sender->metaObject();
- signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal);
+ signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal, false);
+ }
+ if (signal_index < 0) {
+ // re-use tmp_signal_name and signal from above
- if (signal_index < 0) {
- err_method_notfound(sender, signal_arg, "connect");
- err_info_about_objects("connect", sender, receiver);
- return false;
- }
+ smeta = sender->metaObject();
+ signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal, true);
+ }
+ if (signal_index < 0) {
+ err_method_notfound(sender, signal_arg, "connect");
+ err_info_about_objects("connect", sender, receiver);
+ return false;
}
signal_index = QMetaObjectPrivate::originalClone(smeta, signal_index);
int signalOffset, methodOffset;
@@ -2543,16 +2550,21 @@ bool QObject::connect(const QObject *sender, const char *signal,
int method_index = -1;
switch (membcode) {
case QSLOT_CODE:
- method_index = rmeta->indexOfSlot(method);
+ method_index = QMetaObjectPrivate::indexOfSlot(rmeta, method, false);
break;
case QSIGNAL_CODE:
- method_index = rmeta->indexOfSignal(method);
+ method_index = QMetaObjectPrivate::indexOfSignalRelative(&rmeta, method, false);
+ if (method_index >= 0)
+ method_index += rmeta->methodOffset();
break;
}
if (method_index < 0) {
// check for normalized methods
tmp_method_name = QMetaObject::normalizedSignature(method);
method = tmp_method_name.constData();
+
+ // rmeta may have been modified above
+ rmeta = receiver->metaObject();
switch (membcode) {
case QSLOT_CODE:
method_index = rmeta->indexOfSlot(method);
@@ -2740,7 +2752,9 @@ bool QObject::disconnect(const QObject *sender, const char *signal,
do {
int signal_index = -1;
if (signal) {
- signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal);
+ signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal, false);
+ if (signal_index < 0)
+ signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal, true);
if (signal_index < 0)
break;
signal_index = QMetaObjectPrivate::originalClone(smeta, signal_index);
@@ -3360,7 +3374,9 @@ int QObjectPrivate::signalIndex(const char *signalName) const
{
Q_Q(const QObject);
const QMetaObject *base = q->metaObject();
- int relative_index = QMetaObjectPrivate::indexOfSignalRelative(&base, signalName);
+ int relative_index = QMetaObjectPrivate::indexOfSignalRelative(&base, signalName, false);
+ if (relative_index < 0)
+ relative_index = QMetaObjectPrivate::indexOfSignalRelative(&base, signalName, true);
if (relative_index < 0)
return relative_index;
relative_index = QMetaObjectPrivate::originalClone(base, relative_index);
diff --git a/src/corelib/kernel/qobject_p.h b/src/corelib/kernel/qobject_p.h
index 27ab105..cc5bf97 100644
--- a/src/corelib/kernel/qobject_p.h
+++ b/src/corelib/kernel/qobject_p.h
@@ -189,8 +189,8 @@ public:
QList<QObject *> pendingChildInsertedEvents;
#else
// preserve binary compatibility with code compiled without Qt 3 support
- // ### why?
- QList<QObject *> unused;
+ // keeping the binary layout stable helps the Qt Creator debugger
+ void *unused;
#endif
QList<QPointer<QObject> > eventFilters;
diff --git a/src/corelib/plugin/qlibrary.cpp b/src/corelib/plugin/qlibrary.cpp
index f2c2384..a2c575a 100644
--- a/src/corelib/plugin/qlibrary.cpp
+++ b/src/corelib/plugin/qlibrary.cpp
@@ -630,6 +630,22 @@ bool QLibraryPrivate::isPlugin(QSettings *settings)
.arg((QT_VERSION & 0xff00) >> 8)
.arg(QLIBRARY_AS_DEBUG ? QLatin1String("debug") : QLatin1String("false"))
.arg(fileName);
+#ifdef Q_WS_MAC
+ // On Mac, add the application arch to the reg key in order to
+ // cache plugin information separately for each arch. This prevents
+ // Qt from wrongly caching plugin load failures when the archs
+ // don't match.
+#if defined(__x86_64__)
+ regkey += QLatin1String("-x86_64");
+#elif defined(__i386__)
+ regkey += QLatin1String("-i386");
+#elif defined(__ppc64__)
+ regkey += QLatin1String("-ppc64");
+#elif defined(__ppc__)
+ regkey += QLatin1String("-ppc");
+#endif
+#endif // Q_WS_MAC
+
QStringList reg;
#ifndef QT_NO_SETTINGS
if (!settings) {
diff --git a/src/corelib/thread/qorderedmutexlocker_p.h b/src/corelib/thread/qorderedmutexlocker_p.h
index 7d52a29..702125c 100644
--- a/src/corelib/thread/qorderedmutexlocker_p.h
+++ b/src/corelib/thread/qorderedmutexlocker_p.h
@@ -103,9 +103,11 @@ public:
mtx2->lock();
return true;
}
- mtx1->unlock();
- mtx2->lock();
- mtx1->lock();
+ if (!mtx2->tryLock()) {
+ mtx1->unlock();
+ mtx2->lock();
+ mtx1->lock();
+ }
return true;
}
diff --git a/src/corelib/tools/qbytearray.cpp b/src/corelib/tools/qbytearray.cpp
index 556093f..a27e488 100644
--- a/src/corelib/tools/qbytearray.cpp
+++ b/src/corelib/tools/qbytearray.cpp
@@ -1061,6 +1061,11 @@ QByteArray &QByteArray::operator=(const char *str)
\internal
*/
+/*! \fn bool QByteArray::isSharedWith(const QByteArray &other) const
+
+ \internal
+*/
+
/*! \fn char QByteArray::at(int i) const
Returns the character at index position \a i in the byte array.
diff --git a/src/corelib/tools/qbytearray.h b/src/corelib/tools/qbytearray.h
index ef97716..ec592f5f 100644
--- a/src/corelib/tools/qbytearray.h
+++ b/src/corelib/tools/qbytearray.h
@@ -164,6 +164,7 @@ public:
inline const char *constData() const;
inline void detach();
bool isDetached() const;
+ inline bool isSharedWith(const QByteArray &other) const { return d == other.d; }
void clear();
#ifdef Q_COMPILER_MANGLES_RETURN_TYPE
diff --git a/src/corelib/tools/qhash.cpp b/src/corelib/tools/qhash.cpp
index 6231471..285f4c9 100644
--- a/src/corelib/tools/qhash.cpp
+++ b/src/corelib/tools/qhash.cpp
@@ -847,6 +847,11 @@ void QHashData::checkSanity()
\internal
*/
+/*! \fn bool QHash::isSharedWith(const QHash<Key, T> &other) const
+
+ \internal
+*/
+
/*! \fn void QHash::clear()
Removes all items from the hash.
diff --git a/src/corelib/tools/qhash.h b/src/corelib/tools/qhash.h
index 5e93523..2832ca2 100644
--- a/src/corelib/tools/qhash.h
+++ b/src/corelib/tools/qhash.h
@@ -299,6 +299,7 @@ public:
inline void detach() { if (d->ref != 1) detach_helper(); }
inline bool isDetached() const { return d->ref == 1; }
inline void setSharable(bool sharable) { if (!sharable) detach(); d->sharable = sharable; }
+ inline bool isSharedWith(const QHash<Key, T> &other) const { return d == other.d; }
void clear();
diff --git a/src/corelib/tools/qlinkedlist.cpp b/src/corelib/tools/qlinkedlist.cpp
index 5a53c32..909d940 100644
--- a/src/corelib/tools/qlinkedlist.cpp
+++ b/src/corelib/tools/qlinkedlist.cpp
@@ -197,6 +197,11 @@ QLinkedListData QLinkedListData::shared_null = {
\internal
*/
+/*! \fn bool QLinkedList::isSharedWith(const QLinkedList<T> &other) const
+
+ \internal
+*/
+
/*! \fn bool QLinkedList::isEmpty() const
Returns true if the list contains no items; otherwise returns
diff --git a/src/corelib/tools/qlinkedlist.h b/src/corelib/tools/qlinkedlist.h
index f6de966..fe586a4 100644
--- a/src/corelib/tools/qlinkedlist.h
+++ b/src/corelib/tools/qlinkedlist.h
@@ -93,6 +93,7 @@ public:
{ if (d->ref != 1) detach_helper(); }
inline bool isDetached() const { return d->ref == 1; }
inline void setSharable(bool sharable) { if (!sharable) detach(); d->sharable = sharable; }
+ inline bool isSharedWith(const QLinkedList<T> &other) const { return d == other.d; }
inline bool isEmpty() const { return d->size == 0; }
diff --git a/src/corelib/tools/qlist.cpp b/src/corelib/tools/qlist.cpp
index c302857..ce62016 100644
--- a/src/corelib/tools/qlist.cpp
+++ b/src/corelib/tools/qlist.cpp
@@ -599,6 +599,11 @@ void **QListData::erase(void **xi)
\internal
*/
+/*! \fn bool QList::isSharedWith(const QList<T> &other) const
+
+ \internal
+*/
+
/*! \fn bool QList::isEmpty() const
Returns true if the list contains no items; otherwise returns
diff --git a/src/corelib/tools/qlist.h b/src/corelib/tools/qlist.h
index 120442d..1d08c41 100644
--- a/src/corelib/tools/qlist.h
+++ b/src/corelib/tools/qlist.h
@@ -130,6 +130,7 @@ public:
inline bool isDetached() const { return d->ref == 1; }
inline void setSharable(bool sharable) { if (!sharable) detach(); d->sharable = sharable; }
+ inline bool isSharedWith(const QList<T> &other) const { return d == other.d; }
inline bool isEmpty() const { return p.isEmpty(); }
diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp
index 8d79cb3..ff10fa1 100644
--- a/src/corelib/tools/qlocale.cpp
+++ b/src/corelib/tools/qlocale.cpp
@@ -4293,6 +4293,7 @@ bool QLocalePrivate::validateChars(const QString &str, NumberMode numMode, QByte
const bool scientific = numMode == DoubleScientificMode;
bool lastWasE = false;
+ bool lastWasDigit = false;
int eCnt = 0;
int decPointCnt = 0;
bool dec = false;
@@ -4307,6 +4308,7 @@ bool QLocalePrivate::validateChars(const QString &str, NumberMode numMode, QByte
if (dec && decDigits != -1 && decDigits < ++decDigitCnt)
return false;
}
+ lastWasDigit = true;
} else {
switch (c) {
case '.':
@@ -4344,7 +4346,10 @@ bool QLocalePrivate::validateChars(const QString &str, NumberMode numMode, QByte
break;
case ',':
- return false;
+ //it can only be placed after a digit which is before the decimal point
+ if (!lastWasDigit || decPointCnt > 0)
+ return false;
+ break;
case 'e':
if (scientific) {
@@ -4362,10 +4367,12 @@ bool QLocalePrivate::validateChars(const QString &str, NumberMode numMode, QByte
// If it's not a valid digit, it shall be Invalid.
return false;
}
+ lastWasDigit = false;
}
lastWasE = c == 'e';
- buff->append(c);
+ if (c != ',')
+ buff->append(c);
}
return true;
diff --git a/src/corelib/tools/qmap.cpp b/src/corelib/tools/qmap.cpp
index 82cbe78..3143ee4 100644
--- a/src/corelib/tools/qmap.cpp
+++ b/src/corelib/tools/qmap.cpp
@@ -473,6 +473,11 @@ void QMapData::dump()
\internal
*/
+/*! \fn bool QMap::isSharedWith(const QMap<Key, T> &other) const
+
+ \internal
+*/
+
/*! \fn void QMap::setInsertInOrder(bool sharable)
\internal
diff --git a/src/corelib/tools/qmap.h b/src/corelib/tools/qmap.h
index e71064c..9ba9ca5 100644
--- a/src/corelib/tools/qmap.h
+++ b/src/corelib/tools/qmap.h
@@ -182,6 +182,7 @@ public:
inline void detach() { if (d->ref != 1) detach_helper(); }
inline bool isDetached() const { return d->ref == 1; }
inline void setSharable(bool sharable) { if (!sharable) detach(); d->sharable = sharable; }
+ inline bool isSharedWith(const QMap<Key, T> &other) const { return d == other.d; }
inline void setInsertInOrder(bool ordered) { d->insertInOrder = ordered; }
void clear();
diff --git a/src/corelib/tools/qpoint.cpp b/src/corelib/tools/qpoint.cpp
index d60087f..9850ee7 100644
--- a/src/corelib/tools/qpoint.cpp
+++ b/src/corelib/tools/qpoint.cpp
@@ -374,7 +374,7 @@ QDebug operator<<(QDebug dbg, const QPoint &p) {
QDebug operator<<(QDebug d, const QPointF &p)
{
d.nospace() << "QPointF(" << p.x() << ", " << p.y() << ')';
- return d;
+ return d.space();
}
#endif
diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp
index 3ef0e66..dec59b7 100644
--- a/src/corelib/tools/qstring.cpp
+++ b/src/corelib/tools/qstring.cpp
@@ -55,6 +55,7 @@
#include "qtools_p.h"
#include "qhash.h"
#include "qdebug.h"
+#include "qendian.h"
#ifdef Q_OS_MAC
#include <private/qcore_mac_p.h>
@@ -1091,7 +1092,12 @@ QString::QString(QChar ch)
\internal
*/
-/*! \fn void QString::isDetached() const
+/*! \fn bool QString::isDetached() const
+
+ \internal
+*/
+
+/*! \fn bool QString::isSharedWith(const QString &other) const
\internal
*/
@@ -7317,7 +7323,7 @@ QDataStream &operator>>(QDataStream &in, QString &str)
!= (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
ushort *data = reinterpret_cast<ushort *>(str.data());
while (len--) {
- *data = (*data >> 8) | (*data << 8);
+ *data = qbswap(*data);
++data;
}
}
diff --git a/src/corelib/tools/qstring.h b/src/corelib/tools/qstring.h
index c1def0f..5e3b0fd 100644
--- a/src/corelib/tools/qstring.h
+++ b/src/corelib/tools/qstring.h
@@ -122,6 +122,7 @@ public:
inline void detach();
inline bool isDetached() const;
+ inline bool isSharedWith(const QString &other) const { return d == other.d; }
void clear();
inline const QChar at(int i) const;
diff --git a/src/corelib/tools/qstringlist.cpp b/src/corelib/tools/qstringlist.cpp
index 4b0f488..e9bdf57 100644
--- a/src/corelib/tools/qstringlist.cpp
+++ b/src/corelib/tools/qstringlist.cpp
@@ -404,7 +404,17 @@ void QtPrivate::QStringList_replaceInStrings(QStringList *that, const QRegExp &r
*/
QString QtPrivate::QStringList_join(const QStringList *that, const QString &sep)
{
+ int totalLength = 0;
+ const int size = that->size();
+
+ for (int i = 0; i < size; ++i)
+ totalLength += that->at(i).size();
+
+ if(size > 0)
+ totalLength += sep.size() * (size - 1);
+
QString res;
+ res.reserve(totalLength);
for (int i = 0; i < that->size(); ++i) {
if (i)
res += sep;
diff --git a/src/corelib/tools/qvector.cpp b/src/corelib/tools/qvector.cpp
index 48b52d2..3a13540 100644
--- a/src/corelib/tools/qvector.cpp
+++ b/src/corelib/tools/qvector.cpp
@@ -392,6 +392,11 @@ int QVectorData::grow(int sizeofTypedData, int size, int sizeofT, bool excessive
\internal
*/
+/*! \fn bool QVector::isSharedWith(const QVector<T> &other) const
+
+ \internal
+*/
+
/*! \fn T *QVector::data()
Returns a pointer to the data stored in the vector. The pointer
diff --git a/src/corelib/tools/qvector.h b/src/corelib/tools/qvector.h
index 90b7442..61b22fd 100644
--- a/src/corelib/tools/qvector.h
+++ b/src/corelib/tools/qvector.h
@@ -134,6 +134,7 @@ public:
inline void detach() { if (d->ref != 1) detach_helper(); }
inline bool isDetached() const { return d->ref == 1; }
inline void setSharable(bool sharable) { if (!sharable) detach(); d->sharable = sharable; }
+ inline bool isSharedWith(const QVector<T> &other) const { return d == other.d; }
inline T *data() { detach(); return p->array; }
inline const T *data() const { return p->array; }
diff --git a/src/corelib/xml/qxmlstream.cpp b/src/corelib/xml/qxmlstream.cpp
index 5717ca2..1bf00b8 100644
--- a/src/corelib/xml/qxmlstream.cpp
+++ b/src/corelib/xml/qxmlstream.cpp
@@ -3003,8 +3003,7 @@ QXmlStreamWriterPrivate::QXmlStreamWriterPrivate(QXmlStreamWriter *q)
deleteDevice = false;
#ifndef QT_NO_TEXTCODEC
codec = QTextCodec::codecForMib(106); // utf8
- encoder = codec->makeEncoder();
- encoder->state.flags |= QTextCodec::IgnoreHeader; // no byte order mark for utf8
+ encoder = codec->makeEncoder(QTextCodec::IgnoreHeader); // no byte order mark for utf8
#endif
inStartElement = inEmptyElement = false;
wroteSomething = false;
@@ -3278,9 +3277,7 @@ void QXmlStreamWriter::setCodec(QTextCodec *codec)
if (codec) {
d->codec = codec;
delete d->encoder;
- d->encoder = codec->makeEncoder();
- if (codec->mibEnum() == 106)
- d->encoder->state.flags |= QTextCodec::IgnoreHeader; // no byte order mark for utf8
+ d->encoder = codec->makeEncoder(QTextCodec::IgnoreHeader); // no byte order mark for utf8
}
}
diff --git a/src/declarative/3rdparty/3rdparty.pri b/src/declarative/3rdparty/3rdparty.pri
new file mode 100644
index 0000000..fbdcc11
--- /dev/null
+++ b/src/declarative/3rdparty/3rdparty.pri
@@ -0,0 +1,7 @@
+INCLUDEPATH += $$PWD
+
+HEADERS += \
+ $$PWD/qlistmodelinterface_p.h\
+
+SOURCES += \
+ $$PWD/qlistmodelinterface.cpp \
diff --git a/src/declarative/3rdparty/qlistmodelinterface.cpp b/src/declarative/3rdparty/qlistmodelinterface.cpp
new file mode 100644
index 0000000..cfd4cff
--- /dev/null
+++ b/src/declarative/3rdparty/qlistmodelinterface.cpp
@@ -0,0 +1,109 @@
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the QtDeclarative module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain
+** additional rights. These rights are described in the Nokia Qt LGPL
+** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
+** package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qlistmodelinterface_p.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \internal
+ \class QListModelInterface
+ \brief The QListModelInterface class can be subclassed to provide C++ models to QmlGraphics Views
+
+ This class is comprised primarily of pure virtual functions which
+ you must implement in a subclass. You can then use the subclass
+ as a model for a QmlGraphics view, such as a QmlGraphicsListView.
+*/
+
+/*! \fn QListModelInterface::QListModelInterface(QObject *parent)
+ Constructs a QListModelInterface with the specified \a parent.
+*/
+
+ /*! \fn QListModelInterface::QListModelInterface(QObjectPrivate &dd, QObject *parent)
+
+ \internal
+ */
+
+/*! \fn QListModelInterface::~QListModelInterface()
+ The destructor is virtual.
+ */
+
+/*! \fn int QListModelInterface::count() const
+ Returns the number of data entries in the model.
+*/
+
+/*! \fn QHash<int,QVariant> QListModelInterface::data(int index, const QList<int>& roles) const
+ Returns the data at the given \a index for the specifed \a roles.
+*/
+
+/*! \fn bool QListModelInterface::setData(int index, const QHash<int,QVariant>& values)
+ Sets the data at the given \a index. \a values is a mapping of
+ QVariant values to roles. Returns false.
+*/
+
+/*! \fn QList<int> QListModelInterface::roles() const
+ Returns the list of roles for which the list model interface
+ provides data.
+*/
+
+/*! \fn QString QListModelInterface::toString(int role) const
+ Returns a string description of the specified \a role.
+*/
+
+/*! \fn void QListModelInterface::itemsInserted(int index, int count)
+ Emit this signal when \a count items are inserted at \a index.
+ */
+
+/*! \fn void QListModelInterface::itemsRemoved(int index, int count)
+ Emit this signal when \a count items are removed at \a index.
+ */
+
+/*! \fn void QListModelInterface::itemsMoved(int from, int to, int count)
+ Emit this signal when \a count items are moved from index \a from
+ to index \a to.
+ */
+
+/*! \fn void QListModelInterface::itemsChanged(int index, int count, const QList<int> &roles)
+ Emit this signal when \a count items at \a index have had their
+ \a roles changed.
+ */
+
+QT_END_NAMESPACE
diff --git a/src/declarative/3rdparty/qlistmodelinterface_p.h b/src/declarative/3rdparty/qlistmodelinterface_p.h
new file mode 100644
index 0000000..a958ead
--- /dev/null
+++ b/src/declarative/3rdparty/qlistmodelinterface_p.h
@@ -0,0 +1,85 @@
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the QtDeclarative module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain
+** additional rights. These rights are described in the Nokia Qt LGPL
+** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
+** package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QLISTMODELINTERFACE_H
+#define QLISTMODELINTERFACE_H
+
+#include <QtCore/QHash>
+#include <QtCore/QVariant>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class Q_DECLARATIVE_EXPORT QListModelInterface : public QObject
+{
+ Q_OBJECT
+ public:
+ QListModelInterface(QObject *parent = 0) : QObject(parent) {}
+ virtual ~QListModelInterface() {}
+
+ virtual int count() const = 0;
+ virtual QHash<int,QVariant> data(int index, const QList<int>& roles = QList<int>()) const = 0;
+ virtual QVariant data(int index, int role) const = 0;
+ virtual bool setData(int index, const QHash<int,QVariant>& values)
+ { Q_UNUSED(index); Q_UNUSED(values); return false; }
+
+ virtual QList<int> roles() const = 0;
+ virtual QString toString(int role) const = 0;
+
+ Q_SIGNALS:
+ 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, const QList<int> &roles);
+
+ protected:
+ QListModelInterface(QObjectPrivate &dd, QObject *parent)
+ : QObject(dd, parent) {}
+};
+
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+#endif //QTREEMODELINTERFACE_H
diff --git a/src/declarative/QmlChanges.txt b/src/declarative/QmlChanges.txt
new file mode 100644
index 0000000..e54ec95
--- /dev/null
+++ b/src/declarative/QmlChanges.txt
@@ -0,0 +1,122 @@
+
+
+Listview: sectionExpression has been replaced by section.property, section.criteria
+
+
+=============================================================================
+The changes below are pre-4.6.0 release.
+
+QML API Review
+==============
+
+The QML API is being reviewed. This file documents the changes.
+Note that the changes are incremental, so a rename A->B for example may be followed
+by another subsequent rename B->C, if later reviews override earlier reviews.
+
+API Changes
+===========
+
+Renamed Elements:
+LineEdit -> TextInput
+VerticalLayout -> Column
+HorizontalLayout -> Row
+VerticalPositioner -> Column
+HorizontalPositioner -> Row
+GridLayout -> Grid
+GridPositioner -> Grid
+Rect -> Rectangle
+FocusRealm -> FocusScope
+FontFamily -> FontLoader
+Palette -> SystemPalette
+Bind -> Binding
+SetProperties -> PropertyChanges
+RunScript -> StateChangeScript
+SetAnchors -> AnchorChanges
+SetPropertyAction -> PropertyAction
+RunScriptAction -> ScriptAction
+ParentChangeAction -> ParentAction
+VisualModel -> VisualDataModel
+Follow -> SpringFollow
+
+Renamed properties:
+Item: contents -> childrenRect
+MouseRegion: xmin -> minimumX
+MouseRegion: xmax -> maximumX
+MouseRegion: ymin -> minimumY
+MouseRegion: ymin -> maximumY
+Text elements: hAlign -> horizontalAlignment
+Text elements: vAlign -> verticalAlignment
+Text elements: highlightColor -> selectionColor
+Text elements: highlightedTextColor -> selectedTextColor
+Text elements: preserveSelection -> persistentSelection
+State: operations -> changes
+Transition: operations -> animations
+Transition: fromState -> from
+Transition: toState -> to
+Follow: followValue -> value
+Flickable: xPosition -> viewportX
+Flickable: yPosition -> viewportY
+Flickable: xVelocity -> horizontalVelocity
+Flickable: yVelocity -> verticalVelocity
+Flickable: velocityDecay -> reportedVelocitySmoothing
+Flickable: locked -> interactive (note reversal of meaning)
+Flickable: pageXPosition -> visibleArea.xPosition
+Flickable: pageYPosition -> visibleArea.yPosition
+Flickable: pageWidth -> visibleArea.widthRatio
+Flickable: pageHeight -> visibleArea.heightRatio
+WebView: idealWidth -> preferredWidth
+WebView: idealHeight -> preferredHeight
+WebView: status -> statusText
+WebView: mouseX -> clickX (parameter to onDoubleClick)
+WebView: mouseY -> clickY (parameter to onDoubleClick)
+WebView: cacheSize -> pixelCacheSize
+Repeater: component -> delegate
+Repeater: dataSource -> model
+ListView: current -> currentItem
+GridView: current -> currentItem
+ListView: wrap -> keyNavigationWraps
+ListView: autoHighlight -> highlightFollowsCurrentItem
+GridView: wrap -> keyNavigationWraps
+GridView: autoHighlight -> highlightFollowsCurrentItem
+Animation: targets -> matchTargets
+Animation: properties -> matchProperties
+
+Additions:
+MouseRegion: add "acceptedButtons" property
+MouseRegion: add "hoverEnabled" property
+MouseRegion: add "pressedButtons" property
+Timer: add start() and stop() slots
+WebView: add newWindowComponent and newWindowParent properties
+Loader: add status() and progress() properties
+Loader: add sourceComponent property
+Loader: add resizeMode property
+ListView: preferredHighlightBegin, preferredHighlightEnd
+ListView: strictlyEnforceHighlightRange
+Particles: Added emissionRate, emissionVariance and burst()
+
+Deletions:
+Column/VerticalPositioner: lost "margins" property
+Row/HorizontalPositioner: lost "margins" property
+Grid/Positioner/Layout: lost "margins" property
+WebView: lost "interactive" property (always true now)
+Flickable: removed "dragMode" property
+ComponentInstance: removed. Replaced by Loader.sourceComponent
+ListView: removed currentItemMode. Replaced by highligh range.
+ListView: removed snapPos.
+Particles: removed streamIn. Replaced by emissionRate
+
+Other Changes:
+ids must be lowercase: Text { id: foo }, not Text { id: Foo }
+Drag: axis becomes an enum with values "XAxis", "YAxis", "XandYAxis"
+Image: scaleGrid property removed. New item called BorderImage instead.
+KeyActions: changed to a Keys attached property on any item.
+KeyProxy: changed to a Keys.forwardTo property on any item.
+Script: now an intrinsic type in the language
+ - cannot be assigned to properties
+ - good: Item { Script { ... } }
+ - bad: Item { resources: Script { ... } }
+Script: delay-loaded of the QML file until their source has been loaded (this only effects QML files loaded across the network.)
+Scope: declared properties shadow a property of the same name (was previously the reverse)
+ScriptAction and StateChangeScript: the script property now takes script rather than a string containing script (script: doSomething() rather than script: "doSomething()")
+QmlGraphicsItem::transformOrigin default changed from TopLeft to Center
+Animations used as PropertySourceValues are set to 'running: true' as default
diff --git a/src/declarative/debugger/debugger.pri b/src/declarative/debugger/debugger.pri
new file mode 100644
index 0000000..261b2ff
--- /dev/null
+++ b/src/declarative/debugger/debugger.pri
@@ -0,0 +1,15 @@
+INCLUDEPATH += $$PWD
+
+SOURCES += \
+ $$PWD/qmldebuggerstatus.cpp \
+ $$PWD/qpacketprotocol.cpp \
+ $$PWD/qmldebugservice.cpp \
+ $$PWD/qmldebugclient.cpp \
+ $$PWD/qmldebug.cpp
+
+HEADERS += \
+ $$PWD/qmldebuggerstatus_p.h \
+ $$PWD/qpacketprotocol_p.h \
+ $$PWD/qmldebugservice_p.h \
+ $$PWD/qmldebugclient_p.h \
+ $$PWD/qmldebug_p.h
diff --git a/src/declarative/debugger/qmldebug.cpp b/src/declarative/debugger/qmldebug.cpp
new file mode 100644
index 0000000..dc779ac
--- /dev/null
+++ b/src/declarative/debugger/qmldebug.cpp
@@ -0,0 +1,934 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmldebug_p.h"
+
+#include "qmldebugclient_p.h"
+
+#include <qmlenginedebug_p.h>
+
+#include <private/qobject_p.h>
+
+class QmlEngineDebugClient : public QmlDebugClient
+{
+public:
+ QmlEngineDebugClient(QmlDebugConnection *client, QmlEngineDebugPrivate *p);
+
+protected:
+ virtual void messageReceived(const QByteArray &);
+
+private:
+ QmlEngineDebugPrivate *priv;
+};
+
+class QmlEngineDebugPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlEngineDebug)
+public:
+ QmlEngineDebugPrivate(QmlDebugConnection *);
+
+ void message(const QByteArray &);
+
+ QmlEngineDebugClient *client;
+ int nextId;
+ int getId();
+
+ void decode(QDataStream &, QmlDebugContextReference &);
+ void decode(QDataStream &, QmlDebugObjectReference &, bool simple);
+
+ static void remove(QmlEngineDebug *, QmlDebugEnginesQuery *);
+ static void remove(QmlEngineDebug *, QmlDebugRootContextQuery *);
+ static void remove(QmlEngineDebug *, QmlDebugObjectQuery *);
+ static void remove(QmlEngineDebug *, QmlDebugExpressionQuery *);
+
+ QHash<int, QmlDebugEnginesQuery *> enginesQuery;
+ QHash<int, QmlDebugRootContextQuery *> rootContextQuery;
+ QHash<int, QmlDebugObjectQuery *> objectQuery;
+ QHash<int, QmlDebugExpressionQuery *> expressionQuery;
+
+ QHash<int, QmlDebugWatch *> watched;
+};
+
+QmlEngineDebugClient::QmlEngineDebugClient(QmlDebugConnection *client,
+ QmlEngineDebugPrivate *p)
+: QmlDebugClient(QLatin1String("QmlEngine"), client), priv(p)
+{
+ setEnabled(true);
+}
+
+void QmlEngineDebugClient::messageReceived(const QByteArray &data)
+{
+ priv->message(data);
+}
+
+QmlEngineDebugPrivate::QmlEngineDebugPrivate(QmlDebugConnection *c)
+: client(new QmlEngineDebugClient(c, this)), nextId(0)
+{
+}
+
+int QmlEngineDebugPrivate::getId()
+{
+ return nextId++;
+}
+
+void QmlEngineDebugPrivate::remove(QmlEngineDebug *c, QmlDebugEnginesQuery *q)
+{
+ if (c && q) {
+ QmlEngineDebugPrivate *p = (QmlEngineDebugPrivate *)QObjectPrivate::get(c);
+ p->enginesQuery.remove(q->m_queryId);
+ }
+}
+
+void QmlEngineDebugPrivate::remove(QmlEngineDebug *c,
+ QmlDebugRootContextQuery *q)
+{
+ if (c && q) {
+ QmlEngineDebugPrivate *p = (QmlEngineDebugPrivate *)QObjectPrivate::get(c);
+ p->rootContextQuery.remove(q->m_queryId);
+ }
+}
+
+void QmlEngineDebugPrivate::remove(QmlEngineDebug *c, QmlDebugObjectQuery *q)
+{
+ if (c && q) {
+ QmlEngineDebugPrivate *p = (QmlEngineDebugPrivate *)QObjectPrivate::get(c);
+ p->objectQuery.remove(q->m_queryId);
+ }
+}
+
+void QmlEngineDebugPrivate::remove(QmlEngineDebug *c, QmlDebugExpressionQuery *q)
+{
+ if (c && q) {
+ QmlEngineDebugPrivate *p = (QmlEngineDebugPrivate *)QObjectPrivate::get(c);
+ p->expressionQuery.remove(q->m_queryId);
+ }
+}
+
+
+Q_DECLARE_METATYPE(QmlDebugObjectReference);
+void QmlEngineDebugPrivate::decode(QDataStream &ds, QmlDebugObjectReference &o,
+ bool simple)
+{
+ QmlEngineDebugServer::QmlObjectData data;
+ ds >> data;
+ o.m_debugId = data.objectId;
+ o.m_class = data.objectType;
+ o.m_name = data.objectName;
+ o.m_source.m_url = data.url;
+ o.m_source.m_lineNumber = data.lineNumber;
+ o.m_source.m_columnNumber = data.columnNumber;
+ o.m_contextDebugId = data.contextId;
+
+ if (simple)
+ return;
+
+ int childCount;
+ bool recur;
+ ds >> childCount >> recur;
+
+ for (int ii = 0; ii < childCount; ++ii) {
+ o.m_children.append(QmlDebugObjectReference());
+ decode(ds, o.m_children.last(), !recur);
+ }
+
+ int propCount;
+ ds >> propCount;
+
+ for (int ii = 0; ii < propCount; ++ii) {
+ QmlEngineDebugServer::QmlObjectProperty data;
+ ds >> data;
+ QmlDebugPropertyReference prop;
+ prop.m_objectDebugId = o.m_debugId;
+ prop.m_name = data.name;
+ prop.m_binding = data.binding;
+ prop.m_hasNotifySignal = data.hasNotifySignal;
+ prop.m_valueTypeName = data.valueTypeName;
+ switch (data.type) {
+ case QmlEngineDebugServer::QmlObjectProperty::Basic:
+ case QmlEngineDebugServer::QmlObjectProperty::List:
+ case QmlEngineDebugServer::QmlObjectProperty::SignalProperty:
+ {
+ prop.m_value = data.value;
+ break;
+ }
+ case QmlEngineDebugServer::QmlObjectProperty::Object:
+ {
+ QmlDebugObjectReference obj;
+ obj.m_debugId = prop.m_value.toInt();
+ prop.m_value = qVariantFromValue(obj);
+ break;
+ }
+ case QmlEngineDebugServer::QmlObjectProperty::Unknown:
+ break;
+ }
+ o.m_properties << prop;
+ }
+}
+
+void QmlEngineDebugPrivate::decode(QDataStream &ds, QmlDebugContextReference &c)
+{
+ ds >> c.m_name >> c.m_debugId;
+
+ int contextCount;
+ ds >> contextCount;
+
+ for (int ii = 0; ii < contextCount; ++ii) {
+ c.m_contexts.append(QmlDebugContextReference());
+ decode(ds, c.m_contexts.last());
+ }
+
+ int objectCount;
+ ds >> objectCount;
+
+ for (int ii = 0; ii < objectCount; ++ii) {
+ QmlDebugObjectReference obj;
+ decode(ds, obj, true);
+
+ obj.m_contextDebugId = c.m_debugId;
+ c.m_objects << obj;
+ }
+}
+
+void QmlEngineDebugPrivate::message(const QByteArray &data)
+{
+ QDataStream ds(data);
+
+ QByteArray type;
+ ds >> type;
+
+ //qDebug() << "QmlEngineDebugPrivate::message()" << type;
+
+ if (type == "LIST_ENGINES_R") {
+ int queryId;
+ ds >> queryId;
+
+ QmlDebugEnginesQuery *query = enginesQuery.value(queryId);
+ if (!query)
+ return;
+ enginesQuery.remove(queryId);
+
+ int count;
+ ds >> count;
+
+ for (int ii = 0; ii < count; ++ii) {
+ QmlDebugEngineReference ref;
+ ds >> ref.m_name;
+ ds >> ref.m_debugId;
+ query->m_engines << ref;
+ }
+
+ query->m_client = 0;
+ query->setState(QmlDebugQuery::Completed);
+ } else if (type == "LIST_OBJECTS_R") {
+ int queryId;
+ ds >> queryId;
+
+ QmlDebugRootContextQuery *query = rootContextQuery.value(queryId);
+ if (!query)
+ return;
+ rootContextQuery.remove(queryId);
+
+ if (!ds.atEnd())
+ decode(ds, query->m_context);
+
+ query->m_client = 0;
+ query->setState(QmlDebugQuery::Completed);
+ } else if (type == "FETCH_OBJECT_R") {
+ int queryId;
+ ds >> queryId;
+
+ QmlDebugObjectQuery *query = objectQuery.value(queryId);
+ if (!query)
+ return;
+ objectQuery.remove(queryId);
+
+ if (!ds.atEnd())
+ decode(ds, query->m_object, false);
+
+ query->m_client = 0;
+ query->setState(QmlDebugQuery::Completed);
+ } else if (type == "EVAL_EXPRESSION_R") {
+ int queryId;
+ QVariant result;
+ ds >> queryId >> result;
+
+ QmlDebugExpressionQuery *query = expressionQuery.value(queryId);
+ if (!query)
+ return;
+ expressionQuery.remove(queryId);
+
+ query->m_result = result;
+ query->m_client = 0;
+ query->setState(QmlDebugQuery::Completed);
+ } else if (type == "WATCH_PROPERTY_R") {
+ int queryId;
+ bool ok;
+ ds >> queryId >> ok;
+
+ QmlDebugWatch *watch = watched.value(queryId);
+ if (!watch)
+ return;
+
+ watch->setState(ok ? QmlDebugWatch::Active : QmlDebugWatch::Inactive);
+ } else if (type == "WATCH_OBJECT_R") {
+ int queryId;
+ bool ok;
+ ds >> queryId >> ok;
+
+ QmlDebugWatch *watch = watched.value(queryId);
+ if (!watch)
+ return;
+
+ watch->setState(ok ? QmlDebugWatch::Active : QmlDebugWatch::Inactive);
+ } else if (type == "WATCH_EXPR_OBJECT_R") {
+ int queryId;
+ bool ok;
+ ds >> queryId >> ok;
+
+ QmlDebugWatch *watch = watched.value(queryId);
+ if (!watch)
+ return;
+
+ watch->setState(ok ? QmlDebugWatch::Active : QmlDebugWatch::Inactive);
+ } else if (type == "UPDATE_WATCH") {
+ int queryId;
+ int debugId;
+ QByteArray name;
+ QVariant value;
+ ds >> queryId >> debugId >> name >> value;
+
+ QmlDebugWatch *watch = watched.value(queryId, 0);
+ if (!watch)
+ return;
+ emit watch->valueChanged(name, value);
+ }
+}
+
+QmlEngineDebug::QmlEngineDebug(QmlDebugConnection *client, QObject *parent)
+: QObject(*(new QmlEngineDebugPrivate(client)), parent)
+{
+}
+
+QmlDebugPropertyWatch *QmlEngineDebug::addWatch(const QmlDebugPropertyReference &property, QObject *parent)
+{
+ Q_D(QmlEngineDebug);
+
+ QmlDebugPropertyWatch *watch = new QmlDebugPropertyWatch(parent);
+ if (d->client->isConnected()) {
+ int queryId = d->getId();
+ watch->m_queryId = queryId;
+ watch->m_client = this;
+ watch->m_objectDebugId = property.objectDebugId();
+ watch->m_name = property.name();
+ d->watched.insert(queryId, watch);
+
+ QByteArray message;
+ QDataStream ds(&message, QIODevice::WriteOnly);
+ ds << QByteArray("WATCH_PROPERTY") << queryId << property.objectDebugId() << property.name().toUtf8();
+ d->client->sendMessage(message);
+ } else {
+ watch->m_state = QmlDebugWatch::Dead;
+ }
+
+ return watch;
+}
+
+QmlDebugWatch *QmlEngineDebug::addWatch(const QmlDebugContextReference &, const QString &, QObject *)
+{
+ qWarning("QmlEngineDebug::addWatch(): Not implemented");
+ return 0;
+}
+
+QmlDebugObjectExpressionWatch *QmlEngineDebug::addWatch(const QmlDebugObjectReference &object, const QString &expr, QObject *parent)
+{
+ Q_D(QmlEngineDebug);
+ QmlDebugObjectExpressionWatch *watch = new QmlDebugObjectExpressionWatch(parent);
+ if (d->client->isConnected()) {
+ int queryId = d->getId();
+ watch->m_queryId = queryId;
+ watch->m_client = this;
+ watch->m_objectDebugId = object.debugId();
+ watch->m_expr = expr;
+ d->watched.insert(queryId, watch);
+
+ QByteArray message;
+ QDataStream ds(&message, QIODevice::WriteOnly);
+ ds << QByteArray("WATCH_EXPR_OBJECT") << queryId << object.debugId() << expr;
+ d->client->sendMessage(message);
+ } else {
+ watch->m_state = QmlDebugWatch::Dead;
+ }
+ return watch;
+}
+
+QmlDebugWatch *QmlEngineDebug::addWatch(const QmlDebugObjectReference &object, QObject *parent)
+{
+ Q_D(QmlEngineDebug);
+
+ QmlDebugWatch *watch = new QmlDebugWatch(parent);
+ if (d->client->isConnected()) {
+ int queryId = d->getId();
+ watch->m_queryId = queryId;
+ watch->m_client = this;
+ watch->m_objectDebugId = object.debugId();
+ d->watched.insert(queryId, watch);
+
+ QByteArray message;
+ QDataStream ds(&message, QIODevice::WriteOnly);
+ ds << QByteArray("WATCH_OBJECT") << queryId << object.debugId();
+ d->client->sendMessage(message);
+ } else {
+ watch->m_state = QmlDebugWatch::Dead;
+ }
+
+ return watch;
+}
+
+QmlDebugWatch *QmlEngineDebug::addWatch(const QmlDebugFileReference &, QObject *)
+{
+ qWarning("QmlEngineDebug::addWatch(): Not implemented");
+ return 0;
+}
+
+void QmlEngineDebug::removeWatch(QmlDebugWatch *watch)
+{
+ Q_D(QmlEngineDebug);
+
+ if (!watch || !watch->m_client)
+ return;
+
+ watch->m_client = 0;
+ watch->setState(QmlDebugWatch::Inactive);
+
+ d->watched.remove(watch->queryId());
+
+ if (d->client && d->client->isConnected()) {
+ QByteArray message;
+ QDataStream ds(&message, QIODevice::WriteOnly);
+ ds << QByteArray("NO_WATCH") << watch->queryId();
+ d->client->sendMessage(message);
+ }
+}
+
+QmlDebugEnginesQuery *QmlEngineDebug::queryAvailableEngines(QObject *parent)
+{
+ Q_D(QmlEngineDebug);
+
+ QmlDebugEnginesQuery *query = new QmlDebugEnginesQuery(parent);
+ if (d->client->isConnected()) {
+ query->m_client = this;
+ int queryId = d->getId();
+ query->m_queryId = queryId;
+ d->enginesQuery.insert(queryId, query);
+
+ QByteArray message;
+ QDataStream ds(&message, QIODevice::WriteOnly);
+ ds << QByteArray("LIST_ENGINES") << queryId;
+ d->client->sendMessage(message);
+ } else {
+ query->m_state = QmlDebugQuery::Error;
+ }
+
+ return query;
+}
+
+QmlDebugRootContextQuery *QmlEngineDebug::queryRootContexts(const QmlDebugEngineReference &engine, QObject *parent)
+{
+ Q_D(QmlEngineDebug);
+
+ QmlDebugRootContextQuery *query = new QmlDebugRootContextQuery(parent);
+ if (d->client->isConnected() && engine.debugId() != -1) {
+ query->m_client = this;
+ int queryId = d->getId();
+ query->m_queryId = queryId;
+ d->rootContextQuery.insert(queryId, query);
+
+ QByteArray message;
+ QDataStream ds(&message, QIODevice::WriteOnly);
+ ds << QByteArray("LIST_OBJECTS") << queryId << engine.debugId();
+ d->client->sendMessage(message);
+ } else {
+ query->m_state = QmlDebugQuery::Error;
+ }
+
+ return query;
+}
+
+QmlDebugObjectQuery *QmlEngineDebug::queryObject(const QmlDebugObjectReference &object, QObject *parent)
+{
+ Q_D(QmlEngineDebug);
+
+ QmlDebugObjectQuery *query = new QmlDebugObjectQuery(parent);
+ if (d->client->isConnected() && object.debugId() != -1) {
+ query->m_client = this;
+ int queryId = d->getId();
+ query->m_queryId = queryId;
+ d->objectQuery.insert(queryId, query);
+
+ QByteArray message;
+ QDataStream ds(&message, QIODevice::WriteOnly);
+ ds << QByteArray("FETCH_OBJECT") << queryId << object.debugId()
+ << false;
+ d->client->sendMessage(message);
+ } else {
+ query->m_state = QmlDebugQuery::Error;
+ }
+
+ return query;
+}
+
+QmlDebugObjectQuery *QmlEngineDebug::queryObjectRecursive(const QmlDebugObjectReference &object, QObject *parent)
+{
+ Q_D(QmlEngineDebug);
+
+ QmlDebugObjectQuery *query = new QmlDebugObjectQuery(parent);
+ if (d->client->isConnected() && object.debugId() != -1) {
+ query->m_client = this;
+ int queryId = d->getId();
+ query->m_queryId = queryId;
+ d->objectQuery.insert(queryId, query);
+
+ QByteArray message;
+ QDataStream ds(&message, QIODevice::WriteOnly);
+ ds << QByteArray("FETCH_OBJECT") << queryId << object.debugId()
+ << true;
+ d->client->sendMessage(message);
+ } else {
+ query->m_state = QmlDebugQuery::Error;
+ }
+
+ return query;
+}
+
+QmlDebugExpressionQuery *QmlEngineDebug::queryExpressionResult(int objectDebugId, const QString &expr, QObject *parent)
+{
+ Q_D(QmlEngineDebug);
+
+ QmlDebugExpressionQuery *query = new QmlDebugExpressionQuery(parent);
+ if (d->client->isConnected() && objectDebugId != -1) {
+ query->m_client = this;
+ query->m_expr = expr;
+ int queryId = d->getId();
+ query->m_queryId = queryId;
+ d->expressionQuery.insert(queryId, query);
+
+ QByteArray message;
+ QDataStream ds(&message, QIODevice::WriteOnly);
+ ds << QByteArray("EVAL_EXPRESSION") << queryId << objectDebugId << expr;
+ d->client->sendMessage(message);
+ } else {
+ query->m_state = QmlDebugQuery::Error;
+ }
+
+ return query;
+}
+
+QmlDebugWatch::QmlDebugWatch(QObject *parent)
+: QObject(parent), m_state(Waiting), m_queryId(-1), m_client(0), m_objectDebugId(-1)
+{
+}
+
+QmlDebugWatch::~QmlDebugWatch()
+{
+}
+
+int QmlDebugWatch::queryId() const
+{
+ return m_queryId;
+}
+
+int QmlDebugWatch::objectDebugId() const
+{
+ return m_objectDebugId;
+}
+
+QmlDebugWatch::State QmlDebugWatch::state() const
+{
+ return m_state;
+}
+
+void QmlDebugWatch::setState(State s)
+{
+ if (m_state == s)
+ return;
+ m_state = s;
+ emit stateChanged(m_state);
+}
+
+QmlDebugPropertyWatch::QmlDebugPropertyWatch(QObject *parent)
+ : QmlDebugWatch(parent)
+{
+}
+
+QString QmlDebugPropertyWatch::name() const
+{
+ return m_name;
+}
+
+
+QmlDebugObjectExpressionWatch::QmlDebugObjectExpressionWatch(QObject *parent)
+ : QmlDebugWatch(parent)
+{
+}
+
+QString QmlDebugObjectExpressionWatch::expression() const
+{
+ return m_expr;
+}
+
+
+QmlDebugQuery::QmlDebugQuery(QObject *parent)
+: QObject(parent), m_state(Waiting)
+{
+}
+
+QmlDebugQuery::State QmlDebugQuery::state() const
+{
+ return m_state;
+}
+
+bool QmlDebugQuery::isWaiting() const
+{
+ return m_state == Waiting;
+}
+
+void QmlDebugQuery::setState(State s)
+{
+ if (m_state == s)
+ return;
+ m_state = s;
+ emit stateChanged(m_state);
+}
+
+QmlDebugEnginesQuery::QmlDebugEnginesQuery(QObject *parent)
+: QmlDebugQuery(parent), m_client(0), m_queryId(-1)
+{
+}
+
+QmlDebugEnginesQuery::~QmlDebugEnginesQuery()
+{
+ if (m_client && m_queryId != -1)
+ QmlEngineDebugPrivate::remove(m_client, this);
+}
+
+QList<QmlDebugEngineReference> QmlDebugEnginesQuery::engines() const
+{
+ return m_engines;
+}
+
+QmlDebugRootContextQuery::QmlDebugRootContextQuery(QObject *parent)
+: QmlDebugQuery(parent), m_client(0), m_queryId(-1)
+{
+}
+
+QmlDebugRootContextQuery::~QmlDebugRootContextQuery()
+{
+ if (m_client && m_queryId != -1)
+ QmlEngineDebugPrivate::remove(m_client, this);
+}
+
+QmlDebugContextReference QmlDebugRootContextQuery::rootContext() const
+{
+ return m_context;
+}
+
+QmlDebugObjectQuery::QmlDebugObjectQuery(QObject *parent)
+: QmlDebugQuery(parent), m_client(0), m_queryId(-1)
+{
+}
+
+QmlDebugObjectQuery::~QmlDebugObjectQuery()
+{
+ if (m_client && m_queryId != -1)
+ QmlEngineDebugPrivate::remove(m_client, this);
+}
+
+QmlDebugObjectReference QmlDebugObjectQuery::object() const
+{
+ return m_object;
+}
+
+QmlDebugExpressionQuery::QmlDebugExpressionQuery(QObject *parent)
+: QmlDebugQuery(parent), m_client(0), m_queryId(-1)
+{
+}
+
+QmlDebugExpressionQuery::~QmlDebugExpressionQuery()
+{
+ if (m_client && m_queryId != -1)
+ QmlEngineDebugPrivate::remove(m_client, this);
+}
+
+QString QmlDebugExpressionQuery::expression() const
+{
+ return m_expr;
+}
+
+QVariant QmlDebugExpressionQuery::result() const
+{
+ return m_result;
+}
+
+QmlDebugEngineReference::QmlDebugEngineReference()
+: m_debugId(-1)
+{
+}
+
+QmlDebugEngineReference::QmlDebugEngineReference(int debugId)
+: m_debugId(debugId)
+{
+}
+
+QmlDebugEngineReference::QmlDebugEngineReference(const QmlDebugEngineReference &o)
+: m_debugId(o.m_debugId), m_name(o.m_name)
+{
+}
+
+QmlDebugEngineReference &
+QmlDebugEngineReference::operator=(const QmlDebugEngineReference &o)
+{
+ m_debugId = o.m_debugId; m_name = o.m_name;
+ return *this;
+}
+
+int QmlDebugEngineReference::debugId() const
+{
+ return m_debugId;
+}
+
+QString QmlDebugEngineReference::name() const
+{
+ return m_name;
+}
+
+QmlDebugObjectReference::QmlDebugObjectReference()
+: m_debugId(-1), m_contextDebugId(-1)
+{
+}
+
+QmlDebugObjectReference::QmlDebugObjectReference(int debugId)
+: m_debugId(debugId), m_contextDebugId(-1)
+{
+}
+
+QmlDebugObjectReference::QmlDebugObjectReference(const QmlDebugObjectReference &o)
+: m_debugId(o.m_debugId), m_class(o.m_class), m_name(o.m_name),
+ m_source(o.m_source), m_contextDebugId(o.m_contextDebugId),
+ m_properties(o.m_properties), m_children(o.m_children)
+{
+}
+
+QmlDebugObjectReference &
+QmlDebugObjectReference::operator=(const QmlDebugObjectReference &o)
+{
+ m_debugId = o.m_debugId; m_class = o.m_class; m_name = o.m_name;
+ m_source = o.m_source; m_contextDebugId = o.m_contextDebugId;
+ m_properties = o.m_properties; m_children = o.m_children;
+ return *this;
+}
+
+int QmlDebugObjectReference::debugId() const
+{
+ return m_debugId;
+}
+
+QString QmlDebugObjectReference::className() const
+{
+ return m_class;
+}
+
+QString QmlDebugObjectReference::name() const
+{
+ return m_name;
+}
+
+QmlDebugFileReference QmlDebugObjectReference::source() const
+{
+ return m_source;
+}
+
+int QmlDebugObjectReference::contextDebugId() const
+{
+ return m_contextDebugId;
+}
+
+QList<QmlDebugPropertyReference> QmlDebugObjectReference::properties() const
+{
+ return m_properties;
+}
+
+QList<QmlDebugObjectReference> QmlDebugObjectReference::children() const
+{
+ return m_children;
+}
+
+QmlDebugContextReference::QmlDebugContextReference()
+: m_debugId(-1)
+{
+}
+
+QmlDebugContextReference::QmlDebugContextReference(const QmlDebugContextReference &o)
+: m_debugId(o.m_debugId), m_name(o.m_name), m_objects(o.m_objects), m_contexts(o.m_contexts)
+{
+}
+
+QmlDebugContextReference &QmlDebugContextReference::operator=(const QmlDebugContextReference &o)
+{
+ m_debugId = o.m_debugId; m_name = o.m_name; m_objects = o.m_objects;
+ m_contexts = o.m_contexts;
+ return *this;
+}
+
+int QmlDebugContextReference::debugId() const
+{
+ return m_debugId;
+}
+
+QString QmlDebugContextReference::name() const
+{
+ return m_name;
+}
+
+QList<QmlDebugObjectReference> QmlDebugContextReference::objects() const
+{
+ return m_objects;
+}
+
+QList<QmlDebugContextReference> QmlDebugContextReference::contexts() const
+{
+ return m_contexts;
+}
+
+QmlDebugFileReference::QmlDebugFileReference()
+: m_lineNumber(-1), m_columnNumber(-1)
+{
+}
+
+QmlDebugFileReference::QmlDebugFileReference(const QmlDebugFileReference &o)
+: m_url(o.m_url), m_lineNumber(o.m_lineNumber), m_columnNumber(o.m_columnNumber)
+{
+}
+
+QmlDebugFileReference &QmlDebugFileReference::operator=(const QmlDebugFileReference &o)
+{
+ m_url = o.m_url; m_lineNumber = o.m_lineNumber; m_columnNumber = o.m_columnNumber;
+ return *this;
+}
+
+QUrl QmlDebugFileReference::url() const
+{
+ return m_url;
+}
+
+void QmlDebugFileReference::setUrl(const QUrl &u)
+{
+ m_url = u;
+}
+
+int QmlDebugFileReference::lineNumber() const
+{
+ return m_lineNumber;
+}
+
+void QmlDebugFileReference::setLineNumber(int l)
+{
+ m_lineNumber = l;
+}
+
+int QmlDebugFileReference::columnNumber() const
+{
+ return m_columnNumber;
+}
+
+void QmlDebugFileReference::setColumnNumber(int c)
+{
+ m_columnNumber = c;
+}
+
+QmlDebugPropertyReference::QmlDebugPropertyReference()
+: m_objectDebugId(-1), m_hasNotifySignal(false)
+{
+}
+
+QmlDebugPropertyReference::QmlDebugPropertyReference(const QmlDebugPropertyReference &o)
+: m_objectDebugId(o.m_objectDebugId), m_name(o.m_name), m_value(o.m_value),
+ m_valueTypeName(o.m_valueTypeName), m_binding(o.m_binding),
+ m_hasNotifySignal(o.m_hasNotifySignal)
+{
+}
+
+QmlDebugPropertyReference &QmlDebugPropertyReference::operator=(const QmlDebugPropertyReference &o)
+{
+ m_objectDebugId = o.m_objectDebugId; m_name = o.m_name; m_value = o.m_value;
+ m_valueTypeName = o.m_valueTypeName; m_binding = o.m_binding;
+ m_hasNotifySignal = o.m_hasNotifySignal;
+ return *this;
+}
+
+int QmlDebugPropertyReference::objectDebugId() const
+{
+ return m_objectDebugId;
+}
+
+QString QmlDebugPropertyReference::name() const
+{
+ return m_name;
+}
+
+QString QmlDebugPropertyReference::valueTypeName() const
+{
+ return m_valueTypeName;
+}
+
+QVariant QmlDebugPropertyReference::value() const
+{
+ return m_value;
+}
+
+QString QmlDebugPropertyReference::binding() const
+{
+ return m_binding;
+}
+
+bool QmlDebugPropertyReference::hasNotifySignal() const
+{
+ return m_hasNotifySignal;
+}
diff --git a/src/declarative/debugger/qmldebug_p.h b/src/declarative/debugger/qmldebug_p.h
new file mode 100644
index 0000000..cd2adf6
--- /dev/null
+++ b/src/declarative/debugger/qmldebug_p.h
@@ -0,0 +1,366 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+#ifndef QMLDEBUG_H
+#define QMLDEBUG_H
+
+#include <QtCore/qobject.h>
+#include <QtCore/qurl.h>
+#include <QtCore/qvariant.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlDebugConnection;
+class QmlDebugWatch;
+class QmlDebugPropertyWatch;
+class QmlDebugObjectExpressionWatch;
+class QmlDebugEnginesQuery;
+class QmlDebugRootContextQuery;
+class QmlDebugObjectQuery;
+class QmlDebugExpressionQuery;
+class QmlDebugPropertyReference;
+class QmlDebugContextReference;
+class QmlDebugObjectReference;
+class QmlDebugFileReference;
+class QmlDebugEngineReference;
+class QmlEngineDebugPrivate;
+class Q_DECLARATIVE_EXPORT QmlEngineDebug : public QObject
+{
+Q_OBJECT
+public:
+ QmlEngineDebug(QmlDebugConnection *, QObject * = 0);
+
+ QmlDebugPropertyWatch *addWatch(const QmlDebugPropertyReference &,
+ QObject *parent = 0);
+ QmlDebugWatch *addWatch(const QmlDebugContextReference &, const QString &,
+ QObject *parent = 0);
+ QmlDebugObjectExpressionWatch *addWatch(const QmlDebugObjectReference &, const QString &,
+ QObject *parent = 0);
+ QmlDebugWatch *addWatch(const QmlDebugObjectReference &,
+ QObject *parent = 0);
+ QmlDebugWatch *addWatch(const QmlDebugFileReference &,
+ QObject *parent = 0);
+
+ void removeWatch(QmlDebugWatch *watch);
+
+ QmlDebugEnginesQuery *queryAvailableEngines(QObject *parent = 0);
+ QmlDebugRootContextQuery *queryRootContexts(const QmlDebugEngineReference &,
+ QObject *parent = 0);
+ QmlDebugObjectQuery *queryObject(const QmlDebugObjectReference &,
+ QObject *parent = 0);
+ QmlDebugObjectQuery *queryObjectRecursive(const QmlDebugObjectReference &,
+ QObject *parent = 0);
+ QmlDebugExpressionQuery *queryExpressionResult(int objectDebugId,
+ const QString &expr,
+ QObject *parent = 0);
+
+private:
+ Q_DECLARE_PRIVATE(QmlEngineDebug)
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugWatch : public QObject
+{
+Q_OBJECT
+public:
+ enum State { Waiting, Active, Inactive, Dead };
+
+ QmlDebugWatch(QObject *);
+ ~QmlDebugWatch();
+
+ int queryId() const;
+ int objectDebugId() const;
+ State state() const;
+
+Q_SIGNALS:
+ void stateChanged(QmlDebugWatch::State);
+ //void objectChanged(int, const QmlDebugObjectReference &);
+ //void valueChanged(int, const QVariant &);
+
+ // Server sends value as string if it is a user-type variant
+ void valueChanged(const QByteArray &name, const QVariant &value);
+
+private:
+ friend class QmlEngineDebug;
+ friend class QmlEngineDebugPrivate;
+ void setState(State);
+ State m_state;
+ int m_queryId;
+ QmlEngineDebug *m_client;
+ int m_objectDebugId;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugPropertyWatch : public QmlDebugWatch
+{
+ Q_OBJECT
+public:
+ QmlDebugPropertyWatch(QObject *parent);
+
+ QString name() const;
+
+private:
+ friend class QmlEngineDebug;
+ QString m_name;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugObjectExpressionWatch : public QmlDebugWatch
+{
+ Q_OBJECT
+public:
+ QmlDebugObjectExpressionWatch(QObject *parent);
+
+ QString expression() const;
+
+private:
+ friend class QmlEngineDebug;
+ QString m_expr;
+ int m_debugId;
+};
+
+
+class Q_DECLARATIVE_EXPORT QmlDebugQuery : public QObject
+{
+Q_OBJECT
+public:
+ enum State { Waiting, Error, Completed };
+
+ State state() const;
+ bool isWaiting() const;
+
+// bool waitUntilCompleted();
+
+Q_SIGNALS:
+ void stateChanged(QmlDebugQuery::State);
+
+protected:
+ QmlDebugQuery(QObject *);
+
+private:
+ friend class QmlEngineDebug;
+ friend class QmlEngineDebugPrivate;
+ void setState(State);
+ State m_state;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugFileReference
+{
+public:
+ QmlDebugFileReference();
+ QmlDebugFileReference(const QmlDebugFileReference &);
+ QmlDebugFileReference &operator=(const QmlDebugFileReference &);
+
+ QUrl url() const;
+ void setUrl(const QUrl &);
+ int lineNumber() const;
+ void setLineNumber(int);
+ int columnNumber() const;
+ void setColumnNumber(int);
+
+private:
+ friend class QmlEngineDebugPrivate;
+ QUrl m_url;
+ int m_lineNumber;
+ int m_columnNumber;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugEngineReference
+{
+public:
+ QmlDebugEngineReference();
+ QmlDebugEngineReference(int);
+ QmlDebugEngineReference(const QmlDebugEngineReference &);
+ QmlDebugEngineReference &operator=(const QmlDebugEngineReference &);
+
+ int debugId() const;
+ QString name() const;
+
+private:
+ friend class QmlEngineDebugPrivate;
+ int m_debugId;
+ QString m_name;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugObjectReference
+{
+public:
+ QmlDebugObjectReference();
+ QmlDebugObjectReference(int);
+ QmlDebugObjectReference(const QmlDebugObjectReference &);
+ QmlDebugObjectReference &operator=(const QmlDebugObjectReference &);
+
+ int debugId() const;
+ QString className() const;
+ QString name() const;
+
+ QmlDebugFileReference source() const;
+ int contextDebugId() const;
+
+ QList<QmlDebugPropertyReference> properties() const;
+ QList<QmlDebugObjectReference> children() const;
+
+private:
+ friend class QmlEngineDebugPrivate;
+ int m_debugId;
+ QString m_class;
+ QString m_name;
+ QmlDebugFileReference m_source;
+ int m_contextDebugId;
+ QList<QmlDebugPropertyReference> m_properties;
+ QList<QmlDebugObjectReference> m_children;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugContextReference
+{
+public:
+ QmlDebugContextReference();
+ QmlDebugContextReference(const QmlDebugContextReference &);
+ QmlDebugContextReference &operator=(const QmlDebugContextReference &);
+
+ int debugId() const;
+ QString name() const;
+
+ QList<QmlDebugObjectReference> objects() const;
+ QList<QmlDebugContextReference> contexts() const;
+
+private:
+ friend class QmlEngineDebugPrivate;
+ int m_debugId;
+ QString m_name;
+ QList<QmlDebugObjectReference> m_objects;
+ QList<QmlDebugContextReference> m_contexts;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugPropertyReference
+{
+public:
+ QmlDebugPropertyReference();
+ QmlDebugPropertyReference(const QmlDebugPropertyReference &);
+ QmlDebugPropertyReference &operator=(const QmlDebugPropertyReference &);
+
+ int objectDebugId() const;
+ QString name() const;
+ QVariant value() const;
+ QString valueTypeName() const;
+ QString binding() const;
+ bool hasNotifySignal() const;
+
+private:
+ friend class QmlEngineDebugPrivate;
+ int m_objectDebugId;
+ QString m_name;
+ QVariant m_value;
+ QString m_valueTypeName;
+ QString m_binding;
+ bool m_hasNotifySignal;
+};
+
+
+class Q_DECLARATIVE_EXPORT QmlDebugEnginesQuery : public QmlDebugQuery
+{
+Q_OBJECT
+public:
+ virtual ~QmlDebugEnginesQuery();
+ QList<QmlDebugEngineReference> engines() const;
+private:
+ friend class QmlEngineDebug;
+ friend class QmlEngineDebugPrivate;
+ QmlDebugEnginesQuery(QObject *);
+ QmlEngineDebug *m_client;
+ int m_queryId;
+ QList<QmlDebugEngineReference> m_engines;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugRootContextQuery : public QmlDebugQuery
+{
+Q_OBJECT
+public:
+ virtual ~QmlDebugRootContextQuery();
+ QmlDebugContextReference rootContext() const;
+private:
+ friend class QmlEngineDebug;
+ friend class QmlEngineDebugPrivate;
+ QmlDebugRootContextQuery(QObject *);
+ QmlEngineDebug *m_client;
+ int m_queryId;
+ QmlDebugContextReference m_context;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugObjectQuery : public QmlDebugQuery
+{
+Q_OBJECT
+public:
+ virtual ~QmlDebugObjectQuery();
+ QmlDebugObjectReference object() const;
+private:
+ friend class QmlEngineDebug;
+ friend class QmlEngineDebugPrivate;
+ QmlDebugObjectQuery(QObject *);
+ QmlEngineDebug *m_client;
+ int m_queryId;
+ QmlDebugObjectReference m_object;
+
+};
+
+class Q_DECLARATIVE_EXPORT QmlDebugExpressionQuery : public QmlDebugQuery
+{
+Q_OBJECT
+public:
+ virtual ~QmlDebugExpressionQuery();
+ QString expression() const;
+ QVariant result() const;
+private:
+ friend class QmlEngineDebug;
+ friend class QmlEngineDebugPrivate;
+ QmlDebugExpressionQuery(QObject *);
+ QmlEngineDebug *m_client;
+ int m_queryId;
+ QString m_expr;
+ QVariant m_result;
+
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLDEBUG_H
diff --git a/src/declarative/debugger/qmldebugclient.cpp b/src/declarative/debugger/qmldebugclient.cpp
new file mode 100644
index 0000000..68e14c2
--- /dev/null
+++ b/src/declarative/debugger/qmldebugclient.cpp
@@ -0,0 +1,207 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmldebugclient_p.h"
+
+#include "qpacketprotocol_p.h"
+
+#include <QtCore/qdebug.h>
+#include <QtCore/qstringlist.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlDebugConnectionPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ QmlDebugConnectionPrivate(QmlDebugConnection *c);
+ QmlDebugConnection *q;
+ QPacketProtocol *protocol;
+
+ QStringList enabled;
+ QHash<QString, QmlDebugClient *> plugins;
+public Q_SLOTS:
+ void connected();
+ void readyRead();
+};
+
+QmlDebugConnectionPrivate::QmlDebugConnectionPrivate(QmlDebugConnection *c)
+: QObject(c), q(c), protocol(0)
+{
+ protocol = new QPacketProtocol(q, this);
+ QObject::connect(c, SIGNAL(connected()), this, SLOT(connected()));
+ QObject::connect(protocol, SIGNAL(readyRead()), this, SLOT(readyRead()));
+}
+
+void QmlDebugConnectionPrivate::connected()
+{
+ QPacket pack;
+ pack << QString(QLatin1String("QmlDebugServer")) << enabled;
+ protocol->send(pack);
+}
+
+void QmlDebugConnectionPrivate::readyRead()
+{
+ QPacket pack = protocol->read();
+ QString name; QByteArray message;
+ pack >> name >> message;
+
+ QHash<QString, QmlDebugClient *>::Iterator iter =
+ plugins.find(name);
+ if (iter == plugins.end()) {
+ qWarning() << "QmlDebugConnection: Message received for missing plugin" << name;
+ } else {
+ (*iter)->messageReceived(message);
+ }
+}
+
+QmlDebugConnection::QmlDebugConnection(QObject *parent)
+: QTcpSocket(parent), d(new QmlDebugConnectionPrivate(this))
+{
+}
+
+bool QmlDebugConnection::isConnected() const
+{
+ return state() == ConnectedState;
+}
+
+class QmlDebugClientPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlDebugClient)
+public:
+ QmlDebugClientPrivate();
+
+ QString name;
+ QmlDebugConnection *client;
+ bool enabled;
+};
+
+QmlDebugClientPrivate::QmlDebugClientPrivate()
+: client(0), enabled(false)
+{
+}
+
+QmlDebugClient::QmlDebugClient(const QString &name,
+ QmlDebugConnection *parent)
+: QObject(*(new QmlDebugClientPrivate), parent)
+{
+ Q_D(QmlDebugClient);
+ d->name = name;
+ d->client = parent;
+
+ if (!d->client)
+ return;
+
+ if (d->client->d->plugins.contains(name)) {
+ qWarning() << "QmlDebugClient: Conflicting plugin name" << name;
+ d->client = 0;
+ } else {
+ d->client->d->plugins.insert(name, this);
+ }
+}
+
+QString QmlDebugClient::name() const
+{
+ Q_D(const QmlDebugClient);
+ return d->name;
+}
+
+bool QmlDebugClient::isEnabled() const
+{
+ Q_D(const QmlDebugClient);
+ return d->enabled;
+}
+
+void QmlDebugClient::setEnabled(bool e)
+{
+ Q_D(QmlDebugClient);
+ if (e == d->enabled)
+ return;
+
+ d->enabled = e;
+
+ if (d->client) {
+ if (e)
+ d->client->d->enabled.append(d->name);
+ else
+ d->client->d->enabled.removeAll(d->name);
+
+ if (d->client->state() == QTcpSocket::ConnectedState) {
+ QPacket pack;
+ pack << QString(QLatin1String("QmlDebugServer"));
+ if (e) pack << (int)1;
+ else pack << (int)2;
+ pack << d->name;
+ d->client->d->protocol->send(pack);
+ }
+ }
+}
+
+bool QmlDebugClient::isConnected() const
+{
+ Q_D(const QmlDebugClient);
+
+ if (!d->client)
+ return false;
+ return d->client->isConnected();
+}
+
+void QmlDebugClient::sendMessage(const QByteArray &message)
+{
+ Q_D(QmlDebugClient);
+
+ if (!d->client || !d->client->isConnected())
+ return;
+
+ QPacket pack;
+ pack << d->name << message;
+ d->client->d->protocol->send(pack);
+}
+
+void QmlDebugClient::messageReceived(const QByteArray &)
+{
+}
+
+QT_END_NAMESPACE
+
+#include <qmldebugclient.moc>
diff --git a/src/declarative/debugger/qmldebugclient_p.h b/src/declarative/debugger/qmldebugclient_p.h
new file mode 100644
index 0000000..d64541b
--- /dev/null
+++ b/src/declarative/debugger/qmldebugclient_p.h
@@ -0,0 +1,99 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLDEBUGCLIENT_H
+#define QMLDEBUGCLIENT_H
+
+#include <QtNetwork/qtcpsocket.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlDebugConnectionPrivate;
+class Q_DECLARATIVE_EXPORT QmlDebugConnection : public QTcpSocket
+{
+ Q_OBJECT
+ Q_DISABLE_COPY(QmlDebugConnection)
+public:
+ QmlDebugConnection(QObject * = 0);
+
+ bool isConnected() const;
+private:
+ QmlDebugConnectionPrivate *d;
+ friend class QmlDebugClient;
+ friend class QmlDebugClientPrivate;
+};
+
+class QmlDebugClientPrivate;
+class Q_DECLARATIVE_EXPORT QmlDebugClient : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlDebugClient)
+ Q_DISABLE_COPY(QmlDebugClient)
+
+public:
+ QmlDebugClient(const QString &, QmlDebugConnection *parent);
+
+ QString name() const;
+
+ bool isEnabled() const;
+ void setEnabled(bool);
+
+ bool isConnected() const;
+
+ void sendMessage(const QByteArray &);
+
+protected:
+ virtual void messageReceived(const QByteArray &);
+
+private:
+ friend class QmlDebugConnection;
+ friend class QmlDebugConnectionPrivate;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLDEBUGCLIENT_H
diff --git a/src/declarative/debugger/qmldebuggerstatus.cpp b/src/declarative/debugger/qmldebuggerstatus.cpp
new file mode 100644
index 0000000..dc1cfb0
--- /dev/null
+++ b/src/declarative/debugger/qmldebuggerstatus.cpp
@@ -0,0 +1,54 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmldebuggerstatus_p.h"
+
+QT_BEGIN_NAMESPACE
+
+QmlDebuggerStatus::~QmlDebuggerStatus()
+{
+}
+
+void QmlDebuggerStatus::setSelectedState(bool)
+{
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/debugger/qmldebuggerstatus_p.h b/src/declarative/debugger/qmldebuggerstatus_p.h
new file mode 100644
index 0000000..7c8070b
--- /dev/null
+++ b/src/declarative/debugger/qmldebuggerstatus_p.h
@@ -0,0 +1,66 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLDEBUGGERSTATUS_P_H
+#define QMLDEBUGGERSTATUS_P_H
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class Q_DECLARATIVE_EXPORT QmlDebuggerStatus
+{
+public:
+ virtual ~QmlDebuggerStatus();
+
+ virtual void setSelectedState(bool);
+};
+Q_DECLARE_INTERFACE(QmlDebuggerStatus, "com.trolltech.qml.QmlDebuggerStatus")
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QLMDEBUGGERSTATUS_P_H
diff --git a/src/declarative/debugger/qmldebugservice.cpp b/src/declarative/debugger/qmldebugservice.cpp
new file mode 100644
index 0000000..810fbed
--- /dev/null
+++ b/src/declarative/debugger/qmldebugservice.cpp
@@ -0,0 +1,393 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmldebugservice_p.h"
+
+#include "qpacketprotocol_p.h"
+
+#include <QtCore/qdebug.h>
+#include <QtNetwork/qtcpserver.h>
+#include <QtNetwork/qtcpsocket.h>
+#include <QtCore/qstringlist.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlDebugServerPrivate;
+class QmlDebugServer : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlDebugServer)
+ Q_DISABLE_COPY(QmlDebugServer)
+public:
+ static QmlDebugServer *instance();
+ void wait();
+
+private Q_SLOTS:
+ void readyRead();
+
+private:
+ friend class QmlDebugService;
+ friend class QmlDebugServicePrivate;
+ QmlDebugServer(int);
+};
+
+class QmlDebugServerPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlDebugServer)
+public:
+ QmlDebugServerPrivate();
+ void wait();
+
+ int port;
+ QTcpSocket *connection;
+ QPacketProtocol *protocol;
+ QHash<QString, QmlDebugService *> plugins;
+ QStringList enabledPlugins;
+};
+
+class QmlDebugServicePrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlDebugService)
+public:
+ QmlDebugServicePrivate();
+
+ QString name;
+ QmlDebugServer *server;
+};
+
+QmlDebugServerPrivate::QmlDebugServerPrivate()
+: connection(0), protocol(0)
+{
+}
+
+void QmlDebugServerPrivate::wait()
+{
+ Q_Q(QmlDebugServer);
+ QTcpServer server;
+
+ if (!server.listen(QHostAddress::Any, port)) {
+ qWarning("QmlDebugServer: Unable to listen on port %d", port);
+ return;
+ }
+
+ qWarning("QmlDebugServer: Waiting for connection on port %d...", port);
+
+ if (!server.waitForNewConnection(-1)) {
+ qWarning("QmlDebugServer: Connection error");
+ return;
+ }
+
+ connection = server.nextPendingConnection();
+ connection->setParent(q);
+ protocol = new QPacketProtocol(connection, q);
+
+ // ### Wait for hello
+ while (!protocol->packetsAvailable()) {
+ connection->waitForReadyRead();
+ }
+ QPacket hello = protocol->read();
+ QString name;
+ hello >> name >> enabledPlugins;
+ if (name != QLatin1String("QmlDebugServer")) {
+ qWarning("QmlDebugServer: Invalid hello message");
+ delete protocol; delete connection; connection = 0; protocol = 0;
+ return;
+ }
+
+ QObject::connect(protocol, SIGNAL(readyRead()), q, SLOT(readyRead()));
+ q->readyRead();
+
+ qWarning("QmlDebugServer: Connection established");
+}
+
+QmlDebugServer *QmlDebugServer::instance()
+{
+ static bool envTested = false;
+ static QmlDebugServer *server = 0;
+
+ if (!envTested) {
+ envTested = true;
+ QByteArray env = qgetenv("QML_DEBUG_SERVER_PORT");
+
+ bool ok = false;
+ int port = env.toInt(&ok);
+
+ if (ok && port > 1024)
+ server = new QmlDebugServer(port);
+ }
+
+ return server;
+}
+
+void QmlDebugServer::wait()
+{
+ Q_D(QmlDebugServer);
+ d->wait();
+}
+
+QmlDebugServer::QmlDebugServer(int port)
+: QObject(*(new QmlDebugServerPrivate))
+{
+ Q_D(QmlDebugServer);
+ d->port = port;
+}
+
+void QmlDebugServer::readyRead()
+{
+ Q_D(QmlDebugServer);
+
+ QString debugServer(QLatin1String("QmlDebugServer"));
+
+ while (d->protocol->packetsAvailable()) {
+ QPacket pack = d->protocol->read();
+
+ QString name;
+ pack >> name;
+
+ if (name == debugServer) {
+ int op = -1; QString plugin;
+ pack >> op >> plugin;
+
+ if (op == 1) {
+ // Enable
+ if (!d->enabledPlugins.contains(plugin)) {
+ d->enabledPlugins.append(plugin);
+ QHash<QString, QmlDebugService *>::Iterator iter =
+ d->plugins.find(plugin);
+ if (iter != d->plugins.end())
+ (*iter)->enabledChanged(true);
+ }
+
+ } else if (op == 2) {
+ // Disable
+ if (d->enabledPlugins.contains(plugin)) {
+ d->enabledPlugins.removeAll(plugin);
+ QHash<QString, QmlDebugService *>::Iterator iter =
+ d->plugins.find(plugin);
+ if (iter != d->plugins.end())
+ (*iter)->enabledChanged(false);
+ }
+ } else {
+ qWarning("QmlDebugServer: Invalid control message %d", op);
+ }
+
+ } else {
+ QByteArray message;
+ pack >> message;
+
+ QHash<QString, QmlDebugService *>::Iterator iter =
+ d->plugins.find(name);
+ if (iter == d->plugins.end()) {
+ qWarning() << "QmlDebugServer: Message received for missing plugin" << name;
+ } else {
+ (*iter)->messageReceived(message);
+ }
+ }
+ }
+}
+
+QmlDebugServicePrivate::QmlDebugServicePrivate()
+: server(0)
+{
+}
+
+QmlDebugService::QmlDebugService(const QString &name, QObject *parent)
+: QObject(*(new QmlDebugServicePrivate), parent)
+{
+ Q_D(QmlDebugService);
+ d->name = name;
+ d->server = QmlDebugServer::instance();
+
+ if (!d->server)
+ return;
+
+ if (d->server->d_func()->plugins.contains(name)) {
+ qWarning() << "QmlDebugService: Conflicting plugin name" << name;
+ d->server = 0;
+ } else {
+ d->server->d_func()->plugins.insert(name, this);
+ }
+}
+
+QString QmlDebugService::name() const
+{
+ Q_D(const QmlDebugService);
+ return d->name;
+}
+
+bool QmlDebugService::isEnabled() const
+{
+ Q_D(const QmlDebugService);
+ return (d->server && d->server->d_func()->enabledPlugins.contains(d->name));
+}
+
+namespace {
+
+ struct ObjectReference
+ {
+ QPointer<QObject> object;
+ int id;
+ };
+
+ struct ObjectReferenceHash
+ {
+ ObjectReferenceHash() : nextId(0) {}
+
+ QHash<QObject *, ObjectReference> objects;
+ QHash<int, QObject *> ids;
+
+ int nextId;
+ };
+
+}
+Q_GLOBAL_STATIC(ObjectReferenceHash, objectReferenceHash);
+
+
+/*!
+ Returns a unique id for \a object. Calling this method multiple times
+ for the same object will return the same id.
+*/
+int QmlDebugService::idForObject(QObject *object)
+{
+ if (!object)
+ return -1;
+
+ ObjectReferenceHash *hash = objectReferenceHash();
+ QHash<QObject *, ObjectReference>::Iterator iter =
+ hash->objects.find(object);
+
+ if (iter == hash->objects.end()) {
+ int id = hash->nextId++;
+
+ hash->ids.insert(id, object);
+ iter = hash->objects.insert(object, ObjectReference());
+ iter->object = object;
+ iter->id = id;
+ } else if (iter->object != object) {
+ int id = hash->nextId++;
+
+ hash->ids.remove(iter->id);
+
+ hash->ids.insert(id, object);
+ iter->object = object;
+ iter->id = id;
+ }
+ return iter->id;
+}
+
+/*!
+ Returns the object for unique \a id. If the object has not previously been
+ assigned an id, through idForObject(), then 0 is returned. If the object
+ has been destroyed, 0 is returned.
+*/
+QObject *QmlDebugService::objectForId(int id)
+{
+ ObjectReferenceHash *hash = objectReferenceHash();
+
+ QHash<int, QObject *>::Iterator iter = hash->ids.find(id);
+ if (iter == hash->ids.end())
+ return 0;
+
+
+ QHash<QObject *, ObjectReference>::Iterator objIter =
+ hash->objects.find(*iter);
+ Q_ASSERT(objIter != hash->objects.end());
+
+ if (objIter->object == 0) {
+ hash->ids.erase(iter);
+ hash->objects.erase(objIter);
+ return 0;
+ } else {
+ return *iter;
+ }
+}
+
+bool QmlDebugService::isDebuggingEnabled()
+{
+ return QmlDebugServer::instance() != 0;
+}
+
+QString QmlDebugService::objectToString(QObject *obj)
+{
+ if(!obj)
+ return QLatin1String("NULL");
+
+ QString objectName = obj->objectName();
+ if(objectName.isEmpty())
+ objectName = QLatin1String("<unnamed>");
+
+ QString rv = QString::fromUtf8(obj->metaObject()->className()) +
+ QLatin1String(": ") + objectName;
+
+ return rv;
+}
+
+void QmlDebugService::waitForClients()
+{
+ QmlDebugServer::instance()->wait();
+}
+
+void QmlDebugService::sendMessage(const QByteArray &message)
+{
+ Q_D(QmlDebugService);
+
+ if (!d->server || !d->server->d_func()->connection)
+ return;
+
+ QPacket pack;
+ pack << d->name << message;
+ d->server->d_func()->protocol->send(pack);
+ d->server->d_func()->connection->flush();
+}
+
+void QmlDebugService::enabledChanged(bool)
+{
+}
+
+void QmlDebugService::messageReceived(const QByteArray &)
+{
+}
+
+QT_END_NAMESPACE
+
+#include <qmldebugservice.moc>
diff --git a/src/declarative/debugger/qmldebugservice_p.h b/src/declarative/debugger/qmldebugservice_p.h
new file mode 100644
index 0000000..b406a3c
--- /dev/null
+++ b/src/declarative/debugger/qmldebugservice_p.h
@@ -0,0 +1,90 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLDEBUGSERVICE_H
+#define QMLDEBUGSERVICE_H
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlDebugServicePrivate;
+class Q_DECLARATIVE_EXPORT QmlDebugService : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlDebugService)
+ Q_DISABLE_COPY(QmlDebugService)
+public:
+ QmlDebugService(const QString &, QObject *parent = 0);
+
+ QString name() const;
+
+ bool isEnabled() const;
+
+ void sendMessage(const QByteArray &);
+
+ static int idForObject(QObject *);
+ static QObject *objectForId(int);
+
+
+ static bool isDebuggingEnabled();
+ static QString objectToString(QObject *obj);
+
+ static void waitForClients();
+
+protected:
+ virtual void enabledChanged(bool);
+ virtual void messageReceived(const QByteArray &);
+
+private:
+ friend class QmlDebugServer;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLDEBUGSERVICE_H
+
diff --git a/src/declarative/debugger/qpacketprotocol.cpp b/src/declarative/debugger/qpacketprotocol.cpp
new file mode 100644
index 0000000..fb07c62
--- /dev/null
+++ b/src/declarative/debugger/qpacketprotocol.cpp
@@ -0,0 +1,498 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qpacketprotocol_p.h"
+
+#include <QBuffer>
+
+QT_BEGIN_NAMESPACE
+
+#define MAX_PACKET_SIZE 0x7FFFFFFF
+
+/*!
+ \class QPacketProtocol
+ \internal
+
+ \brief The QPacketProtocol class encapsulates communicating discrete packets
+ across fragmented IO channels, such as TCP sockets.
+
+ QPacketProtocol makes it simple to send arbitrary sized data "packets" across
+ fragmented transports such as TCP and UDP.
+
+ As transmission boundaries are not respected, sending packets over protocols
+ like TCP frequently involves "stitching" them back together at the receiver.
+ QPacketProtocol makes this easier by performing this task for you. Packet
+ data sent using QPacketProtocol is prepended with a 4-byte size header
+ allowing the receiving QPacketProtocol to buffer the packet internally until
+ it has all been received. QPacketProtocol does not perform any sanity
+ checking on the size or on the data, so this class should only be used in
+ prototyping or trusted situations where DOS attacks are unlikely.
+
+ QPacketProtocol does not perform any communications itself. Instead it can
+ operate on any QIODevice that supports the QIODevice::readyRead() signal. A
+ logical "packet" is encapsulated by the companion QPacket class. The
+ following example shows two ways to send data using QPacketProtocol. The
+ transmitted data is equivalent in both.
+
+ \code
+ QTcpSocket socket;
+ // ... connect socket ...
+
+ QPacketProtocol protocol(&socket);
+
+ // Send packet the quick way
+ protocol.send() << "Hello world" << 123;
+
+ // Send packet the longer way
+ QPacket packet;
+ packet << "Hello world" << 123;
+ protocol.send(packet);
+ \endcode
+
+ Likewise, the following shows how to read data from QPacketProtocol, assuming
+ that the QPacketProtocol::readyRead() signal has been emitted.
+
+ \code
+ // ... QPacketProtocol::readyRead() is emitted ...
+
+ int a;
+ QByteArray b;
+
+ // Receive packet the quick way
+ protocol.read() >> a >> b;
+
+ // Receive packet the longer way
+ QPacket packet = protocol.read();
+ p >> a >> b;
+ \endcode
+
+ \ingroup io
+ \sa QPacket
+*/
+
+class QPacketProtocolPrivate : public QObject
+{
+Q_OBJECT
+public:
+ QPacketProtocolPrivate(QPacketProtocol * parent, QIODevice * _dev)
+ : QObject(parent), inProgressSize(-1), maxPacketSize(MAX_PACKET_SIZE),
+ dev(_dev)
+ {
+ Q_ASSERT(4 == sizeof(qint32));
+
+ QObject::connect(this, SIGNAL(readyRead()),
+ parent, SIGNAL(readyRead()));
+ QObject::connect(this, SIGNAL(packetWritten()),
+ parent, SIGNAL(packetWritten()));
+ QObject::connect(this, SIGNAL(invalidPacket()),
+ parent, SIGNAL(invalidPacket()));
+ QObject::connect(dev, SIGNAL(readyRead()),
+ this, SLOT(readyToRead()));
+ QObject::connect(dev, SIGNAL(aboutToClose()),
+ this, SLOT(aboutToClose()));
+ QObject::connect(dev, SIGNAL(bytesWritten(qint64)),
+ this, SLOT(bytesWritten(qint64)));
+ }
+
+Q_SIGNALS:
+ void readyRead();
+ void packetWritten();
+ void invalidPacket();
+
+public Q_SLOTS:
+ void aboutToClose()
+ {
+ inProgress.clear();
+ sendingPackets.clear();
+ inProgressSize = -1;
+ }
+
+ void bytesWritten(qint64 bytes)
+ {
+ Q_ASSERT(!sendingPackets.isEmpty());
+
+ while(bytes) {
+ if(sendingPackets.at(0) > bytes) {
+ sendingPackets[0] -= bytes;
+ bytes = 0;
+ } else {
+ bytes -= sendingPackets.at(0);
+ sendingPackets.removeFirst();
+ emit packetWritten();
+ }
+ }
+ }
+
+ void readyToRead()
+ {
+ if(-1 == inProgressSize) {
+ // We need a size header of sizeof(qint32)
+ if(sizeof(qint32) > (uint)dev->bytesAvailable())
+ return;
+
+ // Read size header
+ int read = dev->read((char *)&inProgressSize, sizeof(qint32));
+ Q_ASSERT(read == sizeof(qint32));
+ Q_UNUSED(read);
+
+ // Check sizing constraints
+ if(inProgressSize > maxPacketSize) {
+ QObject::disconnect(dev, SIGNAL(readyRead()),
+ this, SLOT(readyToRead()));
+ QObject::disconnect(dev, SIGNAL(aboutToClose()),
+ this, SLOT(aboutToClose()));
+ QObject::disconnect(dev, SIGNAL(bytesWritten(qint64)),
+ this, SLOT(bytesWritten(qint64)));
+ dev = 0;
+ emit invalidPacket();
+ return;
+ }
+
+ inProgressSize -= sizeof(qint32);
+
+ // Need to get trailing data
+ readyToRead();
+ } else {
+ inProgress.append(dev->read(inProgressSize - inProgress.size()));
+
+ if(inProgressSize == inProgress.size()) {
+ // Packet has arrived!
+ packets.append(inProgress);
+ inProgressSize = -1;
+ inProgress.clear();
+
+ emit readyRead();
+
+ // Need to get trailing data
+ readyToRead();
+ }
+ }
+ }
+
+public:
+ QList<qint64> sendingPackets;
+ QList<QByteArray> packets;
+ QByteArray inProgress;
+ qint32 inProgressSize;
+ qint32 maxPacketSize;
+ QIODevice * dev;
+};
+
+/*!
+ Construct a QPacketProtocol instance that works on \a dev with the
+ specified \a parent.
+ */
+QPacketProtocol::QPacketProtocol(QIODevice * dev, QObject * parent)
+: QObject(parent), d(new QPacketProtocolPrivate(this, dev))
+{
+ Q_ASSERT(dev);
+}
+
+/*!
+ Destroys the QPacketProtocol instance.
+ */
+QPacketProtocol::~QPacketProtocol()
+{
+}
+
+/*!
+ Returns the maximum packet size allowed. By default this is
+ 2,147,483,647 bytes.
+
+ If a packet claiming to be larger than the maximum packet size is received,
+ the QPacketProtocol::invalidPacket() signal is emitted.
+
+ \sa QPacketProtocol::setMaximumPacketSize()
+ */
+qint32 QPacketProtocol::maximumPacketSize() const
+{
+ return d->maxPacketSize;
+}
+
+/*!
+ Sets the maximum allowable packet size to \a max.
+
+ \sa QPacketProtocol::maximumPacketSize()
+ */
+qint32 QPacketProtocol::setMaximumPacketSize(qint32 max)
+{
+ if(max > (signed)sizeof(qint32))
+ d->maxPacketSize = max;
+ return d->maxPacketSize;
+}
+
+/*!
+ Returns a streamable object that is transmitted on destruction. For example
+
+ \code
+ protocol.send() << "Hello world" << 123;
+ \endcode
+
+ will send a packet containing "Hello world" and 123. To construct more
+ complex packets, explicitly construct a QPacket instance.
+ */
+QPacketAutoSend QPacketProtocol::send()
+{
+ return QPacketAutoSend(this);
+}
+
+/*!
+ \fn void QPacketProtocol::send(const QPacket & packet)
+
+ Transmit the \a packet.
+ */
+void QPacketProtocol::send(const QPacket & p)
+{
+ if(p.b.isEmpty())
+ return; // We don't send empty packets
+
+ qint64 sendSize = p.b.size() + sizeof(qint32);
+
+ d->sendingPackets.append(sendSize);
+ qint32 sendSize32 = sendSize;
+ qint64 writeBytes = d->dev->write((char *)&sendSize32, sizeof(qint32));
+ Q_ASSERT(writeBytes == sizeof(qint32));
+ writeBytes = d->dev->write(p.b);
+ Q_ASSERT(writeBytes == p.b.size());
+}
+
+/*!
+ Returns the number of received packets yet to be read.
+ */
+qint64 QPacketProtocol::packetsAvailable() const
+{
+ return d->packets.count();
+}
+
+/*!
+ Discard any unread packets.
+ */
+void QPacketProtocol::clear()
+{
+ d->packets.clear();
+}
+
+/*!
+ Return the next unread packet, or an invalid QPacket instance if no packets
+ are available. This method does NOT block.
+ */
+QPacket QPacketProtocol::read()
+{
+ if(0 == d->packets.count())
+ return QPacket();
+
+ QPacket rv(d->packets.at(0));
+ d->packets.removeFirst();
+ return rv;
+}
+
+/*!
+ Return the QIODevice passed to the QPacketProtocol constructor.
+*/
+QIODevice * QPacketProtocol::device()
+{
+ return d->dev;
+}
+
+/*!
+ \fn void QPacketProtocol::readyRead()
+
+ Emitted whenever a new packet is received. Applications may use
+ QPacketProtocol::read() to retrieve this packet.
+ */
+
+/*!
+ \fn void QPacketProtocol::invalidPacket()
+
+ A packet larger than the maximum allowable packet size was received. The
+ packet will be discarded and, as it indicates corruption in the protocol, no
+ further packets will be received.
+ */
+
+/*!
+ \fn void QPacketProtocol::packetWritten()
+
+ Emitted each time a packet is completing written to the device. This signal
+ may be used for communications flow control.
+ */
+
+/*!
+ \class QPacket
+ \internal
+
+ \brief The QPacket class encapsulates an unfragmentable packet of data to be
+ transmitted by QPacketProtocol.
+
+ The QPacket class works together with QPacketProtocol to make it simple to
+ send arbitrary sized data "packets" across fragmented transports such as TCP
+ and UDP.
+
+ QPacket provides a QDataStream interface to an unfragmentable packet.
+ Applications should construct a QPacket, propagate it with data and then
+ transmit it over a QPacketProtocol instance. For example:
+ \code
+ QPacketProtocol protocol(...);
+
+ QPacket myPacket;
+ myPacket << "Hello world!" << 123;
+ protocol.send(myPacket);
+ \endcode
+
+ As long as both ends of the connection are using the QPacketProtocol class,
+ the data within this packet will be delivered unfragmented at the other end,
+ ready for extraction.
+
+ \code
+ QByteArray greeting;
+ int count;
+
+ QPacket myPacket = protocol.read();
+
+ myPacket >> greeting >> count;
+ \endcode
+
+ Only packets returned from QPacketProtocol::read() may be read from. QPacket
+ instances constructed by directly by applications are for transmission only
+ and are considered "write only". Attempting to read data from them will
+ result in undefined behavior.
+
+ \ingroup io
+ \sa QPacketProtocol
+ */
+
+/*!
+ Constructs an empty write-only packet.
+ */
+QPacket::QPacket()
+: QDataStream(), buf(0)
+{
+ buf = new QBuffer(&b);
+ buf->open(QIODevice::WriteOnly);
+ setDevice(buf);
+}
+
+/*!
+ Destroys the QPacket instance.
+ */
+QPacket::~QPacket()
+{
+ if(buf) {
+ delete buf;
+ buf = 0;
+ }
+}
+
+/*!
+ Creates a copy of \a other. The initial stream positions are shared, but the
+ two packets are otherwise independant.
+ */
+QPacket::QPacket(const QPacket & other)
+: QDataStream(), b(other.b), buf(0)
+{
+ buf = new QBuffer(&b);
+ buf->open(other.buf->openMode());
+ setDevice(buf);
+}
+
+/*!
+ \internal
+ */
+QPacket::QPacket(const QByteArray & ba)
+: QDataStream(), b(ba), buf(0)
+{
+ buf = new QBuffer(&b);
+ buf->open(QIODevice::ReadOnly);
+ setDevice(buf);
+}
+
+/*!
+ Returns true if this packet is empty - that is, contains no data.
+ */
+bool QPacket::isEmpty() const
+{
+ return b.isEmpty();
+}
+
+/*!
+ Clears data in the packet. This is useful for reusing one writable packet.
+ For example
+ \code
+ QPacketProtocol protocol(...);
+
+ QPacket packet;
+
+ packet << "Hello world!" << 123;
+ protocol.send(packet);
+
+ packet.clear();
+ packet << "Goodbyte world!" << 789;
+ protocol.send(packet);
+ \endcode
+ */
+void QPacket::clear()
+{
+ QBuffer::OpenMode oldMode = buf->openMode();
+ buf->close();
+ b.clear();
+ buf->setBuffer(&b); // reset QBuffer internals with new size of b.
+ buf->open(oldMode);
+}
+
+/*!
+ \class QPacketAutoSend
+ \internal
+
+ \internal
+ */
+QPacketAutoSend::QPacketAutoSend(QPacketProtocol * _p)
+: QPacket(), p(_p)
+{
+}
+
+QPacketAutoSend::~QPacketAutoSend()
+{
+ if(!b.isEmpty())
+ p->send(*this);
+}
+
+QT_END_NAMESPACE
+
+#include <qpacketprotocol.moc>
diff --git a/src/declarative/debugger/qpacketprotocol_p.h b/src/declarative/debugger/qpacketprotocol_p.h
new file mode 100644
index 0000000..265af81
--- /dev/null
+++ b/src/declarative/debugger/qpacketprotocol_p.h
@@ -0,0 +1,122 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QPACKETPROTOCOL_H
+#define QPACKETPROTOCOL_H
+
+#include <QtCore/qobject.h>
+#include <QtCore/qdatastream.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QIODevice;
+class QBuffer;
+class QPacket;
+class QPacketAutoSend;
+class QPacketProtocolPrivate;
+
+class Q_DECLARATIVE_EXPORT QPacketProtocol : public QObject
+{
+Q_OBJECT
+public:
+ explicit QPacketProtocol(QIODevice * dev, QObject * parent = 0);
+ virtual ~QPacketProtocol();
+
+ qint32 maximumPacketSize() const;
+ qint32 setMaximumPacketSize(qint32);
+
+ QPacketAutoSend send();
+ void send(const QPacket &);
+
+ qint64 packetsAvailable() const;
+ QPacket read();
+
+ void clear();
+
+ QIODevice * device();
+
+Q_SIGNALS:
+ void readyRead();
+ void invalidPacket();
+ void packetWritten();
+
+private:
+ QPacketProtocolPrivate * d;
+};
+
+
+class Q_DECLARATIVE_EXPORT QPacket : public QDataStream
+{
+public:
+ QPacket();
+ QPacket(const QPacket &);
+ virtual ~QPacket();
+
+ void clear();
+ bool isEmpty() const;
+
+protected:
+ friend class QPacketProtocol;
+ QPacket(const QByteArray & ba);
+ QByteArray b;
+ QBuffer * buf;
+};
+
+class Q_DECLARATIVE_EXPORT QPacketAutoSend : public QPacket
+{
+public:
+ virtual ~QPacketAutoSend();
+
+private:
+ friend class QPacketProtocol;
+ QPacketAutoSend(QPacketProtocol *);
+ QPacketProtocol * p;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/declarative.pro b/src/declarative/declarative.pro
new file mode 100644
index 0000000..86a0370
--- /dev/null
+++ b/src/declarative/declarative.pro
@@ -0,0 +1,30 @@
+TARGET = QtDeclarative
+QPRO_PWD = $$PWD
+QT = core gui xml script network
+contains(QT_CONFIG, svg): QT += svg
+contains(QT_CONFIG, opengl): QT += opengl
+DEFINES += QT_BUILD_DECLARATIVE_LIB QT_NO_URL_CAST_FROM_STRING
+win32-msvc*|win32-icc:QMAKE_LFLAGS += /BASE:0x66000000
+solaris-cc*:QMAKE_CXXFLAGS_RELEASE -= -O2
+
+unix:QMAKE_PKGCONFIG_REQUIRES = QtCore QtGui QtXml
+
+exists("qml_enable_gcov") {
+ QMAKE_CXXFLAGS = -fprofile-arcs -ftest-coverage -fno-elide-constructors
+ LIBS += -lgcov
+}
+
+include(../qbase.pri)
+
+#INCLUDEPATH -= $$QMAKE_INCDIR_QT/$$TARGET
+#DESTDIR=.
+
+#modules
+include(3rdparty/3rdparty.pri)
+include(util/util.pri)
+include(graphicsitems/graphicsitems.pri)
+include(qml/qml.pri)
+include(widgets/widgets.pri)
+include(debugger/debugger.pri)
+
+symbian:TARGET.UID3=0x2001E623
diff --git a/src/declarative/graphicsitems/graphicsitems.pri b/src/declarative/graphicsitems/graphicsitems.pri
new file mode 100644
index 0000000..eb6e0ad
--- /dev/null
+++ b/src/declarative/graphicsitems/graphicsitems.pri
@@ -0,0 +1,90 @@
+INCLUDEPATH += $$PWD
+
+HEADERS += \
+ $$PWD/qmlgraphicsanchors_p.h \
+ $$PWD/qmlgraphicsanchors_p_p.h \
+ $$PWD/qmlgraphicsevents_p_p.h \
+ $$PWD/qmlgraphicsflickable_p.h \
+ $$PWD/qmlgraphicsflickable_p_p.h \
+ $$PWD/qmlgraphicsflipable_p.h \
+ $$PWD/qmlgraphicsgridview_p.h \
+ $$PWD/qmlgraphicsimage_p.h \
+ $$PWD/qmlgraphicsimagebase_p.h \
+ $$PWD/qmlgraphicsborderimage_p.h \
+ $$PWD/qmlgraphicspainteditem_p.h \
+ $$PWD/qmlgraphicspainteditem_p_p.h \
+ $$PWD/qmlgraphicsimage_p_p.h \
+ $$PWD/qmlgraphicsborderimage_p_p.h \
+ $$PWD/qmlgraphicsimagebase_p_p.h \
+ $$PWD/qmlgraphicsanimatedimage_p.h \
+ $$PWD/qmlgraphicsanimatedimage_p_p.h \
+ $$PWD/qmlgraphicsitem.h \
+ $$PWD/qmlgraphicsitem_p.h \
+ $$PWD/qmlgraphicsfocuspanel_p.h \
+ $$PWD/qmlgraphicsfocusscope_p.h \
+ $$PWD/qmlgraphicspositioners_p.h \
+ $$PWD/qmlgraphicspositioners_p_p.h \
+ $$PWD/qmlgraphicsloader_p.h \
+ $$PWD/qmlgraphicsloader_p_p.h \
+ $$PWD/qmlgraphicsmouseregion_p.h \
+ $$PWD/qmlgraphicsmouseregion_p_p.h \
+ $$PWD/qmlgraphicspath_p.h \
+ $$PWD/qmlgraphicspath_p_p.h \
+ $$PWD/qmlgraphicspathview_p.h \
+ $$PWD/qmlgraphicspathview_p_p.h \
+ $$PWD/qmlgraphicsrectangle_p.h \
+ $$PWD/qmlgraphicsrectangle_p_p.h \
+ $$PWD/qmlgraphicsrepeater_p.h \
+ $$PWD/qmlgraphicsrepeater_p_p.h \
+ $$PWD/qmlgraphicsscalegrid_p_p.h \
+ $$PWD/qmlgraphicstextinput_p.h \
+ $$PWD/qmlgraphicstextinput_p_p.h \
+ $$PWD/qmlgraphicstextedit_p.h \
+ $$PWD/qmlgraphicstextedit_p_p.h \
+ $$PWD/qmlgraphicstext_p.h \
+ $$PWD/qmlgraphicstext_p_p.h \
+ $$PWD/qmlgraphicsvisualitemmodel_p.h \
+ $$PWD/qmlgraphicslistview_p.h \
+ $$PWD/qmlgraphicsgraphicsobjectcontainer_p.h \
+ $$PWD/qmlgraphicsparticles_p.h \
+ $$PWD/qmlgraphicslayoutitem_p.h \
+ $$PWD/qmlgraphicsitemchangelistener_p.h \
+ $$PWD/qmlgraphicseffects.cpp
+
+SOURCES += \
+ $$PWD/qmlgraphicsanchors.cpp \
+ $$PWD/qmlgraphicsevents.cpp \
+ $$PWD/qmlgraphicsflickable.cpp \
+ $$PWD/qmlgraphicsflipable.cpp \
+ $$PWD/qmlgraphicsgridview.cpp \
+ $$PWD/qmlgraphicsimage.cpp \
+ $$PWD/qmlgraphicsborderimage.cpp \
+ $$PWD/qmlgraphicsimagebase.cpp \
+ $$PWD/qmlgraphicsanimatedimage.cpp \
+ $$PWD/qmlgraphicspainteditem.cpp \
+ $$PWD/qmlgraphicsitem.cpp \
+ $$PWD/qmlgraphicsfocuspanel.cpp \
+ $$PWD/qmlgraphicsfocusscope.cpp \
+ $$PWD/qmlgraphicspositioners.cpp \
+ $$PWD/qmlgraphicsloader.cpp \
+ $$PWD/qmlgraphicsmouseregion.cpp \
+ $$PWD/qmlgraphicspath.cpp \
+ $$PWD/qmlgraphicspathview.cpp \
+ $$PWD/qmlgraphicsrectangle.cpp \
+ $$PWD/qmlgraphicsrepeater.cpp \
+ $$PWD/qmlgraphicsscalegrid.cpp \
+ $$PWD/qmlgraphicstextinput.cpp \
+ $$PWD/qmlgraphicstext.cpp \
+ $$PWD/qmlgraphicstextedit.cpp \
+ $$PWD/qmlgraphicsvisualitemmodel.cpp \
+ $$PWD/qmlgraphicslistview.cpp \
+ $$PWD/qmlgraphicsgraphicsobjectcontainer.cpp \
+ $$PWD/qmlgraphicsparticles.cpp \
+ $$PWD/qmlgraphicslayoutitem.cpp \
+
+contains(QT_CONFIG, webkit) {
+ QT+=webkit
+ SOURCES += $$PWD/qmlgraphicswebview.cpp
+ HEADERS += $$PWD/qmlgraphicswebview_p.h
+ HEADERS += $$PWD/qmlgraphicswebview_p_p.h
+}
diff --git a/src/declarative/graphicsitems/qmlgraphicsanchors.cpp b/src/declarative/graphicsitems/qmlgraphicsanchors.cpp
new file mode 100644
index 0000000..93055fc
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsanchors.cpp
@@ -0,0 +1,1060 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsanchors_p_p.h"
+
+#include "qmlgraphicsitem.h"
+#include "qmlgraphicsitem_p.h"
+
+#include <qmlinfo.h>
+
+#include <QDebug>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_NOCREATE_TYPE(QmlGraphicsAnchors)
+
+//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)
+
+//### const item?
+//local position
+static qreal position(QmlGraphicsItem *item, QmlGraphicsAnchorLine::AnchorLine anchorLine)
+{
+ qreal ret = 0.0;
+ switch(anchorLine) {
+ case QmlGraphicsAnchorLine::Left:
+ ret = item->x();
+ break;
+ case QmlGraphicsAnchorLine::Right:
+ ret = item->x() + item->width();
+ break;
+ case QmlGraphicsAnchorLine::Top:
+ ret = item->y();
+ break;
+ case QmlGraphicsAnchorLine::Bottom:
+ ret = item->y() + item->height();
+ break;
+ case QmlGraphicsAnchorLine::HCenter:
+ ret = item->x() + item->width()/2;
+ break;
+ case QmlGraphicsAnchorLine::VCenter:
+ ret = item->y() + item->height()/2;
+ break;
+ case QmlGraphicsAnchorLine::Baseline:
+ ret = item->y() + item->baselineOffset();
+ break;
+ default:
+ break;
+ }
+
+ return ret;
+}
+
+//position when origin is 0,0
+static qreal adjustedPosition(QmlGraphicsItem *item, QmlGraphicsAnchorLine::AnchorLine anchorLine)
+{
+ int ret = 0;
+ switch(anchorLine) {
+ case QmlGraphicsAnchorLine::Left:
+ ret = 0;
+ break;
+ case QmlGraphicsAnchorLine::Right:
+ ret = item->width();
+ break;
+ case QmlGraphicsAnchorLine::Top:
+ ret = 0;
+ break;
+ case QmlGraphicsAnchorLine::Bottom:
+ ret = item->height();
+ break;
+ case QmlGraphicsAnchorLine::HCenter:
+ ret = item->width()/2;
+ break;
+ case QmlGraphicsAnchorLine::VCenter:
+ ret = item->height()/2;
+ break;
+ case QmlGraphicsAnchorLine::Baseline:
+ ret = item->baselineOffset();
+ break;
+ default:
+ break;
+ }
+
+ return ret;
+}
+
+/*!
+ \internal
+ \class QmlGraphicsAnchors
+ \ingroup group_layouts
+ \brief The QmlGraphicsAnchors class provides a way to lay out items relative to other items.
+
+ \warning Currently, only anchoring to siblings or parent is supported.
+*/
+
+QmlGraphicsAnchors::QmlGraphicsAnchors(QObject *parent)
+ : QObject(*new QmlGraphicsAnchorsPrivate(0), parent)
+{
+ qFatal("QmlGraphicsAnchors::QmlGraphicsAnchors(QObject*) called");
+}
+
+QmlGraphicsAnchors::QmlGraphicsAnchors(QmlGraphicsItem *item, QObject *parent)
+ : QObject(*new QmlGraphicsAnchorsPrivate(item), parent)
+{
+}
+
+QmlGraphicsAnchors::~QmlGraphicsAnchors()
+{
+ Q_D(QmlGraphicsAnchors);
+ 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 QmlGraphicsAnchorsPrivate::fillChanged()
+{
+ if (!fill || !isItemComplete())
+ return;
+
+ if (updatingFill < 2) {
+ ++updatingFill;
+
+ if (fill == item->parentItem()) { //child-parent
+ setItemPos(QPointF(leftMargin, topMargin));
+ } else if (fill->parentItem() == item->parentItem()) { //siblings
+ setItemPos(QPointF(fill->x()+leftMargin, fill->y()+topMargin));
+ }
+ setItemWidth(fill->width()-leftMargin-rightMargin);
+ setItemHeight(fill->height()-topMargin-bottomMargin);
+
+ --updatingFill;
+ } else {
+ // ### Make this certain :)
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Possible anchor loop detected on fill.");
+ }
+
+}
+
+void QmlGraphicsAnchorsPrivate::centerInChanged()
+{
+ if (!centerIn || fill || !isItemComplete())
+ return;
+
+ if (updatingCenterIn < 2) {
+ ++updatingCenterIn;
+
+ if (centerIn == item->parentItem()) {
+ QPointF p((item->parentItem()->width() - item->width()) / 2. + hCenterOffset,
+ (item->parentItem()->height() - item->height()) / 2. + vCenterOffset);
+ setItemPos(p);
+
+ } else if (centerIn->parentItem() == item->parentItem()) {
+
+ QPointF p(centerIn->x() + (centerIn->width() - item->width()) / 2. + hCenterOffset,
+ centerIn->y() + (centerIn->height() - item->height()) / 2. + vCenterOffset);
+ setItemPos(p);
+ }
+
+ --updatingCenterIn;
+ } else {
+ // ### Make this certain :)
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Possible anchor loop detected on centerIn.");
+ }
+}
+
+void QmlGraphicsAnchorsPrivate::clearItem(QmlGraphicsItem *item)
+{
+ if (!item)
+ return;
+ if (fill == item)
+ fill = 0;
+ if (centerIn == item)
+ centerIn = 0;
+ if (left.item == item) {
+ left.item = 0;
+ usedAnchors &= ~QmlGraphicsAnchors::HasLeftAnchor;
+ }
+ if (right.item == item) {
+ right.item = 0;
+ usedAnchors &= ~QmlGraphicsAnchors::HasRightAnchor;
+ }
+ if (top.item == item) {
+ top.item = 0;
+ usedAnchors &= ~QmlGraphicsAnchors::HasTopAnchor;
+ }
+ if (bottom.item == item) {
+ bottom.item = 0;
+ usedAnchors &= ~QmlGraphicsAnchors::HasBottomAnchor;
+ }
+ if (vCenter.item == item) {
+ vCenter.item = 0;
+ usedAnchors &= ~QmlGraphicsAnchors::HasVCenterAnchor;
+ }
+ if (hCenter.item == item) {
+ hCenter.item = 0;
+ usedAnchors &= ~QmlGraphicsAnchors::HasHCenterAnchor;
+ }
+ if (baseline.item == item) {
+ baseline.item = 0;
+ usedAnchors &= ~QmlGraphicsAnchors::HasBaselineAnchor;
+ }
+}
+
+void QmlGraphicsAnchorsPrivate::addDepend(QmlGraphicsItem *item)
+{
+ if (!item)
+ return;
+ QmlGraphicsItemPrivate *p =
+ static_cast<QmlGraphicsItemPrivate *>(QGraphicsItemPrivate::get(item));
+ p->addItemChangeListener(this, QmlGraphicsItemPrivate::Geometry);
+}
+
+void QmlGraphicsAnchorsPrivate::remDepend(QmlGraphicsItem *item)
+{
+ if (!item)
+ return;
+ QmlGraphicsItemPrivate *p =
+ static_cast<QmlGraphicsItemPrivate *>(QGraphicsItemPrivate::get(item));
+ p->removeItemChangeListener(this, QmlGraphicsItemPrivate::Geometry);
+}
+
+bool QmlGraphicsAnchorsPrivate::isItemComplete() const
+{
+ return componentComplete;
+}
+
+void QmlGraphicsAnchors::classBegin()
+{
+ Q_D(QmlGraphicsAnchors);
+ d->componentComplete = false;
+}
+
+void QmlGraphicsAnchors::componentComplete()
+{
+ Q_D(QmlGraphicsAnchors);
+ d->componentComplete = true;
+}
+
+void QmlGraphicsAnchorsPrivate::setItemHeight(qreal v)
+{
+ updatingMe = true;
+ item->setHeight(v);
+ updatingMe = false;
+}
+
+void QmlGraphicsAnchorsPrivate::setItemWidth(qreal v)
+{
+ updatingMe = true;
+ item->setWidth(v);
+ updatingMe = false;
+}
+
+void QmlGraphicsAnchorsPrivate::setItemX(qreal v)
+{
+ updatingMe = true;
+ item->setX(v);
+ updatingMe = false;
+}
+
+void QmlGraphicsAnchorsPrivate::setItemY(qreal v)
+{
+ updatingMe = true;
+ item->setY(v);
+ updatingMe = false;
+}
+
+void QmlGraphicsAnchorsPrivate::setItemPos(const QPointF &v)
+{
+ updatingMe = true;
+ item->setPos(v);
+ updatingMe = false;
+}
+
+void QmlGraphicsAnchorsPrivate::updateMe()
+{
+ if (updatingMe) {
+ updatingMe = false;
+ return;
+ }
+
+ fillChanged();
+ centerInChanged();
+ updateHorizontalAnchors();
+ updateVerticalAnchors();
+}
+
+void QmlGraphicsAnchorsPrivate::updateOnComplete()
+{
+ fillChanged();
+ centerInChanged();
+ updateHorizontalAnchors();
+ updateVerticalAnchors();
+}
+
+void QmlGraphicsAnchorsPrivate::itemGeometryChanged(QmlGraphicsItem *, const QRectF &newG, const QRectF &oldG)
+{
+ fillChanged();
+ centerInChanged();
+
+ if (newG.x() != oldG.x() || newG.width() != oldG.width())
+ updateHorizontalAnchors();
+ if (newG.y() != oldG.y() || newG.height() != oldG.height())
+ updateVerticalAnchors();
+}
+
+QmlGraphicsItem *QmlGraphicsAnchors::fill() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->fill;
+}
+
+void QmlGraphicsAnchors::setFill(QmlGraphicsItem *f)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (d->fill == f)
+ return;
+
+ if (!f) {
+ d->remDepend(d->fill);
+ d->fill = f;
+ emit fillChanged();
+ return;
+ }
+ if (f != d->item->parentItem() && f->parentItem() != d->item->parentItem()){
+ qmlInfo(d->item) << tr("Can't anchor to an item that isn't a parent or sibling.");
+ return;
+ }
+ d->remDepend(d->fill);
+ d->fill = f;
+ d->addDepend(d->fill);
+ emit fillChanged();
+ d->fillChanged();
+}
+
+void QmlGraphicsAnchors::resetFill()
+{
+ setFill(0);
+}
+
+QmlGraphicsItem *QmlGraphicsAnchors::centerIn() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->centerIn;
+}
+
+void QmlGraphicsAnchors::setCenterIn(QmlGraphicsItem* c)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (d->centerIn == c)
+ return;
+
+ if (!c) {
+ d->remDepend(d->centerIn);
+ d->centerIn = c;
+ emit centerInChanged();
+ return;
+ }
+ if (c != d->item->parentItem() && c->parentItem() != d->item->parentItem()){
+ qmlInfo(d->item) << tr("Can't anchor to an item that isn't a parent or sibling.");
+ return;
+ }
+
+ d->remDepend(d->centerIn);
+ d->centerIn = c;
+ d->addDepend(d->centerIn);
+ emit centerInChanged();
+ d->centerInChanged();
+}
+
+void QmlGraphicsAnchors::resetCenterIn()
+{
+ setCenterIn(0);
+}
+
+bool QmlGraphicsAnchorsPrivate::calcStretch(const QmlGraphicsAnchorLine &edge1,
+ const QmlGraphicsAnchorLine &edge2,
+ int offset1,
+ int offset2,
+ QmlGraphicsAnchorLine::AnchorLine line,
+ int &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 = ((int)position(edge2.item, edge2.anchorLine) + offset2)
+ - ((int)position(edge1.item, edge1.anchorLine) + offset1);
+ } else if (edge2IsParent && edge1IsSibling) {
+ stretch = ((int)position(edge2.item, edge2.anchorLine) + offset2)
+ - ((int)position(item->parentItem(), line)
+ + (int)position(edge1.item, edge1.anchorLine) + offset1);
+ } else if (edge2IsSibling && edge1IsParent) {
+ stretch = ((int)position(item->parentItem(), line) + (int)position(edge2.item, edge2.anchorLine) + offset2)
+ - ((int)position(edge1.item, edge1.anchorLine) + offset1);
+ } else
+ invalid = true;
+
+ return invalid;
+}
+
+void QmlGraphicsAnchorsPrivate::updateVerticalAnchors()
+{
+ if (fill || centerIn || !isItemComplete())
+ return;
+
+ if (updatingVerticalAnchor < 2) {
+ ++updatingVerticalAnchor;
+ if (usedAnchors & QmlGraphicsAnchors::HasTopAnchor) {
+ //Handle stretching
+ bool invalid = true;
+ int height = 0;
+ if (usedAnchors & QmlGraphicsAnchors::HasBottomAnchor) {
+ invalid = calcStretch(top, bottom, topMargin, -bottomMargin, QmlGraphicsAnchorLine::Top, height);
+ } else if (usedAnchors & QmlGraphicsAnchors::HasVCenterAnchor) {
+ invalid = calcStretch(top, vCenter, topMargin, vCenterOffset, QmlGraphicsAnchorLine::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 & QmlGraphicsAnchors::HasBottomAnchor) {
+ //Handle stretching (top + bottom case is handled above)
+ if (usedAnchors & QmlGraphicsAnchors::HasVCenterAnchor) {
+ int height = 0;
+ bool invalid = calcStretch(vCenter, bottom, vCenterOffset, -bottomMargin,
+ QmlGraphicsAnchorLine::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 & QmlGraphicsAnchors::HasVCenterAnchor) {
+ //(stetching handled above)
+
+ //Handle vCenter
+ if (vCenter.item == item->parentItem()) {
+ setItemY(adjustedPosition(vCenter.item, vCenter.anchorLine)
+ - item->height()/2 + vCenterOffset);
+ } else if (vCenter.item->parentItem() == item->parentItem()) {
+ setItemY(position(vCenter.item, vCenter.anchorLine) - item->height()/2 + vCenterOffset);
+ }
+ } else if (usedAnchors & QmlGraphicsAnchors::HasBaselineAnchor) {
+ //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) << QmlGraphicsAnchors::tr("Possible anchor loop detected on vertical anchor.");
+ }
+}
+
+void QmlGraphicsAnchorsPrivate::updateHorizontalAnchors()
+{
+ if (fill || centerIn || !isItemComplete())
+ return;
+
+ if (updatingHorizontalAnchor < 2) {
+ ++updatingHorizontalAnchor;
+
+ if (usedAnchors & QmlGraphicsAnchors::HasLeftAnchor) {
+ //Handle stretching
+ bool invalid = true;
+ int width = 0;
+ if (usedAnchors & QmlGraphicsAnchors::HasRightAnchor) {
+ invalid = calcStretch(left, right, leftMargin, -rightMargin, QmlGraphicsAnchorLine::Left, width);
+ } else if (usedAnchors & QmlGraphicsAnchors::HasHCenterAnchor) {
+ invalid = calcStretch(left, hCenter, leftMargin, hCenterOffset, QmlGraphicsAnchorLine::Left, width);
+ width *= 2;
+ }
+ if (!invalid)
+ setItemWidth(width);
+
+ //Handle left
+ if (left.item == item->parentItem()) {
+ setItemX(adjustedPosition(left.item, left.anchorLine) + leftMargin);
+ } else if (left.item->parentItem() == item->parentItem()) {
+ setItemX(position(left.item, left.anchorLine) + leftMargin);
+ }
+ } else if (usedAnchors & QmlGraphicsAnchors::HasRightAnchor) {
+ //Handle stretching (left + right case is handled in updateLeftAnchor)
+ if (usedAnchors & QmlGraphicsAnchors::HasHCenterAnchor) {
+ int width = 0;
+ bool invalid = calcStretch(hCenter, right, hCenterOffset, -rightMargin,
+ QmlGraphicsAnchorLine::Left, width);
+ if (!invalid)
+ setItemWidth(width*2);
+ }
+
+ //Handle right
+ if (right.item == item->parentItem()) {
+ setItemX(adjustedPosition(right.item, right.anchorLine) - item->width() - rightMargin);
+ } else if (right.item->parentItem() == item->parentItem()) {
+ setItemX(position(right.item, right.anchorLine) - item->width() - rightMargin);
+ }
+ } else if (usedAnchors & QmlGraphicsAnchors::HasHCenterAnchor) {
+ //Handle hCenter
+ if (hCenter.item == item->parentItem()) {
+ setItemX(adjustedPosition(hCenter.item, hCenter.anchorLine) - item->width()/2 + hCenterOffset);
+ } else if (hCenter.item->parentItem() == item->parentItem()) {
+ setItemX(position(hCenter.item, hCenter.anchorLine) - item->width()/2 + hCenterOffset);
+ }
+ }
+
+ --updatingHorizontalAnchor;
+ } else {
+ // ### Make this certain :)
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Possible anchor loop detected on horizontal anchor.");
+ }
+}
+
+QmlGraphicsAnchorLine QmlGraphicsAnchors::top() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->top;
+}
+
+void QmlGraphicsAnchors::setTop(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (!d->checkVAnchorValid(edge) || d->top == edge)
+ return;
+
+ d->usedAnchors |= HasTopAnchor;
+
+ if (!d->checkVValid()) {
+ d->usedAnchors &= ~HasTopAnchor;
+ return;
+ }
+
+ d->remDepend(d->top.item);
+ d->top = edge;
+ d->addDepend(d->top.item);
+ emit topChanged();
+ d->updateVerticalAnchors();
+}
+
+void QmlGraphicsAnchors::resetTop()
+{
+ Q_D(QmlGraphicsAnchors);
+ d->usedAnchors &= ~HasTopAnchor;
+ d->remDepend(d->top.item);
+ d->top = QmlGraphicsAnchorLine();
+ emit topChanged();
+ d->updateVerticalAnchors();
+}
+
+QmlGraphicsAnchorLine QmlGraphicsAnchors::bottom() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->bottom;
+}
+
+void QmlGraphicsAnchors::setBottom(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (!d->checkVAnchorValid(edge) || d->bottom == edge)
+ return;
+
+ d->usedAnchors |= HasBottomAnchor;
+
+ if (!d->checkVValid()) {
+ d->usedAnchors &= ~HasBottomAnchor;
+ return;
+ }
+
+ d->remDepend(d->bottom.item);
+ d->bottom = edge;
+ d->addDepend(d->bottom.item);
+ emit bottomChanged();
+ d->updateVerticalAnchors();
+}
+
+void QmlGraphicsAnchors::resetBottom()
+{
+ Q_D(QmlGraphicsAnchors);
+ d->usedAnchors &= ~HasBottomAnchor;
+ d->remDepend(d->bottom.item);
+ d->bottom = QmlGraphicsAnchorLine();
+ emit bottomChanged();
+ d->updateVerticalAnchors();
+}
+
+QmlGraphicsAnchorLine QmlGraphicsAnchors::verticalCenter() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->vCenter;
+}
+
+void QmlGraphicsAnchors::setVerticalCenter(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (!d->checkVAnchorValid(edge) || d->vCenter == edge)
+ return;
+
+ d->usedAnchors |= HasVCenterAnchor;
+
+ if (!d->checkVValid()) {
+ d->usedAnchors &= ~HasVCenterAnchor;
+ return;
+ }
+
+ d->remDepend(d->vCenter.item);
+ d->vCenter = edge;
+ d->addDepend(d->vCenter.item);
+ emit verticalCenterChanged();
+ d->updateVerticalAnchors();
+}
+
+void QmlGraphicsAnchors::resetVerticalCenter()
+{
+ Q_D(QmlGraphicsAnchors);
+ d->usedAnchors &= ~HasVCenterAnchor;
+ d->remDepend(d->vCenter.item);
+ d->vCenter = QmlGraphicsAnchorLine();
+ emit verticalCenterChanged();
+ d->updateVerticalAnchors();
+}
+
+QmlGraphicsAnchorLine QmlGraphicsAnchors::baseline() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->baseline;
+}
+
+void QmlGraphicsAnchors::setBaseline(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (!d->checkVAnchorValid(edge) || d->baseline == edge)
+ return;
+
+ d->usedAnchors |= HasBaselineAnchor;
+
+ if (!d->checkVValid()) {
+ d->usedAnchors &= ~HasBaselineAnchor;
+ return;
+ }
+
+ d->remDepend(d->baseline.item);
+ d->baseline = edge;
+ d->addDepend(d->baseline.item);
+ emit baselineChanged();
+ d->updateVerticalAnchors();
+}
+
+void QmlGraphicsAnchors::resetBaseline()
+{
+ Q_D(QmlGraphicsAnchors);
+ d->usedAnchors &= ~HasBaselineAnchor;
+ d->remDepend(d->baseline.item);
+ d->baseline = QmlGraphicsAnchorLine();
+ emit baselineChanged();
+ d->updateVerticalAnchors();
+}
+
+QmlGraphicsAnchorLine QmlGraphicsAnchors::left() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->left;
+}
+
+void QmlGraphicsAnchors::setLeft(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (!d->checkHAnchorValid(edge) || d->left == edge)
+ return;
+
+ d->usedAnchors |= HasLeftAnchor;
+
+ if (!d->checkHValid()) {
+ d->usedAnchors &= ~HasLeftAnchor;
+ return;
+ }
+
+ d->remDepend(d->left.item);
+ d->left = edge;
+ d->addDepend(d->left.item);
+ emit leftChanged();
+ d->updateHorizontalAnchors();
+}
+
+void QmlGraphicsAnchors::resetLeft()
+{
+ Q_D(QmlGraphicsAnchors);
+ d->usedAnchors &= ~HasLeftAnchor;
+ d->remDepend(d->left.item);
+ d->left = QmlGraphicsAnchorLine();
+ emit leftChanged();
+ d->updateHorizontalAnchors();
+}
+
+QmlGraphicsAnchorLine QmlGraphicsAnchors::right() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->right;
+}
+
+void QmlGraphicsAnchors::setRight(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (!d->checkHAnchorValid(edge) || d->right == edge)
+ return;
+
+ d->usedAnchors |= HasRightAnchor;
+
+ if (!d->checkHValid()) {
+ d->usedAnchors &= ~HasRightAnchor;
+ return;
+ }
+
+ d->remDepend(d->right.item);
+ d->right = edge;
+ d->addDepend(d->right.item);
+ emit rightChanged();
+ d->updateHorizontalAnchors();
+}
+
+void QmlGraphicsAnchors::resetRight()
+{
+ Q_D(QmlGraphicsAnchors);
+ d->usedAnchors &= ~HasRightAnchor;
+ d->remDepend(d->right.item);
+ d->right = QmlGraphicsAnchorLine();
+ emit rightChanged();
+ d->updateHorizontalAnchors();
+}
+
+QmlGraphicsAnchorLine QmlGraphicsAnchors::horizontalCenter() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->hCenter;
+}
+
+void QmlGraphicsAnchors::setHorizontalCenter(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (!d->checkHAnchorValid(edge) || d->hCenter == edge)
+ return;
+
+ d->usedAnchors |= HasHCenterAnchor;
+
+ if (!d->checkHValid()) {
+ d->usedAnchors &= ~HasHCenterAnchor;
+ return;
+ }
+
+ d->remDepend(d->hCenter.item);
+ d->hCenter = edge;
+ d->addDepend(d->hCenter.item);
+ emit horizontalCenterChanged();
+ d->updateHorizontalAnchors();
+}
+
+void QmlGraphicsAnchors::resetHorizontalCenter()
+{
+ Q_D(QmlGraphicsAnchors);
+ d->usedAnchors &= ~HasHCenterAnchor;
+ d->remDepend(d->hCenter.item);
+ d->hCenter = QmlGraphicsAnchorLine();
+ emit horizontalCenterChanged();
+ d->updateHorizontalAnchors();
+}
+
+qreal QmlGraphicsAnchors::leftMargin() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->leftMargin;
+}
+
+void QmlGraphicsAnchors::setLeftMargin(qreal offset)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (d->leftMargin == offset)
+ return;
+ d->leftMargin = offset;
+ if(d->fill)
+ d->fillChanged();
+ else
+ d->updateHorizontalAnchors();
+ emit leftMarginChanged();
+}
+
+qreal QmlGraphicsAnchors::rightMargin() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->rightMargin;
+}
+
+void QmlGraphicsAnchors::setRightMargin(qreal offset)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (d->rightMargin == offset)
+ return;
+ d->rightMargin = offset;
+ if(d->fill)
+ d->fillChanged();
+ else
+ d->updateHorizontalAnchors();
+ emit rightMarginChanged();
+}
+
+qreal QmlGraphicsAnchors::margins() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->margins;
+}
+
+void QmlGraphicsAnchors::setMargins(qreal offset)
+{
+ Q_D(QmlGraphicsAnchors);
+ 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 QmlGraphicsAnchors::horizontalCenterOffset() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->hCenterOffset;
+}
+
+void QmlGraphicsAnchors::setHorizontalCenterOffset(qreal offset)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (d->hCenterOffset == offset)
+ return;
+ d->hCenterOffset = offset;
+ if(d->centerIn)
+ d->centerInChanged();
+ else
+ d->updateHorizontalAnchors();
+ emit horizontalCenterOffsetChanged();
+}
+
+qreal QmlGraphicsAnchors::topMargin() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->topMargin;
+}
+
+void QmlGraphicsAnchors::setTopMargin(qreal offset)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (d->topMargin == offset)
+ return;
+ d->topMargin = offset;
+ if(d->fill)
+ d->fillChanged();
+ else
+ d->updateVerticalAnchors();
+ emit topMarginChanged();
+}
+
+qreal QmlGraphicsAnchors::bottomMargin() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->bottomMargin;
+}
+
+void QmlGraphicsAnchors::setBottomMargin(qreal offset)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (d->bottomMargin == offset)
+ return;
+ d->bottomMargin = offset;
+ if(d->fill)
+ d->fillChanged();
+ else
+ d->updateVerticalAnchors();
+ emit bottomMarginChanged();
+}
+
+qreal QmlGraphicsAnchors::verticalCenterOffset() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->vCenterOffset;
+}
+
+void QmlGraphicsAnchors::setVerticalCenterOffset(qreal offset)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (d->vCenterOffset == offset)
+ return;
+ d->vCenterOffset = offset;
+ if(d->centerIn)
+ d->centerInChanged();
+ else
+ d->updateVerticalAnchors();
+ emit verticalCenterOffsetChanged();
+}
+
+qreal QmlGraphicsAnchors::baselineOffset() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->baselineOffset;
+}
+
+void QmlGraphicsAnchors::setBaselineOffset(qreal offset)
+{
+ Q_D(QmlGraphicsAnchors);
+ if (d->baselineOffset == offset)
+ return;
+ d->baselineOffset = offset;
+ d->updateVerticalAnchors();
+ emit baselineOffsetChanged();
+}
+
+QmlGraphicsAnchors::UsedAnchors QmlGraphicsAnchors::usedAnchors() const
+{
+ Q_D(const QmlGraphicsAnchors);
+ return d->usedAnchors;
+}
+
+bool QmlGraphicsAnchorsPrivate::checkHValid() const
+{
+ if (usedAnchors & QmlGraphicsAnchors::HasLeftAnchor &&
+ usedAnchors & QmlGraphicsAnchors::HasRightAnchor &&
+ usedAnchors & QmlGraphicsAnchors::HasHCenterAnchor) {
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Can't specify left, right, and hcenter anchors.");
+ return false;
+ }
+
+ return true;
+}
+
+bool QmlGraphicsAnchorsPrivate::checkHAnchorValid(QmlGraphicsAnchorLine anchor) const
+{
+ if (!anchor.item) {
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Can't anchor to a null item.");
+ return false;
+ } else if (anchor.anchorLine & QmlGraphicsAnchorLine::Vertical_Mask) {
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Can't anchor a horizontal edge to a vertical edge.");
+ return false;
+ } else if (anchor.item != item->parentItem() && anchor.item->parentItem() != item->parentItem()){
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Can't anchor to an item that isn't a parent or sibling.");
+ return false;
+ } else if (anchor.item == item) {
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Can't anchor item to self.");
+ return false;
+ }
+
+ return true;
+}
+
+bool QmlGraphicsAnchorsPrivate::checkVValid() const
+{
+ if (usedAnchors & QmlGraphicsAnchors::HasTopAnchor &&
+ usedAnchors & QmlGraphicsAnchors::HasBottomAnchor &&
+ usedAnchors & QmlGraphicsAnchors::HasVCenterAnchor) {
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Can't specify top, bottom, and vcenter anchors.");
+ return false;
+ } else if (usedAnchors & QmlGraphicsAnchors::HasBaselineAnchor &&
+ (usedAnchors & QmlGraphicsAnchors::HasTopAnchor ||
+ usedAnchors & QmlGraphicsAnchors::HasBottomAnchor ||
+ usedAnchors & QmlGraphicsAnchors::HasVCenterAnchor)) {
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Baseline anchor can't be used in conjunction with top, bottom, or vcenter anchors.");
+ return false;
+ }
+
+ return true;
+}
+
+bool QmlGraphicsAnchorsPrivate::checkVAnchorValid(QmlGraphicsAnchorLine anchor) const
+{
+ if (!anchor.item) {
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Can't anchor to a null item.");
+ return false;
+ } else if (anchor.anchorLine & QmlGraphicsAnchorLine::Horizontal_Mask) {
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Can't anchor a vertical edge to a horizontal edge.");
+ return false;
+ } else if (anchor.item != item->parentItem() && anchor.item->parentItem() != item->parentItem()){
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Can't anchor to an item that isn't a parent or sibling.");
+ return false;
+ } else if (anchor.item == item){
+ qmlInfo(item) << QmlGraphicsAnchors::tr("Can't anchor item to self.");
+ return false;
+ }
+
+ return true;
+}
+
+#include <moc_qmlgraphicsanchors_p.cpp>
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/graphicsitems/qmlgraphicsanchors_p.h b/src/declarative/graphicsitems/qmlgraphicsanchors_p.h
new file mode 100644
index 0000000..5a8f8c1
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsanchors_p.h
@@ -0,0 +1,196 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSANCHORS_H
+#define QMLGRAPHICSANCHORS_H
+
+#include "qmlgraphicsitem.h"
+
+#include <qml.h>
+
+#include <QtCore/QObject>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsAnchorsPrivate;
+class QmlGraphicsAnchorLine;
+class Q_DECLARATIVE_EXPORT QmlGraphicsAnchors : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QmlGraphicsAnchorLine left READ left WRITE setLeft RESET resetLeft NOTIFY leftChanged)
+ Q_PROPERTY(QmlGraphicsAnchorLine right READ right WRITE setRight RESET resetRight NOTIFY rightChanged)
+ Q_PROPERTY(QmlGraphicsAnchorLine horizontalCenter READ horizontalCenter WRITE setHorizontalCenter RESET resetHorizontalCenter NOTIFY horizontalCenterChanged)
+ Q_PROPERTY(QmlGraphicsAnchorLine top READ top WRITE setTop RESET resetTop NOTIFY topChanged)
+ Q_PROPERTY(QmlGraphicsAnchorLine bottom READ bottom WRITE setBottom RESET resetBottom NOTIFY bottomChanged)
+ Q_PROPERTY(QmlGraphicsAnchorLine verticalCenter READ verticalCenter WRITE setVerticalCenter RESET resetVerticalCenter NOTIFY verticalCenterChanged)
+ Q_PROPERTY(QmlGraphicsAnchorLine 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(QmlGraphicsItem *fill READ fill WRITE setFill RESET resetFill NOTIFY fillChanged)
+ Q_PROPERTY(QmlGraphicsItem *centerIn READ centerIn WRITE setCenterIn RESET resetCenterIn NOTIFY centerInChanged)
+
+public:
+ QmlGraphicsAnchors(QObject *parent=0);
+ QmlGraphicsAnchors(QmlGraphicsItem *item, QObject *parent=0);
+ virtual ~QmlGraphicsAnchors();
+
+ enum UsedAnchor {
+ HasLeftAnchor = 0x01,
+ HasRightAnchor = 0x02,
+ HasTopAnchor = 0x04,
+ HasBottomAnchor = 0x08,
+ HasHCenterAnchor = 0x10,
+ HasVCenterAnchor = 0x20,
+ HasBaselineAnchor = 0x40,
+ Horizontal_Mask = HasLeftAnchor | HasRightAnchor | HasHCenterAnchor,
+ Vertical_Mask = HasTopAnchor | HasBottomAnchor | HasVCenterAnchor | HasBaselineAnchor
+ };
+ Q_DECLARE_FLAGS(UsedAnchors, UsedAnchor)
+
+ QmlGraphicsAnchorLine left() const;
+ void setLeft(const QmlGraphicsAnchorLine &edge);
+ void resetLeft();
+
+ QmlGraphicsAnchorLine right() const;
+ void setRight(const QmlGraphicsAnchorLine &edge);
+ void resetRight();
+
+ QmlGraphicsAnchorLine horizontalCenter() const;
+ void setHorizontalCenter(const QmlGraphicsAnchorLine &edge);
+ void resetHorizontalCenter();
+
+ QmlGraphicsAnchorLine top() const;
+ void setTop(const QmlGraphicsAnchorLine &edge);
+ void resetTop();
+
+ QmlGraphicsAnchorLine bottom() const;
+ void setBottom(const QmlGraphicsAnchorLine &edge);
+ void resetBottom();
+
+ QmlGraphicsAnchorLine verticalCenter() const;
+ void setVerticalCenter(const QmlGraphicsAnchorLine &edge);
+ void resetVerticalCenter();
+
+ QmlGraphicsAnchorLine baseline() const;
+ void setBaseline(const QmlGraphicsAnchorLine &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);
+
+ QmlGraphicsItem *fill() const;
+ void setFill(QmlGraphicsItem *);
+ void resetFill();
+
+ QmlGraphicsItem *centerIn() const;
+ void setCenterIn(QmlGraphicsItem *);
+ void resetCenterIn();
+
+ UsedAnchors usedAnchors() const;
+
+ 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();
+
+private:
+ friend class QmlGraphicsItem;
+ Q_DISABLE_COPY(QmlGraphicsAnchors)
+ Q_DECLARE_PRIVATE(QmlGraphicsAnchors)
+};
+Q_DECLARE_OPERATORS_FOR_FLAGS(QmlGraphicsAnchors::UsedAnchors)
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsAnchors)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicsanchors_p_p.h b/src/declarative/graphicsitems/qmlgraphicsanchors_p_p.h
new file mode 100644
index 0000000..5b02158
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsanchors_p_p.h
@@ -0,0 +1,174 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSANCHORS_P_H
+#define QMLGRAPHICSANCHORS_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 "qmlgraphicsanchors_p.h"
+#include "qmlgraphicsitemchangelistener_p.h"
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsAnchorLine
+{
+public:
+ QmlGraphicsAnchorLine() : 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
+ };
+
+ QmlGraphicsItem *item;
+ AnchorLine anchorLine;
+
+ bool operator==(const QmlGraphicsAnchorLine& other) const
+ {
+ return item == other.item && anchorLine == other.anchorLine;
+ }
+};
+Q_DECLARE_METATYPE(QmlGraphicsAnchorLine)
+
+
+
+class QmlGraphicsAnchorsPrivate : public QObjectPrivate, public QmlGraphicsItemChangeListener
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsAnchors)
+public:
+ QmlGraphicsAnchorsPrivate(QmlGraphicsItem *i)
+ : updatingMe(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),
+ componentComplete(true)
+ {
+ }
+
+ void init()
+ {
+ }
+
+ void clearItem(QmlGraphicsItem *);
+
+ void addDepend(QmlGraphicsItem *);
+ void remDepend(QmlGraphicsItem *);
+ bool isItemComplete() const;
+
+ bool updatingMe;
+ int updatingHorizontalAnchor;
+ int updatingVerticalAnchor;
+ int updatingFill;
+ int updatingCenterIn;
+
+ void setItemHeight(qreal);
+ void setItemWidth(qreal);
+ void setItemX(qreal);
+ void setItemY(qreal);
+ void setItemPos(const QPointF &);
+
+ void updateOnComplete();
+ void updateMe();
+
+ // QmlGraphicsItemGeometryListener interface
+ void itemGeometryChanged(QmlGraphicsItem *, const QRectF &, const QRectF &);
+ QmlGraphicsAnchorsPrivate *anchorPrivate() { return this; }
+
+ bool checkHValid() const;
+ bool checkVValid() const;
+ bool checkHAnchorValid(QmlGraphicsAnchorLine anchor) const;
+ bool checkVAnchorValid(QmlGraphicsAnchorLine anchor) const;
+ bool calcStretch(const QmlGraphicsAnchorLine &edge1, const QmlGraphicsAnchorLine &edge2, int offset1, int offset2, QmlGraphicsAnchorLine::AnchorLine line, int &stretch);
+
+ void updateHorizontalAnchors();
+ void updateVerticalAnchors();
+ void fillChanged();
+ void centerInChanged();
+
+ QmlGraphicsItem *item;
+ QmlGraphicsAnchors::UsedAnchors usedAnchors;
+
+ QmlGraphicsItem *fill;
+ QmlGraphicsItem *centerIn;
+
+ QmlGraphicsAnchorLine left;
+ QmlGraphicsAnchorLine right;
+ QmlGraphicsAnchorLine top;
+ QmlGraphicsAnchorLine bottom;
+ QmlGraphicsAnchorLine vCenter;
+ QmlGraphicsAnchorLine hCenter;
+ QmlGraphicsAnchorLine baseline;
+
+ qreal leftMargin;
+ qreal rightMargin;
+ qreal topMargin;
+ qreal bottomMargin;
+ qreal margins;
+ qreal vCenterOffset;
+ qreal hCenterOffset;
+ qreal baselineOffset;
+
+ bool componentComplete;
+};
+
+QT_END_NAMESPACE
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicsanimatedimage.cpp b/src/declarative/graphicsitems/qmlgraphicsanimatedimage.cpp
new file mode 100644
index 0000000..e01e569
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsanimatedimage.cpp
@@ -0,0 +1,305 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsanimatedimage_p.h"
+#include "qmlgraphicsanimatedimage_p_p.h"
+
+#include <qmlengine.h>
+
+#include <QMovie>
+#include <QNetworkRequest>
+#include <QNetworkReply>
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QmlGraphicsAnimatedImage
+ \internal
+*/
+
+/*!
+ \qmlclass AnimatedImage QmlGraphicsAnimatedImage
+ \inherits Image
+
+ This item provides for playing animations stored as images containing a series of frames,
+ such as GIF files. The full list of supported formats can be determined with
+ QMovie::supportedFormats().
+
+ \table
+ \row
+ \o \image animatedimageitem.gif
+ \o
+ \qml
+Item {
+ width: anim.width; height: anim.height+8
+ AnimatedImage { id: anim; source: "pics/games-anim.gif" }
+ Rectangle { color: "red"; width: 4; height: 8; y: anim.height
+ x: (anim.width-width)*anim.currentFrame/(anim.frameCount-1)
+ }
+}
+ \endqml
+ \endtable
+*/
+QML_DEFINE_TYPE(Qt,4,6,AnimatedImage,QmlGraphicsAnimatedImage)
+
+QmlGraphicsAnimatedImage::QmlGraphicsAnimatedImage(QmlGraphicsItem *parent)
+ : QmlGraphicsImage(*(new QmlGraphicsAnimatedImagePrivate), parent)
+{
+}
+
+QmlGraphicsAnimatedImage::~QmlGraphicsAnimatedImage()
+{
+ Q_D(QmlGraphicsAnimatedImage);
+ delete d->_movie;
+}
+
+/*!
+ \qmlproperty bool AnimatedImage::paused
+ This property holds whether the animated image is paused or not
+
+ Defaults to false, and can be set to true when you want to pause.
+*/
+bool QmlGraphicsAnimatedImage::isPaused() const
+{
+ Q_D(const QmlGraphicsAnimatedImage);
+ if(!d->_movie)
+ return false;
+ return d->_movie->state()==QMovie::Paused;
+}
+
+void QmlGraphicsAnimatedImage::setPaused(bool pause)
+{
+ Q_D(QmlGraphicsAnimatedImage);
+ if(pause == d->paused)
+ return;
+ d->paused = pause;
+ if(!d->_movie)
+ return;
+ d->_movie->setPaused(pause);
+}
+/*!
+ \qmlproperty bool AnimatedImage::playing
+ This property holds whether the animated image is playing or not
+
+ Defaults to true, so as to start playing immediately.
+*/
+bool QmlGraphicsAnimatedImage::isPlaying() const
+{
+ Q_D(const QmlGraphicsAnimatedImage);
+ if (!d->_movie)
+ return false;
+ return d->_movie->state()!=QMovie::NotRunning;
+}
+
+void QmlGraphicsAnimatedImage::setPlaying(bool play)
+{
+ Q_D(QmlGraphicsAnimatedImage);
+ if(play == d->playing)
+ return;
+ d->playing = play;
+ if (!d->_movie)
+ return;
+ if (play)
+ d->_movie->start();
+ else
+ d->_movie->stop();
+}
+
+/*!
+ \qmlproperty int AnimatedImage::currentFrame
+ \qmlproperty int AnimatedImage::frameCount
+
+ currentFrame is the frame that is currently visible. Watching when this changes can
+ allow other things to animate at the same time as the image. frameCount is the number
+ of frames in the animation. For some animation formats, frameCount is unknown and set to zero.
+*/
+int QmlGraphicsAnimatedImage::currentFrame() const
+{
+ Q_D(const QmlGraphicsAnimatedImage);
+ if (!d->_movie)
+ return d->preset_currentframe;
+ return d->_movie->currentFrameNumber();
+}
+
+void QmlGraphicsAnimatedImage::setCurrentFrame(int frame)
+{
+ Q_D(QmlGraphicsAnimatedImage);
+ if (!d->_movie) {
+ d->preset_currentframe = frame;
+ return;
+ }
+ d->_movie->jumpToFrame(frame);
+}
+
+int QmlGraphicsAnimatedImage::frameCount() const
+{
+ Q_D(const QmlGraphicsAnimatedImage);
+ if (!d->_movie)
+ return 0;
+ return d->_movie->frameCount();
+}
+
+static QString toLocalFileOrQrc(const QUrl& url)
+{
+ QString r = url.toLocalFile();
+ if (r.isEmpty() && url.scheme() == QLatin1String("qrc"))
+ r = QLatin1Char(':') + url.path();
+ return r;
+}
+
+void QmlGraphicsAnimatedImage::setSource(const QUrl &url)
+{
+ Q_D(QmlGraphicsAnimatedImage);
+ if (url == d->url)
+ return;
+
+ delete d->_movie;
+ d->_movie = 0;
+
+ if (d->reply) {
+ d->reply->deleteLater();
+ d->reply = 0;
+ }
+
+ d->url = url;
+
+ if (url.isEmpty()) {
+ delete d->_movie;
+ d->status = Null;
+ } else {
+#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
+ QString lf = toLocalFileOrQrc(url);
+ if (!lf.isEmpty()) {
+ //### should be unified with movieRequestFinished
+ d->_movie = new QMovie(lf);
+ if (!d->_movie->isValid()){
+ qWarning() << "Error Reading Animated Image File" << d->url;
+ delete d->_movie;
+ d->_movie = 0;
+ 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->setPixmap(d->_movie->currentPixmap());
+ d->status = Ready;
+ d->progress = 1.0;
+ emit statusChanged(d->status);
+ emit sourceChanged(d->url);
+ emit progressChanged(d->progress);
+ return;
+ }
+#endif
+ d->status = Loading;
+ 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()));
+ }
+
+ emit statusChanged(d->status);
+}
+
+void QmlGraphicsAnimatedImage::movieRequestFinished()
+{
+ Q_D(QmlGraphicsAnimatedImage);
+ d->_movie = new QMovie(d->reply);
+ if (!d->_movie->isValid()){
+ qWarning() << "Error Reading Animated Image File " << d->url;
+ delete d->_movie;
+ d->_movie = 0;
+ 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->setPixmap(d->_movie->currentPixmap());
+}
+
+void QmlGraphicsAnimatedImage::movieUpdate()
+{
+ Q_D(QmlGraphicsAnimatedImage);
+ d->setPixmap(d->_movie->currentPixmap());
+ emit frameChanged();
+}
+
+void QmlGraphicsAnimatedImage::playingStatusChanged()
+{
+ Q_D(QmlGraphicsAnimatedImage);
+ 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 QmlGraphicsAnimatedImage::componentComplete()
+{
+ Q_D(QmlGraphicsAnimatedImage);
+ if (!d->reply) {
+ setCurrentFrame(d->preset_currentframe);
+ d->preset_currentframe = 0;
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsanimatedimage_p.h b/src/declarative/graphicsitems/qmlgraphicsanimatedimage_p.h
new file mode 100644
index 0000000..a837702
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsanimatedimage_p.h
@@ -0,0 +1,106 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSANIMATEDIMAGE_H
+#define QMLGRAPHICSANIMATEDIMAGE_H
+
+#include "qmlgraphicsimage_p.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QMovie;
+class QmlGraphicsAnimatedImagePrivate;
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsAnimatedImage : public QmlGraphicsImage
+{
+ 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)
+public:
+ QmlGraphicsAnimatedImage(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsAnimatedImage();
+
+ 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 QmlGraphicsImage's src property*/
+ virtual void setSource(const QUrl&);
+
+Q_SIGNALS:
+ void playingChanged();
+ void pausedChanged();
+ void frameChanged();
+
+private Q_SLOTS:
+ void movieUpdate();
+ void movieRequestFinished();
+ void playingStatusChanged();
+
+protected:
+ void componentComplete();
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsAnimatedImage)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsAnimatedImage)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsAnimatedImage)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicsanimatedimage_p_p.h b/src/declarative/graphicsitems/qmlgraphicsanimatedimage_p_p.h
new file mode 100644
index 0000000..0d1c749
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsanimatedimage_p_p.h
@@ -0,0 +1,82 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSANIMATEDIMAGE_P_H
+#define QMLGRAPHICSANIMATEDIMAGE_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 "qmlgraphicsimage_p_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QMovie;
+class QNetworkReply;
+
+class QmlGraphicsAnimatedImagePrivate : public QmlGraphicsImagePrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsAnimatedImage)
+
+public:
+ QmlGraphicsAnimatedImagePrivate()
+ : playing(true), paused(false), preset_currentframe(0), _movie(0), reply(0)
+ {
+ }
+
+ bool playing;
+ bool paused;
+ int preset_currentframe;
+ QMovie *_movie;
+ QNetworkReply *reply;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLGRAPHICSANIMATEDIMAGE_P_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsborderimage.cpp b/src/declarative/graphicsitems/qmlgraphicsborderimage.cpp
new file mode 100644
index 0000000..877e141
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsborderimage.cpp
@@ -0,0 +1,409 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsborderimage_p.h"
+#include "qmlgraphicsborderimage_p_p.h"
+
+#include <qmlengine.h>
+
+#include <QNetworkRequest>
+#include <QNetworkReply>
+#include <QFile>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,BorderImage,QmlGraphicsBorderImage)
+
+/*!
+ \qmlclass BorderImage QmlGraphicsBorderImage
+ \brief The BorderImage element provides an image that can be used as a border.
+ \inherits Item
+
+ \snippet snippets/declarative/border-image.qml 0
+
+ \image BorderImage.png
+ */
+
+/*!
+ \internal
+ \class QmlGraphicsBorderImage BorderImage
+ \brief The QmlGraphicsBorderImage class provides an image item that you can add to a QmlView.
+*/
+
+QmlGraphicsBorderImage::QmlGraphicsBorderImage(QmlGraphicsItem *parent)
+ : QmlGraphicsImageBase(*(new QmlGraphicsBorderImagePrivate), parent)
+{
+}
+
+QmlGraphicsBorderImage::~QmlGraphicsBorderImage()
+{
+ Q_D(QmlGraphicsBorderImage);
+ if (d->sciReply)
+ d->sciReply->deleteLater();
+ if (d->sciPendingPixmapCache)
+ QmlPixmapCache::cancel(d->sciurl, this);
+}
+/*!
+ \qmlproperty enum BorderImage::status
+
+ This property holds the status of image loading. It can be one of:
+ \list
+ \o Null - no image has been set
+ \o Ready - the image has been loaded
+ \o Loading - the image is currently being loaded
+ \o Error - an error occurred while loading the image
+ \endlist
+
+ \sa progress
+*/
+
+/*!
+ \qmlproperty real BorderImage::progress
+
+ This property holds the progress of image loading, from 0.0 (nothing loaded)
+ to 1.0 (finished).
+
+ \sa status
+*/
+
+/*!
+ \qmlproperty bool 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.
+
+ \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 url BorderImage::source
+
+ BorderImage can handle any image format supported by Qt, loaded from any URL scheme supported by Qt.
+
+ It can also handle .sci files, which are a Qml-specific format. A .sci file uses a simple text-based format that specifies
+ the borders, the image file and the tile rules.
+
+ The following .sci file sets the borders to 10 on each side for the image \c picture.png:
+ \qml
+ border.left: 10
+ border.top: 10
+ border.bottom: 10
+ border.right: 10
+ source: picture.png
+ \endqml
+
+ The URL may be absolute, or relative to the URL of the component.
+*/
+
+static QString toLocalFileOrQrc(const QUrl& url)
+{
+ QString r = url.toLocalFile();
+ if (r.isEmpty() && url.scheme() == QLatin1String("qrc"))
+ r = QLatin1Char(':') + url.path();
+ return r;
+}
+
+
+void QmlGraphicsBorderImage::setSource(const QUrl &url)
+{
+ Q_D(QmlGraphicsBorderImage);
+ //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;
+ }
+
+ if (d->pendingPixmapCache) {
+ QmlPixmapCache::cancel(d->url, this);
+ d->pendingPixmapCache = false;
+ }
+ if (d->sciPendingPixmapCache) {
+ QmlPixmapCache::cancel(d->sciurl, this);
+ d->sciPendingPixmapCache = false;
+ }
+
+ d->url = url;
+ d->sciurl = QUrl();
+ if (d->progress != 0.0) {
+ d->progress = 0.0;
+ emit progressChanged(d->progress);
+ }
+
+ if (url.isEmpty()) {
+ d->pix = QPixmap();
+ d->status = Null;
+ setImplicitWidth(0);
+ setImplicitHeight(0);
+ emit statusChanged(d->status);
+ emit sourceChanged(d->url);
+ update();
+ } else {
+ d->status = Loading;
+ if (d->url.path().endsWith(QLatin1String(".sci"))) {
+#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
+ QString lf = toLocalFileOrQrc(d->url);
+ if (!lf.isEmpty()) {
+ QFile file(lf);
+ file.open(QIODevice::ReadOnly);
+ setGridScaledImage(QmlGraphicsGridScaledImage(&file));
+ } else
+#endif
+ {
+ QNetworkRequest req(d->url);
+ d->sciReply = qmlEngine(this)->networkAccessManager()->get(req);
+ QObject::connect(d->sciReply, SIGNAL(finished()),
+ this, SLOT(sciRequestFinished()));
+ }
+ } else {
+ QmlPixmapReply::Status status = QmlPixmapCache::get(d->url, &d->pix);
+ if (status != QmlPixmapReply::Ready && status != QmlPixmapReply::Error) {
+ QmlPixmapReply *reply = QmlPixmapCache::request(qmlEngine(this), d->url);
+ d->pendingPixmapCache = true;
+ connect(reply, SIGNAL(finished()), this, SLOT(requestFinished()));
+ connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
+ this, SLOT(requestProgress(qint64,qint64)));
+ } else {
+ //### should be unified with requestFinished
+ setImplicitWidth(d->pix.width());
+ setImplicitHeight(d->pix.height());
+
+ if (d->pix.isNull())
+ d->status = Error;
+ if (d->status == Loading)
+ d->status = Ready;
+ d->progress = 1.0;
+ emit statusChanged(d->status);
+ emit sourceChanged(d->url);
+ emit progressChanged(d->progress);
+ update();
+ }
+ }
+ }
+
+ emit statusChanged(d->status);
+}
+
+/*!
+ \qmlproperty int BorderImage::border.left
+ \qmlproperty int BorderImage::border.right
+ \qmlproperty int BorderImage::border.top
+ \qmlproperty int BorderImage::border.bottom
+
+ \target ImagexmlpropertiesscaleGrid
+
+ The 4 border lines (2 horizontal and 2 vertical) break an image into 9 sections, as shown below:
+
+ \image declarative-scalegrid.png
+
+ When the image is scaled:
+ \list
+ \i the corners (sections 1, 3, 7, and 9) are not scaled at all
+ \i the middle (section 5) is scaled according to BorderImage::horizontalTileMode and BorderImage::verticalTileMode
+ \i sections 2 and 8 are scaled according to BorderImage::horizontalTileMode
+ \i sections 4 and 6 are scaled according to BorderImage::verticalTileMode
+ \endlist
+
+ Each border line (left, right, top, and bottom) specifies an offset from the respective side. For example, \c{border.bottom: 10} sets the bottom line 10 pixels up from the bottom of the image.
+
+ The border lines can also be specified using a
+ \l {BorderImage::source}{.sci file}.
+*/
+
+QmlGraphicsScaleGrid *QmlGraphicsBorderImage::border()
+{
+ Q_D(QmlGraphicsBorderImage);
+ return d->getScaleGrid();
+}
+
+/*!
+ \qmlproperty TileMode BorderImage::horizontalTileMode
+ \qmlproperty TileMode BorderImage::verticalTileMode
+
+ This property describes how to repeat or stretch the middle parts of the border image.
+
+ \list
+ \o Stretch - Scale the image to fit to the available area.
+ \o Repeat - Tile the image until there is no more space. May crop the last image.
+ \o Round - Like Repeat, but scales the images down to ensure that the last image is not cropped.
+ \endlist
+*/
+QmlGraphicsBorderImage::TileMode QmlGraphicsBorderImage::horizontalTileMode() const
+{
+ Q_D(const QmlGraphicsBorderImage);
+ return d->horizontalTileMode;
+}
+
+void QmlGraphicsBorderImage::setHorizontalTileMode(TileMode t)
+{
+ Q_D(QmlGraphicsBorderImage);
+ if (t != d->horizontalTileMode) {
+ d->horizontalTileMode = t;
+ emit horizontalTileModeChanged();
+ update();
+ }
+}
+
+QmlGraphicsBorderImage::TileMode QmlGraphicsBorderImage::verticalTileMode() const
+{
+ Q_D(const QmlGraphicsBorderImage);
+ return d->verticalTileMode;
+}
+
+void QmlGraphicsBorderImage::setVerticalTileMode(TileMode t)
+{
+ Q_D(QmlGraphicsBorderImage);
+ if (t != d->verticalTileMode) {
+ d->verticalTileMode = t;
+ emit verticalTileModeChanged();
+ update();
+ }
+}
+
+void QmlGraphicsBorderImage::setGridScaledImage(const QmlGraphicsGridScaledImage& sci)
+{
+ Q_D(QmlGraphicsBorderImage);
+ if (!sci.isValid()) {
+ d->status = Error;
+ emit statusChanged(d->status);
+ } else {
+ QmlGraphicsScaleGrid *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()));
+ QmlPixmapReply::Status status = QmlPixmapCache::get(d->sciurl, &d->pix);
+ if (status != QmlPixmapReply::Ready && status != QmlPixmapReply::Error) {
+ QmlPixmapReply *reply = QmlPixmapCache::request(qmlEngine(this), d->sciurl);
+ d->sciPendingPixmapCache = true;
+ connect(reply, SIGNAL(finished()), this, SLOT(requestFinished()));
+ connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
+ this, SLOT(requestProgress(qint64,qint64)));
+ } else {
+ //### should be unified with requestFinished
+ setImplicitWidth(d->pix.width());
+ setImplicitHeight(d->pix.height());
+
+ if (d->pix.isNull())
+ d->status = Error;
+ if (d->status == Loading)
+ d->status = Ready;
+ d->progress = 1.0;
+ emit statusChanged(d->status);
+ emit sourceChanged(d->url);
+ emit progressChanged(1.0);
+ update();
+ }
+ }
+}
+
+void QmlGraphicsBorderImage::requestFinished()
+{
+ Q_D(QmlGraphicsBorderImage);
+
+ if (d->url.path().endsWith(QLatin1String(".sci"))) {
+ d->sciPendingPixmapCache = false;
+ QmlPixmapCache::get(d->sciurl, &d->pix);
+ } else {
+ d->pendingPixmapCache = false;
+ if (QmlPixmapCache::get(d->url, &d->pix) != QmlPixmapReply::Ready)
+ d->status = Error;
+ }
+ setImplicitWidth(d->pix.width());
+ setImplicitHeight(d->pix.height());
+
+ if (d->status == Loading)
+ d->status = Ready;
+ d->progress = 1.0;
+ emit statusChanged(d->status);
+ emit sourceChanged(d->url);
+ emit progressChanged(1.0);
+ update();
+}
+
+void QmlGraphicsBorderImage::sciRequestFinished()
+{
+ Q_D(QmlGraphicsBorderImage);
+ if (d->sciReply->error() != QNetworkReply::NoError) {
+ d->status = Error;
+ d->sciReply->deleteLater();
+ d->sciReply = 0;
+ emit statusChanged(d->status);
+ } else {
+ QmlGraphicsGridScaledImage sci(d->sciReply);
+ d->sciReply->deleteLater();
+ d->sciReply = 0;
+ setGridScaledImage(sci);
+ }
+}
+
+void QmlGraphicsBorderImage::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
+{
+ Q_D(QmlGraphicsBorderImage);
+ if (d->pix.isNull())
+ return;
+
+ bool oldAA = p->testRenderHint(QPainter::Antialiasing);
+ bool oldSmooth = p->testRenderHint(QPainter::SmoothPixmapTransform);
+ if (d->smooth)
+ p->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth);
+
+ const QmlGraphicsScaleGrid *border = d->getScaleGrid();
+ QMargins margins(border->left(), border->top(), border->right(), border->bottom());
+ QTileRules rules((Qt::TileRule)d->horizontalTileMode, (Qt::TileRule)d->verticalTileMode);
+ qDrawBorderPixmap(p, QRect(0, 0, (int)d->width, (int)d->height), margins, d->pix, d->pix.rect(), margins, rules);
+ if (d->smooth) {
+ p->setRenderHint(QPainter::Antialiasing, oldAA);
+ p->setRenderHint(QPainter::SmoothPixmapTransform, oldSmooth);
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsborderimage_p.h b/src/declarative/graphicsitems/qmlgraphicsborderimage_p.h
new file mode 100644
index 0000000..cf3c518
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsborderimage_p.h
@@ -0,0 +1,103 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSBORDERIMAGE_H
+#define QMLGRAPHICSBORDERIMAGE_H
+
+#include "qmlgraphicsimagebase_p.h"
+
+#include <QtNetwork/qnetworkreply.h>
+
+QT_BEGIN_HEADER
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsScaleGrid;
+class QmlGraphicsGridScaledImage;
+class QmlGraphicsBorderImagePrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsBorderImage : public QmlGraphicsImageBase
+{
+ Q_OBJECT
+ Q_ENUMS(TileMode)
+
+ Q_PROPERTY(QmlGraphicsScaleGrid *border READ border CONSTANT)
+ Q_PROPERTY(TileMode horizontalTileMode READ horizontalTileMode WRITE setHorizontalTileMode NOTIFY horizontalTileModeChanged)
+ Q_PROPERTY(TileMode verticalTileMode READ verticalTileMode WRITE setVerticalTileMode NOTIFY verticalTileModeChanged)
+
+public:
+ QmlGraphicsBorderImage(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsBorderImage();
+
+ QmlGraphicsScaleGrid *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 paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+ void setSource(const QUrl &url);
+
+Q_SIGNALS:
+ void horizontalTileModeChanged();
+ void verticalTileModeChanged();
+
+private:
+ void setGridScaledImage(const QmlGraphicsGridScaledImage& sci);
+
+private Q_SLOTS:
+ void requestFinished();
+ void sciRequestFinished();
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsBorderImage)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsBorderImage)
+};
+
+QT_END_NAMESPACE
+QML_DECLARE_TYPE(QmlGraphicsBorderImage)
+QT_END_HEADER
+
+#endif // QMLGRAPHICSBORDERIMAGE_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsborderimage_p_p.h b/src/declarative/graphicsitems/qmlgraphicsborderimage_p_p.h
new file mode 100644
index 0000000..51ebb02
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsborderimage_p_p.h
@@ -0,0 +1,97 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSBORDERIMAGE_P_H
+#define QMLGRAPHICSBORDERIMAGE_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 "qmlgraphicsimagebase_p_p.h"
+#include "qmlgraphicsscalegrid_p_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QNetworkReply;
+class QmlGraphicsBorderImagePrivate : public QmlGraphicsImageBasePrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsBorderImage)
+
+public:
+ QmlGraphicsBorderImagePrivate()
+ : border(0), sciReply(0),
+ sciPendingPixmapCache(false),
+ horizontalTileMode(QmlGraphicsBorderImage::Stretch),
+ verticalTileMode(QmlGraphicsBorderImage::Stretch)
+ {
+ }
+
+ ~QmlGraphicsBorderImagePrivate()
+ {
+ }
+
+ QmlGraphicsScaleGrid *getScaleGrid()
+ {
+ Q_Q(QmlGraphicsBorderImage);
+ if (!border)
+ border = new QmlGraphicsScaleGrid(q);
+ return border;
+ }
+
+ QmlGraphicsScaleGrid *border;
+ QUrl sciurl;
+ QNetworkReply *sciReply;
+ bool sciPendingPixmapCache;
+ QmlGraphicsBorderImage::TileMode horizontalTileMode;
+ QmlGraphicsBorderImage::TileMode verticalTileMode;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLGRAPHICSBORDERIMAGE_P_H
diff --git a/src/declarative/graphicsitems/qmlgraphicseffects.cpp b/src/declarative/graphicsitems/qmlgraphicseffects.cpp
new file mode 100644
index 0000000..e1f5687
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicseffects.cpp
@@ -0,0 +1,183 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <qml.h>
+
+#include <QtGui/qgraphicseffect.h>
+
+QML_DECLARE_TYPE(QGraphicsEffect)
+QML_DEFINE_NOCREATE_TYPE(QGraphicsEffect)
+
+QML_DECLARE_TYPE(QGraphicsBlurEffect)
+QML_DEFINE_TYPE(Qt,4,6,Blur,QGraphicsBlurEffect)
+
+/*!
+ \qmlclass Blur QGraphicsBlurEffect
+ \brief The Blur object provides a blur effect.
+
+ A blur effect blurs the source item. This effect is useful for reducing details;
+ for example, when the a source loses focus and attention should be drawn to other
+ elements. Use blurRadius to control the level of detail and blurHint to control
+ the quality of the blur.
+
+ By default, the blur radius is 5 pixels.
+
+ \img graphicseffect-blur.png
+*/
+
+/*!
+ \qmlproperty real Blur::blurRadius
+
+ This controls how blurry an item will appear.
+
+ A smaller radius produces a sharper appearance, and a larger radius produces
+ a more blurred appearance.
+
+ The default radius is 5 pixels.
+*/
+/*!
+ \qmlproperty enumeration Blur::blurHint
+
+ Use Qt.PerformanceHint to specify a faster blur or Qt.QualityHint hint
+ to specify a higher quality blur.
+
+ If the blur radius is animated, it is recommended you use Qt.PerformanceHint.
+
+ The default hint is Qt.PerformanceHint.
+*/
+
+QML_DECLARE_TYPE(QGraphicsColorizeEffect)
+QML_DEFINE_TYPE(Qt,4,6,Colorize,QGraphicsColorizeEffect)
+
+/*!
+ \qmlclass Colorize QGraphicsColorizeEffect
+ \brief The Colorize object provides a colorize effect.
+
+ A colorize effect renders the source item with a tint of its color.
+
+ By default, the color is light blue.
+
+ \img graphicseffect-colorize.png
+*/
+
+/*!
+ \qmlproperty color Colorize::color
+ The color of the effect.
+
+ By default, the color is light blue.
+*/
+
+/*!
+ \qmlproperty real Colorize::strength
+
+ To what extent the source item is "colored". A strength of 0.0 is equal to no effect,
+ while 1.0 means full colorization. By default, the strength is 1.0.
+*/
+
+QML_DECLARE_TYPE(QGraphicsDropShadowEffect)
+QML_DEFINE_TYPE(Qt,4,6,DropShadow,QGraphicsDropShadowEffect)
+
+/*!
+ \qmlclass DropShadow QGraphicsDropShadowEffect
+ \brief The DropShadow object provides a drop shadow effect.
+
+ A drop shadow effect renders the source item with a drop shadow. The color of
+ the drop shadow can be modified using the color property. The drop
+ shadow offset can be modified using the xOffset and yOffset properties and the blur
+ radius of the drop shadow can be changed with the blurRadius property.
+
+ By default, the drop shadow is a semi-transparent dark gray shadow,
+ blurred with a radius of 1 at an offset of 8 pixels towards the lower right.
+
+ \img graphicseffect-drop-shadow.png
+*/
+
+/*!
+ \qmlproperty real DropShadow::xOffset
+ \qmlproperty real DropShadow::yOffset
+ The shadow offset in pixels.
+
+ By default, xOffset and yOffset are 8 pixels.
+*/
+
+/*!
+ \qmlproperty real DropShadow::blurRadius
+ The blur radius in pixels of the drop shadow.
+
+ Using a smaller radius results in a sharper shadow, whereas using a bigger
+ radius results in a more blurred shadow.
+
+ By default, the blur radius is 1 pixel.
+*/
+
+/*!
+ \qmlproperty color DropShadow::color
+ The color of the drop shadow.
+
+ By default, the drop color is a semi-transparent dark gray.
+*/
+
+QML_DECLARE_TYPE(QGraphicsOpacityEffect)
+QML_DEFINE_TYPE(Qt,4,6,Opacity,QGraphicsOpacityEffect)
+
+/*!
+ \qmlclass Opacity QGraphicsOpacityEffect
+ \brief The Opacity object provides an opacity effect.
+
+ An opacity effect renders the source with an opacity. This effect is useful
+ for making the source semi-transparent, similar to a fade-in/fade-out
+ sequence. The opacity can be modified using the opacity property.
+
+ By default, the opacity is 0.7.
+
+ \img graphicseffect-opacity.png
+*/
+
+/*!
+ \qmlproperty real Opacity::opacity
+ This property specifies how opaque an item should appear.
+
+ The value should be in the range of 0.0 to 1.0, where 0.0 is
+ fully transparent and 1.0 is fully opaque.
+
+ By default, the opacity is 0.7.
+*/
+
diff --git a/src/declarative/graphicsitems/qmlgraphicsevents.cpp b/src/declarative/graphicsitems/qmlgraphicsevents.cpp
new file mode 100644
index 0000000..9958dea
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsevents.cpp
@@ -0,0 +1,195 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsevents_p_p.h"
+
+QT_BEGIN_NAMESPACE
+/*!
+ \qmlclass KeyEvent QmlGraphicsKeyEvent
+ \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
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsKeyEvent
+*/
+
+/*!
+ \qmlproperty int 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 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 KeyEvent::isAutoRepeat
+
+ This property holds whether this event comes from an auto-repeating key.
+*/
+
+/*!
+ \qmlproperty int 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 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.
+*/
+
+
+/*!
+ \qmlclass MouseEvent QmlGraphicsMouseEvent
+ \brief The MouseEvent object provides information about a mouse event.
+
+ The position of the mouse can be found via the x and y properties.
+ The button that caused the event is available via the button property.
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsMouseEvent
+*/
+
+/*!
+ \qmlproperty int MouseEvent::x
+ \qmlproperty int MouseEvent::y
+
+ These properties hold the position of the mouse event.
+*/
+
+/*!
+ \qmlproperty enum 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.MidButton
+ \endlist
+*/
+
+/*!
+ \qmlproperty bool MouseEvent::wasHeld
+
+ This property is true if the mouse button has been held pressed longer the
+ threshold (800ms).
+*/
+
+/*!
+ \qmlproperty int 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.MidButton
+ \endlist
+*/
+
+/*!
+ \qmlproperty int 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
+MouseRegion {
+ onClicked: { if (mouse.button == Qt.LeftButton && mouse.modifiers & Qt.ShiftModifier) doSomething(); }
+}
+ \endqml
+*/
+
+QML_DEFINE_NOCREATE_TYPE(QmlGraphicsKeyEvent)
+QML_DEFINE_NOCREATE_TYPE(QmlGraphicsMouseEvent)
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsevents_p_p.h b/src/declarative/graphicsitems/qmlgraphicsevents_p_p.h
new file mode 100644
index 0000000..b07fd88
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsevents_p_p.h
@@ -0,0 +1,137 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSEVENTS_P_H
+#define QMLGRAPHICSEVENTS_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 <qml.h>
+
+#include <QtCore/qobject.h>
+#include <QtGui/qevent.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsKeyEvent : 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:
+ QmlGraphicsKeyEvent(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); }
+ QmlGraphicsKeyEvent(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;
+};
+
+class QmlGraphicsMouseEvent : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int x READ x)
+ Q_PROPERTY(int 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:
+ QmlGraphicsMouseEvent(int x, int 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) {}
+
+ int x() const { return _x; }
+ int 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; }
+
+ bool isAccepted() { return _accepted; }
+ void setAccepted(bool accepted) { _accepted = accepted; }
+
+private:
+ int _x;
+ int _y;
+ Qt::MouseButton _button;
+ Qt::MouseButtons _buttons;
+ Qt::KeyboardModifiers _modifiers;
+ bool _wasHeld;
+ bool _isClick;
+ bool _accepted;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsKeyEvent)
+QML_DECLARE_TYPE(QmlGraphicsMouseEvent)
+
+#endif // QMLGRAPHICSEVENTS_P_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsflickable.cpp b/src/declarative/graphicsitems/qmlgraphicsflickable.cpp
new file mode 100644
index 0000000..2ff3b30
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsflickable.cpp
@@ -0,0 +1,1374 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsflickable_p.h"
+#include "qmlgraphicsflickable_p_p.h"
+
+#include <QGraphicsSceneMouseEvent>
+#include <QPointer>
+#include <QTimer>
+
+QT_BEGIN_NAMESPACE
+
+
+// FlickThreshold determines how far the "mouse" must have moved
+// before we perform a flick.
+static const int FlickThreshold = 20;
+
+// Really slow flicks can be annoying.
+static const int minimumFlickVelocity = 200;
+
+class QmlGraphicsFlickableVisibleArea : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(qreal xPosition READ xPosition NOTIFY pageChanged)
+ Q_PROPERTY(qreal yPosition READ yPosition NOTIFY pageChanged)
+ Q_PROPERTY(qreal widthRatio READ widthRatio NOTIFY pageChanged)
+ Q_PROPERTY(qreal heightRatio READ heightRatio NOTIFY pageChanged)
+
+public:
+ QmlGraphicsFlickableVisibleArea(QmlGraphicsFlickable *parent=0);
+
+ qreal xPosition() const;
+ qreal widthRatio() const;
+ qreal yPosition() const;
+ qreal heightRatio() const;
+
+ void updateVisible();
+
+signals:
+ void pageChanged();
+
+private:
+ QmlGraphicsFlickable *flickable;
+ qreal m_xPosition;
+ qreal m_widthRatio;
+ qreal m_yPosition;
+ qreal m_heightRatio;
+};
+
+QmlGraphicsFlickableVisibleArea::QmlGraphicsFlickableVisibleArea(QmlGraphicsFlickable *parent)
+ : QObject(parent), flickable(parent), m_xPosition(0.), m_widthRatio(0.)
+ , m_yPosition(0.), m_heightRatio(0.)
+{
+}
+
+qreal QmlGraphicsFlickableVisibleArea::widthRatio() const
+{
+ return m_widthRatio;
+}
+
+qreal QmlGraphicsFlickableVisibleArea::xPosition() const
+{
+ return m_xPosition;
+}
+
+qreal QmlGraphicsFlickableVisibleArea::heightRatio() const
+{
+ return m_heightRatio;
+}
+
+qreal QmlGraphicsFlickableVisibleArea::yPosition() const
+{
+ return m_yPosition;
+}
+
+void QmlGraphicsFlickableVisibleArea::updateVisible()
+{
+ QmlGraphicsFlickablePrivate *p = static_cast<QmlGraphicsFlickablePrivate *>(QGraphicsItemPrivate::get(flickable));
+ bool pageChange = false;
+
+ // Vertical
+ const qreal viewheight = flickable->height();
+ const qreal maxyextent = -flickable->maxYExtent() + flickable->minYExtent();
+ qreal pagePos = (-p->_moveY.value() + flickable->minYExtent()) / (maxyextent + viewheight);
+ qreal pageSize = viewheight / (maxyextent + viewheight);
+
+ if (pageSize != m_heightRatio) {
+ m_heightRatio = pageSize;
+ pageChange = true;
+ }
+ if (pagePos != m_yPosition) {
+ m_yPosition = pagePos;
+ pageChange = true;
+ }
+
+ // Horizontal
+ const qreal viewwidth = flickable->width();
+ const qreal maxxextent = -flickable->maxXExtent() + flickable->minXExtent();
+ pagePos = (-p->_moveX.value() + flickable->minXExtent()) / (maxxextent + viewwidth);
+ pageSize = viewwidth / (maxxextent + viewwidth);
+
+ if (pageSize != m_widthRatio) {
+ m_widthRatio = pageSize;
+ pageChange = true;
+ }
+ if (pagePos != m_xPosition) {
+ m_xPosition = pagePos;
+ pageChange = true;
+ }
+ if (pageChange)
+ emit pageChanged();
+}
+
+
+QmlGraphicsFlickablePrivate::QmlGraphicsFlickablePrivate()
+ : viewport(new QmlGraphicsItem)
+ , _moveX(this, &QmlGraphicsFlickablePrivate::setRoundedViewportX)
+ , _moveY(this, &QmlGraphicsFlickablePrivate::setRoundedViewportY)
+ , vWidth(-1), vHeight(-1), overShoot(true), flicked(false), moving(false), stealMouse(false)
+ , pressed(false), atXEnd(false), atXBeginning(true), atYEnd(false), atYBeginning(true)
+ , interactive(true), deceleration(500), maxVelocity(2000), reportedVelocitySmoothing(100)
+ , delayedPressEvent(0), delayedPressTarget(0), pressDelay(0), fixupDuration(200)
+ , horizontalVelocity(this), verticalVelocity(this), vTime(0), visibleArea(0)
+ , flickDirection(QmlGraphicsFlickable::AutoFlickDirection)
+{
+ fixupXEvent = QmlTimeLineEvent::timeLineEvent<QmlGraphicsFlickablePrivate, &QmlGraphicsFlickablePrivate::fixupX>(&_moveX, this);
+ fixupYEvent = QmlTimeLineEvent::timeLineEvent<QmlGraphicsFlickablePrivate, &QmlGraphicsFlickablePrivate::fixupY>(&_moveY, this);
+}
+
+void QmlGraphicsFlickablePrivate::init()
+{
+ Q_Q(QmlGraphicsFlickable);
+ viewport->setParent(q);
+ QObject::connect(&timeline, SIGNAL(updated()), q, SLOT(ticked()));
+ QObject::connect(&timeline, SIGNAL(completed()), q, SLOT(movementEnding()));
+ q->setAcceptedMouseButtons(Qt::LeftButton);
+ q->setFiltersChildEvents(true);
+ QObject::connect(viewport, SIGNAL(xChanged()), q, SIGNAL(positionXChanged()));
+ QObject::connect(viewport, SIGNAL(yChanged()), q, SIGNAL(positionYChanged()));
+ QObject::connect(q, SIGNAL(heightChanged()), q, SLOT(heightChange()));
+ QObject::connect(q, SIGNAL(widthChanged()), q, SLOT(widthChange()));
+}
+
+void QmlGraphicsFlickablePrivate::flickX(qreal velocity)
+{
+ Q_Q(QmlGraphicsFlickable);
+ qreal maxDistance = -1;
+ // -ve velocity means list is moving up
+ if (velocity > 0) {
+ const qreal minX = q->minXExtent();
+ if (_moveX.value() < minX)
+ maxDistance = qAbs(minX -_moveX.value() + (overShoot?30:0));
+ flickTargetX = minX;
+ } else {
+ const qreal maxX = q->maxXExtent();
+ if (_moveX.value() > maxX)
+ maxDistance = qAbs(maxX - _moveX.value()) + (overShoot?30:0);
+ flickTargetX = maxX;
+ }
+ if (maxDistance > 0) {
+ qreal v = velocity;
+ if (maxVelocity != -1 && maxVelocity < qAbs(v)) {
+ if (v < 0)
+ v = -maxVelocity;
+ else
+ v = maxVelocity;
+ }
+ timeline.reset(_moveX);
+ timeline.accel(_moveX, v, deceleration, maxDistance);
+ timeline.execute(fixupXEvent);
+ if (!flicked) {
+ flicked = true;
+ emit q->flickingChanged();
+ emit q->flickStarted();
+ }
+ } else {
+ timeline.reset(_moveX);
+ fixupX();
+ }
+}
+
+void QmlGraphicsFlickablePrivate::flickY(qreal velocity)
+{
+ Q_Q(QmlGraphicsFlickable);
+ qreal maxDistance = -1;
+ // -ve velocity means list is moving up
+ if (velocity > 0) {
+ const qreal minY = q->minYExtent();
+ if (_moveY.value() < minY)
+ maxDistance = qAbs(minY -_moveY.value() + (overShoot?30:0));
+ flickTargetY = minY;
+ } else {
+ const qreal maxY = q->maxYExtent();
+ if (_moveY.value() > maxY)
+ maxDistance = qAbs(maxY - _moveY.value()) + (overShoot?30:0);
+ flickTargetY = maxY;
+ }
+ if (maxDistance > 0) {
+ qreal v = velocity;
+ if (maxVelocity != -1 && maxVelocity < qAbs(v)) {
+ if (v < 0)
+ v = -maxVelocity;
+ else
+ v = maxVelocity;
+ }
+ timeline.reset(_moveY);
+ timeline.accel(_moveY, v, deceleration, maxDistance);
+ timeline.execute(fixupYEvent);
+ if (!flicked) {
+ flicked = true;
+ emit q->flickingChanged();
+ emit q->flickStarted();
+ }
+ } else {
+ timeline.reset(_moveY);
+ fixupY();
+ }
+}
+
+void QmlGraphicsFlickablePrivate::fixupX()
+{
+ Q_Q(QmlGraphicsFlickable);
+ if (!q->xflick() || _moveX.timeLine())
+ return;
+
+ if (_moveX.value() > q->minXExtent() || (q->maxXExtent() > q->minXExtent())) {
+ timeline.reset(_moveX);
+ if (_moveX.value() != q->minXExtent()) {
+ if (fixupDuration)
+ timeline.move(_moveX, q->minXExtent(), QEasingCurve(QEasingCurve::InOutQuad), fixupDuration);
+ else
+ _moveY.setValue(q->minYExtent());
+ }
+ //emit flickingChanged();
+ } else if (_moveX.value() < q->maxXExtent()) {
+ timeline.reset(_moveX);
+ if (fixupDuration)
+ timeline.move(_moveX, q->maxXExtent(), QEasingCurve(QEasingCurve::InOutQuad), fixupDuration);
+ else
+ _moveY.setValue(q->maxYExtent());
+ //emit flickingChanged();
+ } else {
+ flicked = false;
+ }
+
+ vTime = timeline.time();
+}
+
+void QmlGraphicsFlickablePrivate::fixupY()
+{
+ Q_Q(QmlGraphicsFlickable);
+ if (!q->yflick() || _moveY.timeLine())
+ return;
+
+ if (_moveY.value() > q->minYExtent() || (q->maxYExtent() > q->minYExtent())) {
+ timeline.reset(_moveY);
+ if (_moveY.value() != q->minYExtent()) {
+ if (fixupDuration)
+ timeline.move(_moveY, q->minYExtent(), QEasingCurve(QEasingCurve::InOutQuad), fixupDuration);
+ else
+ _moveY.setValue(q->minYExtent());
+ }
+ //emit flickingChanged();
+ } else if (_moveY.value() < q->maxYExtent()) {
+ timeline.reset(_moveY);
+ if (fixupDuration)
+ timeline.move(_moveY, q->maxYExtent(), QEasingCurve(QEasingCurve::InOutQuad), fixupDuration);
+ else
+ _moveY.setValue(q->maxYExtent());
+ //emit flickingChanged();
+ } else {
+ flicked = false;
+ }
+
+ vTime = timeline.time();
+}
+
+void QmlGraphicsFlickablePrivate::updateBeginningEnd()
+{
+ Q_Q(QmlGraphicsFlickable);
+ bool atBoundaryChange = false;
+
+ // Vertical
+ const int maxyextent = int(-q->maxYExtent());
+ const qreal ypos = -_moveY.value();
+ bool atBeginning = (ypos <= -q->minYExtent());
+ bool atEnd = (maxyextent <= ypos);
+
+ if (atBeginning != atYBeginning) {
+ atYBeginning = atBeginning;
+ atBoundaryChange = true;
+ }
+ if (atEnd != atYEnd) {
+ atYEnd = atEnd;
+ atBoundaryChange = true;
+ }
+
+ // Horizontal
+ const int maxxextent = int(-q->maxXExtent());
+ const qreal xpos = -_moveX.value();
+ atBeginning = (xpos <= -q->minXExtent());
+ atEnd = (maxxextent <= xpos);
+
+ if (atBeginning != atXBeginning) {
+ atXBeginning = atBeginning;
+ atBoundaryChange = true;
+ }
+ if (atEnd != atXEnd) {
+ atXEnd = atEnd;
+ atBoundaryChange = true;
+ }
+
+ if (atBoundaryChange)
+ emit q->isAtBoundaryChanged();
+
+ if (visibleArea)
+ visibleArea->updateVisible();
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Flickable,QmlGraphicsFlickable)
+
+/*!
+ \qmlclass Flickable QmlGraphicsFlickable
+ \brief The Flickable item provides a surface that can be "flicked".
+ \inherits Item
+
+ Flickable places its children on a surface that can be dragged and flicked.
+
+ \code
+ Flickable {
+ width: 200; height: 200; viewportWidth: image.width; viewportHeight: image.height
+ Image { id: image; source: "bigimage.png" }
+ }
+ \endcode
+
+ \image flickable.gif
+
+ \note Flickable does not automatically clip its contents. If
+ it is not full-screen it is likely that \c clip should be set
+ to true.
+
+ \note Due to an implementation detail items placed inside a flickable cannot anchor to it by
+ id, use 'parent' instead.
+*/
+
+/*!
+ \qmlsignal Flickable::onMovementStarted()
+
+ This handler is called when the view begins moving due to user
+ interaction.
+*/
+
+/*!
+ \qmlsignal 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 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 Flickable::onFlickEnded()
+
+ This handler is called when the view stops moving due to a flick.
+*/
+
+/*!
+ \qmlproperty real Flickable::visibleArea.xPosition
+ \qmlproperty real Flickable::visibleArea.widthRatio
+ \qmlproperty real Flickable::visibleArea.yPosition
+ \qmlproperty real 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 in the range 0.0 (beginning) to
+ size ratio (end), i.e. yPosition is in the range 0.0 - heightRatio.
+
+ These properties are typically used to draw a scrollbar, for example:
+ \code
+ Rectangle {
+ opacity: 0.5; anchors.right: MyListView.right-2; width: 6
+ y: MyListView.visibleArea.yPosition * MyListView.height
+ height: MyListView.visibleArea.heightRatio * MyListView.height
+ }
+ \endcode
+*/
+
+QmlGraphicsFlickable::QmlGraphicsFlickable(QmlGraphicsItem *parent)
+ : QmlGraphicsItem(*(new QmlGraphicsFlickablePrivate), parent)
+{
+ Q_D(QmlGraphicsFlickable);
+ d->init();
+}
+
+QmlGraphicsFlickable::QmlGraphicsFlickable(QmlGraphicsFlickablePrivate &dd, QmlGraphicsItem *parent)
+ : QmlGraphicsItem(dd, parent)
+{
+ Q_D(QmlGraphicsFlickable);
+ d->init();
+}
+
+QmlGraphicsFlickable::~QmlGraphicsFlickable()
+{
+}
+
+/*!
+ \qmlproperty int Flickable::viewportX
+ \qmlproperty int Flickable::viewportY
+
+ 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 yPosition will be 100.
+*/
+qreal QmlGraphicsFlickable::viewportX() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return -d->_moveX.value();
+}
+
+void QmlGraphicsFlickable::setViewportX(qreal pos)
+{
+ Q_D(QmlGraphicsFlickable);
+ pos = qRound(pos);
+ d->timeline.reset(d->_moveX);
+ d->vTime = d->timeline.time();
+ if (-pos != d->_moveX.value()) {
+ d->_moveX.setValue(-pos);
+ viewportMoved();
+ }
+}
+
+qreal QmlGraphicsFlickable::viewportY() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return -d->_moveY.value();
+}
+
+void QmlGraphicsFlickable::setViewportY(qreal pos)
+{
+ Q_D(QmlGraphicsFlickable);
+ pos = qRound(pos);
+ d->timeline.reset(d->_moveY);
+ d->vTime = d->timeline.time();
+ if (-pos != d->_moveY.value()) {
+ d->_moveY.setValue(-pos);
+ viewportMoved();
+ }
+}
+
+/*!
+ \qmlproperty bool Flickable::interactive
+
+ A user cannot drag or flick a Flickable that is not interactive.
+
+ 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 viewing detailed information on a location popup that is a child of the Flickable.
+*/
+bool QmlGraphicsFlickable::isInteractive() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->interactive;
+}
+
+void QmlGraphicsFlickable::setInteractive(bool interactive)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (interactive != d->interactive) {
+ d->interactive = interactive;
+ if (!interactive && d->flicked) {
+ d->timeline.clear();
+ d->vTime = d->timeline.time();
+ d->flicked = false;
+ emit flickingChanged();
+ emit flickEnded();
+ }
+ emit interactiveChanged();
+ }
+}
+
+/*!
+ \qmlproperty real Flickable::horizontalVelocity
+ \qmlproperty real Flickable::verticalVelocity
+ \qmlproperty real Flickable::reportedVelocitySmoothing
+
+ The instantaneous velocity of movement along the x and y axes, in pixels/sec.
+
+ The reported velocity is smoothed to avoid erratic output.
+ reportedVelocitySmoothing determines how much smoothing is applied.
+*/
+qreal QmlGraphicsFlickable::horizontalVelocity() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->horizontalVelocity.value();
+}
+
+qreal QmlGraphicsFlickable::verticalVelocity() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->verticalVelocity.value();
+}
+
+/*!
+ \qmlproperty bool Flickable::atXBeginning
+ \qmlproperty bool Flickable::atXEnd
+ \qmlproperty bool Flickable::atYBeginning
+ \qmlproperty bool Flickable::atYEnd
+
+ These properties are true if the flickable view is positioned at the beginning,
+ or end respecively.
+*/
+bool QmlGraphicsFlickable::isAtXEnd() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->atXEnd;
+}
+
+bool QmlGraphicsFlickable::isAtXBeginning() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->atXBeginning;
+}
+
+bool QmlGraphicsFlickable::isAtYEnd() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->atYEnd;
+}
+
+bool QmlGraphicsFlickable::isAtYBeginning() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->atYBeginning;
+}
+
+void QmlGraphicsFlickable::ticked()
+{
+ viewportMoved();
+}
+
+QmlGraphicsItem *QmlGraphicsFlickable::viewport()
+{
+ Q_D(QmlGraphicsFlickable);
+ return d->viewport;
+}
+
+QmlGraphicsFlickableVisibleArea *QmlGraphicsFlickable::visibleArea()
+{
+ Q_D(QmlGraphicsFlickable);
+ if (!d->visibleArea)
+ d->visibleArea = new QmlGraphicsFlickableVisibleArea(this);
+ return d->visibleArea;
+}
+
+/*!
+ \qmlproperty enumeration Flickable::flickDirection
+
+ This property determines which directions the view can be flicked.
+
+ \list
+ \o AutoFlickDirection (default) - allows flicking vertically if the
+ \e viewportHeight is not equal to the \e height of the Flickable.
+ Allows flicking horizontally if the \e viewportWidth is not equal
+ to the \e width of the Flickable.
+ \o HorizontalFlick - allows flicking horizontally.
+ \o VerticalFlick - allows flicking vertically.
+ \o HorizontalAndVerticalFlick - allows flicking in both directions.
+ \endlist
+*/
+QmlGraphicsFlickable::FlickDirection QmlGraphicsFlickable::flickDirection() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->flickDirection;
+}
+
+void QmlGraphicsFlickable::setFlickDirection(FlickDirection direction)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (direction != d->flickDirection) {
+ d->flickDirection = direction;
+ emit flickDirectionChanged();
+ }
+}
+
+void QmlGraphicsFlickablePrivate::handleMousePressEvent(QGraphicsSceneMouseEvent *event)
+{
+ if (interactive && timeline.isActive() && (qAbs(velocityX) > 10 || qAbs(velocityY) > 10))
+ stealMouse = true; // If we've been flicked then steal the click.
+ else
+ stealMouse = false;
+ pressed = true;
+ timeline.clear();
+ velocityX = 0;
+ velocityY = 0;
+ lastPos = QPoint();
+ QmlGraphicsItemPrivate::start(lastPosTime);
+ pressPos = event->pos();
+ pressX = _moveX.value();
+ pressY = _moveY.value();
+ flicked = false;
+ QmlGraphicsItemPrivate::start(pressTime);
+ QmlGraphicsItemPrivate::start(velocityTime);
+}
+
+void QmlGraphicsFlickablePrivate::handleMouseMoveEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_Q(QmlGraphicsFlickable);
+ if (!interactive || lastPosTime.isNull())
+ return;
+ bool rejectY = false;
+ bool rejectX = false;
+ bool moved = false;
+
+ if (q->yflick()) {
+ int dy = int(event->pos().y() - pressPos.y());
+ if (qAbs(dy) > QApplication::startDragDistance() || QmlGraphicsItemPrivate::elapsed(pressTime) > 200) {
+ qreal newY = dy + pressY;
+ const qreal minY = q->minYExtent();
+ const qreal maxY = q->maxYExtent();
+ if (newY > minY)
+ newY = minY + (newY - minY) / 2;
+ if (newY < maxY && maxY - minY <= 0)
+ newY = maxY + (newY - maxY) / 2;
+ if (!q->overShoot() && (newY > minY || newY < maxY)) {
+ if (newY > minY)
+ newY = minY;
+ else if (newY < maxY)
+ newY = maxY;
+ else
+ rejectY = true;
+ }
+ if (!rejectY) {
+ _moveY.setValue(newY);
+ moved = true;
+ }
+ if (qAbs(dy) > QApplication::startDragDistance())
+ stealMouse = true;
+ }
+ }
+
+ if (q->xflick()) {
+ int dx = int(event->pos().x() - pressPos.x());
+ if (qAbs(dx) > QApplication::startDragDistance() || QmlGraphicsItemPrivate::elapsed(pressTime) > 200) {
+ qreal newX = dx + pressX;
+ const qreal minX = q->minXExtent();
+ const qreal maxX = q->maxXExtent();
+ if (newX > minX)
+ newX = minX + (newX - minX) / 2;
+ if (newX < maxX && maxX - minX <= 0)
+ newX = maxX + (newX - maxX) / 2;
+ if (!q->overShoot() && (newX > minX || newX < maxX)) {
+ if (newX > minX)
+ newX = minX;
+ else if (newX < maxX)
+ newX = maxX;
+ else
+ rejectX = true;
+ }
+ if (!rejectX) {
+ _moveX.setValue(newX);
+ moved = true;
+ }
+
+ if (qAbs(dx) > QApplication::startDragDistance())
+ stealMouse = true;
+ }
+ }
+
+ if (!lastPos.isNull()) {
+ qreal elapsed = qreal(QmlGraphicsItemPrivate::restart(lastPosTime)) / 1000.;
+ if (elapsed <= 0)
+ elapsed = 1;
+ if (q->yflick()) {
+ qreal diff = event->pos().y() - lastPos.y();
+ // average to reduce the effect of spurious moves
+ velocityY += diff / elapsed;
+ velocityY /= 2;
+ }
+
+ if (q->xflick()) {
+ qreal diff = event->pos().x() - lastPos.x();
+ // average to reduce the effect of spurious moves
+ velocityX += diff / elapsed;
+ velocityX /= 2;
+ }
+ }
+
+ if (rejectY) velocityY = 0;
+ if (rejectX) velocityX = 0;
+
+ if (moved) {
+ q->movementStarting();
+ q->viewportMoved();
+ }
+
+ lastPos = event->pos();
+}
+
+void QmlGraphicsFlickablePrivate::handleMouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_Q(QmlGraphicsFlickable);
+ pressed = false;
+ if (lastPosTime.isNull())
+ return;
+
+ if (QmlGraphicsItemPrivate::elapsed(lastPosTime) > 100) {
+ // if we drag then pause before release we should not cause a flick.
+ velocityX = 0.0;
+ velocityY = 0.0;
+ }
+
+ vTime = timeline.time();
+ if (qAbs(velocityY) > 10 && qAbs(event->pos().y() - pressPos.y()) > FlickThreshold) {
+ qreal velocity = velocityY;
+ if (qAbs(velocity) < minimumFlickVelocity) // Minimum velocity to avoid annoyingly slow flicks.
+ velocity = velocity < 0 ? -minimumFlickVelocity : minimumFlickVelocity;
+ flickY(velocity);
+ } else {
+ fixupY();
+ }
+
+ if (qAbs(velocityX) > 10 && qAbs(event->pos().x() - pressPos.x()) > FlickThreshold) {
+ qreal velocity = velocityX;
+ if (qAbs(velocity) < minimumFlickVelocity) // Minimum velocity to avoid annoyingly slow flicks.
+ velocity = velocity < 0 ? -minimumFlickVelocity : minimumFlickVelocity;
+ flickX(velocity);
+ } else {
+ fixupX();
+ }
+
+ stealMouse = false;
+ lastPosTime = QTime();
+
+ if (!timeline.isActive())
+ q->movementEnding();
+}
+
+void QmlGraphicsFlickable::mousePressEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (d->interactive) {
+ d->handleMousePressEvent(event);
+ event->accept();
+ } else {
+ QmlGraphicsItem::mousePressEvent(event);
+ }
+}
+
+void QmlGraphicsFlickable::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (d->interactive) {
+ d->handleMouseMoveEvent(event);
+ event->accept();
+ } else {
+ QmlGraphicsItem::mouseMoveEvent(event);
+ }
+}
+
+void QmlGraphicsFlickable::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (d->interactive) {
+ d->clearDelayedPress();
+ d->handleMouseReleaseEvent(event);
+ event->accept();
+ ungrabMouse();
+ } else {
+ QmlGraphicsItem::mouseReleaseEvent(event);
+ }
+}
+
+void QmlGraphicsFlickable::wheelEvent(QGraphicsSceneWheelEvent *event)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (!d->interactive) {
+ QmlGraphicsItem::wheelEvent(event);
+ } else if (yflick()) {
+ if (event->delta() > 0)
+ d->velocityY = qMax(event->delta() - d->verticalVelocity.value(), qreal(250.0));
+ else
+ d->velocityY = qMin(event->delta() - d->verticalVelocity.value(), qreal(-250.0));
+ d->flicked = false;
+ d->flickY(d->velocityY);
+ event->accept();
+ } else if (xflick()) {
+ if (event->delta() > 0)
+ d->velocityX = qMax(event->delta() - d->horizontalVelocity.value(), qreal(250.0));
+ else
+ d->velocityX = qMin(event->delta() - d->horizontalVelocity.value(), qreal(-250.0));
+ d->flicked = false;
+ d->flickX(d->velocityX);
+ event->accept();
+ } else {
+ QmlGraphicsItem::wheelEvent(event);
+ }
+}
+
+void QmlGraphicsFlickablePrivate::captureDelayedPress(QGraphicsSceneMouseEvent *event)
+{
+ Q_Q(QmlGraphicsFlickable);
+ if (!q->scene() || pressDelay <= 0)
+ return;
+ delayedPressTarget = q->scene()->mouseGrabberItem();
+ delayedPressEvent = new QGraphicsSceneMouseEvent(event->type());
+ delayedPressEvent->setAccepted(false);
+ for (int i = 0x1; i <= 0x10; i <<= 1) {
+ if (event->buttons() & i) {
+ Qt::MouseButton button = Qt::MouseButton(i);
+ delayedPressEvent->setButtonDownPos(button, event->buttonDownPos(button));
+ delayedPressEvent->setButtonDownScenePos(button, event->buttonDownScenePos(button));
+ delayedPressEvent->setButtonDownScreenPos(button, event->buttonDownScreenPos(button));
+ }
+ }
+ delayedPressEvent->setButtons(event->buttons());
+ delayedPressEvent->setButton(event->button());
+ delayedPressEvent->setPos(event->pos());
+ delayedPressEvent->setScenePos(event->scenePos());
+ delayedPressEvent->setScreenPos(event->screenPos());
+ delayedPressEvent->setLastPos(event->lastPos());
+ delayedPressEvent->setLastScenePos(event->lastScenePos());
+ delayedPressEvent->setLastScreenPos(event->lastScreenPos());
+ delayedPressEvent->setModifiers(event->modifiers());
+ delayedPressTimer.start(pressDelay, q);
+}
+
+void QmlGraphicsFlickablePrivate::clearDelayedPress()
+{
+ if (delayedPressEvent) {
+ delayedPressTimer.stop();
+ delete delayedPressEvent;
+ delayedPressEvent = 0;
+ }
+}
+
+void QmlGraphicsFlickablePrivate::setRoundedViewportX(qreal x)
+{
+ viewport->setX(qRound(x));
+}
+
+void QmlGraphicsFlickablePrivate::setRoundedViewportY(qreal y)
+{
+ viewport->setY(qRound(y));
+}
+
+void QmlGraphicsFlickable::timerEvent(QTimerEvent *event)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (event->timerId() == d->delayedPressTimer.timerId()) {
+ d->delayedPressTimer.stop();
+ if (d->delayedPressEvent) {
+ QmlGraphicsItem *grabber = scene() ? qobject_cast<QmlGraphicsItem*>(scene()->mouseGrabberItem()) : 0;
+ if (!grabber || grabber != this)
+ scene()->sendEvent(d->delayedPressTarget, d->delayedPressEvent);
+ delete d->delayedPressEvent;
+ d->delayedPressEvent = 0;
+ }
+ }
+}
+
+qreal QmlGraphicsFlickable::minYExtent() const
+{
+ return 0.0;
+}
+
+qreal QmlGraphicsFlickable::minXExtent() const
+{
+ return 0.0;
+}
+
+/* returns -ve */
+qreal QmlGraphicsFlickable::maxXExtent() const
+{
+ return width() - vWidth();
+}
+/* returns -ve */
+qreal QmlGraphicsFlickable::maxYExtent() const
+{
+ return height() - vHeight();
+}
+
+void QmlGraphicsFlickable::viewportMoved()
+{
+ Q_D(QmlGraphicsFlickable);
+
+ int elapsed = QmlGraphicsItemPrivate::restart(d->velocityTime);
+ if (!elapsed)
+ return;
+
+ qreal prevY = d->lastFlickablePosition.x();
+ qreal prevX = d->lastFlickablePosition.y();
+ d->velocityTimeline.clear();
+ if (d->pressed) {
+ qreal horizontalVelocity = (prevX - d->_moveX.value()) * 1000 / elapsed;
+ qreal verticalVelocity = (prevY - d->_moveY.value()) * 1000 / elapsed;
+ d->velocityTimeline.move(d->horizontalVelocity, horizontalVelocity, d->reportedVelocitySmoothing);
+ d->velocityTimeline.move(d->horizontalVelocity, 0, d->reportedVelocitySmoothing);
+ d->velocityTimeline.move(d->verticalVelocity, verticalVelocity, d->reportedVelocitySmoothing);
+ d->velocityTimeline.move(d->verticalVelocity, 0, d->reportedVelocitySmoothing);
+ } else {
+ if (d->timeline.time() > d->vTime) {
+ qreal horizontalVelocity = (prevX - d->_moveX.value()) * 1000 / (d->timeline.time() - d->vTime);
+ qreal verticalVelocity = (prevY - d->_moveY.value()) * 1000 / (d->timeline.time() - d->vTime);
+ d->horizontalVelocity.setValue(horizontalVelocity);
+ d->verticalVelocity.setValue(verticalVelocity);
+ }
+ }
+
+ d->lastFlickablePosition = QPointF(d->_moveY.value(), d->_moveX.value());
+
+ d->vTime = d->timeline.time();
+ d->updateBeginningEnd();
+}
+
+void QmlGraphicsFlickable::cancelFlick()
+{
+ Q_D(QmlGraphicsFlickable);
+ d->timeline.reset(d->_moveX);
+ d->timeline.reset(d->_moveY);
+ movementEnding();
+}
+
+void QmlGraphicsFlickablePrivate::data_removeAt(int)
+{
+ // ###
+}
+
+int QmlGraphicsFlickablePrivate::data_count() const
+{
+ // ###
+ return 0;
+}
+
+void QmlGraphicsFlickablePrivate::data_append(QObject *o)
+{
+ Q_Q(QmlGraphicsFlickable);
+ QmlGraphicsItem *i = qobject_cast<QmlGraphicsItem *>(o);
+ if (i)
+ viewport->fxChildren()->append(i);
+ else
+ o->setParent(q);
+}
+
+void QmlGraphicsFlickablePrivate::data_insert(int, QObject *)
+{
+ // ###
+}
+
+QObject *QmlGraphicsFlickablePrivate::data_at(int) const
+{
+ // ###
+ return 0;
+}
+
+void QmlGraphicsFlickablePrivate::data_clear()
+{
+ // ###
+}
+
+
+QmlList<QObject *> *QmlGraphicsFlickable::flickableData()
+{
+ Q_D(QmlGraphicsFlickable);
+ return &d->data;
+}
+
+QmlList<QmlGraphicsItem *> *QmlGraphicsFlickable::flickableChildren()
+{
+ Q_D(QmlGraphicsFlickable);
+ return d->viewport->fxChildren();
+}
+
+/*!
+ \qmlproperty bool Flickable::overShoot
+ This property holds the number of pixels the surface may overshoot the
+ Flickable's boundaries when flicked.
+
+ If overShoot is non-zero the contents can be flicked beyond the boundary
+ of the Flickable before being moved back to the boundary. This provides
+ the feeling that the edges of the view are soft, rather than a hard
+ physical boundary.
+*/
+bool QmlGraphicsFlickable::overShoot() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->overShoot;
+}
+
+void QmlGraphicsFlickable::setOverShoot(bool o)
+{
+ Q_D(QmlGraphicsFlickable);
+ d->overShoot = o;
+}
+
+/*!
+ \qmlproperty int Flickable::viewportWidth
+ \qmlproperty int Flickable::viewportHeight
+
+ The dimensions of the viewport (the surface controlled by Flickable). Typically this
+ should be set to the combined size of the items placed in the Flickable.
+
+ \code
+ Flickable {
+ width: 320; height: 480; viewportWidth: image.width; viewportHeight: image.height
+ Image { id: image; source: "bigimage.png" }
+ }
+ \endcode
+*/
+qreal QmlGraphicsFlickable::viewportWidth() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->vWidth;
+}
+
+void QmlGraphicsFlickable::setViewportWidth(qreal w)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (d->vWidth == w)
+ return;
+ d->vWidth = w;
+ if (w < 0)
+ d->viewport->setWidth(width());
+ else
+ d->viewport->setWidth(w);
+ // Make sure that we're entirely in view.
+ if (!d->pressed)
+ d->fixupX();
+ emit viewportWidthChanged();
+ d->updateBeginningEnd();
+}
+
+void QmlGraphicsFlickable::widthChange()
+{
+ Q_D(QmlGraphicsFlickable);
+ if (d->vWidth < 0) {
+ d->viewport->setWidth(width());
+ emit viewportWidthChanged();
+ }
+ d->updateBeginningEnd();
+}
+
+void QmlGraphicsFlickable::heightChange()
+{
+ Q_D(QmlGraphicsFlickable);
+ if (d->vHeight < 0) {
+ d->viewport->setHeight(height());
+ emit viewportHeightChanged();
+ }
+ d->updateBeginningEnd();
+}
+
+qreal QmlGraphicsFlickable::viewportHeight() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->vHeight;
+}
+
+void QmlGraphicsFlickable::setViewportHeight(qreal h)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (d->vHeight == h)
+ return;
+ d->vHeight = h;
+ if (h < 0)
+ d->viewport->setHeight(height());
+ else
+ d->viewport->setHeight(h);
+ // Make sure that we're entirely in view.
+ if (!d->pressed)
+ d->fixupY();
+ emit viewportHeightChanged();
+ d->updateBeginningEnd();
+}
+
+qreal QmlGraphicsFlickable::vWidth() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ if (d->vWidth < 0)
+ return width();
+ else
+ return d->vWidth;
+}
+
+qreal QmlGraphicsFlickable::vHeight() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ if (d->vHeight < 0)
+ return height();
+ else
+ return d->vHeight;
+}
+
+bool QmlGraphicsFlickable::xflick() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ if (d->flickDirection == QmlGraphicsFlickable::AutoFlickDirection)
+ return vWidth() != width();
+ return d->flickDirection & QmlGraphicsFlickable::HorizontalFlick;
+}
+
+bool QmlGraphicsFlickable::yflick() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ if (d->flickDirection == QmlGraphicsFlickable::AutoFlickDirection)
+ return vHeight() != height();
+ return d->flickDirection & QmlGraphicsFlickable::VerticalFlick;
+}
+
+bool QmlGraphicsFlickable::sendMouseEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsFlickable);
+ QGraphicsSceneMouseEvent mouseEvent(event->type());
+ QRectF myRect = mapToScene(QRectF(0, 0, width(), height())).boundingRect();
+
+ QGraphicsScene *s = scene();
+ QmlGraphicsItem *grabber = s ? qobject_cast<QmlGraphicsItem*>(s->mouseGrabberItem()) : 0;
+ if ((d->stealMouse || myRect.contains(event->scenePos().toPoint())) && (!grabber || !grabber->keepMouseGrab())) {
+ mouseEvent.setAccepted(false);
+ for (int i = 0x1; i <= 0x10; i <<= 1) {
+ if (event->buttons() & i) {
+ Qt::MouseButton button = Qt::MouseButton(i);
+ mouseEvent.setButtonDownPos(button, mapFromScene(event->buttonDownPos(button)));
+ }
+ }
+ mouseEvent.setScenePos(event->scenePos());
+ mouseEvent.setLastScenePos(event->lastScenePos());
+ mouseEvent.setPos(mapFromScene(event->scenePos()));
+ mouseEvent.setLastPos(mapFromScene(event->lastScenePos()));
+
+ switch(mouseEvent.type()) {
+ case QEvent::GraphicsSceneMouseMove:
+ d->handleMouseMoveEvent(&mouseEvent);
+ break;
+ case QEvent::GraphicsSceneMousePress:
+ if (d->delayedPressEvent)
+ return false;
+
+ d->handleMousePressEvent(&mouseEvent);
+ d->captureDelayedPress(event);
+ break;
+ case QEvent::GraphicsSceneMouseRelease:
+ if (d->delayedPressEvent) {
+ scene()->sendEvent(d->delayedPressTarget, d->delayedPressEvent);
+ d->clearDelayedPress();
+ }
+ d->handleMouseReleaseEvent(&mouseEvent);
+ break;
+ default:
+ break;
+ }
+ grabber = qobject_cast<QmlGraphicsItem*>(s->mouseGrabberItem());
+ if (grabber && d->stealMouse && !grabber->keepMouseGrab() && grabber != this) {
+ d->clearDelayedPress();
+ grabMouse();
+ }
+
+ return d->stealMouse || d->delayedPressEvent;
+ } else if (!d->lastPosTime.isNull()) {
+ d->lastPosTime = QTime();
+ }
+ if (mouseEvent.type() == QEvent::GraphicsSceneMouseRelease)
+ d->clearDelayedPress();
+ return false;
+}
+
+bool QmlGraphicsFlickable::sceneEventFilter(QGraphicsItem *i, QEvent *e)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (!isVisible() || !d->interactive)
+ return QmlGraphicsItem::sceneEventFilter(i, e);
+ switch (e->type()) {
+ case QEvent::GraphicsSceneMousePress:
+ case QEvent::GraphicsSceneMouseMove:
+ case QEvent::GraphicsSceneMouseRelease:
+ return sendMouseEvent(static_cast<QGraphicsSceneMouseEvent *>(e));
+ default:
+ break;
+ }
+
+ return QmlGraphicsItem::sceneEventFilter(i, e);
+}
+
+/*!
+ \qmlproperty real Flickable::maximumFlickVelocity
+ This property holds the maximum velocity that the user can flick the view in pixels/second.
+
+ The default is 2000 pixels/s
+*/
+qreal QmlGraphicsFlickable::maximumFlickVelocity() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->maxVelocity;
+}
+
+void QmlGraphicsFlickable::setMaximumFlickVelocity(qreal v)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (v == d->maxVelocity)
+ return;
+ d->maxVelocity = v;
+}
+
+/*!
+ \qmlproperty real Flickable::flickDeceleration
+ This property holds the rate at which a flick will decelerate.
+
+ The default is 500.
+*/
+qreal QmlGraphicsFlickable::flickDeceleration() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->deceleration;
+}
+
+void QmlGraphicsFlickable::setFlickDeceleration(qreal deceleration)
+{
+ Q_D(QmlGraphicsFlickable);
+ d->deceleration = deceleration;
+}
+
+/*!
+ \qmlproperty bool Flickable::flicking
+
+ This property holds whether the view is currently moving due to
+ the user flicking the view.
+*/
+bool QmlGraphicsFlickable::isFlicking() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->flicked;
+}
+
+/*!
+ \qmlproperty int 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 undesireable 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.
+*/
+int QmlGraphicsFlickable::pressDelay() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->pressDelay;
+}
+
+void QmlGraphicsFlickable::setPressDelay(int delay)
+{
+ Q_D(QmlGraphicsFlickable);
+ if (d->pressDelay == delay)
+ return;
+ d->pressDelay = delay;
+}
+
+qreal QmlGraphicsFlickable::reportedVelocitySmoothing() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->reportedVelocitySmoothing;
+}
+
+void QmlGraphicsFlickable::setReportedVelocitySmoothing(qreal reportedVelocitySmoothing)
+{
+ Q_D(QmlGraphicsFlickable);
+ Q_ASSERT(reportedVelocitySmoothing >= 0);
+ if (reportedVelocitySmoothing == d->reportedVelocitySmoothing)
+ return;
+ d->reportedVelocitySmoothing = reportedVelocitySmoothing;
+ emit reportedVelocitySmoothingChanged(reportedVelocitySmoothing);
+}
+
+/*!
+ \qmlproperty bool Flickable::moving
+
+ This property holds whether the view is currently moving due to
+ the user either dragging or flicking the view.
+*/
+bool QmlGraphicsFlickable::isMoving() const
+{
+ Q_D(const QmlGraphicsFlickable);
+ return d->moving;
+}
+
+void QmlGraphicsFlickable::movementStarting()
+{
+ Q_D(QmlGraphicsFlickable);
+ if (!d->moving) {
+ d->moving = true;
+ emit movingChanged();
+ emit movementStarted();
+ }
+}
+
+void QmlGraphicsFlickable::movementEnding()
+{
+ Q_D(QmlGraphicsFlickable);
+ if (d->moving) {
+ d->moving = false;
+ emit movingChanged();
+ emit movementEnded();
+ }
+ if (d->flicked) {
+ d->flicked = false;
+ emit flickingChanged();
+ emit flickEnded();
+ }
+ d->horizontalVelocity.setValue(0);
+ d->verticalVelocity.setValue(0);
+}
+
+void QmlGraphicsFlickablePrivate::updateVelocity()
+{
+ Q_Q(QmlGraphicsFlickable);
+ emit q->horizontalVelocityChanged();
+ emit q->verticalVelocityChanged();
+}
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsFlickableVisibleArea)
+QML_DEFINE_TYPE(Qt,4,6,VisibleArea,QmlGraphicsFlickableVisibleArea)
+
+#include <qmlgraphicsflickable.moc>
diff --git a/src/declarative/graphicsitems/qmlgraphicsflickable_p.h b/src/declarative/graphicsitems/qmlgraphicsflickable_p.h
new file mode 100644
index 0000000..ea07da4
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsflickable_p.h
@@ -0,0 +1,210 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSFLICKABLE_H
+#define QMLGRAPHICSFLICKABLE_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsFlickablePrivate;
+class QmlGraphicsFlickableVisibleArea;
+class Q_DECLARATIVE_EXPORT QmlGraphicsFlickable : public QmlGraphicsItem
+{
+ Q_OBJECT
+
+ Q_PROPERTY(qreal viewportWidth READ viewportWidth WRITE setViewportWidth NOTIFY viewportWidthChanged)
+ Q_PROPERTY(qreal viewportHeight READ viewportHeight WRITE setViewportHeight NOTIFY viewportHeightChanged)
+ Q_PROPERTY(qreal viewportX READ viewportX WRITE setViewportX NOTIFY positionXChanged)
+ Q_PROPERTY(qreal viewportY READ viewportY WRITE setViewportY NOTIFY positionYChanged)
+
+ Q_PROPERTY(qreal horizontalVelocity READ horizontalVelocity NOTIFY horizontalVelocityChanged)
+ Q_PROPERTY(qreal verticalVelocity READ verticalVelocity NOTIFY verticalVelocityChanged)
+ Q_PROPERTY(qreal reportedVelocitySmoothing READ reportedVelocitySmoothing WRITE setReportedVelocitySmoothing NOTIFY reportedVelocitySmoothingChanged)
+
+ Q_PROPERTY(bool overShoot READ overShoot WRITE setOverShoot)
+ Q_PROPERTY(qreal maximumFlickVelocity READ maximumFlickVelocity WRITE setMaximumFlickVelocity)
+ Q_PROPERTY(qreal flickDeceleration READ flickDeceleration WRITE setFlickDeceleration)
+ Q_PROPERTY(bool moving READ isMoving NOTIFY movingChanged)
+ Q_PROPERTY(bool flicking READ isFlicking NOTIFY flickingChanged)
+ Q_PROPERTY(FlickDirection flickDirection READ flickDirection WRITE setFlickDirection NOTIFY flickDirectionChanged)
+
+ Q_PROPERTY(bool interactive READ isInteractive WRITE setInteractive NOTIFY interactiveChanged)
+ Q_PROPERTY(int pressDelay READ pressDelay WRITE setPressDelay)
+
+ 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(QmlGraphicsFlickableVisibleArea *visibleArea READ visibleArea CONSTANT)
+
+ Q_PROPERTY(QmlList<QObject *>* flickableData READ flickableData)
+ Q_PROPERTY(QmlList<QmlGraphicsItem *>* flickableChildren READ flickableChildren)
+ Q_CLASSINFO("DefaultProperty", "flickableData")
+
+ Q_ENUMS(FlickDirection)
+
+public:
+ QmlGraphicsFlickable(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsFlickable();
+
+ QmlList<QObject *> *flickableData();
+ QmlList<QmlGraphicsItem *> *flickableChildren();
+
+ bool overShoot() const;
+ void setOverShoot(bool);
+
+ qreal viewportWidth() const;
+ void setViewportWidth(qreal);
+
+ qreal viewportHeight() const;
+ void setViewportHeight(qreal);
+
+ qreal viewportX() const;
+ void setViewportX(qreal pos);
+
+ qreal viewportY() const;
+ void setViewportY(qreal pos);
+
+ bool isMoving() const;
+ bool isFlicking() const;
+
+ int pressDelay() const;
+ void setPressDelay(int delay);
+
+ qreal reportedVelocitySmoothing() const;
+ void setReportedVelocitySmoothing(qreal);
+
+ 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;
+
+ QmlGraphicsItem *viewport();
+
+ enum FlickDirection { AutoFlickDirection=0x00, HorizontalFlick=0x01, VerticalFlick=0x02, HorizontalAndVerticalFlick=0x03 };
+ FlickDirection flickDirection() const;
+ void setFlickDirection(FlickDirection);
+
+Q_SIGNALS:
+ void viewportWidthChanged();
+ void viewportHeightChanged();
+ void positionXChanged();
+ void positionYChanged();
+ void movingChanged();
+ void flickingChanged();
+ void movementStarted();
+ void movementEnded();
+ void flickStarted();
+ void flickEnded();
+ void reportedVelocitySmoothingChanged(int);
+ void horizontalVelocityChanged();
+ void verticalVelocityChanged();
+ void isAtBoundaryChanged();
+ void pageChanged();
+ void flickDirectionChanged();
+ void interactiveChanged();
+
+protected:
+ virtual bool sceneEventFilter(QGraphicsItem *, QEvent *);
+ void mousePressEvent(QGraphicsSceneMouseEvent *event);
+ void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
+ void wheelEvent(QGraphicsSceneWheelEvent *event);
+ void timerEvent(QTimerEvent *event);
+
+ QmlGraphicsFlickableVisibleArea *visibleArea();
+
+protected Q_SLOTS:
+ virtual void ticked();
+ void movementStarting();
+ void movementEnding();
+ void heightChange();
+ void widthChange();
+
+protected:
+ virtual qreal minXExtent() const;
+ virtual qreal minYExtent() const;
+ virtual qreal maxXExtent() const;
+ virtual qreal maxYExtent() const;
+ qreal vWidth() const;
+ qreal vHeight() const;
+ virtual void viewportMoved();
+ bool sendMouseEvent(QGraphicsSceneMouseEvent *event);
+
+ bool xflick() const;
+ bool yflick() const;
+ void cancelFlick();
+
+protected:
+ QmlGraphicsFlickable(QmlGraphicsFlickablePrivate &dd, QmlGraphicsItem *parent);
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsFlickable)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsFlickable)
+ friend class QmlGraphicsFlickableVisibleArea;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsFlickable)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicsflickable_p_p.h b/src/declarative/graphicsitems/qmlgraphicsflickable_p_p.h
new file mode 100644
index 0000000..ae164cc
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsflickable_p_p.h
@@ -0,0 +1,164 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSFLICKABLE_P_H
+#define QMLGRAPHICSFLICKABLE_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 "qmlgraphicsflickable_p.h"
+
+#include "qmlgraphicsitem_p.h"
+
+#include <qml.h>
+#include <qmltimeline_p_p.h>
+#include <qmlanimation_p_p.h>
+
+#include <qdatetime.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsFlickableVisibleArea;
+class QmlGraphicsFlickablePrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsFlickable)
+
+public:
+ QmlGraphicsFlickablePrivate();
+ void init();
+ virtual void flickX(qreal velocity);
+ virtual void flickY(qreal velocity);
+ virtual void fixupX();
+ virtual void fixupY();
+ void updateBeginningEnd();
+
+ void captureDelayedPress(QGraphicsSceneMouseEvent *event);
+ void clearDelayedPress();
+
+ void setRoundedViewportX(qreal x);
+ void setRoundedViewportY(qreal y);
+
+public:
+ QmlGraphicsItem *viewport;
+ QmlTimeLineValueProxy<QmlGraphicsFlickablePrivate> _moveX;
+ QmlTimeLineValueProxy<QmlGraphicsFlickablePrivate> _moveY;
+ QmlTimeLine timeline;
+ qreal vWidth;
+ qreal vHeight;
+ bool overShoot : 1;
+ bool flicked : 1;
+ bool moving : 1;
+ bool stealMouse : 1;
+ bool pressed : 1;
+ bool atXEnd : 1;
+ bool atXBeginning : 1;
+ bool atYEnd : 1;
+ bool atYBeginning : 1;
+ bool interactive : 1;
+ QTime lastPosTime;
+ QPointF lastPos;
+ QPointF pressPos;
+ qreal pressX;
+ qreal pressY;
+ qreal velocityX;
+ qreal velocityY;
+ QTime pressTime;
+ QmlTimeLineEvent fixupXEvent;
+ QmlTimeLineEvent fixupYEvent;
+ qreal deceleration;
+ qreal maxVelocity;
+ QTime velocityTime;
+ QPointF lastFlickablePosition;
+ qreal reportedVelocitySmoothing;
+ qreal flickTargetX;
+ qreal flickTargetY;
+ QGraphicsSceneMouseEvent *delayedPressEvent;
+ QGraphicsItem *delayedPressTarget;
+ QBasicTimer delayedPressTimer;
+ int pressDelay;
+ int fixupDuration;
+
+ void updateVelocity();
+ struct Velocity : public QmlTimeLineValue
+ {
+ Velocity(QmlGraphicsFlickablePrivate *p)
+ : parent(p) {}
+ virtual void setValue(qreal v) {
+ QmlTimeLineValue::setValue(v);
+ parent->updateVelocity();
+ }
+ QmlGraphicsFlickablePrivate *parent;
+ };
+ Velocity horizontalVelocity;
+ Velocity verticalVelocity;
+ int vTime;
+ QmlTimeLine velocityTimeline;
+ QmlGraphicsFlickableVisibleArea *visibleArea;
+ QmlGraphicsFlickable::FlickDirection flickDirection;
+
+ void handleMousePressEvent(QGraphicsSceneMouseEvent *);
+ void handleMouseMoveEvent(QGraphicsSceneMouseEvent *);
+ void handleMouseReleaseEvent(QGraphicsSceneMouseEvent *);
+
+ // flickableData property
+ void data_removeAt(int);
+ int data_count() const;
+ void data_append(QObject *);
+ void data_insert(int, QObject *);
+ QObject *data_at(int) const;
+ void data_clear();
+
+ friend class QmlGraphicsFlickableVisibleArea;
+ QML_DECLARE_LIST_PROXY(QmlGraphicsFlickablePrivate, QObject *, data)
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicsflipable.cpp b/src/declarative/graphicsitems/qmlgraphicsflipable.cpp
new file mode 100644
index 0000000..ff8995b
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsflipable.cpp
@@ -0,0 +1,239 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsflipable_p.h"
+
+#include "qmlgraphicsitem_p.h"
+
+#include <qmlinfo.h>
+
+#include <QtGui/qgraphicstransform.h>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,Flipable,QmlGraphicsFlipable)
+
+class QmlGraphicsFlipablePrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsFlipable)
+public:
+ QmlGraphicsFlipablePrivate() : current(QmlGraphicsFlipable::Front), front(0), back(0) {}
+
+ void updateSceneTransformFromParent();
+
+ QmlGraphicsFlipable::Side current;
+ QmlGraphicsItem *front;
+ QmlGraphicsItem *back;
+};
+
+/*!
+ \qmlclass Flipable QmlGraphicsFlipable
+ \brief The Flipable item provides a surface that can be flipped.
+ \inherits Item
+
+ Flipable allows you to specify a front and a back and then flip between those sides.
+
+ Here's an example that flips between the front and back sides when clicked:
+
+ \qml
+
+ Flipable {
+ id: flipable
+ width: 250; height: 250
+ property int angle: 0
+
+ transform: Rotation {
+ id: rotation
+ origin.x: flipable.width/2; origin.y: flipable.height/2
+ axis.x: 0; axis.y: 1; axis.z: 0 // rotate around y-axis
+ angle: flipable.angle
+ }
+
+ front: Image { source: "front.png" }
+ back: Image { source: "back.png" }
+
+ states: State {
+ name: "back"
+ PropertyChanges { target: flipable; angle: 180 }
+ }
+
+ transitions: Transition {
+ NumberAnimation { matchProperties: "angle"; duration: 2000 }
+ }
+
+ MouseRegion {
+ // change between default and 'back' states
+ onClicked: flipable.state = (flipable.state == 'back' ? '' : 'back')
+ anchors.fill: parent
+ }
+ }
+ \endqml
+
+ \image flipable.gif
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsFlipable
+ \brief The QmlGraphicsFlipable class provides a flipable surface.
+
+ \ingroup group_widgets
+
+ QmlGraphicsFlipable allows you to specify a front and a back, as well as an
+ axis for the flip.
+*/
+
+QmlGraphicsFlipable::QmlGraphicsFlipable(QmlGraphicsItem *parent)
+: QmlGraphicsItem(*(new QmlGraphicsFlipablePrivate), parent)
+{
+}
+
+QmlGraphicsFlipable::~QmlGraphicsFlipable()
+{
+}
+
+/*!
+ \qmlproperty Item Flipable::front
+ \qmlproperty Item Flipable::back
+
+ The front and back sides of the flipable.
+*/
+
+QmlGraphicsItem *QmlGraphicsFlipable::front()
+{
+ Q_D(const QmlGraphicsFlipable);
+ return d->front;
+}
+
+void QmlGraphicsFlipable::setFront(QmlGraphicsItem *front)
+{
+ Q_D(QmlGraphicsFlipable);
+ if (d->front) {
+ qmlInfo(this) << tr("front is a write-once property");
+ return;
+ }
+ d->front = front;
+ fxChildren()->append(d->front);
+ if (Back == d->current)
+ d->front->setOpacity(0.);
+}
+
+QmlGraphicsItem *QmlGraphicsFlipable::back()
+{
+ Q_D(const QmlGraphicsFlipable);
+ return d->back;
+}
+
+void QmlGraphicsFlipable::setBack(QmlGraphicsItem *back)
+{
+ Q_D(QmlGraphicsFlipable);
+ if (d->back) {
+ qmlInfo(this) << tr("back is a write-once property");
+ return;
+ }
+ d->back = back;
+ fxChildren()->append(d->back);
+ if (Front == d->current)
+ d->back->setOpacity(0.);
+}
+
+/*!
+ \qmlproperty enumeration Flipable::side
+
+ The side of the Flippable currently visible. Possible values are \c
+ Front and \c Back.
+*/
+QmlGraphicsFlipable::Side QmlGraphicsFlipable::side() const
+{
+ Q_D(const QmlGraphicsFlipable);
+ if (d->dirtySceneTransform)
+ const_cast<QmlGraphicsFlipablePrivate *>(d)->updateSceneTransformFromParent();
+
+ return d->current;
+}
+
+// determination on the currently visible side of the flipable
+// has to be done on the complete scene transform to give
+// correct results.
+void QmlGraphicsFlipablePrivate::updateSceneTransformFromParent()
+{
+ Q_Q(QmlGraphicsFlipable);
+
+ QmlGraphicsItemPrivate::updateSceneTransformFromParent();
+ QPointF p1(0, 0);
+ QPointF p2(1, 0);
+ QPointF p3(1, 1);
+
+ p1 = sceneTransform.map(p1);
+ p2 = sceneTransform.map(p2);
+ p3 = sceneTransform.map(p3);
+
+ qreal cross = (p1.x() - p2.x()) * (p3.y() - p2.y()) -
+ (p1.y() - p2.y()) * (p3.x() - p2.x());
+
+ QmlGraphicsFlipable::Side newSide;
+ if (cross > 0) {
+ newSide = QmlGraphicsFlipable::Back;
+ } else {
+ newSide = QmlGraphicsFlipable::Front;
+ }
+
+ if (newSide != current) {
+ current = newSide;
+ if (current == QmlGraphicsFlipable::Back) {
+ QTransform mat;
+ mat.translate(back->width()/2,back->height()/2);
+ if (back->width() && p1.x() >= p2.x())
+ mat.rotate(180, Qt::YAxis);
+ if (back->height() && p2.y() >= p3.y())
+ mat.rotate(180, Qt::XAxis);
+ mat.translate(-back->width()/2,-back->height()/2);
+ back->setTransform(mat);
+ }
+ if (front)
+ front->setOpacity((current==QmlGraphicsFlipable::Front)?1.:0.);
+ if (back)
+ back->setOpacity((current==QmlGraphicsFlipable::Back)?1.:0.);
+ emit q->sideChanged();
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsflipable_p.h b/src/declarative/graphicsitems/qmlgraphicsflipable_p.h
new file mode 100644
index 0000000..c189786
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsflipable_p.h
@@ -0,0 +1,95 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSFLIPABLE_H
+#define QMLGRAPHICSFLIPABLE_H
+
+#include "qmlgraphicsitem.h"
+
+#include <QtCore/QObject>
+#include <QtGui/QTransform>
+#include <QtGui/qvector3d.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsFlipablePrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsFlipable : public QmlGraphicsItem
+{
+ Q_OBJECT
+
+ Q_ENUMS(Side)
+ Q_PROPERTY(QmlGraphicsItem *front READ front WRITE setFront)
+ Q_PROPERTY(QmlGraphicsItem *back READ back WRITE setBack)
+ Q_PROPERTY(Side side READ side NOTIFY sideChanged)
+ //### flipAxis
+ //### flipRotation
+public:
+ QmlGraphicsFlipable(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsFlipable();
+
+ QmlGraphicsItem *front();
+ void setFront(QmlGraphicsItem *);
+
+ QmlGraphicsItem *back();
+ void setBack(QmlGraphicsItem *);
+
+ enum Side { Front, Back };
+ Side side() const;
+
+Q_SIGNALS:
+ void sideChanged();
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsFlipable)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsFlipable)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsFlipable)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSFLIPABLE_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsfocuspanel.cpp b/src/declarative/graphicsitems/qmlgraphicsfocuspanel.cpp
new file mode 100644
index 0000000..333b689
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsfocuspanel.cpp
@@ -0,0 +1,90 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsfocuspanel_p.h"
+
+#include <QtGui/qgraphicsscene.h>
+#include <QEvent>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,FocusPanel,QmlGraphicsFocusPanel)
+
+/*!
+ \qmlclass FocusPanel QmlGraphicsFocusPanel
+ \brief The FocusPanel item explicitly creates a focus panel.
+ \inherits Item
+
+ Focus panels assist in keyboard focus handling when building QML
+ applications. All the details are covered in the
+ \l {qmlfocus}{keyboard focus documentation}.
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsFocusPanel
+*/
+
+QmlGraphicsFocusPanel::QmlGraphicsFocusPanel(QmlGraphicsItem *parent) :
+ QmlGraphicsItem(parent)
+{
+ setFlag(ItemIsPanel);
+}
+
+QmlGraphicsFocusPanel::~QmlGraphicsFocusPanel()
+{
+}
+
+/*!
+ \qmlproperty bool FocusPanel::active
+
+ Sets whether the item is the active focus panel.
+*/
+
+bool QmlGraphicsFocusPanel::sceneEvent(QEvent *event)
+{
+ if (event->type() == QEvent::WindowActivate ||
+ event->type() == QEvent::WindowDeactivate)
+ emit activeChanged();
+ return QmlGraphicsItem::sceneEvent(event);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsfocuspanel_p.h b/src/declarative/graphicsitems/qmlgraphicsfocuspanel_p.h
new file mode 100644
index 0000000..4c5cc14
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsfocuspanel_p.h
@@ -0,0 +1,77 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSFOCUSPANEL_H
+#define QMLGRAPHICSFOCUSPANEL_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsFocusPanel : public QmlGraphicsItem
+{
+ Q_OBJECT
+ Q_PROPERTY(bool active READ isActive WRITE setActive NOTIFY activeChanged)
+public:
+ QmlGraphicsFocusPanel(QmlGraphicsItem *parent=0);
+ virtual ~QmlGraphicsFocusPanel();
+
+Q_SIGNALS:
+ void activeChanged();
+
+protected:
+ bool sceneEvent(QEvent *event);
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsFocusPanel)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsFocusPanel)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSFOCUSPANEL_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsfocusscope.cpp b/src/declarative/graphicsitems/qmlgraphicsfocusscope.cpp
new file mode 100644
index 0000000..828756c
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsfocusscope.cpp
@@ -0,0 +1,71 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsfocusscope_p.h"
+
+QT_BEGIN_NAMESPACE
+QML_DEFINE_TYPE(Qt,4,6,FocusScope,QmlGraphicsFocusScope)
+
+/*!
+ \qmlclass FocusScope QmlGraphicsFocusScope
+ \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}.
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsFocusScope
+*/
+
+QmlGraphicsFocusScope::QmlGraphicsFocusScope(QmlGraphicsItem *parent) :
+ QmlGraphicsItem(parent)
+{
+ setFlag(QGraphicsItem::ItemIsFocusScope);
+}
+
+QmlGraphicsFocusScope::~QmlGraphicsFocusScope()
+{
+}
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsfocusscope_p.h b/src/declarative/graphicsitems/qmlgraphicsfocusscope_p.h
new file mode 100644
index 0000000..0ea9da5
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsfocusscope_p.h
@@ -0,0 +1,68 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSFOCUSSCOPE_H
+#define QMLGRAPHICSFOCUSSCOPE_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+//### set component root as focusscope
+class Q_DECLARATIVE_EXPORT QmlGraphicsFocusScope : public QmlGraphicsItem
+{
+ Q_OBJECT
+public:
+ QmlGraphicsFocusScope(QmlGraphicsItem *parent=0);
+ virtual ~QmlGraphicsFocusScope();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsFocusScope)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSFOCUSSCOPE_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsgraphicsobjectcontainer.cpp b/src/declarative/graphicsitems/qmlgraphicsgraphicsobjectcontainer.cpp
new file mode 100644
index 0000000..a5a7935
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsgraphicsobjectcontainer.cpp
@@ -0,0 +1,271 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsgraphicsobjectcontainer_p.h"
+
+#include "qmlgraphicsitem_p.h"
+
+#include <QGraphicsObject>
+#include <QGraphicsWidget>
+#include <QGraphicsSceneResizeEvent>
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsGraphicsObjectContainerPrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsGraphicsObjectContainer)
+
+public:
+ QmlGraphicsGraphicsObjectContainerPrivate() : QmlGraphicsItemPrivate(), graphicsObject(0), syncedResize(false)
+ { }
+
+ void _q_updateSize();
+
+ void setFiltering(bool on)
+ {
+ Q_Q(QmlGraphicsGraphicsObjectContainer);
+ if (graphicsObject && graphicsObject->isWidget()) {
+ if (!on) {
+ graphicsObject->removeEventFilter(q);
+ QObject::disconnect(q, SIGNAL(widthChanged()), q, SLOT(_q_updateSize()));
+ QObject::disconnect(q, SIGNAL(heightChanged()), q, SLOT(_q_updateSize()));
+ } else {
+ graphicsObject->installEventFilter(q);
+ QObject::connect(q, SIGNAL(widthChanged()), q, SLOT(_q_updateSize()));
+ QObject::connect(q, SIGNAL(heightChanged()), q, SLOT(_q_updateSize()));
+ }
+ }
+ }
+
+
+ QGraphicsObject *graphicsObject;
+ bool syncedResize;
+};
+
+
+/*!
+ \qmlclass GraphicsObjectContainer QmlGraphicsGraphicsObjectContainer
+ \brief The GraphicsObjectContainer element allows you to add QGraphicsObjects into Fluid UI elements.
+
+ While any QObject based class can be exposed to QML, QmlGraphicsItem
+ provides a lot of important functionality, including anchors and proper
+ management of child items. GraphicsObjectContainer helps provide these
+ functions to other QGraphicsObjects, so that they can be used unaltered in
+ a QML scene. QGraphicsObjects, which are not QmlGraphicsItems, and which are
+ placed in a QML scene outside of a GraphicsObjectContainer, will not appear
+ on screen at all.
+
+ A GraphicsObjectContainer can have one element inside it, and it must be a
+ QGraphicsObject or subclass which has been exposed to the QML engine.
+ The graphics object inside the GraphicsObjectContainer can then be used
+ like any other item in QML with the exception of not being reparentable
+ and not having the standard properties of QML items (such as anchors).
+
+ As the contained object is positioned relative to the container, anchors
+ affecting the container item will affect the onscreen position of the
+ contained item. If synchronizedResizing is set to true, then anchors
+ affecting the container item's size will also affect the contained item's
+ size.
+
+ Example:
+ \code
+ import Qt 4.6
+ import MyApp 2.1 as Widgets
+ Rectangle{
+ id: rect
+ property alias widgetPropertyThree: widget.myThirdProperty;
+ GraphicsObjectContainer{
+ synchronizedResizing: true
+ anchors.margins: 10
+ anchors.fill: parent
+ Widgets.MyWidget{
+ myProperty: "A Value"
+ myOtherProperty: rect.color
+ }
+ }
+ }
+ \endcode
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsGraphicsObjectContainer
+ \brief The QmlGraphicsGraphicsObjectContainer class allows you to add QGraphicsObjects into Fluid UI applications.
+*/
+
+QML_DEFINE_NOCREATE_TYPE(QGraphicsObject)
+QML_DEFINE_TYPE(Qt,4,6,GraphicsObjectContainer,QmlGraphicsGraphicsObjectContainer)
+
+QmlGraphicsGraphicsObjectContainer::QmlGraphicsGraphicsObjectContainer(QmlGraphicsItem *parent)
+: QmlGraphicsItem(*new QmlGraphicsGraphicsObjectContainerPrivate, parent)
+{
+}
+
+QmlGraphicsGraphicsObjectContainer::~QmlGraphicsGraphicsObjectContainer()
+{
+}
+
+QGraphicsObject *QmlGraphicsGraphicsObjectContainer::graphicsObject() const
+{
+ Q_D(const QmlGraphicsGraphicsObjectContainer);
+ return d->graphicsObject;
+}
+
+/*!
+ \qmlproperty QGraphicsObject GraphicsObjectContainer::graphicsObject
+ The QGraphicsObject associated with this element.
+*/
+void QmlGraphicsGraphicsObjectContainer::setGraphicsObject(QGraphicsObject *object)
+{
+ Q_D(QmlGraphicsGraphicsObjectContainer);
+ if (object == d->graphicsObject)
+ return;
+
+ //### remove previously set item?
+
+ d->setFiltering(false);
+
+ d->graphicsObject = object;
+
+ if (d->graphicsObject) {
+ d->graphicsObject->setParentItem(this);
+
+ if (d->syncedResize && d->graphicsObject->isWidget()) {
+ QGraphicsWidget *gw = static_cast<QGraphicsWidget*>(d->graphicsObject);
+ QSizeF gwSize = gw->size(); //### should we use sizeHint?
+ QSizeF newSize = gwSize;
+ if (heightValid())
+ newSize.setHeight(height());
+ if (widthValid())
+ newSize.setWidth(width());
+ if (gwSize != newSize)
+ gw->resize(newSize);
+
+ gwSize = gw->size();
+ setImplicitWidth(gwSize.width());
+ setImplicitHeight(gwSize.height());
+
+ d->setFiltering(true);
+ }
+ }
+}
+
+QVariant QmlGraphicsGraphicsObjectContainer::itemChange(GraphicsItemChange change, const QVariant &value)
+{
+ Q_D(QmlGraphicsGraphicsObjectContainer);
+ if (change == ItemSceneHasChanged) {
+ QGraphicsObject *o = d->graphicsObject;
+ d->graphicsObject = 0;
+ setGraphicsObject(o);
+ }
+ return QmlGraphicsItem::itemChange(change, value);
+}
+
+bool QmlGraphicsGraphicsObjectContainer::eventFilter(QObject *watched, QEvent *e)
+{
+ Q_D(QmlGraphicsGraphicsObjectContainer);
+ if (watched == d->graphicsObject && e->type() == QEvent::GraphicsSceneResize) {
+ if (d->graphicsObject && d->graphicsObject->isWidget() && d->syncedResize) {
+ QSizeF newSize = static_cast<QGraphicsWidget*>(d->graphicsObject)->size();
+ setImplicitWidth(newSize.width());
+ setImplicitHeight(newSize.height());
+ }
+ }
+ return QmlGraphicsItem::eventFilter(watched, e);
+}
+
+/*!
+ \qmlproperty bool GraphicsObjectContainer::synchronizedResizing
+
+ This property determines whether or not the container and graphics object will synchronize their
+ sizes.
+
+ \note This property only applies when wrapping a QGraphicsWidget.
+
+ If synchronizedResizing is enabled, the container and widget will
+ synchronize their sizes as follows.
+ \list
+ \o If a size has been set on the container, the widget will be resized to the container.
+ Any changes in the container's size will be reflected in the widget.
+
+ \o \e Otherwise, the container will initially be sized to the preferred size of the widget.
+ Any changes to the container's size will be reflected in the widget, and any changes to the
+ widget's size will be reflected in the container.
+ \endlist
+*/
+bool QmlGraphicsGraphicsObjectContainer::synchronizedResizing() const
+{
+ Q_D(const QmlGraphicsGraphicsObjectContainer);
+ return d->syncedResize;
+}
+
+void QmlGraphicsGraphicsObjectContainer::setSynchronizedResizing(bool on)
+{
+ Q_D(QmlGraphicsGraphicsObjectContainer);
+ if (on == d->syncedResize)
+ return;
+
+ d->syncedResize = on;
+ d->setFiltering(on);
+}
+
+void QmlGraphicsGraphicsObjectContainerPrivate::_q_updateSize()
+{
+ if (!graphicsObject || !graphicsObject->isWidget() || !syncedResize)
+ return;
+
+ QGraphicsWidget *gw = static_cast<QGraphicsWidget*>(graphicsObject);
+ const QSizeF newSize(width, height);
+ gw->resize(newSize);
+
+ //### will respecting the widgets min/max ever get us in trouble? (all other items always
+ // size to exactly what you tell them)
+ /*QSizeF constrainedSize = newSize.expandedTo(gw->minimumSize()).boundedTo(gw->maximumSize());
+ gw->resize(constrainedSize);
+ if (constrainedSize != newSize) {
+ setImplicitWidth(constrainedSize.width());
+ setImplicitHeight(constrainedSize.height());
+ }*/
+}
+
+#include <moc_qmlgraphicsgraphicsobjectcontainer_p.cpp>
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsgraphicsobjectcontainer_p.h b/src/declarative/graphicsitems/qmlgraphicsgraphicsobjectcontainer_p.h
new file mode 100644
index 0000000..1091145
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsgraphicsobjectcontainer_p.h
@@ -0,0 +1,90 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSGRAPHICSOBJECTCONTAINER_H
+#define QMLGRAPHICSGRAPHICSOBJECTCONTAINER_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QGraphicsObject;
+class QmlGraphicsGraphicsObjectContainerPrivate;
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsGraphicsObjectContainer : public QmlGraphicsItem
+{
+ Q_OBJECT
+
+ Q_CLASSINFO("DefaultProperty", "graphicsObject")
+ Q_PROPERTY(QGraphicsObject *graphicsObject READ graphicsObject WRITE setGraphicsObject)
+ Q_PROPERTY(bool synchronizedResizing READ synchronizedResizing WRITE setSynchronizedResizing)
+
+public:
+ QmlGraphicsGraphicsObjectContainer(QmlGraphicsItem *parent = 0);
+ ~QmlGraphicsGraphicsObjectContainer();
+
+ QGraphicsObject *graphicsObject() const;
+ void setGraphicsObject(QGraphicsObject *);
+
+ bool synchronizedResizing() const;
+ void setSynchronizedResizing(bool on);
+
+protected:
+ QVariant itemChange(GraphicsItemChange change, const QVariant &value);
+ bool eventFilter(QObject *watched, QEvent *e);
+
+private:
+ Q_PRIVATE_SLOT(d_func(), void _q_updateSize())
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsGraphicsObjectContainer)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QGraphicsObject)
+QML_DECLARE_TYPE(QmlGraphicsGraphicsObjectContainer)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSGRAPHICSOBJECTCONTAINER_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsgridview.cpp b/src/declarative/graphicsitems/qmlgraphicsgridview.cpp
new file mode 100644
index 0000000..83911c0
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsgridview.cpp
@@ -0,0 +1,1761 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsgridview_p.h"
+
+#include "qmlgraphicsvisualitemmodel_p.h"
+#include "qmlgraphicsflickable_p_p.h"
+
+#include <qmleasefollow_p.h>
+
+#include <qlistmodelinterface_p.h>
+#include <QKeyEvent>
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsGridViewAttached : public QObject
+{
+ Q_OBJECT
+public:
+ QmlGraphicsGridViewAttached(QObject *parent)
+ : QObject(parent), m_isCurrent(false), m_delayRemove(false) {}
+ ~QmlGraphicsGridViewAttached() {
+ attachedProperties.remove(parent());
+ }
+
+ Q_PROPERTY(QmlGraphicsGridView *view READ view CONSTANT)
+ QmlGraphicsGridView *view() { return m_view; }
+
+ Q_PROPERTY(bool isCurrentItem READ isCurrentItem NOTIFY currentItemChanged)
+ bool isCurrentItem() const { return m_isCurrent; }
+ void setIsCurrentItem(bool c) {
+ if (m_isCurrent != c) {
+ m_isCurrent = c;
+ emit currentItemChanged();
+ }
+ }
+
+ Q_PROPERTY(bool delayRemove READ delayRemove WRITE setDelayRemove NOTIFY delayRemoveChanged)
+ bool delayRemove() const { return m_delayRemove; }
+ void setDelayRemove(bool delay) {
+ if (m_delayRemove != delay) {
+ m_delayRemove = delay;
+ emit delayRemoveChanged();
+ }
+ }
+
+ static QmlGraphicsGridViewAttached *properties(QObject *obj) {
+ QmlGraphicsGridViewAttached *rv = attachedProperties.value(obj);
+ if (!rv) {
+ rv = new QmlGraphicsGridViewAttached(obj);
+ attachedProperties.insert(obj, rv);
+ }
+ return rv;
+ }
+
+ void emitAdd() { emit add(); }
+ void emitRemove() { emit remove(); }
+
+Q_SIGNALS:
+ void currentItemChanged();
+ void delayRemoveChanged();
+ void add();
+ void remove();
+
+public:
+ QmlGraphicsGridView *m_view;
+ bool m_isCurrent;
+ bool m_delayRemove;
+
+ static QHash<QObject*, QmlGraphicsGridViewAttached*> attachedProperties;
+};
+
+QHash<QObject*, QmlGraphicsGridViewAttached*> QmlGraphicsGridViewAttached::attachedProperties;
+
+
+//----------------------------------------------------------------------------
+
+class FxGridItem
+{
+public:
+ FxGridItem(QmlGraphicsItem *i, QmlGraphicsGridView *v) : item(i), view(v) {
+ attached = QmlGraphicsGridViewAttached::properties(item);
+ attached->m_view = view;
+ }
+ ~FxGridItem() {}
+
+ qreal rowPos() const { return (view->flow() == QmlGraphicsGridView::LeftToRight ? item->y() : item->x()); }
+ qreal colPos() const { return (view->flow() == QmlGraphicsGridView::LeftToRight ? item->x() : item->y()); }
+ qreal endRowPos() const {
+ return view->flow() == QmlGraphicsGridView::LeftToRight
+ ? item->y() + view->cellHeight() - 1
+ : item->x() + view->cellWidth() - 1;
+ }
+ void setPosition(qreal col, qreal row) {
+ if (view->flow() == QmlGraphicsGridView::LeftToRight) {
+ item->setPos(QPointF(col, row));
+ } else {
+ item->setPos(QPointF(row, col));
+ }
+ }
+
+ QmlGraphicsItem *item;
+ QmlGraphicsGridView *view;
+ QmlGraphicsGridViewAttached *attached;
+ int index;
+};
+
+//----------------------------------------------------------------------------
+
+class QmlGraphicsGridViewPrivate : public QmlGraphicsFlickablePrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsGridView)
+
+public:
+ QmlGraphicsGridViewPrivate()
+ : currentItem(0), flow(QmlGraphicsGridView::LeftToRight)
+ , visiblePos(0), visibleIndex(0) , currentIndex(-1)
+ , cellWidth(100), cellHeight(100), columns(1), requestedIndex(-1)
+ , highlightComponent(0), highlight(0), trackedItem(0)
+ , moveReason(Other), buffer(0), highlightXAnimator(0), highlightYAnimator(0)
+ , bufferMode(NoBuffer)
+ , ownModel(false), wrap(false), autoHighlight(true)
+ , fixCurrentVisibility(false), lazyRelease(false), layoutScheduled(false)
+ , deferredRelease(false) {}
+
+ void init();
+ void clear();
+ FxGridItem *createItem(int modelIndex);
+ void releaseItem(FxGridItem *item);
+ void refill(qreal from, qreal to, bool doBuffer=false);
+
+ void updateGrid();
+ void scheduleLayout();
+ void layout(bool removed=false);
+ void updateUnrequestedIndexes();
+ void updateUnrequestedPositions();
+ void updateTrackedItem();
+ void createHighlight();
+ void updateHighlight();
+ void updateCurrent(int modelIndex);
+
+ FxGridItem *visibleItem(int modelIndex) const {
+ if (modelIndex >= visibleIndex && modelIndex < visibleIndex + visibleItems.count()) {
+ for (int i = modelIndex - visibleIndex; i < visibleItems.count(); ++i) {
+ FxGridItem *item = visibleItems.at(i);
+ if (item->index == modelIndex)
+ return item;
+ }
+ }
+ return 0;
+ }
+
+ qreal position() const {
+ Q_Q(const QmlGraphicsGridView);
+ return flow == QmlGraphicsGridView::LeftToRight ? q->viewportY() : q->viewportX();
+ }
+ void setPosition(qreal pos) {
+ Q_Q(QmlGraphicsGridView);
+ if (flow == QmlGraphicsGridView::LeftToRight)
+ q->setViewportY(pos);
+ else
+ q->setViewportX(pos);
+ }
+ int size() const {
+ Q_Q(const QmlGraphicsGridView);
+ return flow == QmlGraphicsGridView::LeftToRight ? q->height() : q->width();
+ }
+ qreal startPosition() const {
+ qreal pos = 0;
+ if (!visibleItems.isEmpty())
+ pos = visibleItems.first()->rowPos() - visibleIndex / columns * rowSize();
+ return pos;
+ }
+
+ qreal endPosition() const {
+ qreal pos = 0;
+ if (model && model->count())
+ pos = rowPosAt(model->count() - 1) + rowSize();
+ return pos;
+ }
+
+ bool isValid() const {
+ return model && model->count() && model->isValid();
+ }
+
+ int rowSize() const {
+ return flow == QmlGraphicsGridView::LeftToRight ? cellHeight : cellWidth;
+ }
+ int colSize() const {
+ return flow == QmlGraphicsGridView::LeftToRight ? cellWidth : cellHeight;
+ }
+
+ qreal colPosAt(int modelIndex) const {
+ if (FxGridItem *item = visibleItem(modelIndex))
+ return item->colPos();
+ if (!visibleItems.isEmpty()) {
+ if (modelIndex < visibleIndex) {
+ int count = (visibleIndex - modelIndex) % columns;
+ int col = visibleItems.first()->colPos() / colSize();
+ col = (columns - count + col) % columns;
+ return col * colSize();
+ } else {
+ int count = columns - 1 - (modelIndex - visibleItems.last()->index - 1) % columns;
+ return visibleItems.last()->colPos() - count * colSize();
+ }
+ } else {
+ return (modelIndex % columns) * colSize();
+ }
+ return 0;
+ }
+ qreal rowPosAt(int modelIndex) const {
+ if (FxGridItem *item = visibleItem(modelIndex))
+ return item->rowPos();
+ if (!visibleItems.isEmpty()) {
+ if (modelIndex < visibleIndex) {
+ int firstCol = visibleItems.first()->colPos() / colSize();
+ int col = visibleIndex - modelIndex + (columns - firstCol - 1);
+ int rows = col / columns;
+ return visibleItems.first()->rowPos() - rows * rowSize();
+ } else {
+ int count = modelIndex - visibleItems.last()->index;
+ int col = visibleItems.last()->colPos() + count * colSize();
+ int rows = col / (columns * colSize());
+ return visibleItems.last()->rowPos() + rows * rowSize();
+ }
+ } else {
+ return (modelIndex / columns) * rowSize();
+ }
+ return 0;
+ }
+
+ FxGridItem *firstVisibleItem() const {
+ const qreal pos = position();
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ FxGridItem *item = visibleItems.at(i);
+ if (item->index != -1 && item->endRowPos() > 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 mapFromModel(int modelIndex) const {
+ if (modelIndex < visibleIndex || modelIndex >= visibleIndex + visibleItems.count())
+ return -1;
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ FxGridItem *listItem = visibleItems.at(i);
+ if (listItem->index == modelIndex)
+ return i + visibleIndex;
+ if (listItem->index > modelIndex)
+ return -1;
+ }
+ return -1; // Not in visibleList
+ }
+
+ // for debugging only
+ void checkVisible() const {
+ int skip = 0;
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ FxGridItem *listItem = visibleItems.at(i);
+ if (listItem->index == -1) {
+ ++skip;
+ } else if (listItem->index != visibleIndex + i - skip) {
+ for (int j = 0; j < visibleItems.count(); j++)
+ qDebug() << " index" << j << "item index" << visibleItems.at(j)->index;
+ qFatal("index %d %d %d", visibleIndex, i, listItem->index);
+ }
+ }
+ }
+
+ QGuard<QmlGraphicsVisualModel> model;
+ QVariant modelVariant;
+ QList<FxGridItem*> visibleItems;
+ QHash<QmlGraphicsItem*,int> unrequestedItems;
+ FxGridItem *currentItem;
+ QmlGraphicsGridView::Flow flow;
+ int visiblePos;
+ int visibleIndex;
+ int currentIndex;
+ int cellWidth;
+ int cellHeight;
+ int columns;
+ int requestedIndex;
+ QmlComponent *highlightComponent;
+ FxGridItem *highlight;
+ FxGridItem *trackedItem;
+ enum MovementReason { Other, SetIndex, Mouse };
+ MovementReason moveReason;
+ int buffer;
+ QmlEaseFollow *highlightXAnimator;
+ QmlEaseFollow *highlightYAnimator;
+ enum BufferMode { NoBuffer = 0x00, BufferBefore = 0x01, BufferAfter = 0x02 };
+ BufferMode bufferMode;
+
+ bool ownModel : 1;
+ bool wrap : 1;
+ bool autoHighlight : 1;
+ bool fixCurrentVisibility : 1;
+ bool lazyRelease : 1;
+ bool layoutScheduled : 1;
+ bool deferredRelease : 1;
+};
+
+void QmlGraphicsGridViewPrivate::init()
+{
+ Q_Q(QmlGraphicsGridView);
+ q->setFlag(QGraphicsItem::ItemIsFocusScope);
+ QObject::connect(q, SIGNAL(widthChanged()), q, SLOT(sizeChange()));
+ QObject::connect(q, SIGNAL(heightChanged()), q, SLOT(sizeChange()));
+ q->setFlickDirection(QmlGraphicsFlickable::VerticalFlick);
+}
+
+void QmlGraphicsGridViewPrivate::clear()
+{
+ for (int i = 0; i < visibleItems.count(); ++i)
+ releaseItem(visibleItems.at(i));
+ visibleItems.clear();
+ visiblePos = 0;
+ visibleIndex = 0;
+ releaseItem(currentItem);
+ currentItem = 0;
+ createHighlight();
+ trackedItem = 0;
+}
+
+FxGridItem *QmlGraphicsGridViewPrivate::createItem(int modelIndex)
+{
+ Q_Q(QmlGraphicsGridView);
+ // create object
+ requestedIndex = modelIndex;
+ FxGridItem *listItem = 0;
+ if (QmlGraphicsItem *item = model->item(modelIndex, false)) {
+ listItem = new FxGridItem(item, q);
+ listItem->index = modelIndex;
+ // complete
+ model->completeItem();
+ listItem->item->setZValue(1);
+ listItem->item->setParent(q->viewport());
+ unrequestedItems.remove(listItem->item);
+ }
+ requestedIndex = 0;
+ return listItem;
+}
+
+
+void QmlGraphicsGridViewPrivate::releaseItem(FxGridItem *item)
+{
+ Q_Q(QmlGraphicsGridView);
+ if (!item || !model)
+ return;
+ if (trackedItem == item) {
+ QObject::disconnect(trackedItem->item, SIGNAL(yChanged()), q, SLOT(trackedPositionChanged()));
+ QObject::disconnect(trackedItem->item, SIGNAL(xChanged()), q, SLOT(trackedPositionChanged()));
+ trackedItem = 0;
+ }
+ 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;
+}
+
+void QmlGraphicsGridViewPrivate::refill(qreal from, qreal to, bool doBuffer)
+{
+ Q_Q(QmlGraphicsGridView);
+ if (!isValid() || !q->isComponentComplete())
+ return;
+
+ 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;
+
+ bool changed = false;
+
+ int colPos = colPosAt(visibleIndex);
+ int rowPos = rowPosAt(visibleIndex);
+ int modelIndex = visibleIndex;
+ if (visibleItems.count()) {
+ rowPos = visibleItems.last()->rowPos();
+ colPos = visibleItems.last()->colPos() + colSize();
+ if (colPos > colSize() * (columns-1)) {
+ colPos = 0;
+ rowPos += rowSize();
+ }
+ int i = visibleItems.count() - 1;
+ while (i > 0 && visibleItems.at(i)->index == -1)
+ --i;
+ modelIndex = visibleItems.at(i)->index + 1;
+ }
+ int colNum = colPos / colSize();
+
+ FxGridItem *item = 0;
+
+ // Item creation and release is staggered in order to avoid
+ // creating/releasing multiple items in one frame
+ // while flicking (as much as possible).
+ while (modelIndex < model->count() && rowPos <= fillTo + rowSize()*(columns - colNum)/(columns+1)) {
+// qDebug() << "refill: append item" << modelIndex;
+ if (!(item = createItem(modelIndex)))
+ break;
+ item->setPosition(colPos, rowPos);
+ visibleItems.append(item);
+ colPos += colSize();
+ colNum++;
+ if (colPos > colSize() * (columns-1)) {
+ colPos = 0;
+ colNum = 0;
+ rowPos += rowSize();
+ }
+ ++modelIndex;
+ changed = true;
+ if (doBuffer) // never buffer more than one item per frame
+ break;
+ }
+
+ if (visibleItems.count()) {
+ rowPos = visibleItems.first()->rowPos();
+ colPos = visibleItems.first()->colPos() - colSize();
+ if (colPos < 0) {
+ colPos = colSize() * (columns - 1);
+ rowPos -= rowSize();
+ }
+ }
+ colNum = colPos / 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 = createItem(visibleIndex-1)))
+ break;
+ --visibleIndex;
+ item->setPosition(colPos, rowPos);
+ visibleItems.prepend(item);
+ colPos -= colSize();
+ colNum--;
+ if (colPos < 0) {
+ colPos = colSize() * (columns - 1);
+ colNum = columns-1;
+ rowPos -= rowSize();
+ }
+ changed = true;
+ if (doBuffer) // never buffer more than one item per frame
+ break;
+ }
+
+ if (!lazyRelease || !changed || deferredRelease) { // avoid destroying items in the same frame that we create
+ while (visibleItems.count() > 1
+ && (item = visibleItems.first())
+ && item->endRowPos() < 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 = 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;
+ }
+ deferredRelease = false;
+ } else {
+ deferredRelease = true;
+ }
+ if (changed) {
+ if (flow == QmlGraphicsGridView::LeftToRight)
+ q->setViewportHeight(endPosition() - startPosition());
+ else
+ q->setViewportWidth(endPosition() - startPosition());
+ } else if (!doBuffer && buffer && bufferMode != NoBuffer) {
+ refill(from, to, true);
+ }
+ lazyRelease = false;
+}
+
+void QmlGraphicsGridViewPrivate::updateGrid()
+{
+ Q_Q(QmlGraphicsGridView);
+ columns = (int)qMax((flow == QmlGraphicsGridView::LeftToRight ? q->width() : q->height()) / colSize(), qreal(1.));
+ if (isValid()) {
+ if (flow == QmlGraphicsGridView::LeftToRight)
+ q->setViewportHeight(endPosition() - startPosition());
+ else
+ q->setViewportWidth(endPosition() - startPosition());
+ }
+}
+
+void QmlGraphicsGridViewPrivate::scheduleLayout()
+{
+ Q_Q(QmlGraphicsGridView);
+ if (!layoutScheduled) {
+ layoutScheduled = true;
+ QMetaObject::invokeMethod(q, "layout", Qt::QueuedConnection);
+ }
+}
+
+void QmlGraphicsGridViewPrivate::layout(bool removed)
+{
+ Q_Q(QmlGraphicsGridView);
+ layoutScheduled = false;
+ if (visibleItems.count()) {
+ qreal rowPos = visibleItems.first()->rowPos();
+ qreal colPos = visibleItems.first()->colPos();
+ int col = visibleIndex % columns;
+ if (colPos != col * colSize()) {
+ if (removed)
+ rowPos -= rowSize();
+ colPos = col * colSize();
+ visibleItems.first()->setPosition(colPos, rowPos);
+ }
+ for (int i = 1; i < visibleItems.count(); ++i) {
+ FxGridItem *item = visibleItems.at(i);
+ colPos += colSize();
+ if (colPos > colSize() * (columns-1)) {
+ colPos = 0;
+ rowPos += rowSize();
+ }
+ item->setPosition(colPos, rowPos);
+ }
+ }
+ q->refill();
+ updateHighlight();
+ moveReason = Other;
+ if (flow == QmlGraphicsGridView::LeftToRight) {
+ q->setViewportHeight(endPosition() - startPosition());
+ fixupY();
+ } else {
+ q->setViewportWidth(endPosition() - startPosition());
+ fixupX();
+ }
+ updateUnrequestedPositions();
+}
+
+void QmlGraphicsGridViewPrivate::updateUnrequestedIndexes()
+{
+ Q_Q(QmlGraphicsGridView);
+ QHash<QmlGraphicsItem*,int>::iterator it;
+ for (it = unrequestedItems.begin(); it != unrequestedItems.end(); ++it)
+ *it = model->indexOf(it.key(), q);
+}
+
+void QmlGraphicsGridViewPrivate::updateUnrequestedPositions()
+{
+ QHash<QmlGraphicsItem*,int>::const_iterator it;
+ for (it = unrequestedItems.begin(); it != unrequestedItems.end(); ++it) {
+ if (flow == QmlGraphicsGridView::LeftToRight) {
+ it.key()->setPos(QPointF(colPosAt(*it), rowPosAt(*it)));
+ } else {
+ it.key()->setPos(QPointF(rowPosAt(*it), colPosAt(*it)));
+ }
+ }
+}
+
+void QmlGraphicsGridViewPrivate::updateTrackedItem()
+{
+ Q_Q(QmlGraphicsGridView);
+ FxGridItem *item = currentItem;
+ if (highlight)
+ item = highlight;
+
+ FxGridItem *oldTracked = trackedItem;
+
+ if (trackedItem && item != trackedItem) {
+ QObject::disconnect(trackedItem->item, SIGNAL(yChanged()), q, SLOT(trackedPositionChanged()));
+ QObject::disconnect(trackedItem->item, SIGNAL(xChanged()), q, SLOT(trackedPositionChanged()));
+ trackedItem = 0;
+ }
+
+ if (!trackedItem && item) {
+ trackedItem = item;
+ QObject::connect(trackedItem->item, SIGNAL(yChanged()), q, SLOT(trackedPositionChanged()));
+ QObject::connect(trackedItem->item, SIGNAL(xChanged()), q, SLOT(trackedPositionChanged()));
+ }
+ if (trackedItem && trackedItem != oldTracked)
+ q->trackedPositionChanged();
+}
+
+void QmlGraphicsGridViewPrivate::createHighlight()
+{
+ Q_Q(QmlGraphicsGridView);
+ bool changed = false;
+ if (highlight) {
+ if (trackedItem == highlight)
+ trackedItem = 0;
+ delete highlight->item;
+ delete highlight;
+ highlight = 0;
+ delete highlightXAnimator;
+ delete highlightYAnimator;
+ highlightXAnimator = 0;
+ highlightYAnimator = 0;
+ changed = true;
+ }
+
+ if (currentItem) {
+ QmlGraphicsItem *item = 0;
+ if (highlightComponent) {
+ QmlContext *highlightContext = new QmlContext(qmlContext(q));
+ QObject *nobj = highlightComponent->create(highlightContext);
+ if (nobj) {
+ highlightContext->setParent(nobj);
+ item = qobject_cast<QmlGraphicsItem *>(nobj);
+ if (!item)
+ delete nobj;
+ } else {
+ delete highlightContext;
+ }
+ } else {
+ item = new QmlGraphicsItem;
+ item->setParent(q->viewport());
+ }
+ if (item) {
+ item->setParent(q->viewport());
+ highlight = new FxGridItem(item, q);
+ highlightXAnimator = new QmlEaseFollow(q);
+ highlightXAnimator->setTarget(QmlMetaProperty(highlight->item, QLatin1String("x")));
+ highlightXAnimator->setDuration(150);
+ highlightXAnimator->setEnabled(autoHighlight);
+ highlightYAnimator = new QmlEaseFollow(q);
+ highlightYAnimator->setTarget(QmlMetaProperty(highlight->item, QLatin1String("y")));
+ highlightYAnimator->setDuration(150);
+ highlightYAnimator->setEnabled(autoHighlight);
+ changed = true;
+ }
+ }
+ if (changed)
+ emit q->highlightChanged();
+}
+
+void QmlGraphicsGridViewPrivate::updateHighlight()
+{
+ if ((!currentItem && highlight) || (currentItem && !highlight))
+ createHighlight();
+ if (currentItem && autoHighlight && highlight && !moving) {
+ // auto-update highlight
+ highlightXAnimator->setSourceValue(currentItem->item->x());
+ highlightYAnimator->setSourceValue(currentItem->item->y());
+ highlight->item->setWidth(currentItem->item->width());
+ highlight->item->setHeight(currentItem->item->height());
+ }
+ updateTrackedItem();
+}
+
+void QmlGraphicsGridViewPrivate::updateCurrent(int modelIndex)
+{
+ Q_Q(QmlGraphicsGridView);
+ if (!q->isComponentComplete() || !isValid() || modelIndex < 0 || modelIndex >= model->count()) {
+ if (currentItem) {
+ currentItem->attached->setIsCurrentItem(false);
+ releaseItem(currentItem);
+ currentItem = 0;
+ currentIndex = -1;
+ updateHighlight();
+ emit q->currentIndexChanged();
+ }
+ return;
+ }
+
+ if (currentItem && currentIndex == modelIndex) {
+ updateHighlight();
+ return;
+ }
+
+ FxGridItem *oldCurrentItem = currentItem;
+ currentIndex = modelIndex;
+ currentItem = createItem(modelIndex);
+ fixCurrentVisibility = true;
+ if (oldCurrentItem && (!currentItem || oldCurrentItem->item != currentItem->item))
+ oldCurrentItem->attached->setIsCurrentItem(false);
+ if (currentItem) {
+ currentItem->setPosition(colPosAt(modelIndex), rowPosAt(modelIndex));
+ currentItem->item->setFocus(true);
+ currentItem->attached->setIsCurrentItem(true);
+ }
+ updateHighlight();
+ emit q->currentIndexChanged();
+ releaseItem(oldCurrentItem);
+}
+
+//----------------------------------------------------------------------------
+
+/*!
+ \qmlclass GridView QmlGraphicsGridView
+ \inherits Flickable
+ \brief The GridView item provides a grid view of items provided by a model.
+
+ The model is typically provided by a QAbstractListModel "C++ model object",
+ but can also be created directly in QML.
+
+ The items are laid out top to bottom (vertically) or left to right (horizontally)
+ and may be flicked to scroll.
+
+ The below example creates a very simple grid, using a QML model.
+
+ \image gridview.png
+
+ \snippet doc/src/snippets/declarative/gridview/gridview.qml 3
+
+ The model is defined as a ListModel using QML:
+ \quotefile doc/src/snippets/declarative/gridview/dummydata/ContactModel.qml
+
+ In this case ListModel is a handy way for us to test our UI. In practice
+ the model would be implemented in C++, or perhaps via a SQL data source.
+*/
+QmlGraphicsGridView::QmlGraphicsGridView(QmlGraphicsItem *parent)
+ : QmlGraphicsFlickable(*(new QmlGraphicsGridViewPrivate), parent)
+{
+ Q_D(QmlGraphicsGridView);
+ d->init();
+}
+
+QmlGraphicsGridView::~QmlGraphicsGridView()
+{
+ Q_D(QmlGraphicsGridView);
+ d->clear();
+ if (d->ownModel)
+ delete d->model;
+}
+
+/*!
+ \qmlattachedproperty bool GridView::isCurrentItem
+ This attched property is true if this delegate is the current item; otherwise false.
+
+ It is attached to each instance of the delegate.
+*/
+
+/*!
+ \qmlattachedproperty GridView GridView::view
+ This attached property holds the view that manages this delegate instance.
+
+ It is attached to each instance of the delegate.
+*/
+
+/*!
+ \qmlattachedproperty bool 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.
+
+ \code
+ Component {
+ id: myDelegate
+ Item {
+ id: wrapper
+ GridView.onRemove: SequentialAnimation {
+ PropertyAction { target: wrapper.GridView; property: "delayRemove"; value: true }
+ NumberAnimation { target: wrapper; property: "scale"; to: 0; duration: 250; easing: "easeInOutQuad" }
+ PropertyAction { target: wrapper.GridView; property: "delayRemove"; value: false }
+ }
+ }
+ }
+ \endcode
+*/
+
+/*!
+ \qmlattachedsignal GridView::onAdd()
+ This attached handler is called immediately after an item is added to the view.
+*/
+
+/*!
+ \qmlattachedsignal GridView::onRemove()
+ This attached handler is called immediately before an item is removed from the view.
+*/
+
+
+/*!
+ \qmlproperty model GridView::model
+ This property holds the model providing data for the grid.
+
+ 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. The C++ model object must be a \l
+ {QAbstractItemModel} subclass, a VisualModel, or a simple list.
+
+ \sa {qmlmodels}{Data Models}
+*/
+QVariant QmlGraphicsGridView::model() const
+{
+ Q_D(const QmlGraphicsGridView);
+ return d->modelVariant;
+}
+
+void QmlGraphicsGridView::setModel(const QVariant &model)
+{
+ Q_D(QmlGraphicsGridView);
+ if (d->model) {
+ disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
+ disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
+ disconnect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));
+ disconnect(d->model, SIGNAL(createdItem(int, QmlGraphicsItem*)), this, SLOT(createdItem(int,QmlGraphicsItem*)));
+ disconnect(d->model, SIGNAL(destroyingItem(QmlGraphicsItem*)), this, SLOT(destroyingItem(QmlGraphicsItem*)));
+ }
+ d->clear();
+ d->modelVariant = model;
+ QObject *object = qvariant_cast<QObject*>(model);
+ QmlGraphicsVisualModel *vim = 0;
+ if (object && (vim = qobject_cast<QmlGraphicsVisualModel *>(object))) {
+ if (d->ownModel) {
+ delete d->model;
+ d->ownModel = false;
+ }
+ d->model = vim;
+ } else {
+ if (!d->ownModel) {
+ d->model = new QmlGraphicsVisualDataModel(qmlContext(this));
+ d->ownModel = true;
+ }
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model))
+ dataModel->setModel(model);
+ }
+ if (d->model) {
+ if (isComponentComplete()) {
+ refill();
+ if (d->currentIndex >= d->model->count() || d->currentIndex < 0) {
+ setCurrentIndex(0);
+ } else {
+ d->moveReason = QmlGraphicsGridViewPrivate::SetIndex;
+ d->updateCurrent(d->currentIndex);
+ }
+ }
+ connect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
+ connect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
+ connect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));
+ connect(d->model, SIGNAL(createdItem(int, QmlGraphicsItem*)), this, SLOT(createdItem(int,QmlGraphicsItem*)));
+ connect(d->model, SIGNAL(destroyingItem(QmlGraphicsItem*)), this, SLOT(destroyingItem(QmlGraphicsItem*)));
+ emit countChanged();
+ }
+}
+
+/*!
+ \qmlproperty component 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}.
+
+ Note that the GridView 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/gridview/gridview.qml 0
+*/
+QmlComponent *QmlGraphicsGridView::delegate() const
+{
+ Q_D(const QmlGraphicsGridView);
+ if (d->model) {
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model))
+ return dataModel->delegate();
+ }
+
+ return 0;
+}
+
+void QmlGraphicsGridView::setDelegate(QmlComponent *delegate)
+{
+ Q_D(QmlGraphicsGridView);
+ if (delegate == this->delegate())
+ return;
+
+ if (!d->ownModel) {
+ d->model = new QmlGraphicsVisualDataModel(qmlContext(this));
+ d->ownModel = true;
+ }
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model)) {
+ dataModel->setDelegate(delegate);
+ if (isComponentComplete()) {
+ refill();
+ d->moveReason = QmlGraphicsGridViewPrivate::SetIndex;
+ d->updateCurrent(d->currentIndex);
+ }
+ }
+}
+
+/*!
+ \qmlproperty int GridView::currentIndex
+ \qmlproperty Item GridView::currentItem
+
+ \c currentIndex holds the index of the current item.
+ \c currentItem is the current item. Note that the position of the current item
+ may only be approximate until it becomes visible in the view.
+*/
+int QmlGraphicsGridView::currentIndex() const
+{
+ Q_D(const QmlGraphicsGridView);
+ return d->currentIndex;
+}
+
+void QmlGraphicsGridView::setCurrentIndex(int index)
+{
+ Q_D(QmlGraphicsGridView);
+ if (isComponentComplete() && d->isValid() && index != d->currentIndex && index < d->model->count() && index >= 0) {
+ d->moveReason = QmlGraphicsGridViewPrivate::SetIndex;
+ cancelFlick();
+ d->updateCurrent(index);
+ } else {
+ d->currentIndex = index;
+ }
+}
+
+QmlGraphicsItem *QmlGraphicsGridView::currentItem()
+{
+ Q_D(QmlGraphicsGridView);
+ if (!d->currentItem)
+ return 0;
+ return d->currentItem->item;
+}
+
+/*!
+ \qmlproperty Item GridView::highlightItem
+
+ \c highlightItem holds the highlight item, which was created
+ from the \l highlight component.
+
+ The highlightItem is managed by the view unless
+ \l highlightFollowsCurrentItem is set to false.
+
+ \sa highlight, highlightFollowsCurrentItem
+*/
+QmlGraphicsItem *QmlGraphicsGridView::highlightItem()
+{
+ Q_D(QmlGraphicsGridView);
+ if (!d->highlight)
+ return 0;
+ return d->highlight->item;
+}
+
+/*!
+ \qmlproperty int GridView::count
+ This property holds the number of items in the view.
+*/
+int QmlGraphicsGridView::count() const
+{
+ Q_D(const QmlGraphicsGridView);
+ if (d->model)
+ return d->model->count();
+ return 0;
+}
+
+/*!
+ \qmlproperty component GridView::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, unless the highlightFollowsCurrentItem property is false.
+
+ The below example demonstrates how to make a simple highlight:
+ \snippet doc/src/snippets/declarative/gridview/gridview.qml 1
+
+ \sa highlightItem, highlightFollowsCurrentItem
+*/
+QmlComponent *QmlGraphicsGridView::highlight() const
+{
+ Q_D(const QmlGraphicsGridView);
+ return d->highlightComponent;
+}
+
+void QmlGraphicsGridView::setHighlight(QmlComponent *highlight)
+{
+ Q_D(QmlGraphicsGridView);
+ if (highlight != d->highlightComponent) {
+ d->highlightComponent = highlight;
+ d->updateCurrent(d->currentIndex);
+ }
+}
+
+/*!
+ \qmlproperty bool GridView::highlightFollowsCurrentItem
+ This property sets whether the highlight is managed by the view.
+
+ If highlightFollowsCurrentItem is true, the highlight will be moved smoothly
+ to follow the current item. If highlightFollowsCurrentItem is false, the
+ highlight will not be moved by the view, and must be implemented
+ by the highlight component, for example:
+
+ \code
+ Component {
+ id: myHighlight
+ Rectangle {
+ id: wrapper; color: "lightsteelblue"; radius: 4; width: 320; height: 60 >
+ y: SpringFollow { source: Wrapper.GridView.view.currentItem.y; spring: 3; damping: 0.2 }
+ x: SpringFollow { source: Wrapper.GridView.view.currentItem.x; spring: 3; damping: 0.2 }
+ }
+ }
+ \endcode
+*/
+bool QmlGraphicsGridView::highlightFollowsCurrentItem() const
+{
+ Q_D(const QmlGraphicsGridView);
+ return d->autoHighlight;
+}
+
+void QmlGraphicsGridView::setHighlightFollowsCurrentItem(bool autoHighlight)
+{
+ Q_D(QmlGraphicsGridView);
+ if (d->autoHighlight != autoHighlight) {
+ d->autoHighlight = autoHighlight;
+ if (d->highlightXAnimator) {
+ d->highlightXAnimator->setEnabled(d->autoHighlight);
+ d->highlightYAnimator->setEnabled(d->autoHighlight);
+ }
+ d->updateHighlight();
+ }
+}
+
+/*!
+ \qmlproperty enumeration GridView::flow
+ This property holds the flow of the grid.
+
+ Possible values are \c LeftToRight (default) and \c TopToBottom.
+
+ If \a flow is \c LeftToRight, the view will scroll vertically.
+ If \a flow is \c TopToBottom, the view will scroll horizontally.
+*/
+QmlGraphicsGridView::Flow QmlGraphicsGridView::flow() const
+{
+ Q_D(const QmlGraphicsGridView);
+ return d->flow;
+}
+
+void QmlGraphicsGridView::setFlow(Flow flow)
+{
+ Q_D(QmlGraphicsGridView);
+ if (d->flow != flow) {
+ d->flow = flow;
+ if (d->flow == LeftToRight) {
+ setViewportWidth(-1);
+ setFlickDirection(QmlGraphicsFlickable::VerticalFlick);
+ } else {
+ setViewportHeight(-1);
+ setFlickDirection(QmlGraphicsFlickable::HorizontalFlick);
+ }
+ d->clear();
+ d->updateGrid();
+ refill();
+ d->updateCurrent(d->currentIndex);
+ }
+}
+
+/*!
+ \qmlproperty bool GridView::keyNavigationWraps
+ This property holds whether the grid wraps key navigation
+
+ If this property is true then key presses to move off of one end of the grid will cause the
+ selection to jump to the other side.
+*/
+bool QmlGraphicsGridView::isWrapEnabled() const
+{
+ Q_D(const QmlGraphicsGridView);
+ return d->wrap;
+}
+
+void QmlGraphicsGridView::setWrapEnabled(bool wrap)
+{
+ Q_D(QmlGraphicsGridView);
+ d->wrap = wrap;
+}
+
+/*!
+ \qmlproperty int GridView::cacheBuffer
+ This property holds the number of off-screen pixels to cache.
+
+ This property determines the number of pixels above the top of the view
+ and below the bottom of the view to cache. Setting this value can make
+ scrolling the view smoother at the expense of additional memory usage.
+*/
+int QmlGraphicsGridView::cacheBuffer() const
+{
+ Q_D(const QmlGraphicsGridView);
+ return d->buffer;
+}
+
+void QmlGraphicsGridView::setCacheBuffer(int buffer)
+{
+ Q_D(QmlGraphicsGridView);
+ if (d->buffer != buffer) {
+ d->buffer = buffer;
+ if (isComponentComplete())
+ refill();
+ }
+}
+
+/*!
+ \qmlproperty int GridView::cellWidth
+ \qmlproperty int GridView::cellHeight
+
+ These properties holds the width and height of each cell in the grid
+
+ The default cell size is 100x100.
+*/
+int QmlGraphicsGridView::cellWidth() const
+{
+ Q_D(const QmlGraphicsGridView);
+ return d->cellWidth;
+}
+
+void QmlGraphicsGridView::setCellWidth(int cellWidth)
+{
+ Q_D(QmlGraphicsGridView);
+ if (cellWidth != d->cellWidth && cellWidth > 0) {
+ d->cellWidth = qMax(1, cellWidth);
+ d->updateGrid();
+ emit cellWidthChanged();
+ d->layout();
+ }
+}
+
+int QmlGraphicsGridView::cellHeight() const
+{
+ Q_D(const QmlGraphicsGridView);
+ return d->cellHeight;
+}
+
+void QmlGraphicsGridView::setCellHeight(int cellHeight)
+{
+ Q_D(QmlGraphicsGridView);
+ if (cellHeight != d->cellHeight && cellHeight > 0) {
+ d->cellHeight = qMax(1, cellHeight);
+ d->updateGrid();
+ emit cellHeightChanged();
+ d->layout();
+ }
+}
+
+void QmlGraphicsGridView::sizeChange()
+{
+ Q_D(QmlGraphicsGridView);
+ if (isComponentComplete()) {
+ d->updateGrid();
+ d->layout();
+ }
+}
+
+void QmlGraphicsGridView::viewportMoved()
+{
+ Q_D(QmlGraphicsGridView);
+ QmlGraphicsFlickable::viewportMoved();
+ d->lazyRelease = true;
+ if (d->flicked) {
+ if (yflick()) {
+ if (d->velocityY > 0)
+ d->bufferMode = QmlGraphicsGridViewPrivate::BufferBefore;
+ else if (d->velocityY < 0)
+ d->bufferMode = QmlGraphicsGridViewPrivate::BufferAfter;
+ }
+
+ if (xflick()) {
+ if (d->velocityX > 0)
+ d->bufferMode = QmlGraphicsGridViewPrivate::BufferBefore;
+ else if (d->velocityX < 0)
+ d->bufferMode = QmlGraphicsGridViewPrivate::BufferAfter;
+ }
+ }
+ refill();
+}
+
+qreal QmlGraphicsGridView::minYExtent() const
+{
+ Q_D(const QmlGraphicsGridView);
+ if (d->flow == QmlGraphicsGridView::TopToBottom)
+ return QmlGraphicsFlickable::minYExtent();
+ return -d->startPosition();
+}
+
+qreal QmlGraphicsGridView::maxYExtent() const
+{
+ Q_D(const QmlGraphicsGridView);
+ if (d->flow == QmlGraphicsGridView::TopToBottom)
+ return QmlGraphicsFlickable::maxYExtent();
+ qreal extent = -(d->endPosition() - height());
+ const qreal minY = minYExtent();
+ if (extent > minY)
+ extent = minY;
+ return extent;
+}
+
+qreal QmlGraphicsGridView::minXExtent() const
+{
+ Q_D(const QmlGraphicsGridView);
+ if (d->flow == QmlGraphicsGridView::LeftToRight)
+ return QmlGraphicsFlickable::minXExtent();
+ return -d->startPosition();
+}
+
+qreal QmlGraphicsGridView::maxXExtent() const
+{
+ Q_D(const QmlGraphicsGridView);
+ if (d->flow == QmlGraphicsGridView::LeftToRight)
+ return QmlGraphicsFlickable::maxXExtent();
+ qreal extent = -(d->endPosition() - width());
+ const qreal minX = minXExtent();
+ if (extent > minX)
+ extent = minX;
+ return extent;
+}
+
+void QmlGraphicsGridView::keyPressEvent(QKeyEvent *event)
+{
+ Q_D(QmlGraphicsGridView);
+ QmlGraphicsFlickable::keyPressEvent(event);
+ if (event->isAccepted())
+ return;
+ if (d->model && d->model->count() && d->interactive) {
+ d->moveReason = QmlGraphicsGridViewPrivate::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;
+ }
+ }
+ d->moveReason = QmlGraphicsGridViewPrivate::Other;
+ event->ignore();
+}
+
+/*!
+ \qmlmethod 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.
+*/
+void QmlGraphicsGridView::moveCurrentIndexUp()
+{
+ Q_D(QmlGraphicsGridView);
+ if (d->flow == QmlGraphicsGridView::LeftToRight) {
+ if (currentIndex() >= d->columns || d->wrap) {
+ int index = currentIndex() - d->columns;
+ setCurrentIndex(index >= 0 ? index : d->model->count()-1);
+ }
+ } else {
+ if (currentIndex() > 0 || d->wrap) {
+ int index = currentIndex() - 1;
+ setCurrentIndex(index >= 0 ? index : d->model->count()-1);
+ }
+ }
+}
+
+/*!
+ \qmlmethod 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.
+*/
+void QmlGraphicsGridView::moveCurrentIndexDown()
+{
+ Q_D(QmlGraphicsGridView);
+ if (d->flow == QmlGraphicsGridView::LeftToRight) {
+ if (currentIndex() < d->model->count() - d->columns || d->wrap) {
+ int index = currentIndex()+d->columns;
+ setCurrentIndex(index < d->model->count() ? index : 0);
+ }
+ } else {
+ if (currentIndex() < d->model->count() - 1 || d->wrap) {
+ int index = currentIndex() + 1;
+ setCurrentIndex(index < d->model->count() ? index : 0);
+ }
+ }
+}
+
+/*!
+ \qmlmethod 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.
+*/
+void QmlGraphicsGridView::moveCurrentIndexLeft()
+{
+ Q_D(QmlGraphicsGridView);
+ if (d->flow == QmlGraphicsGridView::LeftToRight) {
+ if (currentIndex() > 0 || d->wrap) {
+ int index = currentIndex() - 1;
+ setCurrentIndex(index >= 0 ? index : d->model->count()-1);
+ }
+ } else {
+ if (currentIndex() >= d->columns || d->wrap) {
+ int index = currentIndex() - d->columns;
+ setCurrentIndex(index >= 0 ? index : d->model->count()-1);
+ }
+ }
+}
+
+/*!
+ \qmlmethod 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.
+*/
+void QmlGraphicsGridView::moveCurrentIndexRight()
+{
+ Q_D(QmlGraphicsGridView);
+ if (d->flow == QmlGraphicsGridView::LeftToRight) {
+ if (currentIndex() < d->model->count() - 1 || d->wrap) {
+ int index = currentIndex() + 1;
+ setCurrentIndex(index < d->model->count() ? index : 0);
+ }
+ } else {
+ if (currentIndex() < d->model->count() - d->columns || d->wrap) {
+ int index = currentIndex()+d->columns;
+ setCurrentIndex(index < d->model->count() ? index : 0);
+ }
+ }
+}
+
+void QmlGraphicsGridView::positionViewAtIndex(int index)
+{
+ Q_D(QmlGraphicsGridView);
+ if (!d->isValid() || index < 0 || index >= d->model->count())
+ return;
+
+ qreal maxExtent = d->flow == QmlGraphicsGridView::LeftToRight ? -maxYExtent() : -maxXExtent();
+ FxGridItem *item = d->visibleItem(index);
+ if (item) {
+ // Already created - just move to top of view
+ int pos = qMin(item->rowPos(), maxExtent);
+ d->setPosition(pos);
+ } else {
+ int pos = d->rowPosAt(index);
+ // save the currently visible items in case any of them end up visible again
+ QList<FxGridItem*> oldVisible = d->visibleItems;
+ d->visibleItems.clear();
+ d->visibleIndex = index - index % d->columns;
+ d->setPosition(pos);
+ // setPosition() will cause refill. Adjust if we have moved beyond range
+ if (d->position() > maxExtent)
+ d->setPosition(maxExtent);
+ // now release the reference to all the old visible items.
+ for (int i = 0; i < oldVisible.count(); ++i)
+ d->releaseItem(oldVisible.at(i));
+ }
+}
+
+
+void QmlGraphicsGridView::componentComplete()
+{
+ Q_D(QmlGraphicsGridView);
+ QmlGraphicsFlickable::componentComplete();
+ d->updateGrid();
+ refill();
+ if (d->currentIndex < 0)
+ d->updateCurrent(0);
+ else
+ d->updateCurrent(d->currentIndex);
+}
+
+void QmlGraphicsGridView::trackedPositionChanged()
+{
+ Q_D(QmlGraphicsGridView);
+ if (!d->trackedItem || !d->currentItem)
+ return;
+ if (!isFlicking() && !d->moving && d->moveReason == QmlGraphicsGridViewPrivate::SetIndex) {
+ const qreal viewPos = d->position();
+ if (d->trackedItem->rowPos() < viewPos && d->currentItem->rowPos() < viewPos) {
+ d->setPosition(d->currentItem->rowPos() < d->trackedItem->rowPos() ? d->trackedItem->rowPos() : d->currentItem->rowPos());
+ } else if (d->trackedItem->endRowPos() > viewPos + d->size()
+ && d->currentItem->endRowPos() > viewPos + d->size()) {
+ qreal pos;
+ if (d->trackedItem->endRowPos() < d->currentItem->endRowPos()) {
+ pos = d->trackedItem->endRowPos() - d->size();
+ if (d->rowSize() > d->size())
+ pos = d->trackedItem->rowPos();
+ } else {
+ pos = d->currentItem->endRowPos() - d->size();
+ if (d->rowSize() > d->size())
+ pos = d->currentItem->rowPos();
+ }
+ d->setPosition(pos);
+ }
+ }
+}
+
+void QmlGraphicsGridView::itemsInserted(int modelIndex, int count)
+{
+ Q_D(QmlGraphicsGridView);
+ if (!d->visibleItems.count() || d->model->count() <= 1) {
+ refill();
+ d->updateCurrent(qMax(0, qMin(d->currentIndex, d->model->count()-1)));
+ emit countChanged();
+ return;
+ }
+
+ int index = d->mapFromModel(modelIndex);
+ if (index == -1) {
+ int i = d->visibleItems.count() - 1;
+ while (i > 0 && d->visibleItems.at(i)->index == -1)
+ --i;
+ if (d->visibleItems.at(i)->index + 1 == modelIndex) {
+ // Special case of appending an item to the model.
+ index = d->visibleIndex + d->visibleItems.count();
+ } else {
+ if (modelIndex <= d->visibleIndex) {
+ // Insert before visible items
+ d->visibleIndex += count;
+ for (int i = 0; i < d->visibleItems.count(); ++i) {
+ FxGridItem *listItem = d->visibleItems.at(i);
+ if (listItem->index != -1 && listItem->index >= modelIndex)
+ listItem->index += count;
+ }
+ }
+ if (d->currentIndex >= modelIndex) {
+ // adjust current item index
+ d->currentIndex += count;
+ if (d->currentItem)
+ d->currentItem->index = d->currentIndex;
+ }
+ d->layout();
+ emit countChanged();
+ return;
+ }
+ }
+
+ // At least some of the added items will be visible
+ int insertCount = count;
+ if (index < d->visibleIndex) {
+ insertCount -= d->visibleIndex - index;
+ index = d->visibleIndex;
+ modelIndex = d->visibleIndex;
+ }
+
+ index -= d->visibleIndex;
+ int to = d->buffer+d->position()+d->size()-1;
+ int colPos, rowPos;
+ if (index < d->visibleItems.count()) {
+ colPos = d->visibleItems.at(index)->colPos();
+ rowPos = d->visibleItems.at(index)->rowPos();
+ } else {
+ // appending items to visible list
+ colPos = d->visibleItems.at(index-1)->colPos() + d->colSize();
+ rowPos = d->visibleItems.at(index-1)->rowPos();
+ if (colPos > d->colSize() * (d->columns-1)) {
+ colPos = 0;
+ rowPos += d->rowSize();
+ }
+ }
+
+ QList<FxGridItem*> added;
+ int i = 0;
+ while (i < insertCount && rowPos <= to + d->rowSize()*(d->columns - (colPos/d->colSize()))/qreal(d->columns)) {
+ FxGridItem *item = d->createItem(modelIndex + i);
+ d->visibleItems.insert(index, item);
+ item->setPosition(colPos, rowPos);
+ added.append(item);
+ colPos += d->colSize();
+ if (colPos > d->colSize() * (d->columns-1)) {
+ colPos = 0;
+ rowPos += d->rowSize();
+ }
+ ++index;
+ ++i;
+ }
+ if (i < insertCount) {
+ // We didn't insert all our new items, which means anything
+ // beyond the current index is not visible - remove it.
+ while (d->visibleItems.count() > index) {
+ d->releaseItem(d->visibleItems.takeLast());
+ }
+ }
+
+ if (d->currentIndex >= modelIndex) {
+ // adjust current item index
+ d->currentIndex += count;
+ if (d->currentItem) {
+ d->currentItem->index = d->currentIndex;
+ d->currentItem->setPosition(d->colPosAt(d->currentIndex), d->rowPosAt(d->currentIndex));
+ }
+ }
+ // Update the indexes of the following visible items.
+ for (; index < d->visibleItems.count(); ++index) {
+ FxGridItem *listItem = d->visibleItems.at(index);
+ if (listItem->index != -1)
+ listItem->index += count;
+ }
+
+ // everything is in order now - emit add() signal
+ for (int j = 0; j < added.count(); ++j)
+ added.at(j)->attached->emitAdd();
+ d->layout();
+ emit countChanged();
+}
+
+void QmlGraphicsGridView::itemsRemoved(int modelIndex, int count)
+{
+ Q_D(QmlGraphicsGridView);
+ bool currentRemoved = d->currentIndex >= modelIndex && d->currentIndex < modelIndex + count;
+ bool removedVisible = false;
+
+ // Remove the items from the visible list, skipping anything already marked for removal
+ QList<FxGridItem*>::Iterator it = d->visibleItems.begin();
+ while (it != d->visibleItems.end()) {
+ FxGridItem *item = *it;
+ if (item->index == -1 || item->index < modelIndex) {
+ // already removed, or before removed items
+ if (item->index < modelIndex)
+ removedVisible = true;
+ ++it;
+ } else if (item->index >= modelIndex + count) {
+ // after removed items
+ item->index -= count;
+ ++it;
+ } else {
+ // removed item
+ removedVisible = true;
+ item->attached->emitRemove();
+ if (item->attached->delayRemove()) {
+ item->index = -1;
+ connect(item->attached, SIGNAL(delayRemoveChanged()), this, SLOT(destroyRemoved()), Qt::QueuedConnection);
+ ++it;
+ } else {
+ it = d->visibleItems.erase(it);
+ d->releaseItem(item);
+ }
+ }
+ }
+
+ // fix current
+ if (d->currentIndex >= modelIndex + count) {
+ d->currentIndex -= count;
+ if (d->currentItem)
+ d->currentItem->index -= count;
+ } else if (currentRemoved) {
+ // current item has been removed.
+ d->releaseItem(d->currentItem);
+ d->currentItem = 0;
+ d->currentIndex = -1;
+ d->updateCurrent(qMin(modelIndex, d->model->count()-1));
+ }
+
+ // update visibleIndex
+ for (it = d->visibleItems.begin(); it != d->visibleItems.end(); ++it) {
+ if ((*it)->index != -1) {
+ d->visibleIndex = (*it)->index;
+ break;
+ }
+ }
+
+ if (removedVisible) {
+ if (d->visibleItems.isEmpty()) {
+ d->visibleIndex = 0;
+ d->setPosition(0);
+ refill();
+ } else {
+ // Correct the positioning of the items
+ d->scheduleLayout();
+ }
+ }
+
+ emit countChanged();
+}
+
+void QmlGraphicsGridView::layout()
+{
+ Q_D(QmlGraphicsGridView);
+ if (d->layoutScheduled)
+ d->layout();
+}
+
+void QmlGraphicsGridView::destroyRemoved()
+{
+ Q_D(QmlGraphicsGridView);
+ for (QList<FxGridItem*>::Iterator it = d->visibleItems.begin();
+ it != d->visibleItems.end();) {
+ FxGridItem *listItem = *it;
+ if (listItem->index == -1 && listItem->attached->delayRemove() == false) {
+ d->releaseItem(listItem);
+ it = d->visibleItems.erase(it);
+ } else {
+ ++it;
+ }
+ }
+
+ // Correct the positioning of the items
+ d->layout();
+}
+
+void QmlGraphicsGridView::itemsMoved(int from, int to, int count)
+{
+ Q_D(QmlGraphicsGridView);
+ QHash<int,FxGridItem*> moved;
+
+ bool removedBeforeVisible = false;
+ FxGridItem *firstItem = d->firstVisibleItem();
+
+ if (from < to && from < d->visibleIndex && to > d->visibleIndex)
+ removedBeforeVisible = true;
+
+ QList<FxGridItem*>::Iterator it = d->visibleItems.begin();
+ while (it != d->visibleItems.end()) {
+ FxGridItem *item = *it;
+ if (item->index >= from && item->index < from + count) {
+ // take the items that are moving
+ item->index += (to-from);
+ moved.insert(item->index, item);
+ it = d->visibleItems.erase(it);
+ if (item->rowPos() < firstItem->rowPos())
+ removedBeforeVisible = true;
+ } else {
+ if (item->index > from && item->index != -1) {
+ // move everything after the moved items.
+ item->index -= count;
+ if (item->index < d->visibleIndex)
+ d->visibleIndex = item->index;
+ } else if (item->index != -1) {
+ removedBeforeVisible = true;
+ }
+ ++it;
+ }
+ }
+
+ int remaining = count;
+ int endIndex = d->visibleIndex;
+ it = d->visibleItems.begin();
+ while (it != d->visibleItems.end()) {
+ FxGridItem *item = *it;
+ if (remaining && item->index >= to && item->index < to + count) {
+ // place items in the target position, reusing any existing items
+ FxGridItem *movedItem = moved.take(item->index);
+ if (!movedItem)
+ movedItem = d->createItem(item->index);
+ it = d->visibleItems.insert(it, movedItem);
+ ++it;
+ --remaining;
+ } else {
+ if (item->index != -1) {
+ if (item->index >= to) {
+ // update everything after the moved items.
+ item->index += count;
+ }
+ endIndex = item->index;
+ }
+ ++it;
+ }
+ }
+
+ // If we have moved items to the end of the visible items
+ // then add any existing moved items that we have
+ while (FxGridItem *item = moved.take(endIndex+1)) {
+ d->visibleItems.append(item);
+ ++endIndex;
+ }
+
+ // Whatever moved items remain are no longer visible items.
+ while (moved.count())
+ d->releaseItem(moved.take(moved.begin().key()));
+
+ d->layout(removedBeforeVisible);
+}
+
+void QmlGraphicsGridView::createdItem(int index, QmlGraphicsItem *item)
+{
+ Q_D(QmlGraphicsGridView);
+ item->setParentItem(this);
+ if (d->requestedIndex != index) {
+ item->setParentItem(this);
+ d->unrequestedItems.insert(item, index);
+ if (d->flow == QmlGraphicsGridView::LeftToRight) {
+ item->setPos(QPointF(d->colPosAt(index), d->rowPosAt(index)));
+ } else {
+ item->setPos(QPointF(d->rowPosAt(index), d->colPosAt(index)));
+ }
+ }
+}
+
+void QmlGraphicsGridView::destroyingItem(QmlGraphicsItem *item)
+{
+ Q_D(QmlGraphicsGridView);
+ d->unrequestedItems.remove(item);
+}
+
+
+void QmlGraphicsGridView::refill()
+{
+ Q_D(QmlGraphicsGridView);
+ d->refill(d->position(), d->position()+d->size()-1);
+}
+
+
+QmlGraphicsGridViewAttached *QmlGraphicsGridView::qmlAttachedProperties(QObject *obj)
+{
+ return QmlGraphicsGridViewAttached::properties(obj);
+}
+
+QML_DEFINE_TYPE(Qt, 4,6, GridView, QmlGraphicsGridView)
+
+QT_END_NAMESPACE
+
+#include <qmlgraphicsgridview.moc>
diff --git a/src/declarative/graphicsitems/qmlgraphicsgridview_p.h b/src/declarative/graphicsitems/qmlgraphicsgridview_p.h
new file mode 100644
index 0000000..d2ef70e
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsgridview_p.h
@@ -0,0 +1,164 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSGRIDVIEW_H
+#define QMLGRAPHICSGRIDVIEW_H
+
+#include "qmlgraphicsflickable_p.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+class QmlGraphicsVisualModel;
+class QmlGraphicsGridViewAttached;
+class QmlGraphicsGridViewPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsGridView : public QmlGraphicsFlickable
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsGridView)
+
+ Q_PROPERTY(QVariant model READ model WRITE setModel)
+ Q_PROPERTY(QmlComponent *delegate READ delegate WRITE setDelegate)
+ Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
+ Q_PROPERTY(QmlGraphicsItem *currentItem READ currentItem NOTIFY currentIndexChanged)
+ Q_PROPERTY(int count READ count NOTIFY countChanged)
+
+ Q_PROPERTY(QmlComponent *highlight READ highlight WRITE setHighlight)
+ Q_PROPERTY(QmlGraphicsItem *highlightItem READ highlightItem NOTIFY highlightChanged)
+ Q_PROPERTY(bool highlightFollowsCurrentItem READ highlightFollowsCurrentItem WRITE setHighlightFollowsCurrentItem)
+
+ Q_PROPERTY(Flow flow READ flow WRITE setFlow)
+ Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled)
+ Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer)
+ Q_PROPERTY(int cellWidth READ cellWidth WRITE setCellWidth NOTIFY cellWidthChanged)
+ Q_PROPERTY(int cellHeight READ cellHeight WRITE setCellHeight NOTIFY cellHeightChanged)
+ Q_CLASSINFO("DefaultProperty", "data")
+
+public:
+ QmlGraphicsGridView(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsGridView();
+
+ QVariant model() const;
+ void setModel(const QVariant &);
+
+ QmlComponent *delegate() const;
+ void setDelegate(QmlComponent *);
+
+ int currentIndex() const;
+ void setCurrentIndex(int idx);
+
+ QmlGraphicsItem *currentItem();
+ QmlGraphicsItem *highlightItem();
+ int count() const;
+
+ QmlComponent *highlight() const;
+ void setHighlight(QmlComponent *highlight);
+
+ bool highlightFollowsCurrentItem() const;
+ void setHighlightFollowsCurrentItem(bool);
+
+ Q_ENUMS(Flow)
+ enum Flow { LeftToRight, TopToBottom };
+ Flow flow() const;
+ void setFlow(Flow);
+
+ bool isWrapEnabled() const;
+ void setWrapEnabled(bool);
+
+ int cacheBuffer() const;
+ void setCacheBuffer(int);
+
+ int cellWidth() const;
+ void setCellWidth(int);
+
+ int cellHeight() const;
+ void setCellHeight(int);
+
+ static QmlGraphicsGridViewAttached *qmlAttachedProperties(QObject *);
+
+public Q_SLOTS:
+ void moveCurrentIndexUp();
+ void moveCurrentIndexDown();
+ void moveCurrentIndexLeft();
+ void moveCurrentIndexRight();
+ void positionViewAtIndex(int index);
+
+Q_SIGNALS:
+ void countChanged();
+ void currentIndexChanged();
+ void cellWidthChanged();
+ void cellHeightChanged();
+ void highlightChanged();
+
+protected:
+ virtual void viewportMoved();
+ virtual qreal minYExtent() const;
+ virtual qreal maxYExtent() const;
+ virtual qreal minXExtent() const;
+ virtual qreal maxXExtent() const;
+ virtual void keyPressEvent(QKeyEvent *);
+ virtual void componentComplete();
+
+private Q_SLOTS:
+ void trackedPositionChanged();
+ void itemsInserted(int index, int count);
+ void itemsRemoved(int index, int count);
+ void itemsMoved(int from, int to, int count);
+ void destroyRemoved();
+ void createdItem(int index, QmlGraphicsItem *item);
+ void destroyingItem(QmlGraphicsItem *item);
+ void sizeChange();
+ void layout();
+
+private:
+ void refill();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsGridView)
+QML_DECLARE_TYPEINFO(QmlGraphicsGridView, QML_HAS_ATTACHED_PROPERTIES)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicsimage.cpp b/src/declarative/graphicsitems/qmlgraphicsimage.cpp
new file mode 100644
index 0000000..7e63c8b
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsimage.cpp
@@ -0,0 +1,369 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsimage_p.h"
+#include "qmlgraphicsimage_p_p.h"
+
+#include <QKeyEvent>
+#include <QPainter>
+
+QT_BEGIN_NAMESPACE
+
+
+QML_DEFINE_TYPE(Qt,4,6,Image,QmlGraphicsImage)
+
+/*!
+ \qmlclass Image QmlGraphicsImage
+ \brief The Image element allows you to add bitmaps to a scene.
+ \inherits Item
+
+ The Image element supports untransformed, stretched and tiled.
+
+ For an explanation of stretching and tiling, see the fillMode property description.
+
+ Examples:
+ \table
+ \row
+ \o \image declarative-qtlogo1.png
+ \o Untransformed
+ \qml
+ Image { source: "pics/qtlogo.png" }
+ \endqml
+ \row
+ \o \image declarative-qtlogo2.png
+ \o fillMode: Stretch (default)
+ \qml
+ Image {
+ width: 160
+ height: 160
+ source: "pics/qtlogo.png"
+ }
+ \endqml
+ \row
+ \o \image declarative-qtlogo3.png
+ \o fillMode: Tile
+ \qml
+ Image {
+ fillMode: Image.Tile
+ width: 160; height: 160
+ source: "pics/qtlogo.png"
+ }
+ \endqml
+ \row
+ \o \image declarative-qtlogo6.png
+ \o fillMode: TileVertically
+ \qml
+ Image {
+ fillMode: Image.TileVertically
+ width: 160; height: 160
+ source: "pics/qtlogo.png"
+ }
+ \endqml
+ \row
+ \o \image declarative-qtlogo5.png
+ \o fillMode: TileHorizontally
+ \qml
+ Image {
+ fillMode: Image.TileHorizontally
+ width: 160; height: 160
+ source: "pics/qtlogo.png"
+ }
+ \endqml
+ \endtable
+ */
+
+/*!
+ \internal
+ \class QmlGraphicsImage Image
+ \brief The QmlGraphicsImage class provides an image item that you can add to a QmlView.
+
+ \ingroup group_coreitems
+
+ Example:
+ \qml
+ Image { source: "pics/star.png" }
+ \endqml
+
+ A QmlGraphicsImage object can be instantiated in Qml using the tag \l Image.
+*/
+
+QmlGraphicsImage::QmlGraphicsImage(QmlGraphicsItem *parent)
+ : QmlGraphicsImageBase(*(new QmlGraphicsImagePrivate), parent)
+{
+ connect(this, SIGNAL(sourceChanged(QUrl)), this, SLOT(updatePaintedGeometry()));
+}
+
+QmlGraphicsImage::QmlGraphicsImage(QmlGraphicsImagePrivate &dd, QmlGraphicsItem *parent)
+ : QmlGraphicsImageBase(dd, parent)
+{
+}
+
+QmlGraphicsImage::~QmlGraphicsImage()
+{
+}
+
+void QmlGraphicsImage::setSource(const QUrl &url)
+{
+ QmlGraphicsImageBase::setSource(url);
+ updatePaintedGeometry();
+}
+
+/*!
+ \qmlproperty QPixmap Image::pixmap
+
+ This property holds the QPixmap image to display.
+
+ This is useful for displaying images provided by a C++ implementation,
+ for example, a model may provide a data role of type QPixmap.
+*/
+
+QPixmap QmlGraphicsImage::pixmap() const
+{
+ Q_D(const QmlGraphicsImage);
+ return d->pix;
+}
+
+void QmlGraphicsImage::setPixmap(const QPixmap &pix)
+{
+ Q_D(QmlGraphicsImage);
+ if (!d->url.isEmpty())
+ return;
+ d->setPixmap(pix);
+}
+
+void QmlGraphicsImagePrivate::setPixmap(const QPixmap &pixmap)
+{
+ Q_Q(QmlGraphicsImage);
+ pix = pixmap;
+
+ q->setImplicitWidth(pix.width());
+ q->setImplicitHeight(pix.height());
+ status = pix.isNull() ? QmlGraphicsImageBase::Null : QmlGraphicsImageBase::Ready;
+
+ q->update();
+ emit q->pixmapChanged();
+}
+
+/*!
+ \qmlproperty enumeration Image::fillMode
+
+ Set this property to define what happens when the image set for the item is smaller
+ than the size of the item.
+
+ \list
+ \o Stretch - the image is scaled to fit
+ \o PreserveAspectFit - the image is scaled uniformly to fit without cropping
+ \o PreserveAspectCrop - the image is scaled uniformly to fill, cropping if necessary
+ \o Tile - the image is duplicated horizontally and vertically
+ \o TileVertically - the image is stretched horizontally and tiled vertically
+ \o TileHorizontally - the image is stretched vertically and tiled horizontally
+ \endlist
+
+ \image declarative-image_fillMode.gif
+*/
+QmlGraphicsImage::FillMode QmlGraphicsImage::fillMode() const
+{
+ Q_D(const QmlGraphicsImage);
+ return d->fillMode;
+}
+
+void QmlGraphicsImage::setFillMode(FillMode mode)
+{
+ Q_D(QmlGraphicsImage);
+ if (d->fillMode == mode)
+ return;
+ d->fillMode = mode;
+ update();
+ updatePaintedGeometry();
+ emit fillModeChanged();
+}
+
+qreal QmlGraphicsImage::paintedWidth() const
+{
+ Q_D(const QmlGraphicsImage);
+ return d->paintedWidth;
+}
+
+qreal QmlGraphicsImage::paintedHeight() const
+{
+ Q_D(const QmlGraphicsImage);
+ return d->paintedHeight;
+}
+
+/*!
+ \qmlproperty enum Image::status
+
+ This property holds the status of image loading. It can be one of:
+ \list
+ \o Null - no image has been set
+ \o Ready - the image has been loaded
+ \o Loading - the image is currently being loaded
+ \o Error - an error occurred while loading the image
+ \endlist
+
+ \sa progress
+*/
+
+/*!
+ \qmlproperty real Image::progress
+
+ This property holds the progress of image loading, from 0.0 (nothing loaded)
+ to 1.0 (finished).
+
+ \sa status
+*/
+
+/*!
+ \qmlproperty bool 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.
+*/
+
+void QmlGraphicsImage::updatePaintedGeometry()
+{
+ Q_D(QmlGraphicsImage);
+
+ if (d->fillMode == PreserveAspectFit) {
+ qreal widthScale = width() / qreal(d->pix.width());
+ qreal heightScale = height() / qreal(d->pix.height());
+ if (!d->pix.width() || !d->pix.height())
+ return;
+ if (widthScale <= heightScale) {
+ d->paintedWidth = width();
+ d->paintedHeight = widthScale * qreal(d->pix.height());
+ } else if(heightScale < widthScale) {
+ d->paintedWidth = heightScale * qreal(d->pix.width());
+ d->paintedHeight = height();
+ }
+ } else {
+ d->paintedWidth = width();
+ d->paintedHeight = height();
+ }
+ emit paintedGeometryChanged();
+}
+
+void QmlGraphicsImage::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
+{
+ QmlGraphicsImageBase::geometryChanged(newGeometry, oldGeometry);
+ updatePaintedGeometry();
+}
+
+/*!
+ \qmlproperty url 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.
+*/
+
+void QmlGraphicsImage::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
+{
+ Q_D(QmlGraphicsImage);
+ if (d->pix.isNull())
+ return;
+
+ bool oldAA = p->testRenderHint(QPainter::Antialiasing);
+ bool oldSmooth = p->testRenderHint(QPainter::SmoothPixmapTransform);
+ if (d->smooth)
+ p->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth);
+
+ if (width() != d->pix.width() || height() != d->pix.height()) {
+ if (d->fillMode >= Tile) {
+ if (d->fillMode == Tile)
+ p->drawTiledPixmap(QRectF(0,0,width(),height()), d->pix);
+ else if (d->fillMode == TileVertically)
+ p->drawTiledPixmap(QRectF(0,0,d->pix.width(),height()), d->pix);
+ else
+ p->drawTiledPixmap(QRectF(0,0,width(),d->pix.height()), d->pix);
+ } else {
+ qreal widthScale = width() / qreal(d->pix.width());
+ qreal heightScale = height() / qreal(d->pix.height());
+
+ QTransform scale;
+
+ if (d->fillMode == PreserveAspectFit) {
+ if (widthScale <= heightScale) {
+ heightScale = widthScale;
+ scale.translate(0, (height() - heightScale * d->pix.height()) / 2);
+ } else if(heightScale < widthScale) {
+ widthScale = heightScale;
+ scale.translate((width() - widthScale * d->pix.width()) / 2, 0);
+ }
+ } else if (d->fillMode == PreserveAspectCrop) {
+ if (widthScale < heightScale) {
+ widthScale = heightScale;
+ scale.translate((width() - widthScale * d->pix.width()) / 2, 0);
+ } else if(heightScale < widthScale) {
+ heightScale = widthScale;
+ scale.translate(0, (height() - heightScale * d->pix.height()) / 2);
+ }
+ }
+ if (clip()) {
+ p->save();
+ p->setClipRect(boundingRect(), Qt::IntersectClip);
+ }
+ scale.scale(widthScale, heightScale);
+ QTransform old = p->transform();
+ p->setWorldTransform(scale * old);
+ p->drawPixmap(0, 0, d->pix);
+ p->setWorldTransform(old);
+ if (clip()) {
+ p->restore();
+ }
+ }
+ } else {
+ p->drawPixmap(0, 0, d->pix);
+ }
+
+ if (d->smooth) {
+ p->setRenderHint(QPainter::Antialiasing, oldAA);
+ p->setRenderHint(QPainter::SmoothPixmapTransform, oldSmooth);
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsimage_p.h b/src/declarative/graphicsitems/qmlgraphicsimage_p.h
new file mode 100644
index 0000000..dde5d79
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsimage_p.h
@@ -0,0 +1,102 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSIMAGE_H
+#define QMLGRAPHICSIMAGE_H
+
+#include "qmlgraphicsimagebase_p.h"
+
+#include <QtNetwork/qnetworkreply.h>
+
+QT_BEGIN_HEADER
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsImagePrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsImage : public QmlGraphicsImageBase
+{
+ Q_OBJECT
+ Q_ENUMS(FillMode)
+
+ Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap NOTIFY pixmapChanged DESIGNABLE false)
+ 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)
+
+public:
+ QmlGraphicsImage(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsImage();
+
+ enum FillMode { Stretch, PreserveAspectFit, PreserveAspectCrop, Tile, TileVertically, TileHorizontally };
+ FillMode fillMode() const;
+ void setFillMode(FillMode);
+
+ QPixmap pixmap() const;
+ void setPixmap(const QPixmap &);
+
+ qreal paintedWidth() const;
+ qreal paintedHeight() const;
+
+ void setSource(const QUrl &url);
+ void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+
+Q_SIGNALS:
+ void fillModeChanged();
+ void paintedGeometryChanged();
+
+protected:
+ QmlGraphicsImage(QmlGraphicsImagePrivate &dd, QmlGraphicsItem *parent);
+ void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry);
+
+protected Q_SLOTS:
+ void updatePaintedGeometry();
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsImage)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsImage)
+};
+
+QT_END_NAMESPACE
+QML_DECLARE_TYPE(QmlGraphicsImage)
+QT_END_HEADER
+
+#endif // QMLGRAPHICSIMAGE_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsimage_p_p.h b/src/declarative/graphicsitems/qmlgraphicsimage_p_p.h
new file mode 100644
index 0000000..3a5acca
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsimage_p_p.h
@@ -0,0 +1,79 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSIMAGE_P_H
+#define QMLGRAPHICSIMAGE_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 "qmlgraphicsitem_p.h"
+#include "qmlgraphicsimagebase_p_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsImagePrivate : public QmlGraphicsImageBasePrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsImage)
+
+public:
+ QmlGraphicsImagePrivate()
+ : fillMode(QmlGraphicsImage::Stretch), paintedWidth(0), paintedHeight(0)
+ {
+ }
+
+ QmlGraphicsImage::FillMode fillMode;
+ qreal paintedWidth;
+ qreal paintedHeight;
+ void setPixmap(const QPixmap &pix);
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLGRAPHICSIMAGE_P_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsimagebase.cpp b/src/declarative/graphicsitems/qmlgraphicsimagebase.cpp
new file mode 100644
index 0000000..08617ac
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsimagebase.cpp
@@ -0,0 +1,191 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsimagebase_p.h"
+#include "qmlgraphicsimagebase_p_p.h"
+
+#include <qmlengine.h>
+#include <qmlpixmapcache_p.h>
+
+#include <QFile>
+
+QT_BEGIN_NAMESPACE
+
+QmlGraphicsImageBase::QmlGraphicsImageBase(QmlGraphicsImageBasePrivate &dd, QmlGraphicsItem *parent)
+ : QmlGraphicsItem(dd, parent)
+{
+ setFlag(QGraphicsItem::ItemHasNoContents, false);
+}
+
+QmlGraphicsImageBase::~QmlGraphicsImageBase()
+{
+ Q_D(QmlGraphicsImageBase);
+ if (d->pendingPixmapCache)
+ QmlPixmapCache::cancel(d->url, this);
+}
+
+QmlGraphicsImageBase::Status QmlGraphicsImageBase::status() const
+{
+ Q_D(const QmlGraphicsImageBase);
+ return d->status;
+}
+
+
+qreal QmlGraphicsImageBase::progress() const
+{
+ Q_D(const QmlGraphicsImageBase);
+ return d->progress;
+}
+
+QUrl QmlGraphicsImageBase::source() const
+{
+ Q_D(const QmlGraphicsImageBase);
+ return d->url;
+}
+
+void QmlGraphicsImageBase::setSource(const QUrl &url)
+{
+ Q_D(QmlGraphicsImageBase);
+ //equality is fairly expensive, so we bypass for simple, common case
+ if ((d->url.isEmpty() == url.isEmpty()) && url == d->url)
+ return;
+
+ if (d->pendingPixmapCache) {
+ QmlPixmapCache::cancel(d->url, this);
+ d->pendingPixmapCache = false;
+ }
+
+ d->url = url;
+ if (d->progress != 0.0) {
+ d->progress = 0.0;
+ emit progressChanged(d->progress);
+ }
+
+ if (url.isEmpty()) {
+ d->pix = QPixmap();
+ d->status = Null;
+ setImplicitWidth(0);
+ setImplicitHeight(0);
+ emit statusChanged(d->status);
+ emit sourceChanged(d->url);
+ emit pixmapChanged();
+ update();
+ } else {
+ d->status = Loading;
+ QmlPixmapReply::Status status = QmlPixmapCache::get(d->url, &d->pix);
+ if (status != QmlPixmapReply::Ready && status != QmlPixmapReply::Error) {
+ QmlPixmapReply *reply = QmlPixmapCache::request(qmlEngine(this), d->url);
+ d->pendingPixmapCache = true;
+
+ static int replyDownloadProgress = -1;
+ static int replyFinished = -1;
+ static int thisRequestProgress = -1;
+ static int thisRequestFinished = -1;
+ if (replyDownloadProgress == -1) {
+ replyDownloadProgress =
+ QmlPixmapReply::staticMetaObject.indexOfSignal("downloadProgress(qint64,qint64)");
+ replyFinished =
+ QmlPixmapReply::staticMetaObject.indexOfSignal("finished()");
+ thisRequestProgress =
+ QmlGraphicsImageBase::staticMetaObject.indexOfSlot("requestProgress(qint64,qint64)");
+ thisRequestFinished =
+ QmlGraphicsImageBase::staticMetaObject.indexOfSlot("requestFinished()");
+ }
+
+ QMetaObject::connect(reply, replyFinished, this,
+ thisRequestFinished, Qt::DirectConnection);
+ QMetaObject::connect(reply, replyDownloadProgress, this,
+ thisRequestProgress, Qt::DirectConnection);
+ } else {
+ //### should be unified with requestFinished
+ if (status == QmlPixmapReply::Ready) {
+ setImplicitWidth(d->pix.width());
+ setImplicitHeight(d->pix.height());
+
+ if (d->status == Loading)
+ d->status = Ready;
+ } else {
+ d->status = Error;
+ }
+ d->progress = 1.0;
+ emit statusChanged(d->status);
+ emit sourceChanged(d->url);
+ emit progressChanged(d->progress);
+ emit pixmapChanged();
+ update();
+ }
+ }
+
+ emit statusChanged(d->status);
+}
+
+void QmlGraphicsImageBase::requestFinished()
+{
+ Q_D(QmlGraphicsImageBase);
+
+ d->pendingPixmapCache = false;
+
+ if (QmlPixmapCache::get(d->url, &d->pix) != QmlPixmapReply::Ready)
+ d->status = Error;
+ setImplicitWidth(d->pix.width());
+ setImplicitHeight(d->pix.height());
+
+ if (d->status == Loading)
+ d->status = Ready;
+ d->progress = 1.0;
+ emit statusChanged(d->status);
+ emit sourceChanged(d->url);
+ emit progressChanged(1.0);
+ emit pixmapChanged();
+ update();
+}
+
+void QmlGraphicsImageBase::requestProgress(qint64 received, qint64 total)
+{
+ Q_D(QmlGraphicsImageBase);
+ if (d->status == Loading && total > 0) {
+ d->progress = qreal(received)/total;
+ emit progressChanged(d->progress);
+ }
+}
+
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsimagebase_p.h b/src/declarative/graphicsitems/qmlgraphicsimagebase_p.h
new file mode 100644
index 0000000..61ea975
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsimagebase_p.h
@@ -0,0 +1,92 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSIMAGEBASE_H
+#define QMLGRAPHICSIMAGEBASE_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsImageBasePrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsImageBase : public QmlGraphicsItem
+{
+ 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)
+
+public:
+ ~QmlGraphicsImageBase();
+ enum Status { Null, Ready, Loading, Error };
+ Status status() const;
+ qreal progress() const;
+
+ QUrl source() const;
+ virtual void setSource(const QUrl &url);
+
+Q_SIGNALS:
+ void sourceChanged(const QUrl &);
+ void statusChanged(Status);
+ void progressChanged(qreal progress);
+ void pixmapChanged();
+
+protected:
+ QmlGraphicsImageBase(QmlGraphicsImageBasePrivate &dd, QmlGraphicsItem *parent);
+
+private Q_SLOTS:
+ virtual void requestFinished();
+ void requestProgress(qint64,qint64);
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsImageBase)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsImageBase)
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSIMAGEBASE_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsimagebase_p_p.h b/src/declarative/graphicsitems/qmlgraphicsimagebase_p_p.h
new file mode 100644
index 0000000..44b2332
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsimagebase_p_p.h
@@ -0,0 +1,84 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSIMAGEBASE_P_H
+#define QMLGRAPHICSIMAGEBASE_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 "qmlgraphicsitem_p.h"
+
+#include <QtCore/QPointer>
+
+QT_BEGIN_NAMESPACE
+
+class QNetworkReply;
+class QmlGraphicsImageBasePrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsImageBase)
+
+public:
+ QmlGraphicsImageBasePrivate()
+ : status(QmlGraphicsImageBase::Null),
+ progress(0.0),
+ pendingPixmapCache(false)
+ {
+ }
+
+ QPixmap pix;
+ QmlGraphicsImageBase::Status status;
+ QUrl url;
+ qreal progress;
+ bool pendingPixmapCache;
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicsitem.cpp b/src/declarative/graphicsitems/qmlgraphicsitem.cpp
new file mode 100644
index 0000000..8973cb4
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsitem.cpp
@@ -0,0 +1,3099 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsitem_p.h"
+#include "qmlgraphicsitem.h"
+
+#include "qmlgraphicsevents_p_p.h"
+
+#include <qfxperf_p_p.h>
+#include <qmlengine.h>
+#include <qmlopenmetaobject_p.h>
+#include <qmlstate_p.h>
+#include <qmlview.h>
+#include <qmlstategroup_p.h>
+#include <qmlcomponent.h>
+
+#include <QDebug>
+#include <QPen>
+#include <QFile>
+#include <QEvent>
+#include <QGraphicsSceneMouseEvent>
+#include <QtCore/qnumeric.h>
+#include <QtScript/qscriptengine.h>
+#include <QtGui/qgraphicstransform.h>
+#include <QtGui/qgraphicseffect.h>
+#include <qlistmodelinterface_p.h>
+
+QT_BEGIN_NAMESPACE
+
+#ifndef FLT_MAX
+#define FLT_MAX 1E+37
+#endif
+
+QML_DEFINE_TYPE(Qt,4,6,Item,QmlGraphicsItem)
+
+QML_DEFINE_NOCREATE_TYPE(QGraphicsTransform);
+QML_DEFINE_TYPE(Qt,4,6,Scale,QGraphicsScale)
+QML_DEFINE_TYPE(Qt,4,6,Rotation,QGraphicsRotation)
+
+#include "qmlgraphicseffects.cpp"
+
+/*!
+ \qmlclass Transform QGraphicsTransform
+ \brief The Transform elements provide a way of building advanced transformations on Items.
+
+ 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 Item. Each Transform is applied in order,
+ one at a time, to the Item it's assigned to.
+
+ \sa Rotation, Scale
+*/
+
+/*!
+ \qmlclass Scale QGraphicsScale
+ \brief The Scale object provides a way to scale an Item.
+
+ The Scale object gives more control over scaling than using Item's 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
+*/
+
+/*!
+ \qmlproperty real Scale::origin.x
+ \qmlproperty real 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 Scale::xScale
+
+ The scaling factor for the X axis.
+*/
+
+/*!
+ \qmlproperty real Scale::yScale
+
+ The scaling factor for the Y axis.
+*/
+
+/*!
+ \qmlclass Rotation QGraphicsRotation
+ \brief The Rotation object provides a way to rotate an Item.
+
+ The Rotation object gives more control over rotation than using Item's 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
+*/
+
+/*!
+ \qmlproperty real Rotation::origin.x
+ \qmlproperty real 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 Rotation::axis.x
+ \qmlproperty real Rotation::axis.y
+ \qmlproperty real 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 Rotation::angle
+
+ The angle to rotate, in degrees clockwise.
+*/
+
+
+/*!
+ \group group_animation
+ \title Animation
+*/
+
+/*!
+ \group group_coreitems
+ \title Basic Items
+*/
+
+/*!
+ \group group_effects
+ \title Effects
+*/
+
+/*!
+ \group group_layouts
+ \title Layouts
+*/
+
+/*!
+ \group group_states
+ \title States and Transitions
+*/
+
+/*!
+ \group group_utility
+ \title Utility
+*/
+
+/*!
+ \group group_views
+ \title Views
+*/
+
+/*!
+ \group group_widgets
+ \title Widgets
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsContents
+ \ingroup group_utility
+ \brief The QmlGraphicsContents class gives access to the height and width of an item's contents.
+
+*/
+
+QmlGraphicsContents::QmlGraphicsContents() : m_x(0), m_y(0), m_width(0), m_height(0)
+{
+}
+
+/*!
+ \qmlproperty real Item::childrenRect.x
+ \qmlproperty real Item::childrenRect.y
+ \qmlproperty real Item::childrenRect.width
+ \qmlproperty real 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.
+*/
+
+QRectF QmlGraphicsContents::rectF() const
+{
+ return QRectF(m_x, m_y, m_width, m_height);
+}
+
+//TODO: optimization: only check sender(), if there is one
+void QmlGraphicsContents::calcHeight()
+{
+ qreal oldy = m_y;
+ qreal oldheight = m_height;
+
+ qreal top = FLT_MAX;
+ qreal bottom = 0;
+
+ QList<QGraphicsItem *> children = m_item->childItems();
+ for (int i = 0; i < children.count(); ++i) {
+ QmlGraphicsItem *child = qobject_cast<QmlGraphicsItem *>(children.at(i));
+ if(!child)//### Should this be ignoring non-QmlGraphicsItem graphicsobjects?
+ continue;
+ 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));
+
+ if (m_height != oldheight || m_y != oldy)
+ emit rectChanged();
+}
+
+//TODO: optimization: only check sender(), if there is one
+void QmlGraphicsContents::calcWidth()
+{
+ qreal oldx = m_x;
+ qreal oldwidth = m_width;
+
+ qreal left = FLT_MAX;
+ qreal right = 0;
+
+ QList<QGraphicsItem *> children = m_item->childItems();
+ for (int i = 0; i < children.count(); ++i) {
+ QmlGraphicsItem *child = qobject_cast<QmlGraphicsItem *>(children.at(i));
+ if(!child)//### Should this be ignoring non-QmlGraphicsItem graphicsobjects?
+ continue;
+ 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));
+
+ if (m_width != oldwidth || m_x != oldx)
+ emit rectChanged();
+}
+
+void QmlGraphicsContents::setItem(QmlGraphicsItem *item)
+{
+ m_item = item;
+
+ QList<QGraphicsItem *> children = m_item->childItems();
+ for (int i = 0; i < children.count(); ++i) {
+ QmlGraphicsItem *child = qobject_cast<QmlGraphicsItem *>(children.at(i));
+ if(!child)//### Should this be ignoring non-QmlGraphicsItem graphicsobjects?
+ continue;
+ connect(child, SIGNAL(heightChanged()), this, SLOT(calcHeight()));
+ connect(child, SIGNAL(yChanged()), this, SLOT(calcHeight()));
+ connect(child, SIGNAL(widthChanged()), this, SLOT(calcWidth()));
+ connect(child, SIGNAL(xChanged()), this, SLOT(calcWidth()));
+ connect(this, SIGNAL(rectChanged()), m_item, SIGNAL(childrenRectChanged()));
+ }
+
+ calcHeight();
+ calcWidth();
+}
+
+/*
+ Key filters can be installed on a QmlGraphicsItem, 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 QmlGraphicsItemKeyFilter
+{
+public:
+ QmlGraphicsItemKeyFilter(QmlGraphicsItem * = 0);
+ virtual ~QmlGraphicsItemKeyFilter();
+
+ virtual void keyPressed(QKeyEvent *event);
+ virtual void keyReleased(QKeyEvent *event);
+ virtual void inputMethodEvent(QInputMethodEvent *event);
+ virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
+ virtual void componentComplete();
+
+private:
+ QmlGraphicsItemKeyFilter *m_next;
+};
+
+QmlGraphicsItemKeyFilter::QmlGraphicsItemKeyFilter(QmlGraphicsItem *item)
+: m_next(0)
+{
+ QmlGraphicsItemPrivate *p =
+ item?static_cast<QmlGraphicsItemPrivate *>(QGraphicsItemPrivate::get(item)):0;
+ if (p) {
+ m_next = p->keyHandler;
+ p->keyHandler = this;
+ }
+}
+
+QmlGraphicsItemKeyFilter::~QmlGraphicsItemKeyFilter()
+{
+}
+
+void QmlGraphicsItemKeyFilter::keyPressed(QKeyEvent *event)
+{
+ if (m_next) m_next->keyPressed(event);
+}
+
+void QmlGraphicsItemKeyFilter::keyReleased(QKeyEvent *event)
+{
+ if (m_next) m_next->keyReleased(event);
+}
+
+void QmlGraphicsItemKeyFilter::inputMethodEvent(QInputMethodEvent *event)
+{
+ if (m_next) m_next->inputMethodEvent(event);
+}
+
+QVariant QmlGraphicsItemKeyFilter::inputMethodQuery(Qt::InputMethodQuery query) const
+{
+ if (m_next) return m_next->inputMethodQuery(query);
+ return QVariant();
+}
+
+void QmlGraphicsItemKeyFilter::componentComplete()
+{
+ if (m_next) m_next->componentComplete();
+}
+
+
+/*!
+ \qmlclass KeyNavigation
+ \brief The KeyNavigation attached property supports key navigation by arrow keys.
+
+ It is common in key-based UIs to use arrow keys to navigate
+ between focussed items. The KeyNavigation property provides a
+ convenient way of specifying which item will gain focus
+ when an arrow key is pressed. The following example provides
+ key navigation for a 2x2 grid of items.
+
+ \code
+ Grid {
+ columns: 2
+ width: 100; height: 100
+ Rectangle {
+ id: item1
+ focus: true
+ width: 50; height: 50
+ color: focus ? "red" : "lightgray"
+ KeyNavigation.right: item2
+ KeyNavigation.down: item3
+ }
+ Rectangle {
+ id: item2
+ width: 50; height: 50
+ color: focus ? "red" : "lightgray"
+ KeyNavigation.left: item1
+ KeyNavigation.down: item4
+ }
+ Rectangle {
+ id: item3
+ width: 50; height: 50
+ color: focus ? "red" : "lightgray"
+ KeyNavigation.right: item4
+ KeyNavigation.up: item1
+ }
+ Rectangle {
+ id: item4
+ width: 50; height: 50
+ color: focus ? "red" : "lightgray"
+ KeyNavigation.left: item3
+ KeyNavigation.up: item2
+ }
+ }
+ \endcode
+
+ KeyNavigation receives key events after the item it is attached to.
+ If the item accepts an arrow key event, the KeyNavigation
+ attached property will not receive an event for that key.
+
+ If an item has been set for a direction and the KeyNavigation
+ attached property receives the corresponding
+ key press and release events, the events will be accepted by
+ KeyNaviagtion and will not propagate any further.
+
+ \sa {Keys}{Keys attached property}
+*/
+
+/*!
+ \qmlproperty Item KeyNavigation::left
+ \qmlproperty Item KeyNavigation::right
+ \qmlproperty Item KeyNavigation::up
+ \qmlproperty Item KeyNavigation::down
+
+ These properties hold the item to assign focus to
+ when Key_Left, Key_Right, Key_Up or Key_Down are
+ pressed.
+*/
+
+class QmlGraphicsKeyNavigationAttachedPrivate : public QObjectPrivate
+{
+public:
+ QmlGraphicsKeyNavigationAttachedPrivate()
+ : QObjectPrivate(), left(0), right(0), up(0), down(0) {}
+
+ QmlGraphicsItem *left;
+ QmlGraphicsItem *right;
+ QmlGraphicsItem *up;
+ QmlGraphicsItem *down;
+};
+
+class QmlGraphicsKeyNavigationAttached : public QObject, public QmlGraphicsItemKeyFilter
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlGraphicsKeyNavigationAttached)
+
+ Q_PROPERTY(QmlGraphicsItem *left READ left WRITE setLeft NOTIFY changed)
+ Q_PROPERTY(QmlGraphicsItem *right READ right WRITE setRight NOTIFY changed)
+ Q_PROPERTY(QmlGraphicsItem *up READ up WRITE setUp NOTIFY changed)
+ Q_PROPERTY(QmlGraphicsItem *down READ down WRITE setDown NOTIFY changed)
+public:
+ QmlGraphicsKeyNavigationAttached(QObject * = 0);
+
+ QmlGraphicsItem *left() const;
+ void setLeft(QmlGraphicsItem *);
+ QmlGraphicsItem *right() const;
+ void setRight(QmlGraphicsItem *);
+ QmlGraphicsItem *up() const;
+ void setUp(QmlGraphicsItem *);
+ QmlGraphicsItem *down() const;
+ void setDown(QmlGraphicsItem *);
+
+ static QmlGraphicsKeyNavigationAttached *qmlAttachedProperties(QObject *);
+
+Q_SIGNALS:
+ void changed();
+
+private:
+ virtual void keyPressed(QKeyEvent *event);
+ virtual void keyReleased(QKeyEvent *event);
+};
+
+QmlGraphicsKeyNavigationAttached::QmlGraphicsKeyNavigationAttached(QObject *parent)
+: QObject(*(new QmlGraphicsKeyNavigationAttachedPrivate), parent),
+ QmlGraphicsItemKeyFilter(qobject_cast<QmlGraphicsItem*>(parent))
+{
+}
+
+QmlGraphicsKeyNavigationAttached *
+QmlGraphicsKeyNavigationAttached::qmlAttachedProperties(QObject *obj)
+{
+ return new QmlGraphicsKeyNavigationAttached(obj);
+}
+
+QmlGraphicsItem *QmlGraphicsKeyNavigationAttached::left() const
+{
+ Q_D(const QmlGraphicsKeyNavigationAttached);
+ return d->left;
+}
+
+void QmlGraphicsKeyNavigationAttached::setLeft(QmlGraphicsItem *i)
+{
+ Q_D(QmlGraphicsKeyNavigationAttached);
+ d->left = i;
+ emit changed();
+}
+
+QmlGraphicsItem *QmlGraphicsKeyNavigationAttached::right() const
+{
+ Q_D(const QmlGraphicsKeyNavigationAttached);
+ return d->right;
+}
+
+void QmlGraphicsKeyNavigationAttached::setRight(QmlGraphicsItem *i)
+{
+ Q_D(QmlGraphicsKeyNavigationAttached);
+ d->right = i;
+ emit changed();
+}
+
+QmlGraphicsItem *QmlGraphicsKeyNavigationAttached::up() const
+{
+ Q_D(const QmlGraphicsKeyNavigationAttached);
+ return d->up;
+}
+
+void QmlGraphicsKeyNavigationAttached::setUp(QmlGraphicsItem *i)
+{
+ Q_D(QmlGraphicsKeyNavigationAttached);
+ d->up = i;
+ emit changed();
+}
+
+QmlGraphicsItem *QmlGraphicsKeyNavigationAttached::down() const
+{
+ Q_D(const QmlGraphicsKeyNavigationAttached);
+ return d->down;
+}
+
+void QmlGraphicsKeyNavigationAttached::setDown(QmlGraphicsItem *i)
+{
+ Q_D(QmlGraphicsKeyNavigationAttached);
+ d->down = i;
+ emit changed();
+}
+
+void QmlGraphicsKeyNavigationAttached::keyPressed(QKeyEvent *event)
+{
+ Q_D(QmlGraphicsKeyNavigationAttached);
+
+ event->ignore();
+
+ switch(event->key()) {
+ case Qt::Key_Left:
+ if (d->left) {
+ d->left->setFocus(true);
+ event->accept();
+ }
+ break;
+ case Qt::Key_Right:
+ if (d->right) {
+ d->right->setFocus(true);
+ event->accept();
+ }
+ break;
+ case Qt::Key_Up:
+ if (d->up) {
+ d->up->setFocus(true);
+ event->accept();
+ }
+ break;
+ case Qt::Key_Down:
+ if (d->down) {
+ d->down->setFocus(true);
+ event->accept();
+ }
+ break;
+ default:
+ break;
+ }
+
+ if (!event->isAccepted()) QmlGraphicsItemKeyFilter::keyPressed(event);
+}
+
+void QmlGraphicsKeyNavigationAttached::keyReleased(QKeyEvent *event)
+{
+ Q_D(QmlGraphicsKeyNavigationAttached);
+
+ event->ignore();
+
+ switch(event->key()) {
+ case Qt::Key_Left:
+ if (d->left) {
+ event->accept();
+ }
+ break;
+ case Qt::Key_Right:
+ if (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;
+ default:
+ break;
+ }
+
+ if (!event->isAccepted()) QmlGraphicsItemKeyFilter::keyReleased(event);
+}
+
+/*!
+ \qmlclass Keys
+ \brief The Keys attached property provides key handling to Items.
+
+ All visual primitives support key handling via the \e Keys
+ attached property. Keys can be handled via the \e onPressed
+ and \e 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 heirarchy.
+
+ \code
+ Item {
+ focus: true
+ Keys.onPressed: {
+ if (event.key == Qt.Key_Left) {
+ console.log("move left");
+ event.accepted = true;
+ }
+ }
+ }
+ \endcode
+
+ Some keys may alternatively be handled via specific signal properties,
+ for example \e onSelectPressed. These handlers automatically set
+ \e event.accepted to true.
+
+ \code
+ Item {
+ focus: true
+ Keys.onLeftPressed: console.log("move left")
+ }
+ \endcode
+
+ See \l {Qt::Key}{Qt.Key} for the list of keyboard codes.
+
+ \sa KeyEvent, {KeyNavigation}{KeyNavigation attached property}
+*/
+
+/*!
+ \qmlproperty bool Keys::enabled
+
+ This flags enables key handling if true (default); otherwise
+ no key handlers will be called.
+*/
+
+/*!
+ \qmlproperty List<Object> 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
+ ListView { id: list1 ... }
+ ListView { id: list2 ... }
+ Keys.forwardTo: [list1, list2]
+ focus: true
+ \endqml
+*/
+
+/*!
+ \qmlsignal Keys::onPressed(event)
+
+ This handler is called when a key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onReleased(event)
+
+ This handler is called when a key has been released. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDigit0Pressed(event)
+
+ This handler is called when the digit '0' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDigit1Pressed(event)
+
+ This handler is called when the digit '1' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDigit2Pressed(event)
+
+ This handler is called when the digit '2' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDigit3Pressed(event)
+
+ This handler is called when the digit '3' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDigit4Pressed(event)
+
+ This handler is called when the digit '4' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDigit5Pressed(event)
+
+ This handler is called when the digit '5' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDigit6Pressed(event)
+
+ This handler is called when the digit '6' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDigit7Pressed(event)
+
+ This handler is called when the digit '7' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDigit8Pressed(event)
+
+ This handler is called when the digit '8' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDigit9Pressed(event)
+
+ This handler is called when the digit '9' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onLeftPressed(event)
+
+ This handler is called when the Left arrow has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onRightPressed(event)
+
+ This handler is called when the Right arrow has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onUpPressed(event)
+
+ This handler is called when the Up arrow has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDownPressed(event)
+
+ This handler is called when the Down arrow has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onAsteriskPressed(event)
+
+ This handler is called when the Asterisk '*' has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onEscapePressed(event)
+
+ This handler is called when the Escape key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onReturnPressed(event)
+
+ This handler is called when the Return key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onEnterPressed(event)
+
+ This handler is called when the Enter key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onDeletePressed(event)
+
+ This handler is called when the Delete key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onSpacePressed(event)
+
+ This handler is called when the Space key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onBackPressed(event)
+
+ This handler is called when the Back key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onCancelPressed(event)
+
+ This handler is called when the Cancel key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onSelectPressed(event)
+
+ This handler is called when the Select key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onYesPressed(event)
+
+ This handler is called when the Yes key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onNoPressed(event)
+
+ This handler is called when the No key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onContext1Pressed(event)
+
+ This handler is called when the Context1 key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onContext2Pressed(event)
+
+ This handler is called when the Context2 key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onContext3Pressed(event)
+
+ This handler is called when the Context3 key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onContext4Pressed(event)
+
+ This handler is called when the Context4 key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onCallPressed(event)
+
+ This handler is called when the Call key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onHangupPressed(event)
+
+ This handler is called when the Hangup key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onFlipPressed(event)
+
+ This handler is called when the Flip key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onMenuPressed(event)
+
+ This handler is called when the Menu key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onVolumeUpPressed(event)
+
+ This handler is called when the VolumeUp key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+/*!
+ \qmlsignal Keys::onVolumeDownPressed(event)
+
+ This handler is called when the VolumeDown key has been pressed. The \a event
+ parameter provides information about the event.
+*/
+
+
+class QmlGraphicsKeysAttachedPrivate : public QObjectPrivate
+{
+public:
+ QmlGraphicsKeysAttachedPrivate()
+ : QObjectPrivate(), inPress(false), inRelease(false)
+ , inIM(false), enabled(true), imeItem(0), item(0)
+ {}
+
+ bool isConnected(const char *signalName);
+
+ QGraphicsItem *finalFocusProxy(QGraphicsItem *item) const
+ {
+ QGraphicsItem *fp;
+ while ((fp = item->focusProxy()))
+ item = fp;
+ return item;
+ }
+
+ //loop detection
+ bool inPress:1;
+ bool inRelease:1;
+ bool inIM:1;
+
+ bool enabled : 1;
+
+ QGraphicsItem *imeItem;
+ QList<QmlGraphicsItem *> targets;
+ QmlGraphicsItem *item;
+};
+
+class QmlGraphicsKeysAttached : public QObject, public QmlGraphicsItemKeyFilter
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlGraphicsKeysAttached)
+
+ Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
+ Q_PROPERTY(QList<QmlGraphicsItem *> *forwardTo READ forwardTo)
+
+public:
+ QmlGraphicsKeysAttached(QObject *parent=0);
+ ~QmlGraphicsKeysAttached();
+
+ bool enabled() const { Q_D(const QmlGraphicsKeysAttached); return d->enabled; }
+ void setEnabled(bool enabled) {
+ Q_D(QmlGraphicsKeysAttached);
+ if (enabled != d->enabled) {
+ d->enabled = enabled;
+ emit enabledChanged();
+ }
+ }
+
+ QList<QmlGraphicsItem *> *forwardTo() {
+ Q_D(QmlGraphicsKeysAttached);
+ return &d->targets;
+ }
+
+ virtual void componentComplete();
+
+ static QmlGraphicsKeysAttached *qmlAttachedProperties(QObject *);
+
+Q_SIGNALS:
+ void enabledChanged();
+ void pressed(QmlGraphicsKeyEvent *event);
+ void released(QmlGraphicsKeyEvent *event);
+ void digit0Pressed(QmlGraphicsKeyEvent *event);
+ void digit1Pressed(QmlGraphicsKeyEvent *event);
+ void digit2Pressed(QmlGraphicsKeyEvent *event);
+ void digit3Pressed(QmlGraphicsKeyEvent *event);
+ void digit4Pressed(QmlGraphicsKeyEvent *event);
+ void digit5Pressed(QmlGraphicsKeyEvent *event);
+ void digit6Pressed(QmlGraphicsKeyEvent *event);
+ void digit7Pressed(QmlGraphicsKeyEvent *event);
+ void digit8Pressed(QmlGraphicsKeyEvent *event);
+ void digit9Pressed(QmlGraphicsKeyEvent *event);
+
+ void leftPressed(QmlGraphicsKeyEvent *event);
+ void rightPressed(QmlGraphicsKeyEvent *event);
+ void upPressed(QmlGraphicsKeyEvent *event);
+ void downPressed(QmlGraphicsKeyEvent *event);
+
+ void asteriskPressed(QmlGraphicsKeyEvent *event);
+ void numberSignPressed(QmlGraphicsKeyEvent *event);
+ void escapePressed(QmlGraphicsKeyEvent *event);
+ void returnPressed(QmlGraphicsKeyEvent *event);
+ void enterPressed(QmlGraphicsKeyEvent *event);
+ void deletePressed(QmlGraphicsKeyEvent *event);
+ void spacePressed(QmlGraphicsKeyEvent *event);
+ void backPressed(QmlGraphicsKeyEvent *event);
+ void cancelPressed(QmlGraphicsKeyEvent *event);
+ void selectPressed(QmlGraphicsKeyEvent *event);
+ void yesPressed(QmlGraphicsKeyEvent *event);
+ void noPressed(QmlGraphicsKeyEvent *event);
+ void context1Pressed(QmlGraphicsKeyEvent *event);
+ void context2Pressed(QmlGraphicsKeyEvent *event);
+ void context3Pressed(QmlGraphicsKeyEvent *event);
+ void context4Pressed(QmlGraphicsKeyEvent *event);
+ void callPressed(QmlGraphicsKeyEvent *event);
+ void hangupPressed(QmlGraphicsKeyEvent *event);
+ void flipPressed(QmlGraphicsKeyEvent *event);
+ void menuPressed(QmlGraphicsKeyEvent *event);
+ void volumeUpPressed(QmlGraphicsKeyEvent *event);
+ void volumeDownPressed(QmlGraphicsKeyEvent *event);
+
+private:
+ virtual void keyPressed(QKeyEvent *event);
+ virtual void keyReleased(QKeyEvent *event);
+ virtual void inputMethodEvent(QInputMethodEvent *);
+ 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[];
+};
+
+const QmlGraphicsKeysAttached::SigMap QmlGraphicsKeysAttached::sigMap[] = {
+ { Qt::Key_Left, "leftPressed" },
+ { Qt::Key_Right, "rightPressed" },
+ { Qt::Key_Up, "upPressed" },
+ { Qt::Key_Down, "downPressed" },
+ { 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 QmlGraphicsKeysAttachedPrivate::isConnected(const char *signalName)
+{
+ return isSignalConnected(signalIndex(signalName));
+}
+
+QmlGraphicsKeysAttached::QmlGraphicsKeysAttached(QObject *parent)
+: QObject(*(new QmlGraphicsKeysAttachedPrivate), parent),
+ QmlGraphicsItemKeyFilter(qobject_cast<QmlGraphicsItem*>(parent))
+{
+ Q_D(QmlGraphicsKeysAttached);
+ d->item = qobject_cast<QmlGraphicsItem*>(parent);
+}
+
+QmlGraphicsKeysAttached::~QmlGraphicsKeysAttached()
+{
+}
+
+void QmlGraphicsKeysAttached::componentComplete()
+{
+ Q_D(QmlGraphicsKeysAttached);
+ if (d->item) {
+ for (int ii = 0; ii < d->targets.count(); ++ii) {
+ QGraphicsItem *targetItem = d->finalFocusProxy(d->targets.at(ii));
+ if (targetItem && (targetItem->flags() & QGraphicsItem::ItemAcceptsInputMethod)) {
+ d->item->setFlag(QGraphicsItem::ItemAcceptsInputMethod);
+ break;
+ }
+ }
+ }
+}
+
+void QmlGraphicsKeysAttached::keyPressed(QKeyEvent *event)
+{
+ Q_D(QmlGraphicsKeysAttached);
+ if (!d->enabled || d->inPress) {
+ event->ignore();
+ return;
+ }
+
+ // first process forwards
+ if (d->item && d->item->scene()) {
+ d->inPress = true;
+ for (int ii = 0; ii < d->targets.count(); ++ii) {
+ QGraphicsItem *i = d->finalFocusProxy(d->targets.at(ii));
+ if (i) {
+ d->item->scene()->sendEvent(i, event);
+ if (event->isAccepted()) {
+ d->inPress = false;
+ return;
+ }
+ }
+ }
+ d->inPress = false;
+ }
+
+ QmlGraphicsKeyEvent ke(*event);
+ QByteArray keySignal = keyToSignal(event->key());
+ if (!keySignal.isEmpty()) {
+ keySignal += "(QmlGraphicsKeyEvent*)";
+ if (d->isConnected(keySignal)) {
+ // If we specifically handle a key then default to accepted
+ ke.setAccepted(true);
+ int idx = QmlGraphicsKeysAttached::staticMetaObject.indexOfSignal(keySignal);
+ metaObject()->method(idx).invoke(this, Qt::DirectConnection, Q_ARG(QmlGraphicsKeyEvent*, &ke));
+ }
+ }
+ if (!ke.isAccepted())
+ emit pressed(&ke);
+ event->setAccepted(ke.isAccepted());
+
+ if (!event->isAccepted()) QmlGraphicsItemKeyFilter::keyPressed(event);
+}
+
+void QmlGraphicsKeysAttached::keyReleased(QKeyEvent *event)
+{
+ Q_D(QmlGraphicsKeysAttached);
+ if (!d->enabled || d->inRelease) {
+ event->ignore();
+ return;
+ }
+
+ if (d->item && d->item->scene()) {
+ d->inRelease = true;
+ for (int ii = 0; ii < d->targets.count(); ++ii) {
+ QGraphicsItem *i = d->finalFocusProxy(d->targets.at(ii));
+ if (i) {
+ d->item->scene()->sendEvent(i, event);
+ if (event->isAccepted()) {
+ d->inRelease = false;
+ return;
+ }
+ }
+ }
+ d->inRelease = false;
+ }
+
+ QmlGraphicsKeyEvent ke(*event);
+ emit released(&ke);
+ event->setAccepted(ke.isAccepted());
+
+ if (!event->isAccepted()) QmlGraphicsItemKeyFilter::keyReleased(event);
+}
+
+void QmlGraphicsKeysAttached::inputMethodEvent(QInputMethodEvent *event)
+{
+ Q_D(QmlGraphicsKeysAttached);
+ if (d->item && !d->inIM && d->item->scene()) {
+ d->inIM = true;
+ for (int ii = 0; ii < d->targets.count(); ++ii) {
+ QGraphicsItem *i = d->finalFocusProxy(d->targets.at(ii));
+ if (i && (i->flags() & QGraphicsItem::ItemAcceptsInputMethod)) {
+ d->item->scene()->sendEvent(i, event);
+ if (event->isAccepted()) {
+ d->imeItem = i;
+ d->inIM = false;
+ return;
+ }
+ }
+ }
+ d->inIM = false;
+ }
+ if (!event->isAccepted()) QmlGraphicsItemKeyFilter::inputMethodEvent(event);
+}
+
+class QmlGraphicsItemAccessor : public QGraphicsItem
+{
+public:
+ QVariant doInputMethodQuery(Qt::InputMethodQuery query) const {
+ return QGraphicsItem::inputMethodQuery(query);
+ }
+};
+
+QVariant QmlGraphicsKeysAttached::inputMethodQuery(Qt::InputMethodQuery query) const
+{
+ Q_D(const QmlGraphicsKeysAttached);
+ if (d->item) {
+ for (int ii = 0; ii < d->targets.count(); ++ii) {
+ QGraphicsItem *i = d->finalFocusProxy(d->targets.at(ii));
+ if (i && (i->flags() & QGraphicsItem::ItemAcceptsInputMethod) && i == d->imeItem) { //### how robust is i == d->imeItem check?
+ QVariant v = static_cast<QmlGraphicsItemAccessor *>(i)->doInputMethodQuery(query);
+ if (v.userType() == QVariant::RectF)
+ v = d->item->mapRectFromItem(i, v.toRectF()); //### cost?
+ return v;
+ }
+ }
+ }
+ return QmlGraphicsItemKeyFilter::inputMethodQuery(query);
+}
+
+QmlGraphicsKeysAttached *QmlGraphicsKeysAttached::qmlAttachedProperties(QObject *obj)
+{
+ return new QmlGraphicsKeysAttached(obj);
+}
+
+/*!
+ \class QmlGraphicsItem
+ \brief The QmlGraphicsItem class provides the most basic of all visual items in QML.
+
+ All visual items in Qt Declarative inherit from QmlGraphicsItem. Although QmlGraphicsItem
+ 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 QmlGraphicsItem to provide your own custom visual item that inherits
+ these features.
+*/
+
+/*!
+ \qmlclass Item QmlGraphicsItem
+ \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 Identity
+
+ Each item has an "id" - the identifier of the Item.
+
+ The identifier can be used in bindings and other expressions to
+ refer to the item. For example:
+
+ \qml
+ Text { id: myText; ... }
+ Text { text: myText.text }
+ \endqml
+
+ The identifier is available throughout to the \l {components}{component}
+ where it is declared. The identifier must be unique in the component.
+
+ The id should not be thought of as a "property" - it makes no sense
+ to write \c myText.id, for example.
+
+ \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.
+
+ \ingroup group_coreitems
+*/
+
+/*!
+ \property QmlGraphicsItem::baseline
+ \internal
+*/
+
+/*!
+ \property QmlGraphicsItem::effect
+ \internal
+*/
+
+/*!
+ \property QmlGraphicsItem::focus
+ \internal
+*/
+
+/*!
+ \property QmlGraphicsItem::wantsFocus
+ \internal
+*/
+
+/*!
+ \property QmlGraphicsItem::transformOrigin
+ \internal
+*/
+
+/*!
+ \fn void QmlGraphicsItem::childrenRectChanged()
+ \internal
+*/
+
+/*!
+ \fn void QmlGraphicsItem::baselineOffsetChanged()
+ \internal
+*/
+
+/*!
+ \fn void QmlGraphicsItem::widthChanged()
+ \internal
+*/
+
+/*!
+ \fn void QmlGraphicsItem::heightChanged()
+ \internal
+*/
+
+/*!
+ \fn void QmlGraphicsItem::stateChanged(const QString &state)
+ \internal
+*/
+
+/*!
+ \fn void QmlGraphicsItem::parentChanged()
+ \internal
+*/
+
+/*!
+ \fn void QmlGraphicsItem::childrenChanged()
+ \internal
+*/
+
+/*!
+ \fn void QmlGraphicsItem::focusChanged()
+ \internal
+*/
+
+/*!
+ \fn void QmlGraphicsItem::wantsFocusChanged()
+ \internal
+*/
+
+// ### Must fix
+struct RegisterAnchorLineAtStartup {
+ RegisterAnchorLineAtStartup() {
+ qRegisterMetaType<QmlGraphicsAnchorLine>("QmlGraphicsAnchorLine");
+ }
+};
+static RegisterAnchorLineAtStartup registerAnchorLineAtStartup;
+
+
+/*!
+ \fn QmlGraphicsItem::QmlGraphicsItem(QmlGraphicsItem *parent)
+
+ Constructs a QmlGraphicsItem with the given \a parent.
+*/
+QmlGraphicsItem::QmlGraphicsItem(QmlGraphicsItem* parent)
+ : QGraphicsObject(*(new QmlGraphicsItemPrivate), parent, 0)
+{
+ Q_D(QmlGraphicsItem);
+ d->init(parent);
+}
+
+/*! \internal
+*/
+QmlGraphicsItem::QmlGraphicsItem(QmlGraphicsItemPrivate &dd, QmlGraphicsItem *parent)
+ : QGraphicsObject(dd, parent, 0)
+{
+ Q_D(QmlGraphicsItem);
+ d->init(parent);
+}
+
+/*!
+ Destroys the QmlGraphicsItem.
+*/
+QmlGraphicsItem::~QmlGraphicsItem()
+{
+ Q_D(QmlGraphicsItem);
+ for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
+ QmlGraphicsAnchorsPrivate *anchor = d->changeListeners.at(ii).listener->anchorPrivate();
+ if (anchor)
+ anchor->clearItem(this);
+ }
+ if (!d->parent || (parentItem() && !parentItem()->QGraphicsItem::d_ptr->inDestructor)) {
+ for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
+ QmlGraphicsAnchorsPrivate *anchor = d->changeListeners.at(ii).listener->anchorPrivate();
+ if (anchor && anchor->item && anchor->item->parentItem() != this) //child will be deleted anyway
+ anchor->updateOnComplete();
+ }
+ }
+ for(int ii = 0; ii < d->changeListeners.count(); ++ii) {
+ const QmlGraphicsItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
+ if (change.types & QmlGraphicsItemPrivate::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;
+}
+
+/*!
+ \qmlproperty enum 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
+ rotate: 45
+ }
+ \endqml
+
+ The default transform origin is \c Center.
+*/
+
+/*!
+ \qmlproperty Item Item::parent
+ This property holds the parent of the item.
+*/
+
+/*!
+ \property QmlGraphicsItem::parent
+ This property holds the parent of the item.
+*/
+void QmlGraphicsItem::setParentItem(QmlGraphicsItem *parent)
+{
+ QmlGraphicsItem *oldParent = parentItem();
+ if (parent == oldParent || !parent) return;
+
+ Q_D(QmlGraphicsItem);
+ QObject::setParent(parent);
+ d->setParentItemHelper(parent, /*newParentVariant=*/0, /*thisPointerVariant=*/0);
+ if (oldParent)
+ emit oldParent->childrenChanged();
+ emit parentChanged();
+}
+
+/*!
+ \fn void QmlGraphicsItem::setParent(QmlGraphicsItem *parent)
+ \overload
+ Sets both the parent object and parent item to \a parent. This
+ function avoids the programming error of calling setParent()
+ when you mean setParentItem().
+*/
+
+/*!
+ Returns the QmlGraphicsItem parent of this item.
+*/
+QmlGraphicsItem *QmlGraphicsItem::parentItem() const
+{
+ return qobject_cast<QmlGraphicsItem *>(QGraphicsObject::parentItem());
+}
+
+/*!
+ \qmlproperty list<Item> Item::children
+ \qmlproperty list<Object> 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
+*/
+
+/*!
+ \property QmlGraphicsItem::children
+ \internal
+*/
+
+/*!
+ \property QmlGraphicsItem::resources
+ \internal
+*/
+
+/*!
+ Returns true if construction of the QML component is complete; otherwise
+ returns false.
+
+ It is often desireable to delay some processing until the component is
+ completed.
+
+ \sa componentComplete()
+*/
+bool QmlGraphicsItem::isComponentComplete() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->_componentComplete;
+}
+
+/*!
+ \property QmlGraphicsItem::anchors
+ \internal
+*/
+
+/*! \internal */
+QmlGraphicsAnchors *QmlGraphicsItem::anchors()
+{
+ Q_D(QmlGraphicsItem);
+ return d->anchors();
+}
+
+void QmlGraphicsItemPrivate::data_removeAt(int)
+{
+ // ###
+}
+
+int QmlGraphicsItemPrivate::data_count() const
+{
+ // ###
+ return 0;
+}
+
+void QmlGraphicsItemPrivate::data_append(QObject *o)
+{
+ Q_Q(QmlGraphicsItem);
+ QmlGraphicsItem *i = qobject_cast<QmlGraphicsItem *>(o);
+ if (i)
+ q->fxChildren()->append(i);
+ else
+ resources_append(o);
+}
+
+void QmlGraphicsItemPrivate::data_insert(int, QObject *)
+{
+ // ###
+}
+
+QObject *QmlGraphicsItemPrivate::data_at(int) const
+{
+ // ###
+ return 0;
+}
+
+void QmlGraphicsItemPrivate::data_clear()
+{
+ // ###
+}
+
+void QmlGraphicsItemPrivate::resources_removeAt(int)
+{
+ // ###
+}
+
+int QmlGraphicsItemPrivate::resources_count() const
+{
+ Q_Q(const QmlGraphicsItem);
+ return q->children().count();
+}
+
+void QmlGraphicsItemPrivate::resources_append(QObject *o)
+{
+ Q_Q(QmlGraphicsItem);
+ o->setParent(q);
+}
+
+void QmlGraphicsItemPrivate::resources_insert(int, QObject *)
+{
+ // ###
+}
+
+QObject *QmlGraphicsItemPrivate::resources_at(int idx) const
+{
+ Q_Q(const QmlGraphicsItem);
+ QObjectList children = q->children();
+ if (idx < children.count())
+ return children.at(idx);
+ else
+ return 0;
+}
+
+void QmlGraphicsItemPrivate::resources_clear()
+{
+ // ###
+}
+
+void QmlGraphicsItemPrivate::children_removeAt(int)
+{
+ // ###
+}
+
+int QmlGraphicsItemPrivate::children_count() const
+{
+ Q_Q(const QmlGraphicsItem);
+ return q->childItems().count();
+}
+
+void QmlGraphicsItemPrivate::children_append(QmlGraphicsItem *i)
+{
+ Q_Q(QmlGraphicsItem);
+ i->setParentItem(q);
+}
+
+void QmlGraphicsItemPrivate::children_insert(int, QmlGraphicsItem *)
+{
+ // ###
+}
+
+QmlGraphicsItem *QmlGraphicsItemPrivate::children_at(int idx) const
+{
+ Q_Q(const QmlGraphicsItem);
+ QList<QGraphicsItem *> children = q->childItems();
+ if (idx < children.count())
+ return qobject_cast<QmlGraphicsItem *>(children.at(idx));
+ else
+ return 0;
+}
+
+void QmlGraphicsItemPrivate::children_clear()
+{
+ // ###
+}
+
+
+void QmlGraphicsItemPrivate::transform_removeAt(int i)
+{
+ if (!transformData)
+ return;
+ transformData->graphicsTransforms.removeAt(i);
+ dirtySceneTransform = 1;
+}
+
+int QmlGraphicsItemPrivate::transform_count() const
+{
+ return transformData ? transformData->graphicsTransforms.size() : 0;
+}
+
+void QmlGraphicsItemPrivate::transform_append(QGraphicsTransform *item)
+{
+ appendGraphicsTransform(item);
+}
+
+void QmlGraphicsItemPrivate::transform_insert(int, QGraphicsTransform *)
+{
+ // ###
+}
+
+QGraphicsTransform *QmlGraphicsItemPrivate::transform_at(int idx) const
+{
+ if (!transformData)
+ return 0;
+ return transformData->graphicsTransforms.at(idx);
+}
+
+void QmlGraphicsItemPrivate::transform_clear()
+{
+ if (!transformData)
+ return;
+ Q_Q(QmlGraphicsItem);
+ q->setTransformations(QList<QGraphicsTransform *>());
+}
+
+/*!
+ \qmlproperty list<Object> Item::data
+ \default
+
+ The data property is allows you to freely mix visual children and resources
+ of 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 {}
+ Script {}
+ }
+ \endqml
+
+ instead of:
+ \qml
+ Item {
+ children: [
+ Text {},
+ Rectangle {}
+ ]
+ resources: [
+ Script {}
+ ]
+ }
+ \endqml
+
+ data is a behind-the-scenes property: you should never need to explicitly
+ specify it.
+ */
+
+/*!
+ \property QmlGraphicsItem::data
+ \internal
+*/
+
+/*! \internal */
+QmlList<QObject *> *QmlGraphicsItem::data()
+{
+ Q_D(QmlGraphicsItem);
+ return &d->data;
+}
+
+/*!
+ \property QmlGraphicsItem::childrenRect
+ \brief The geometry of an item's children.
+
+ childrenRect provides an easy way to access the (collective) position and size of the item's children.
+*/
+QRectF QmlGraphicsItem::childrenRect()
+{
+ Q_D(QmlGraphicsItem);
+ if (!d->_contents) {
+ d->_contents = new QmlGraphicsContents;
+ d->_contents->setParent(this);
+ d->_contents->setItem(this);
+ }
+ return d->_contents->rectF();
+}
+
+bool QmlGraphicsItem::clip() const
+{
+ return flags() & ItemClipsChildrenToShape;
+}
+
+void QmlGraphicsItem::setClip(bool c)
+{
+ setFlag(ItemClipsChildrenToShape, c);
+}
+
+/*!
+ \qmlproperty real Item::x
+ \qmlproperty real Item::y
+ \qmlproperty real Item::width
+ \qmlproperty real Item::height
+
+ Defines the item's position and size relative to its parent.
+
+ \qml
+ Item { x: 100; y: 100; width: 100; height: 100 }
+ \endqml
+ */
+
+/*!
+ \property QmlGraphicsItem::width
+
+ Defines the item's width relative to its parent.
+ */
+
+/*!
+ \property QmlGraphicsItem::height
+
+ Defines the item's height relative to its parent.
+ */
+
+/*!
+ \qmlproperty real Item::z
+
+ Sets the stacking order of the item. By default the stacking order is 0.
+
+ Items with a higher stacking value are drawn on top of items 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 Item::visible
+
+ Whether the item is visible. By default this is true.
+
+ \note visible is not linked to actual visibility; if an item
+ moves off screen, or the opacity changes to 0, this will
+ not affect the visible property.
+*/
+
+
+/*!
+ 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 QmlGraphicsItem::geometryChanged(const QRectF &newGeometry,
+ const QRectF &oldGeometry)
+{
+ Q_D(QmlGraphicsItem);
+
+ if (d->_anchors)
+ d->_anchors->d_func()->updateMe();
+
+ if (transformOrigin() != QmlGraphicsItem::TopLeft)
+ setTransformOriginPoint(d->computeTransformOrigin());
+
+ if (newGeometry.x() != oldGeometry.x())
+ emit xChanged();
+ if (newGeometry.width() != oldGeometry.width())
+ emit widthChanged();
+ if (newGeometry.y() != oldGeometry.y())
+ emit yChanged();
+ if (newGeometry.height() != oldGeometry.height())
+ emit heightChanged();
+
+ for(int ii = 0; ii < d->changeListeners.count(); ++ii) {
+ const QmlGraphicsItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
+ if (change.types & QmlGraphicsItemPrivate::Geometry)
+ change.listener->itemGeometryChanged(this, newGeometry, oldGeometry);
+ }
+}
+
+void QmlGraphicsItemPrivate::removeItemChangeListener(QmlGraphicsItemChangeListener *listener, ChangeTypes types)
+{
+ ChangeListener change(listener, types);
+ changeListeners.removeOne(change);
+}
+
+/*! \internal */
+void QmlGraphicsItem::keyPressEvent(QKeyEvent *event)
+{
+ Q_D(QmlGraphicsItem);
+ if (d->keyHandler)
+ d->keyHandler->keyPressed(event);
+ else
+ event->ignore();
+}
+
+/*! \internal */
+void QmlGraphicsItem::keyReleaseEvent(QKeyEvent *event)
+{
+ Q_D(QmlGraphicsItem);
+ if (d->keyHandler)
+ d->keyHandler->keyReleased(event);
+ else
+ event->ignore();
+}
+
+/*! \internal */
+void QmlGraphicsItem::inputMethodEvent(QInputMethodEvent *event)
+{
+ Q_D(QmlGraphicsItem);
+ if (d->keyHandler)
+ d->keyHandler->inputMethodEvent(event);
+ else
+ event->ignore();
+}
+
+/*! \internal */
+QVariant QmlGraphicsItem::inputMethodQuery(Qt::InputMethodQuery query) const
+{
+ Q_D(const QmlGraphicsItem);
+ QVariant v;
+ if (d->keyHandler)
+ v = d->keyHandler->inputMethodQuery(query);
+
+ if (!v.isValid())
+ v = QGraphicsObject::inputMethodQuery(query);
+
+ return v;
+}
+
+/*!
+ \internal
+*/
+QmlGraphicsAnchorLine QmlGraphicsItem::left() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->anchorLines()->left;
+}
+
+/*!
+ \internal
+*/
+QmlGraphicsAnchorLine QmlGraphicsItem::right() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->anchorLines()->right;
+}
+
+/*!
+ \internal
+*/
+QmlGraphicsAnchorLine QmlGraphicsItem::horizontalCenter() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->anchorLines()->hCenter;
+}
+
+/*!
+ \internal
+*/
+QmlGraphicsAnchorLine QmlGraphicsItem::top() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->anchorLines()->top;
+}
+
+/*!
+ \internal
+*/
+QmlGraphicsAnchorLine QmlGraphicsItem::bottom() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->anchorLines()->bottom;
+}
+
+/*!
+ \internal
+*/
+QmlGraphicsAnchorLine QmlGraphicsItem::verticalCenter() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->anchorLines()->vCenter;
+}
+
+
+/*!
+ \internal
+*/
+QmlGraphicsAnchorLine QmlGraphicsItem::baseline() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->anchorLines()->baseline;
+}
+
+/*!
+ \property QmlGraphicsItem::top
+ \internal
+*/
+
+/*!
+ \property QmlGraphicsItem::bottom
+ \internal
+*/
+
+/*!
+ \property QmlGraphicsItem::left
+ \internal
+*/
+
+/*!
+ \property QmlGraphicsItem::right
+ \internal
+*/
+
+/*!
+ \property QmlGraphicsItem::horizontalCenter
+ \internal
+*/
+
+/*!
+ \property QmlGraphicsItem::verticalCenter
+ \internal
+*/
+
+/*!
+ \qmlproperty AnchorLine Item::top
+ \qmlproperty AnchorLine Item::bottom
+ \qmlproperty AnchorLine Item::left
+ \qmlproperty AnchorLine Item::right
+ \qmlproperty AnchorLine Item::horizontalCenter
+ \qmlproperty AnchorLine Item::verticalCenter
+ \qmlproperty AnchorLine Item::baseline
+
+ The anchor lines of the item.
+
+ For more information see \l {anchor-layout}{Anchor Layouts}.
+*/
+
+/*!
+ \qmlproperty AnchorLine Item::anchors.top
+ \qmlproperty AnchorLine Item::anchors.bottom
+ \qmlproperty AnchorLine Item::anchors.left
+ \qmlproperty AnchorLine Item::anchors.right
+ \qmlproperty AnchorLine Item::anchors.horizontalCenter
+ \qmlproperty AnchorLine Item::anchors.verticalCenter
+ \qmlproperty AnchorLine Item::anchors.baseline
+
+ \qmlproperty Item Item::anchors.fill
+ \qmlproperty Item Item::anchors.centerIn
+
+ \qmlproperty real Item::anchors.margins
+ \qmlproperty real Item::anchors.topMargin
+ \qmlproperty real Item::anchors.bottomMargin
+ \qmlproperty real Item::anchors.leftMargin
+ \qmlproperty real Item::anchors.rightMargin
+ \qmlproperty real Item::anchors.horizontalCenterOffset
+ \qmlproperty real Item::anchors.verticalCenterOffset
+ \qmlproperty real Item::anchors.baselineOffset
+
+ 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 margins property can be used to set all of the various margins at once, to the same value.
+
+ 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
+ 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
+ Image { id: pic; ... }
+ Text {
+ id: label
+ anchors.left: pic.right
+ anchors.leftMargin: 5
+ ...
+ }
+ \endqml
+ \endtable
+
+ 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.
+
+ \note You can only anchor an item to siblings or a parent.
+
+ For more information see \l {anchor-layout}{Anchor Layouts}.
+*/
+
+/*!
+ \property QmlGraphicsItem::baselineOffset
+ \brief The position of the item's baseline in local coordinates.
+
+ The baseline of a 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.
+*/
+qreal QmlGraphicsItem::baselineOffset() const
+{
+ Q_D(const QmlGraphicsItem);
+ if (!d->_baselineOffset.isValid()) {
+ return 0.0;
+ } else
+ return d->_baselineOffset;
+}
+
+void QmlGraphicsItem::setBaselineOffset(qreal offset)
+{
+ Q_D(QmlGraphicsItem);
+ if (offset == d->_baselineOffset)
+ return;
+
+ d->_baselineOffset = offset;
+ emit baselineOffsetChanged();
+
+ for(int ii = 0; ii < d->changeListeners.count(); ++ii) {
+ const QmlGraphicsItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
+ if (change.types & QmlGraphicsItemPrivate::Geometry) {
+ QmlGraphicsAnchorsPrivate *anchor = change.listener->anchorPrivate();
+ if (anchor)
+ anchor->updateVerticalAnchors();
+ }
+ }
+}
+
+/*!
+ \qmlproperty real 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: "green"
+ width: 25; height: 25
+ }
+ Rectangle {
+ color: "red"
+ x: 25; y: 25; width: 50; height: 50
+ rotation: 30
+ }
+ }
+ \endqml
+ \endtable
+*/
+
+/*!
+ \qmlproperty real 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
+*/
+
+/*!
+ \qmlproperty real Item::opacity
+
+ The opacity of the item. Opacity is specified as a number between 0
+ (fully transparent) and 1 (fully opaque). The default is 1.
+
+ Opacity is an \e inherited attribute. That is, the opacity is
+ also applied individually to child items. In almost all cases this
+ is what you want. If you can spot the issue in the following
+ example, you might need to use an \l Opacity effect instead.
+
+ \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
+*/
+
+/*!
+ Returns a value indicating whether mouse input should
+ remain with this item exclusively.
+
+ \sa setKeepMouseGrab()
+ */
+bool QmlGraphicsItem::keepMouseGrab() const
+{
+ Q_D(const QmlGraphicsItem);
+ 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 QmlGraphicsItem::setKeepMouseGrab(bool keep)
+{
+ Q_D(QmlGraphicsItem);
+ d->_keepMouse = keep;
+}
+
+/*!
+ \internal
+
+ This function emits the \e focusChanged signal.
+
+ Subclasses overriding this function should call up
+ to their base class.
+*/
+void QmlGraphicsItem::focusChanged(bool flag)
+{
+ Q_UNUSED(flag);
+ emit focusChanged();
+}
+
+/*! \internal */
+QmlList<QmlGraphicsItem *> *QmlGraphicsItem::fxChildren()
+{
+ Q_D(QmlGraphicsItem);
+ return &(d->children);
+}
+
+/*! \internal */
+QmlList<QObject *> *QmlGraphicsItem::resources()
+{
+ Q_D(QmlGraphicsItem);
+ return &(d->resources);
+}
+
+/*!
+ \qmlproperty list<State> Item::states
+ This property holds a list of states defined by the item.
+
+ \qml
+ Item {
+ states: [
+ State { ... },
+ State { ... }
+ ...
+ ]
+ }
+ \endqml
+
+ \sa {qmlstate}{States}
+*/
+
+/*!
+ \property QmlGraphicsItem::states
+ \internal
+*/
+/*! \internal */
+QmlList<QmlState *>* QmlGraphicsItem::states()
+{
+ Q_D(QmlGraphicsItem);
+ return d->states()->statesProperty();
+}
+
+/*!
+ \qmlproperty list<Transition> Item::transitions
+ This property holds a list of transitions defined by the item.
+
+ \qml
+ Item {
+ transitions: [
+ Transition { ... },
+ Transition { ... }
+ ...
+ ]
+ }
+ \endqml
+
+ \sa {state-transitions}{Transitions}
+*/
+
+/*!
+ \property QmlGraphicsItem::transitions
+ \internal
+*/
+
+/*! \internal */
+QmlList<QmlTransition *>* QmlGraphicsItem::transitions()
+{
+ Q_D(QmlGraphicsItem);
+ return d->states()->transitionsProperty();
+}
+
+/*
+ \qmlproperty list<Filter> 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 { ... },
+ Relection { ... }
+ ...
+ ]
+ }
+ \endqml
+*/
+
+/*!
+ \qmlproperty bool Item::clip
+ This property holds whether clipping is enabled.
+
+ 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 QmlGraphicsItem::clip
+ This property holds whether clipping is enabled.
+
+ 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.
+*/
+
+/*!
+ \qmlproperty string 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:
+
+ \qml
+ Script {
+ function toggle() {
+ if (button.state == 'On')
+ button.state = 'Off';
+ else
+ button.state = 'On';
+ }
+ }
+ \endqml
+
+ 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}
+*/
+
+/*!
+ \property QmlGraphicsItem::state
+ \internal
+*/
+
+/*! \internal */
+QString QmlGraphicsItem::state() const
+{
+ Q_D(const QmlGraphicsItem);
+ if (!d->_stateGroup)
+ return QString();
+ else
+ return d->_stateGroup->state();
+}
+
+/*! \internal */
+void QmlGraphicsItem::setState(const QString &state)
+{
+ Q_D(QmlGraphicsItem);
+ d->states()->setState(state);
+}
+
+/*!
+ \qmlproperty list<Transform> Item::transform
+ This property holds the list of transformations to apply.
+
+ For more information see \l Transform.
+*/
+
+/*!
+ \property QmlGraphicsItem::transform
+ \internal
+*/
+
+/*! \internal */
+QmlList<QGraphicsTransform *>* QmlGraphicsItem::transform()
+{
+ Q_D(QmlGraphicsItem);
+ return &(d->transform);
+}
+
+/*!
+ \internal
+
+ classBegin() is called when the item is constructed, but its
+ properties have not yet been set.
+
+ \sa componentComplete(), isComponentComplete()
+*/
+void QmlGraphicsItem::classBegin()
+{
+ Q_D(QmlGraphicsItem);
+ d->_componentComplete = false;
+ if (d->_stateGroup)
+ d->_stateGroup->classBegin();
+ if (d->_anchors)
+ d->_anchors->classBegin();
+}
+
+/*!
+ \internal
+
+ componentComplete() is called when all items in the component
+ have been constructed. It is often desireable to delay some
+ processing until the component is complete an all bindings in the
+ component have been resolved.
+*/
+void QmlGraphicsItem::componentComplete()
+{
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::ItemComponentComplete> cc;
+#endif
+
+ Q_D(QmlGraphicsItem);
+ d->_componentComplete = true;
+ if (d->_stateGroup)
+ d->_stateGroup->componentComplete();
+ if (d->_anchors) {
+ d->_anchors->componentComplete();
+ d->_anchors->d_func()->updateOnComplete();
+ }
+ if (d->keyHandler)
+ d->keyHandler->componentComplete();
+}
+
+QmlStateGroup *QmlGraphicsItemPrivate::states()
+{
+ Q_Q(QmlGraphicsItem);
+ if (!_stateGroup) {
+ _stateGroup = new QmlStateGroup;
+ if (!_componentComplete)
+ _stateGroup->classBegin();
+ QObject::connect(_stateGroup, SIGNAL(stateChanged(QString)),
+ q, SIGNAL(stateChanged(QString)));
+ }
+
+ return _stateGroup;
+}
+
+QmlGraphicsItemPrivate::AnchorLines::AnchorLines(QmlGraphicsItem *q)
+{
+ left.item = q;
+ left.anchorLine = QmlGraphicsAnchorLine::Left;
+ right.item = q;
+ right.anchorLine = QmlGraphicsAnchorLine::Right;
+ hCenter.item = q;
+ hCenter.anchorLine = QmlGraphicsAnchorLine::HCenter;
+ top.item = q;
+ top.anchorLine = QmlGraphicsAnchorLine::Top;
+ bottom.item = q;
+ bottom.anchorLine = QmlGraphicsAnchorLine::Bottom;
+ vCenter.item = q;
+ vCenter.anchorLine = QmlGraphicsAnchorLine::VCenter;
+ baseline.item = q;
+ baseline.anchorLine = QmlGraphicsAnchorLine::Baseline;
+}
+
+QPointF QmlGraphicsItemPrivate::computeTransformOrigin() const
+{
+ Q_Q(const QmlGraphicsItem);
+
+ QRectF br = q->boundingRect();
+
+ switch(origin) {
+ default:
+ case QmlGraphicsItem::TopLeft:
+ return QPointF(0, 0);
+ case QmlGraphicsItem::Top:
+ return QPointF(br.width() / 2., 0);
+ case QmlGraphicsItem::TopRight:
+ return QPointF(br.width(), 0);
+ case QmlGraphicsItem::Left:
+ return QPointF(0, br.height() / 2.);
+ case QmlGraphicsItem::Center:
+ return QPointF(br.width() / 2., br.height() / 2.);
+ case QmlGraphicsItem::Right:
+ return QPointF(br.width(), br.height() / 2.);
+ case QmlGraphicsItem::BottomLeft:
+ return QPointF(0, br.height());
+ case QmlGraphicsItem::Bottom:
+ return QPointF(br.width() / 2., br.height());
+ case QmlGraphicsItem::BottomRight:
+ return QPointF(br.width(), br.height());
+ }
+}
+
+/*! \internal */
+bool QmlGraphicsItem::sceneEvent(QEvent *event)
+{
+ bool rv = QGraphicsItem::sceneEvent(event);
+
+ if (event->type() == QEvent::FocusIn ||
+ event->type() == QEvent::FocusOut) {
+ focusChanged(hasFocus());
+ }
+
+ return rv;
+}
+
+/*! \internal */
+QVariant QmlGraphicsItem::itemChange(GraphicsItemChange change,
+ const QVariant &value)
+{
+ Q_D(const QmlGraphicsItem);
+ switch (change) {
+ case ItemParentHasChanged:
+ emit parentChanged();
+ break;
+ case ItemChildAddedChange:
+ case ItemChildRemovedChange:
+ emit childrenChanged();
+ break;
+ case ItemVisibleHasChanged: {
+ for(int ii = 0; ii < d->changeListeners.count(); ++ii) {
+ const QmlGraphicsItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
+ if (change.types & QmlGraphicsItemPrivate::Visibility) {
+ change.listener->itemVisibilityChanged(this);
+ }
+ }
+ }
+ break;
+ case ItemOpacityHasChanged: {
+ for(int ii = 0; ii < d->changeListeners.count(); ++ii) {
+ const QmlGraphicsItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
+ if (change.types & QmlGraphicsItemPrivate::Opacity) {
+ change.listener->itemOpacityChanged(this);
+ }
+ }
+ }
+ break;
+ default:
+ break;
+ }
+
+ return QGraphicsItem::itemChange(change, value);
+}
+
+/*! \internal */
+QRectF QmlGraphicsItem::boundingRect() const
+{
+ Q_D(const QmlGraphicsItem);
+ return QRectF(0, 0, d->width, d->height);
+}
+
+/*!
+ \enum QmlGraphicsItem::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.
+*/
+
+/*!
+ Returns the current transform origin.
+*/
+QmlGraphicsItem::TransformOrigin QmlGraphicsItem::transformOrigin() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->origin;
+}
+
+/*!
+ Set the transform \a origin.
+*/
+void QmlGraphicsItem::setTransformOrigin(TransformOrigin origin)
+{
+ Q_D(QmlGraphicsItem);
+ if (origin != d->origin) {
+ d->origin = origin;
+ QGraphicsItem::setTransformOriginPoint(d->computeTransformOrigin());
+ emit transformOriginChanged(d->origin);
+ }
+}
+
+/*!
+ \property QmlGraphicsItem::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 QmlGraphicsItem::smooth() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->smooth;
+}
+
+/*!
+ Sets whether the item should be drawn with antialiasing and
+ smooth pixmap filtering to \a smooth.
+
+ \sa smooth()
+*/
+void QmlGraphicsItem::setSmooth(bool smooth)
+{
+ Q_D(QmlGraphicsItem);
+ if (d->smooth == smooth)
+ return;
+ d->smooth = smooth;
+ update();
+}
+
+qreal QmlGraphicsItem::width() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->width;
+}
+
+void QmlGraphicsItem::setWidth(qreal w)
+{
+ Q_D(QmlGraphicsItem);
+ if (qIsNaN(w))
+ return;
+
+ d->widthValid = true;
+ if (d->width == w)
+ return;
+
+ qreal oldWidth = d->width;
+
+ prepareGeometryChange();
+ d->width = w;
+ update();
+
+ geometryChanged(QRectF(x(), y(), width(), height()),
+ QRectF(x(), y(), oldWidth, height()));
+}
+
+void QmlGraphicsItem::resetWidth()
+{
+ Q_D(QmlGraphicsItem);
+ d->widthValid = false;
+ setImplicitWidth(implicitWidth());
+}
+
+/*!
+ Returns the width of the item that is implied by other properties that determine the content.
+*/
+qreal QmlGraphicsItem::implicitWidth() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->implicitWidth;
+}
+
+/*!
+ Sets the implied width of the item to \a w.
+ This is the width implied by other properties that determine the content.
+*/
+void QmlGraphicsItem::setImplicitWidth(qreal w)
+{
+ Q_D(QmlGraphicsItem);
+ d->implicitWidth = w;
+ if (d->width == w || widthValid())
+ return;
+
+ qreal oldWidth = d->width;
+
+ prepareGeometryChange();
+ d->width = w;
+ update();
+
+ geometryChanged(QRectF(x(), y(), width(), height()),
+ QRectF(x(), y(), oldWidth, height()));
+}
+
+/*!
+ Returns whether the width property has been set explicitly.
+*/
+bool QmlGraphicsItem::widthValid() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->widthValid;
+}
+
+qreal QmlGraphicsItem::height() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->height;
+}
+
+void QmlGraphicsItem::setHeight(qreal h)
+{
+ Q_D(QmlGraphicsItem);
+ if (qIsNaN(h))
+ return;
+
+ d->heightValid = true;
+ if (d->height == h)
+ return;
+
+ qreal oldHeight = d->height;
+
+ prepareGeometryChange();
+ d->height = h;
+ update();
+
+ geometryChanged(QRectF(x(), y(), width(), height()),
+ QRectF(x(), y(), width(), oldHeight));
+}
+
+void QmlGraphicsItem::resetHeight()
+{
+ Q_D(QmlGraphicsItem);
+ d->heightValid = false;
+ setImplicitHeight(implicitHeight());
+}
+
+/*!
+ Returns the height of the item that is implied by other properties that determine the content.
+*/
+qreal QmlGraphicsItem::implicitHeight() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->implicitHeight;
+}
+
+/*!
+ Sets the implied height of the item to \a h.
+ This is the height implied by other properties that determine the content.
+*/
+void QmlGraphicsItem::setImplicitHeight(qreal h)
+{
+ Q_D(QmlGraphicsItem);
+ d->implicitHeight = h;
+ if (d->height == h || heightValid())
+ return;
+
+ qreal oldHeight = d->height;
+
+ prepareGeometryChange();
+ d->height = h;
+ update();
+
+ geometryChanged(QRectF(x(), y(), width(), height()),
+ QRectF(x(), y(), width(), oldHeight));
+}
+
+/*!
+ Returns whether the height property has been set explicitly.
+*/
+bool QmlGraphicsItem::heightValid() const
+{
+ Q_D(const QmlGraphicsItem);
+ return d->heightValid;
+}
+
+/*!
+ \qmlproperty bool Item::wantsFocus
+
+ This property indicates whether the item has has an active focus request.
+
+ \sa {qmlfocus}{Keyboard Focus}
+*/
+
+/*! \internal */
+bool QmlGraphicsItem::wantsFocus() const
+{
+ return focusItem() != 0;
+}
+
+/*!
+ \qmlproperty bool Item::focus
+ This property indicates whether the item has keyboard input focus. Set this
+ property to true to request focus.
+
+ \sa {qmlfocus}{Keyboard Focus}
+*/
+
+/*! \internal */
+bool QmlGraphicsItem::hasFocus() const
+{
+ return QGraphicsItem::hasFocus();
+}
+
+/*! \internal */
+void QmlGraphicsItem::setFocus(bool focus)
+{
+ if (focus)
+ QGraphicsItem::setFocus(Qt::OtherFocusReason);
+ else
+ QGraphicsItem::clearFocus();
+}
+
+/*!
+ \reimp
+ \internal
+*/
+void QmlGraphicsItem::paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *)
+{
+}
+
+/*!
+ \reimp
+ \internal
+*/
+bool QmlGraphicsItem::event(QEvent *ev)
+{
+ return QGraphicsObject::event(ev);
+}
+
+QDebug operator<<(QDebug debug, QmlGraphicsItem *item)
+{
+ if (!item) {
+ debug << "QmlGraphicsItem(0)";
+ return debug;
+ }
+
+ debug << item->metaObject()->className() << "(this =" << ((void*)item)
+ << ", parent =" << ((void*)item->parentItem())
+ << ", geometry =" << QRectF(item->pos(), QSizeF(item->width(), item->height()))
+ << ", z =" << item->zValue() << ')';
+ return debug;
+}
+
+int QmlGraphicsItemPrivate::consistentTime = -1;
+void QmlGraphicsItemPrivate::setConsistentTime(int t)
+{
+ consistentTime = t;
+}
+
+QTime QmlGraphicsItemPrivate::currentTime()
+{
+ if (consistentTime == -1)
+ return QTime::currentTime();
+ else
+ return QTime(0, 0).addMSecs(consistentTime);
+}
+
+void QmlGraphicsItemPrivate::start(QTime &t)
+{
+ t = currentTime();
+}
+
+int QmlGraphicsItemPrivate::elapsed(QTime &t)
+{
+ int n = t.msecsTo(currentTime());
+ if (n < 0) // passed midnight
+ n += 86400 * 1000;
+ return n;
+}
+
+int QmlGraphicsItemPrivate::restart(QTime &t)
+{
+ QTime time = currentTime();
+ int n = t.msecsTo(time);
+ if (n < 0) // passed midnight
+ n += 86400*1000;
+ t = time;
+ return n;
+}
+
+#include <qmlgraphicsitem.moc>
+#include <moc_qmlgraphicsitem.cpp>
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsKeysAttached)
+QML_DECLARE_TYPEINFO(QmlGraphicsKeysAttached, QML_HAS_ATTACHED_PROPERTIES)
+QML_DEFINE_TYPE(Qt,4,6,Keys,QmlGraphicsKeysAttached)
+QML_DECLARE_TYPE(QmlGraphicsKeyNavigationAttached)
+QML_DECLARE_TYPEINFO(QmlGraphicsKeyNavigationAttached, QML_HAS_ATTACHED_PROPERTIES)
+QML_DEFINE_TYPE(Qt,4,6,KeyNavigation,QmlGraphicsKeyNavigationAttached)
diff --git a/src/declarative/graphicsitems/qmlgraphicsitem.h b/src/declarative/graphicsitems/qmlgraphicsitem.h
new file mode 100644
index 0000000..8ae2d5c
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsitem.h
@@ -0,0 +1,239 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSITEM_H
+#define QMLGRAPHICSITEM_H
+
+#include <qml.h>
+#include <qmlcomponent.h>
+
+#include <QtCore/QObject>
+#include <QtCore/QList>
+#include <QtGui/qgraphicsitem.h>
+#include <QtGui/qgraphicstransform.h>
+#include <QtGui/qfont.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlState;
+class QmlGraphicsAnchorLine;
+class QmlTransition;
+class QmlGraphicsKeyEvent;
+class QmlGraphicsAnchors;
+class QmlGraphicsItemPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsItem : public QGraphicsObject, public QmlParserStatus
+{
+ Q_OBJECT
+ Q_INTERFACES(QmlParserStatus)
+
+ Q_PROPERTY(QmlGraphicsItem * parent READ parentItem WRITE setParentItem NOTIFY parentChanged DESIGNABLE false FINAL)
+ Q_PROPERTY(QmlList<QObject *> *data READ data DESIGNABLE false)
+ Q_PROPERTY(QmlList<QmlGraphicsItem *>* children READ fxChildren DESIGNABLE false NOTIFY childrenChanged)
+ Q_PROPERTY(QmlList<QObject *>* resources READ resources DESIGNABLE false)
+ Q_PROPERTY(QmlList<QmlState *>* states READ states DESIGNABLE false)
+ Q_PROPERTY(QmlList<QmlTransition *>* transitions READ transitions DESIGNABLE false)
+ Q_PROPERTY(QString state READ state WRITE setState NOTIFY stateChanged)
+ 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(QRectF childrenRect READ childrenRect NOTIFY childrenRectChanged DESIGNABLE false FINAL)
+ Q_PROPERTY(QmlGraphicsAnchors * anchors READ anchors DESIGNABLE false CONSTANT FINAL)
+ Q_PROPERTY(QmlGraphicsAnchorLine left READ left CONSTANT FINAL)
+ Q_PROPERTY(QmlGraphicsAnchorLine right READ right CONSTANT FINAL)
+ Q_PROPERTY(QmlGraphicsAnchorLine horizontalCenter READ horizontalCenter CONSTANT FINAL)
+ Q_PROPERTY(QmlGraphicsAnchorLine top READ top CONSTANT FINAL)
+ Q_PROPERTY(QmlGraphicsAnchorLine bottom READ bottom CONSTANT FINAL)
+ Q_PROPERTY(QmlGraphicsAnchorLine verticalCenter READ verticalCenter CONSTANT FINAL)
+ Q_PROPERTY(QmlGraphicsAnchorLine baseline READ baseline CONSTANT FINAL)
+ Q_PROPERTY(qreal baselineOffset READ baselineOffset WRITE setBaselineOffset NOTIFY baselineOffsetChanged)
+ Q_PROPERTY(bool clip READ clip WRITE setClip) // ### move to QGI/QGO, NOTIFY
+ Q_PROPERTY(bool focus READ hasFocus WRITE setFocus NOTIFY focusChanged FINAL)
+ Q_PROPERTY(bool wantsFocus READ wantsFocus NOTIFY wantsFocusChanged)
+ Q_PROPERTY(QmlList<QGraphicsTransform *>* transform READ transform DESIGNABLE false FINAL)
+ Q_PROPERTY(TransformOrigin transformOrigin READ transformOrigin WRITE setTransformOrigin NOTIFY transformOriginChanged)
+ Q_PROPERTY(bool smooth READ smooth WRITE setSmooth)
+ Q_PROPERTY(QGraphicsEffect *effect READ graphicsEffect WRITE setGraphicsEffect)
+ Q_ENUMS(TransformOrigin)
+ Q_CLASSINFO("DefaultProperty", "data")
+
+public:
+ enum TransformOrigin {
+ TopLeft, Top, TopRight,
+ Left, Center, Right,
+ BottomLeft, Bottom, BottomRight
+ };
+
+ QmlGraphicsItem(QmlGraphicsItem *parent = 0);
+ virtual ~QmlGraphicsItem();
+
+ QmlGraphicsItem *parentItem() const;
+ void setParentItem(QmlGraphicsItem *parent);
+ void setParent(QmlGraphicsItem *parent) { setParentItem(parent); }
+
+ QmlList<QObject *> *data();
+ QmlList<QmlGraphicsItem *> *fxChildren();
+ QmlList<QObject *> *resources();
+
+ QmlGraphicsAnchors *anchors();
+ QRectF childrenRect();
+
+ bool clip() const;
+ void setClip(bool);
+
+ QmlList<QmlState *>* states();
+ QmlList<QmlTransition *>* transitions();
+
+ QString state() const;
+ void setState(const QString &);
+
+ qreal baselineOffset() const;
+ void setBaselineOffset(qreal);
+
+ QmlList<QGraphicsTransform *> *transform();
+
+ qreal width() const;
+ void setWidth(qreal);
+ void resetWidth();
+ qreal implicitWidth() const;
+
+ qreal height() const;
+ void setHeight(qreal);
+ void resetHeight();
+ qreal implicitHeight() const;
+
+ TransformOrigin transformOrigin() const;
+ void setTransformOrigin(TransformOrigin);
+
+ bool smooth() const;
+ void setSmooth(bool);
+
+ QRectF boundingRect() const;
+ virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+
+ bool wantsFocus() const;
+ bool hasFocus() const;
+ void setFocus(bool);
+
+ bool keepMouseGrab() const;
+ void setKeepMouseGrab(bool);
+
+ QmlGraphicsAnchorLine left() const;
+ QmlGraphicsAnchorLine right() const;
+ QmlGraphicsAnchorLine horizontalCenter() const;
+ QmlGraphicsAnchorLine top() const;
+ QmlGraphicsAnchorLine bottom() const;
+ QmlGraphicsAnchorLine verticalCenter() const;
+ QmlGraphicsAnchorLine baseline() const;
+
+Q_SIGNALS:
+ void widthChanged();
+ void heightChanged();
+ void childrenChanged();
+ void childrenRectChanged();
+ void baselineOffsetChanged();
+ void stateChanged(const QString &);
+ void focusChanged();
+ void wantsFocusChanged();
+ void parentChanged();
+ void transformOriginChanged(TransformOrigin);
+
+protected:
+ bool isComponentComplete() const;
+ virtual bool sceneEvent(QEvent *);
+ virtual bool event(QEvent *);
+ virtual QVariant itemChange(GraphicsItemChange, const QVariant &);
+
+ void setImplicitWidth(qreal);
+ bool widthValid() const; // ### better name?
+ void setImplicitHeight(qreal);
+ bool heightValid() const; // ### better name?
+
+ virtual void classBegin();
+ virtual void componentComplete();
+ virtual void focusChanged(bool);
+ virtual void keyPressEvent(QKeyEvent *event);
+ virtual void keyReleaseEvent(QKeyEvent *event);
+ virtual void inputMethodEvent(QInputMethodEvent *);
+ virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
+ virtual void geometryChanged(const QRectF &newGeometry,
+ const QRectF &oldGeometry);
+
+protected:
+ QmlGraphicsItem(QmlGraphicsItemPrivate &dd, QmlGraphicsItem *parent = 0);
+
+private:
+ friend class QmlStatePrivate;
+ friend class QmlGraphicsAnchors;
+ Q_DISABLE_COPY(QmlGraphicsItem)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsItem)
+};
+
+template<typename T>
+ T qobject_cast(QGraphicsObject *o)
+{
+ QObject *obj = o;
+ return qobject_cast<T>(obj);
+}
+
+// ### move to QGO
+template<typename T>
+T qobject_cast(QGraphicsItem *item)
+{
+ if (!item) return 0;
+ QObject *o = item->toGraphicsObject();
+ return qobject_cast<T>(o);
+}
+
+QDebug Q_DECLARATIVE_EXPORT operator<<(QDebug debug, QmlGraphicsItem *item);
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsItem)
+QML_DECLARE_TYPE(QGraphicsTransform)
+QML_DECLARE_TYPE(QGraphicsScale)
+QML_DECLARE_TYPE(QGraphicsRotation)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSITEM_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsitem_p.h b/src/declarative/graphicsitems/qmlgraphicsitem_p.h
new file mode 100644
index 0000000..1741808
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsitem_p.h
@@ -0,0 +1,287 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSITEM_P_H
+#define QMLGRAPHICSITEM_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 "qmlgraphicsitem.h"
+
+#include "qmlgraphicsanchors_p.h"
+#include "qmlgraphicsanchors_p_p.h"
+#include "qmlgraphicsitemchangelistener_p.h"
+#include <private/qpodvector_p.h>
+
+#include "../util/qmlstate_p.h"
+#include "../util/qmlnullablevalue_p_p.h"
+#include <qml.h>
+#include <qmlcontext.h>
+
+#include <QtCore/qlist.h>
+#include <QtCore/qdebug.h>
+
+#include <private/qgraphicsitem_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QNetworkReply;
+class QmlGraphicsItemKeyFilter;
+
+//### merge into private?
+class QmlGraphicsContents : public QObject
+{
+ Q_OBJECT
+public:
+ QmlGraphicsContents();
+
+ QRectF rectF() const;
+
+ void setItem(QmlGraphicsItem *item);
+
+public Q_SLOTS:
+ void calcHeight();
+ void calcWidth();
+
+Q_SIGNALS:
+ void rectChanged();
+
+private:
+ QmlGraphicsItem *m_item;
+ qreal m_x;
+ qreal m_y;
+ qreal m_width;
+ qreal m_height;
+};
+
+class QmlGraphicsItemPrivate : public QGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsItem)
+
+public:
+ QmlGraphicsItemPrivate()
+ : _anchors(0), _contents(0),
+ _baselineOffset(0),
+ _anchorLines(0),
+ _stateGroup(0), origin(QmlGraphicsItem::Center),
+ widthValid(false), heightValid(false),
+ _componentComplete(true), _keepMouse(false),
+ smooth(false), keyHandler(0),
+ width(0), height(0), implicitWidth(0), implicitHeight(0)
+ {
+ QGraphicsItemPrivate::acceptedMouseButtons = 0;
+ QGraphicsItemPrivate::flags = QGraphicsItem::GraphicsItemFlags(
+ QGraphicsItem::ItemHasNoContents
+ | QGraphicsItem::ItemIsFocusable
+ | QGraphicsItem::ItemNegativeZStacksBehindParent);
+
+ }
+
+ void init(QmlGraphicsItem *parent)
+ {
+ Q_Q(QmlGraphicsItem);
+
+ if (parent)
+ q->setParentItem(parent);
+ _baselineOffset.invalidate();
+ mouseSetsFocus = false;
+ }
+
+ QString _id;
+
+ // data property
+ void data_removeAt(int);
+ int data_count() const;
+ void data_append(QObject *);
+ void data_insert(int, QObject *);
+ QObject *data_at(int) const;
+ void data_clear();
+ QML_DECLARE_LIST_PROXY(QmlGraphicsItemPrivate, QObject *, data)
+
+ // resources property
+ void resources_removeAt(int);
+ int resources_count() const;
+ void resources_append(QObject *);
+ void resources_insert(int, QObject *);
+ QObject *resources_at(int) const;
+ void resources_clear();
+ QML_DECLARE_LIST_PROXY(QmlGraphicsItemPrivate, QObject *, resources)
+
+ // children property
+ void children_removeAt(int);
+ int children_count() const;
+ void children_append(QmlGraphicsItem *);
+ void children_insert(int, QmlGraphicsItem *);
+ QmlGraphicsItem *children_at(int) const;
+ void children_clear();
+ QML_DECLARE_LIST_PROXY(QmlGraphicsItemPrivate, QmlGraphicsItem *, children)
+
+ // transform property
+ void transform_removeAt(int);
+ int transform_count() const;
+ void transform_append(QGraphicsTransform *);
+ void transform_insert(int, QGraphicsTransform *);
+ QGraphicsTransform *transform_at(int) const;
+ void transform_clear();
+ QML_DECLARE_LIST_PROXY(QmlGraphicsItemPrivate, QGraphicsTransform *, transform)
+
+ QmlGraphicsAnchors *anchors() {
+ if (!_anchors) {
+ Q_Q(QmlGraphicsItem);
+ _anchors = new QmlGraphicsAnchors(q);
+ if (!_componentComplete)
+ _anchors->classBegin();
+ }
+ return _anchors;
+ }
+ QmlGraphicsAnchors *_anchors;
+ QmlGraphicsContents *_contents;
+
+ QmlNullableValue<qreal> _baselineOffset;
+
+ struct AnchorLines {
+ AnchorLines(QmlGraphicsItem *);
+ QmlGraphicsAnchorLine left;
+ QmlGraphicsAnchorLine right;
+ QmlGraphicsAnchorLine hCenter;
+ QmlGraphicsAnchorLine top;
+ QmlGraphicsAnchorLine bottom;
+ QmlGraphicsAnchorLine vCenter;
+ QmlGraphicsAnchorLine baseline;
+ };
+ mutable AnchorLines *_anchorLines;
+ AnchorLines *anchorLines() const {
+ Q_Q(const QmlGraphicsItem);
+ if (!_anchorLines) _anchorLines =
+ new AnchorLines(const_cast<QmlGraphicsItem *>(q));
+ return _anchorLines;
+ }
+
+ enum ChangeType {
+ Geometry = 0x01,
+ SiblingOrder = 0x02,
+ Visibility = 0x04,
+ Opacity = 0x08,
+ Destroyed = 0x10
+ };
+
+ Q_DECLARE_FLAGS(ChangeTypes, ChangeType)
+
+ struct ChangeListener {
+ ChangeListener(QmlGraphicsItemChangeListener *l, QmlGraphicsItemPrivate::ChangeTypes t) : listener(l), types(t) {}
+ QmlGraphicsItemChangeListener *listener;
+ QmlGraphicsItemPrivate::ChangeTypes types;
+ bool operator==(const ChangeListener &other) const { return listener == other.listener && types == other.types; }
+ };
+
+ void addItemChangeListener(QmlGraphicsItemChangeListener *listener, ChangeTypes types) {
+ changeListeners.append(ChangeListener(listener, types));
+ }
+ void removeItemChangeListener(QmlGraphicsItemChangeListener *, ChangeTypes types);
+ QPODVector<ChangeListener,4> changeListeners;
+
+ QmlStateGroup *states();
+ QmlStateGroup *_stateGroup;
+
+ QmlGraphicsItem::TransformOrigin origin:4;
+ bool widthValid:1;
+ bool heightValid:1;
+ bool _componentComplete:1;
+ bool _keepMouse:1;
+ bool smooth:1;
+
+ QmlGraphicsItemKeyFilter *keyHandler;
+
+ qreal width;
+ qreal height;
+ qreal implicitWidth;
+ qreal implicitHeight;
+
+ QPointF computeTransformOrigin() const;
+
+ virtual void setPosHelper(const QPointF &pos)
+ {
+ Q_Q(QmlGraphicsItem);
+ QRectF oldGeometry(this->pos.x(), this->pos.y(), width, height);
+ QGraphicsItemPrivate::setPosHelper(pos);
+ q->geometryChanged(QRectF(this->pos.x(), this->pos.y(), width, height), oldGeometry);
+ }
+
+ // Reimplemented from QGraphicsItemPrivate
+ virtual void subFocusItemChange()
+ {
+ emit q_func()->wantsFocusChanged();
+ }
+
+ // Reimplemented from QGraphicsItemPrivate
+ virtual void siblingOrderChange()
+ {
+ Q_Q(QmlGraphicsItem);
+ for(int ii = 0; ii < changeListeners.count(); ++ii) {
+ const QmlGraphicsItemPrivate::ChangeListener &change = changeListeners.at(ii);
+ if (change.types & QmlGraphicsItemPrivate::SiblingOrder) {
+ change.listener->itemSiblingOrderChanged(q);
+ }
+ }
+ }
+
+ static int consistentTime;
+ static QTime currentTime();
+ static void Q_DECLARATIVE_EXPORT setConsistentTime(int t);
+ static void start(QTime &);
+ static int elapsed(QTime &);
+ static int restart(QTime &);
+};
+
+Q_DECLARE_OPERATORS_FOR_FLAGS(QmlGraphicsItemPrivate::ChangeTypes);
+
+QT_END_NAMESPACE
+
+#endif // QMLGRAPHICSITEM_P_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsitemchangelistener_p.h b/src/declarative/graphicsitems/qmlgraphicsitemchangelistener_p.h
new file mode 100644
index 0000000..f430df0
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsitemchangelistener_p.h
@@ -0,0 +1,76 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSITEMCHANGELISTENER
+#define QMLGRAPHICSITEMCHANGELISTENER
+
+//
+// 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 QmlGraphicsItem;
+class QmlGraphicsAnchorsPrivate;
+class QmlGraphicsItemChangeListener
+{
+public:
+ virtual void itemGeometryChanged(QmlGraphicsItem *, const QRectF &, const QRectF &) {}
+ virtual void itemSiblingOrderChanged(QmlGraphicsItem *) {}
+ virtual void itemVisibilityChanged(QmlGraphicsItem *) {}
+ virtual void itemOpacityChanged(QmlGraphicsItem *) {}
+ virtual void itemDestroyed(QmlGraphicsItem *) {}
+ virtual QmlGraphicsAnchorsPrivate *anchorPrivate() { return 0; }
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLGRAPHICSITEMCHANGELISTENER
diff --git a/src/declarative/graphicsitems/qmlgraphicslayoutitem.cpp b/src/declarative/graphicsitems/qmlgraphicslayoutitem.cpp
new file mode 100644
index 0000000..7227eb0
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicslayoutitem.cpp
@@ -0,0 +1,108 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicslayoutitem_p.h"
+
+#include <QDebug>
+
+#include <limits.h>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,LayoutItem,QmlGraphicsLayoutItem)
+
+/*!
+ \qmlclass LayoutItem QmlGraphicsLayoutItem
+ \brief The LayoutItem element allows you to place your Fluid UI elements inside a classical Qt layout.
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsLayoutItem
+ \brief The QmlGraphicsLayoutItem class allows you to place your Fluid UI elements inside a classical Qt layout.
+*/
+
+
+/*!
+ \qmlproperty QSizeF LayoutItem::maximumSize
+
+ The maximumSize property can be set to specify the maximum desired size of this LayoutItem
+*/
+
+/*!
+ \qmlproperty QSizeF LayoutItem::minimumSize
+
+ The minimumSize property can be set to specify the minimum desired size of this LayoutItem
+*/
+
+/*!
+ \qmlproperty QSizeF LayoutItem::preferredSize
+
+ The preferredSize property can be set to specify the preferred size of this LayoutItem
+*/
+
+QmlGraphicsLayoutItem::QmlGraphicsLayoutItem(QmlGraphicsItem* parent)
+ : QmlGraphicsItem(parent), m_maximumSize(INT_MAX,INT_MAX), m_minimumSize(0,0), m_preferredSize(0,0)
+{
+ setGraphicsItem(this);
+}
+
+void QmlGraphicsLayoutItem::setGeometry(const QRectF & rect)
+{
+ setX(rect.x());
+ setY(rect.y());
+ setWidth(rect.width());
+ setHeight(rect.height());
+}
+
+QSizeF QmlGraphicsLayoutItem::sizeHint(Qt::SizeHint w, const QSizeF &constraint) const
+{
+ Q_UNUSED(constraint);
+ if(w == Qt::MinimumSize){
+ return m_minimumSize;
+ }else if(w == Qt::MaximumSize){
+ return m_maximumSize;
+ }else{
+ return m_preferredSize;
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicslayoutitem_p.h b/src/declarative/graphicsitems/qmlgraphicslayoutitem_p.h
new file mode 100644
index 0000000..3278b63
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicslayoutitem_p.h
@@ -0,0 +1,94 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSGRAPHICSLAYOUTITEM_H
+#define QMLGRAPHICSGRAPHICSLAYOUTITEM_H
+#include "qmlgraphicsitem.h"
+
+#include <QGraphicsLayoutItem>
+#include <QSizeF>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsLayoutItem : public QmlGraphicsItem, public QGraphicsLayoutItem
+{
+ Q_OBJECT
+ Q_INTERFACES(QGraphicsLayoutItem)
+ Q_PROPERTY(QSizeF maximumSize READ maximumSize WRITE setMaximumSize NOTIFY maximumSizeChanged)
+ Q_PROPERTY(QSizeF minimumSize READ minimumSize WRITE setMinimumSize NOTIFY minimumSizeChanged)
+ Q_PROPERTY(QSizeF preferredSize READ preferredSize WRITE setPreferredSize NOTIFY preferredSizeChanged)
+public:
+ QmlGraphicsLayoutItem(QmlGraphicsItem* parent=0);
+
+ QSizeF maximumSize() const { return m_maximumSize; }
+ void setMaximumSize(const QSizeF &s) { if(s==m_maximumSize) return; m_maximumSize = s; emit maximumSizeChanged(); }
+
+ QSizeF minimumSize() const { return m_minimumSize; }
+ void setMinimumSize(const QSizeF &s) { if(s==m_minimumSize) return; m_minimumSize = s; emit minimumSizeChanged(); }
+
+ QSizeF preferredSize() const { return m_preferredSize; }
+ void setPreferredSize(const QSizeF &s) { if(s==m_preferredSize) return; m_preferredSize = s; emit preferredSizeChanged(); }
+
+ virtual void setGeometry(const QRectF & rect);
+protected:
+ virtual QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const;
+
+Q_SIGNALS:
+ void maximumSizeChanged();
+ void minimumSizeChanged();
+ void preferredSizeChanged();
+
+private:
+ QSizeF m_maximumSize;
+ QSizeF m_minimumSize;
+ QSizeF m_preferredSize;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsLayoutItem)
+
+QT_END_HEADER
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicslistview.cpp b/src/declarative/graphicsitems/qmlgraphicslistview.cpp
new file mode 100644
index 0000000..d0b3739
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicslistview.cpp
@@ -0,0 +1,2748 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicslistview_p.h"
+
+#include "qmlgraphicsflickable_p_p.h"
+#include "qmlgraphicsvisualitemmodel_p.h"
+
+#include <qmleasefollow_p.h>
+#include <qmlexpression.h>
+#include <qmlengine.h>
+
+#include <qlistmodelinterface_p.h>
+#include <QKeyEvent>
+
+QT_BEGIN_NAMESPACE
+
+void QmlGraphicsViewSection::setProperty(const QString &property)
+{
+ if (property != m_property) {
+ m_property = property;
+ emit changed();
+ }
+}
+
+void QmlGraphicsViewSection::setCriteria(QmlGraphicsViewSection::SectionCriteria criteria)
+{
+ if (criteria != m_criteria) {
+ m_criteria = criteria;
+ emit changed();
+ }
+}
+
+void QmlGraphicsViewSection::setDelegate(QmlComponent *delegate)
+{
+ if (delegate != m_delegate) {
+ m_delegate = delegate;
+ emit delegateChanged();
+ }
+}
+
+QString QmlGraphicsViewSection::sectionString(const QString &value)
+{
+ if (m_criteria == FirstCharacter)
+ return value.isEmpty() ? QString() : value.at(0);
+ else
+ return value;
+}
+
+class QmlGraphicsListViewAttached : public QObject
+{
+ Q_OBJECT
+public:
+ QmlGraphicsListViewAttached(QObject *parent)
+ : QObject(parent), m_view(0), m_isCurrent(false), m_delayRemove(false) {}
+ ~QmlGraphicsListViewAttached() {}
+
+ Q_PROPERTY(QmlGraphicsListView *view READ view CONSTANT)
+ QmlGraphicsListView *view() { return m_view; }
+
+ Q_PROPERTY(bool isCurrentItem READ isCurrentItem NOTIFY currentItemChanged)
+ bool isCurrentItem() const { return m_isCurrent; }
+ void setIsCurrentItem(bool c) {
+ if (m_isCurrent != c) {
+ m_isCurrent = c;
+ emit currentItemChanged();
+ }
+ }
+
+ Q_PROPERTY(QString prevSection READ prevSection NOTIFY prevSectionChanged)
+ QString prevSection() const { return m_prevSection; }
+ void setPrevSection(const QString &sect) {
+ if (m_prevSection != sect) {
+ m_prevSection = sect;
+ emit prevSectionChanged();
+ }
+ }
+
+ Q_PROPERTY(QString section READ section NOTIFY sectionChanged)
+ QString section() const { return m_section; }
+ void setSection(const QString &sect) {
+ if (m_section != sect) {
+ m_section = sect;
+ emit sectionChanged();
+ }
+ }
+
+ Q_PROPERTY(bool delayRemove READ delayRemove WRITE setDelayRemove NOTIFY delayRemoveChanged)
+ bool delayRemove() const { return m_delayRemove; }
+ void setDelayRemove(bool delay) {
+ if (m_delayRemove != delay) {
+ m_delayRemove = delay;
+ emit delayRemoveChanged();
+ }
+ }
+
+ void emitAdd() { emit add(); }
+ void emitRemove() { emit remove(); }
+
+Q_SIGNALS:
+ void currentItemChanged();
+ void sectionChanged();
+ void prevSectionChanged();
+ void delayRemoveChanged();
+ void add();
+ void remove();
+
+public:
+ QmlGraphicsListView *m_view;
+ bool m_isCurrent;
+ mutable QString m_section;
+ QString m_prevSection;
+ bool m_delayRemove;
+};
+
+//----------------------------------------------------------------------------
+
+class FxListItem
+{
+public:
+ FxListItem(QmlGraphicsItem *i, QmlGraphicsListView *v) : item(i), section(0), view(v) {
+ attached = static_cast<QmlGraphicsListViewAttached*>(qmlAttachedPropertiesObject<QmlGraphicsListView>(item));
+ if (attached)
+ attached->m_view = view;
+ }
+ ~FxListItem() {}
+ qreal position() const {
+ if (section)
+ return (view->orientation() == QmlGraphicsListView::Vertical ? section->y() : section->x());
+ else
+ return (view->orientation() == QmlGraphicsListView::Vertical ? item->y() : item->x());
+ }
+ int size() const {
+ if (section)
+ return (view->orientation() == QmlGraphicsListView::Vertical ? item->height()+section->height() : item->width()+section->height());
+ else
+ return (view->orientation() == QmlGraphicsListView::Vertical ? item->height() : item->width());
+ }
+ qreal endPosition() const {
+ return (view->orientation() == QmlGraphicsListView::Vertical
+ ? item->y() + (item->height() > 0 ? item->height() : 1)
+ : item->x() + (item->width() > 0 ? item->width() : 1)) - 1;
+ }
+ void setPosition(qreal pos) {
+ if (view->orientation() == QmlGraphicsListView::Vertical) {
+ if (section) {
+ section->setY(pos);
+ pos += section->height();
+ }
+ item->setY(pos);
+ } else {
+ if (section) {
+ section->setX(pos);
+ pos += section->width();
+ }
+ item->setX(pos);
+ }
+ }
+
+ QmlGraphicsItem *item;
+ QmlGraphicsItem *section;
+ QmlGraphicsListView *view;
+ QmlGraphicsListViewAttached *attached;
+ int index;
+};
+
+//----------------------------------------------------------------------------
+
+class QmlGraphicsListViewPrivate : public QmlGraphicsFlickablePrivate, private QmlGraphicsItemChangeListener
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsListView)
+
+public:
+ QmlGraphicsListViewPrivate()
+ : currentItem(0), orient(QmlGraphicsListView::Vertical)
+ , visiblePos(0), visibleIndex(0)
+ , averageSize(100.0), currentIndex(-1), requestedIndex(-1)
+ , highlightRangeStart(0), highlightRangeEnd(0)
+ , highlightComponent(0), highlight(0), trackedItem(0)
+ , moveReason(Other), buffer(0), highlightPosAnimator(0), highlightSizeAnimator(0)
+ , sectionCriteria(0), spacing(0.0)
+ , highlightMoveSpeed(400), highlightResizeSpeed(400), highlightRange(QmlGraphicsListView::NoHighlightRange)
+ , snapMode(QmlGraphicsListView::NoSnap), overshootDist(0.0)
+ , footerComponent(0), footer(0), headerComponent(0), header(0)
+ , bufferMode(NoBuffer)
+ , ownModel(false), wrap(false), autoHighlight(true), haveHighlightRange(false)
+ , correctFlick(true), inFlickCorrection(false), lazyRelease(false)
+ , deferredRelease(false), minExtentDirty(true), maxExtentDirty(true)
+ {}
+
+ void init();
+ void clear();
+ FxListItem *createItem(int modelIndex);
+ void releaseItem(FxListItem *item);
+
+ FxListItem *visibleItem(int modelIndex) const {
+ if (modelIndex >= visibleIndex && modelIndex < visibleIndex + visibleItems.count()) {
+ for (int i = modelIndex - visibleIndex; i < visibleItems.count(); ++i) {
+ FxListItem *item = visibleItems.at(i);
+ if (item->index == modelIndex)
+ return item;
+ }
+ }
+ return 0;
+ }
+
+ FxListItem *firstVisibleItem() const {
+ const qreal pos = position();
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ FxListItem *item = visibleItems.at(i);
+ if (item->index != -1 && item->endPosition() > pos)
+ return item;
+ }
+ return visibleItems.count() ? visibleItems.first() : 0;
+ }
+
+ FxListItem *nextVisibleItem() const {
+ const qreal pos = position();
+ bool foundFirst = false;
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ FxListItem *item = visibleItems.at(i);
+ if (item->index != -1) {
+ if (foundFirst)
+ return item;
+ else if (item->position() < pos && item->endPosition() > pos)
+ foundFirst = true;
+ }
+ }
+ return 0;
+ }
+
+ qreal position() const {
+ Q_Q(const QmlGraphicsListView);
+ return orient == QmlGraphicsListView::Vertical ? q->viewportY() : q->viewportX();
+ }
+ void setPosition(qreal pos) {
+ Q_Q(QmlGraphicsListView);
+ if (orient == QmlGraphicsListView::Vertical)
+ q->setViewportY(pos);
+ else
+ q->setViewportX(pos);
+ }
+ qreal size() const {
+ Q_Q(const QmlGraphicsListView);
+ return orient == QmlGraphicsListView::Vertical ? q->height() : q->width();
+ }
+
+ qreal startPosition() const {
+ qreal pos = 0;
+ if (!visibleItems.isEmpty()) {
+ pos = (*visibleItems.constBegin())->position();
+ if (visibleIndex > 0)
+ pos -= visibleIndex * (averageSize + spacing) - spacing;
+ }
+ return pos;
+ }
+
+ qreal endPosition() 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);
+ }
+ return pos;
+ }
+
+ qreal positionAt(int modelIndex) const {
+ if (FxListItem *item = visibleItem(modelIndex))
+ return item->position();
+ if (!visibleItems.isEmpty()) {
+ if (modelIndex < visibleIndex) {
+ int count = visibleIndex - modelIndex;
+ return (*visibleItems.constBegin())->position() - count * (averageSize + spacing);
+ } else {
+ int idx = visibleItems.count() - 1;
+ while (idx >= 0 && visibleItems.at(idx)->index == -1)
+ --idx;
+ if (idx < 0)
+ idx = visibleIndex;
+ else
+ idx = visibleItems.at(idx)->index;
+ int count = modelIndex - idx - 1;
+ return (*(--visibleItems.constEnd()))->endPosition() + spacing + count * (averageSize + spacing) + 1;
+ }
+ }
+ return 0;
+ }
+
+ QString sectionAt(int modelIndex) {
+ if (FxListItem *item = visibleItem(modelIndex))
+ return item->attached->section();
+
+ QString section;
+ if (sectionCriteria) {
+ QString propValue = model->stringValue(modelIndex, sectionCriteria->property());
+ section = sectionCriteria->sectionString(propValue);
+ }
+
+ return section;
+ }
+
+ bool isValid() const {
+ return model && model->count() && model->isValid();
+ }
+
+ int snapIndex() {
+ int index = currentIndex;
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ FxListItem *item = visibleItems[i];
+ if (item->index == -1)
+ continue;
+ qreal itemTop = item->position();
+ if (itemTop >= highlight->position()-item->size()/2 && itemTop < highlight->position()+item->size()/2)
+ return item->index;
+ }
+ return index;
+ }
+
+ qreal snapPosAt(qreal pos) {
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ FxListItem *item = visibleItems[i];
+ if (item->index == -1)
+ continue;
+ qreal itemTop = item->position();
+ if (item->index == model->count()-1 || (itemTop+item->size()/2 >= pos))
+ return item->position();
+ }
+ if (visibleItems.count()) {
+ qreal firstPos = visibleItems.first()->position();
+ qreal endPos = visibleItems.last()->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 - startPosition()) / averageSize) * averageSize + startPosition();
+ }
+
+ FxListItem *snapItemAt(qreal pos) {
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ FxListItem *item = visibleItems[i];
+ if (item->index == -1)
+ continue;
+ qreal itemTop = item->position();
+ if (item->index == model->count()-1 || (itemTop+item->size()/2 >= pos))
+ return item;
+ }
+ if (visibleItems.count() && visibleItems.first()->position() <= pos)
+ return visibleItems.first();
+ return 0;
+ }
+
+ int lastVisibleIndex() const {
+ int lastIndex = -1;
+ for (int i = visibleItems.count()-1; i >= 0; --i) {
+ FxListItem *listItem = visibleItems.at(i);
+ if (listItem->index != -1) {
+ lastIndex = listItem->index;
+ break;
+ }
+ }
+ return lastIndex;
+ }
+
+ // map a model index to visibleItems index.
+ // These may differ if removed items are still present in the visible list,
+ // e.g. doing a removal animation
+ int mapFromModel(int modelIndex) const {
+ if (modelIndex < visibleIndex || modelIndex >= visibleIndex + visibleItems.count())
+ return -1;
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ FxListItem *listItem = visibleItems.at(i);
+ if (listItem->index == modelIndex)
+ return i + visibleIndex;
+ if (listItem->index > modelIndex)
+ return -1;
+ }
+ return -1; // Not in visibleList
+ }
+
+ bool mapRangeFromModel(int &index, int &count) const {
+ if (index + count < visibleIndex)
+ return false;
+
+ int lastIndex = -1;
+ for (int i = visibleItems.count()-1; i >= 0; --i) {
+ FxListItem *listItem = visibleItems.at(i);
+ if (listItem->index != -1) {
+ lastIndex = listItem->index;
+ break;
+ }
+ }
+
+ if (index > lastIndex)
+ return false;
+
+ int last = qMin(index + count - 1, lastIndex);
+ index = qMax(index, visibleIndex);
+ count = last - index + 1;
+
+ return true;
+ }
+
+ void updateViewport() {
+ Q_Q(QmlGraphicsListView);
+ if (orient == QmlGraphicsListView::Vertical) {
+ q->setViewportHeight(endPosition() - startPosition() + 1);
+ } else {
+ q->setViewportWidth(endPosition() - startPosition() + 1);
+ }
+ }
+
+ void itemGeometryChanged(QmlGraphicsItem *, const QRectF &newGeometry, const QRectF &oldGeometry) {
+ if ((orient == QmlGraphicsListView::Vertical && newGeometry.height() != oldGeometry.height())
+ || newGeometry.width() != oldGeometry.width()) {
+ layout();
+ fixupPosition();
+ }
+ }
+
+ // for debugging only
+ void checkVisible() const {
+ int skip = 0;
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ FxListItem *listItem = visibleItems.at(i);
+ if (listItem->index == -1) {
+ ++skip;
+ } else if (listItem->index != visibleIndex + i - skip) {
+ qFatal("index %d %d %d", visibleIndex, i, listItem->index);
+ }
+ }
+ }
+
+ void refill(qreal from, qreal to, bool doBuffer = false);
+ void layout();
+ void updateUnrequestedIndexes();
+ void updateUnrequestedPositions();
+ void updateTrackedItem();
+ void createHighlight();
+ void updateHighlight();
+ void createSection(FxListItem *);
+ void updateSections();
+ void updateCurrentSection();
+ void updateCurrent(int);
+ void updateAverage();
+ void updateHeader();
+ void updateFooter();
+ void fixupPosition();
+ virtual void fixupY();
+ virtual void fixupX();
+ virtual void flickX(qreal velocity);
+ virtual void flickY(qreal velocity);
+
+ QGuard<QmlGraphicsVisualModel> model;
+ QVariant modelVariant;
+ QList<FxListItem*> visibleItems;
+ QHash<QmlGraphicsItem*,int> unrequestedItems;
+ FxListItem *currentItem;
+ QmlGraphicsListView::Orientation orient;
+ int visiblePos;
+ int visibleIndex;
+ qreal averageSize;
+ int currentIndex;
+ int requestedIndex;
+ qreal highlightRangeStart;
+ qreal highlightRangeEnd;
+ QmlComponent *highlightComponent;
+ FxListItem *highlight;
+ FxListItem *trackedItem;
+ enum MovementReason { Other, SetIndex, Mouse };
+ MovementReason moveReason;
+ int buffer;
+ QmlEaseFollow *highlightPosAnimator;
+ QmlEaseFollow *highlightSizeAnimator;
+ QmlGraphicsViewSection *sectionCriteria;
+ QString currentSection;
+ static const int sectionCacheSize = 3;
+ QmlGraphicsItem *sectionCache[sectionCacheSize];
+ qreal spacing;
+ qreal highlightMoveSpeed;
+ qreal highlightResizeSpeed;
+ QmlGraphicsListView::HighlightRangeMode highlightRange;
+ QmlGraphicsListView::SnapMode snapMode;
+ qreal overshootDist;
+ QmlComponent *footerComponent;
+ FxListItem *footer;
+ QmlComponent *headerComponent;
+ FxListItem *header;
+ enum BufferMode { NoBuffer = 0x00, BufferBefore = 0x01, BufferAfter = 0x02 };
+ int bufferMode;
+ mutable qreal minExtent;
+ mutable qreal maxExtent;
+
+ bool ownModel : 1;
+ bool wrap : 1;
+ bool autoHighlight : 1;
+ bool haveHighlightRange : 1;
+ bool correctFlick : 1;
+ bool inFlickCorrection : 1;
+ bool lazyRelease : 1;
+ bool deferredRelease : 1;
+ mutable bool minExtentDirty : 1;
+ mutable bool maxExtentDirty : 1;
+};
+
+void QmlGraphicsListViewPrivate::init()
+{
+ Q_Q(QmlGraphicsListView);
+ q->setFlag(QGraphicsItem::ItemIsFocusScope);
+ addItemChangeListener(this, Geometry);
+ QObject::connect(q, SIGNAL(movementEnded()), q, SLOT(animStopped()));
+ q->setFlickDirection(QmlGraphicsFlickable::VerticalFlick);
+ ::memset(sectionCache, 0, sizeof(QmlGraphicsItem*) * sectionCacheSize);
+}
+
+void QmlGraphicsListViewPrivate::clear()
+{
+ for (int i = 0; i < visibleItems.count(); ++i)
+ releaseItem(visibleItems.at(i));
+ visibleItems.clear();
+ for (int i = 0; i < sectionCacheSize; ++i) {
+ delete sectionCache[i];
+ sectionCache[i] = 0;
+ }
+ visiblePos = header ? header->size() : 0;
+ visibleIndex = 0;
+ releaseItem(currentItem);
+ currentItem = 0;
+ createHighlight();
+ trackedItem = 0;
+ minExtentDirty = true;
+ maxExtentDirty = true;
+}
+
+FxListItem *QmlGraphicsListViewPrivate::createItem(int modelIndex)
+{
+ Q_Q(QmlGraphicsListView);
+ // create object
+ requestedIndex = modelIndex;
+ FxListItem *listItem = 0;
+ if (QmlGraphicsItem *item = model->item(modelIndex, false)) {
+ listItem = new FxListItem(item, q);
+ 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 (FxListItem *item = visibleItem(modelIndex-1))
+ listItem->attached->m_prevSection = item->attached->section();
+ else
+ listItem->attached->m_prevSection = sectionAt(modelIndex-1);
+ }
+ }
+ // complete
+ model->completeItem();
+ listItem->item->setZValue(1);
+ listItem->item->setParent(q->viewport());
+ QmlGraphicsItemPrivate *itemPrivate = static_cast<QmlGraphicsItemPrivate*>(QGraphicsItemPrivate::get(item));
+ itemPrivate->addItemChangeListener(this, QmlGraphicsItemPrivate::Geometry);
+ if (sectionCriteria && sectionCriteria->delegate()) {
+ if (listItem->attached->m_prevSection != listItem->attached->m_section)
+ createSection(listItem);
+ }
+ unrequestedItems.remove(listItem->item);
+ }
+ requestedIndex = -1;
+
+ return listItem;
+}
+
+void QmlGraphicsListViewPrivate::releaseItem(FxListItem *item)
+{
+ Q_Q(QmlGraphicsListView);
+ if (!item || !model)
+ return;
+ if (trackedItem == item) {
+ const char *notifier1 = orient == QmlGraphicsListView::Vertical ? SIGNAL(yChanged()) : SIGNAL(xChanged());
+ const char *notifier2 = orient == QmlGraphicsListView::Vertical ? SIGNAL(heightChanged()) : SIGNAL(widthChanged());
+ QObject::disconnect(trackedItem->item, notifier1, q, SLOT(trackedPositionChanged()));
+ QObject::disconnect(trackedItem->item, notifier2, q, SLOT(trackedPositionChanged()));
+ trackedItem = 0;
+ }
+ QmlGraphicsItemPrivate *itemPrivate = static_cast<QmlGraphicsItemPrivate*>(QGraphicsItemPrivate::get(item->item));
+ itemPrivate->removeItemChangeListener(this, QmlGraphicsItemPrivate::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));
+ }
+ if (item->section) {
+ int i = 0;
+ do {
+ if (!sectionCache[i]) {
+ sectionCache[i] = item->section;
+ sectionCache[i]->setVisible(false);
+ item->section = 0;
+ break;
+ }
+ ++i;
+ } while (i < sectionCacheSize);
+ delete item->section;
+ }
+ delete item;
+}
+
+void QmlGraphicsListViewPrivate::refill(qreal from, qreal to, bool doBuffer)
+{
+ Q_Q(QmlGraphicsListView);
+ if (!isValid() || !q->isComponentComplete())
+ return;
+ 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;
+
+ int modelIndex = visibleIndex;
+ qreal itemEnd = visiblePos-1;
+ if (!visibleItems.isEmpty()) {
+ visiblePos = (*visibleItems.constBegin())->position();
+ itemEnd = (*(--visibleItems.constEnd()))->endPosition() + spacing;
+ int i = visibleItems.count() - 1;
+ while (i > 0 && visibleItems.at(i)->index == -1)
+ --i;
+ modelIndex = visibleItems.at(i)->index + 1;
+ }
+
+ bool changed = false;
+ FxListItem *item = 0;
+ int pos = itemEnd + 1;
+ while (modelIndex < model->count() && pos <= fillTo) {
+ //qDebug() << "refill: append item" << modelIndex << "pos" << pos;
+ if (!(item = createItem(modelIndex)))
+ break;
+ item->setPosition(pos);
+ pos += item->size() + spacing;
+ visibleItems.append(item);
+ ++modelIndex;
+ changed = true;
+ if (doBuffer) // never buffer more than one item per frame
+ break;
+ }
+ while (visibleIndex > 0 && visibleIndex <= model->count() && visiblePos > fillFrom) {
+ //qDebug() << "refill: prepend item" << visibleIndex-1 << "current top pos" << visiblePos;
+ if (!(item = createItem(visibleIndex-1)))
+ break;
+ --visibleIndex;
+ visiblePos -= item->size() + spacing;
+ item->setPosition(visiblePos);
+ visibleItems.prepend(item);
+ changed = true;
+ if (doBuffer) // never buffer more than one item per frame
+ break;
+ }
+
+ if (!lazyRelease || !changed || deferredRelease) { // avoid destroying items in the same frame that we create
+ while (visibleItems.count() > 1 && (item = visibleItems.first()) && item->endPosition() < bufferFrom) {
+ if (item->attached->delayRemove())
+ break;
+ //qDebug() << "refill: remove first" << visibleIndex << "top end pos" << item->endPosition();
+ if (item->index != -1)
+ visibleIndex++;
+ visibleItems.removeFirst();
+ releaseItem(item);
+ changed = true;
+ }
+ while (visibleItems.count() > 1 && (item = visibleItems.last()) && item->position() > bufferTo) {
+ if (item->attached->delayRemove())
+ break;
+ //qDebug() << "refill: remove last" << visibleIndex+visibleItems.count()-1;
+ visibleItems.removeLast();
+ releaseItem(item);
+ changed = true;
+ }
+ deferredRelease = false;
+ } else {
+ deferredRelease = true;
+ }
+ if (changed) {
+ minExtentDirty = true;
+ maxExtentDirty = true;
+ if (visibleItems.count())
+ visiblePos = (*visibleItems.constBegin())->position();
+ updateAverage();
+ if (sectionCriteria)
+ updateCurrentSection();
+ if (header)
+ updateHeader();
+ if (footer)
+ updateFooter();
+ updateViewport();
+ updateUnrequestedPositions();
+ } else if (!doBuffer && buffer && bufferMode != NoBuffer) {
+ refill(from, to, true);
+ }
+ lazyRelease = false;
+}
+
+void QmlGraphicsListViewPrivate::layout()
+{
+ Q_Q(QmlGraphicsListView);
+ updateSections();
+ if (!visibleItems.isEmpty()) {
+ int oldEnd = visibleItems.last()->endPosition();
+ int pos = visibleItems.first()->endPosition() + spacing + 1;
+ for (int i=1; i < visibleItems.count(); ++i) {
+ FxListItem *item = visibleItems.at(i);
+ item->setPosition(pos);
+ pos += item->size() + spacing;
+ }
+ // move current item if it is after the visible items.
+ if (currentItem && currentIndex > lastVisibleIndex())
+ currentItem->setPosition(currentItem->position() + (visibleItems.last()->endPosition() - oldEnd));
+ }
+ if (!isValid())
+ return;
+ q->refill();
+ minExtentDirty = true;
+ maxExtentDirty = true;
+ updateHighlight();
+ fixupPosition();
+ q->refill();
+ if (header)
+ updateHeader();
+ if (footer)
+ updateFooter();
+ updateViewport();
+}
+
+void QmlGraphicsListViewPrivate::updateUnrequestedIndexes()
+{
+ Q_Q(QmlGraphicsListView);
+ QHash<QmlGraphicsItem*,int>::iterator it;
+ for (it = unrequestedItems.begin(); it != unrequestedItems.end(); ++it)
+ *it = model->indexOf(it.key(), q);
+}
+
+void QmlGraphicsListViewPrivate::updateUnrequestedPositions()
+{
+ Q_Q(QmlGraphicsListView);
+ if (unrequestedItems.count()) {
+ qreal pos = position();
+ QHash<QmlGraphicsItem*,int>::const_iterator it;
+ for (it = unrequestedItems.begin(); it != unrequestedItems.end(); ++it) {
+ QmlGraphicsItem *item = it.key();
+ if (orient == QmlGraphicsListView::Vertical) {
+ if (item->y() + item->height() > pos && item->y() < pos + q->height())
+ item->setY(positionAt(*it));
+ } else {
+ if (item->x() + item->width() > pos && item->x() < pos + q->width())
+ item->setX(positionAt(*it));
+ }
+ }
+ }
+}
+
+void QmlGraphicsListViewPrivate::updateTrackedItem()
+{
+ Q_Q(QmlGraphicsListView);
+ FxListItem *item = currentItem;
+ if (highlight)
+ item = highlight;
+
+ FxListItem *oldTracked = trackedItem;
+
+ const char *notifier1 = orient == QmlGraphicsListView::Vertical ? SIGNAL(yChanged()) : SIGNAL(xChanged());
+ const char *notifier2 = orient == QmlGraphicsListView::Vertical ? SIGNAL(heightChanged()) : SIGNAL(widthChanged());
+
+ if (trackedItem && item != trackedItem) {
+ QObject::disconnect(trackedItem->item, notifier1, q, SLOT(trackedPositionChanged()));
+ QObject::disconnect(trackedItem->item, notifier2, q, SLOT(trackedPositionChanged()));
+ trackedItem = 0;
+ }
+
+ if (!trackedItem && item) {
+ trackedItem = item;
+ QObject::connect(trackedItem->item, notifier1, q, SLOT(trackedPositionChanged()));
+ QObject::connect(trackedItem->item, notifier2, q, SLOT(trackedPositionChanged()));
+ }
+ if (trackedItem && trackedItem != oldTracked)
+ q->trackedPositionChanged();
+}
+
+void QmlGraphicsListViewPrivate::createHighlight()
+{
+ Q_Q(QmlGraphicsListView);
+ bool changed = false;
+ if (highlight) {
+ if (trackedItem == highlight)
+ trackedItem = 0;
+ delete highlight->item;
+ delete highlight;
+ highlight = 0;
+ delete highlightPosAnimator;
+ delete highlightSizeAnimator;
+ highlightPosAnimator = 0;
+ highlightSizeAnimator = 0;
+ changed = true;
+ }
+
+ if (currentItem) {
+ QmlGraphicsItem *item = 0;
+ if (highlightComponent) {
+ QmlContext *highlightContext = new QmlContext(qmlContext(q));
+ QObject *nobj = highlightComponent->create(highlightContext);
+ if (nobj) {
+ highlightContext->setParent(nobj);
+ item = qobject_cast<QmlGraphicsItem *>(nobj);
+ if (!item)
+ delete nobj;
+ } else {
+ delete highlightContext;
+ }
+ } else {
+ item = new QmlGraphicsItem;
+ }
+ if (item) {
+ item->setParent(q->viewport());
+ highlight = new FxListItem(item, q);
+ if (orient == QmlGraphicsListView::Vertical)
+ highlight->item->setHeight(currentItem->item->height());
+ else
+ highlight->item->setWidth(currentItem->item->width());
+ const QLatin1String posProp(orient == QmlGraphicsListView::Vertical ? "y" : "x");
+ highlightPosAnimator = new QmlEaseFollow(q);
+ highlightPosAnimator->setTarget(QmlMetaProperty(highlight->item, posProp));
+ highlightPosAnimator->setVelocity(highlightMoveSpeed);
+ highlightPosAnimator->setEnabled(autoHighlight);
+ const QLatin1String sizeProp(orient == QmlGraphicsListView::Vertical ? "height" : "width");
+ highlightSizeAnimator = new QmlEaseFollow(q);
+ highlightSizeAnimator->setVelocity(highlightResizeSpeed);
+ highlightSizeAnimator->setTarget(QmlMetaProperty(highlight->item, sizeProp));
+ highlightSizeAnimator->setEnabled(autoHighlight);
+ changed = true;
+ }
+ }
+ if (changed)
+ emit q->highlightChanged();
+}
+
+void QmlGraphicsListViewPrivate::updateHighlight()
+{
+ if ((!currentItem && highlight) || (currentItem && !highlight))
+ createHighlight();
+ if (currentItem && autoHighlight && highlight && !moving) {
+ // auto-update highlight
+ highlightPosAnimator->setSourceValue(currentItem->position());
+ highlightSizeAnimator->setSourceValue(currentItem->size());
+ if (orient == QmlGraphicsListView::Vertical) {
+ if (highlight->item->width() == 0)
+ highlight->item->setWidth(currentItem->item->width());
+ } else {
+ if (highlight->item->height() == 0)
+ highlight->item->setHeight(currentItem->item->height());
+ }
+ }
+ updateTrackedItem();
+}
+
+void QmlGraphicsListViewPrivate::createSection(FxListItem *listItem)
+{
+ Q_Q(QmlGraphicsListView);
+ if (!sectionCriteria || !sectionCriteria->delegate())
+ return;
+ if (listItem->attached->m_prevSection != listItem->attached->m_section) {
+ if (!listItem->section) {
+ int i = sectionCacheSize-1;
+ while (i >= 0 && !sectionCache[i])
+ --i;
+ if (i >= 0) {
+ listItem->section = sectionCache[i];
+ sectionCache[i] = 0;
+ listItem->section->setVisible(true);
+ QmlContext *context = QmlEngine::contextForObject(listItem->section)->parentContext();
+ context->setContextProperty(QLatin1String("section"), listItem->attached->m_section);
+ } else {
+ QmlContext *context = new QmlContext(qmlContext(q));
+ context->setContextProperty(QLatin1String("section"), listItem->attached->m_section);
+ QObject *nobj = sectionCriteria->delegate()->create(context);
+ if (nobj) {
+ context->setParent(nobj);
+ listItem->section = qobject_cast<QmlGraphicsItem *>(nobj);
+ if (!listItem->section) {
+ delete nobj;
+ } else {
+ listItem->section->setZValue(1);
+ listItem->section->setParent(q->viewport());
+ }
+ } else {
+ delete context;
+ }
+ }
+ }
+ } else if (listItem->section) {
+ int i = 0;
+ do {
+ if (!sectionCache[i]) {
+ sectionCache[i] = listItem->section;
+ sectionCache[i]->setVisible(false);
+ listItem->section = 0;
+ return;
+ }
+ ++i;
+ } while (i < sectionCacheSize);
+ delete listItem->section;
+ listItem->section = 0;
+ }
+}
+
+void QmlGraphicsListViewPrivate::updateSections()
+{
+ if (sectionCriteria) {
+ QString prevSection;
+ if (visibleIndex > 0)
+ prevSection = sectionAt(visibleIndex-1);
+ for (int i = 0; i < visibleItems.count(); ++i) {
+ if (visibleItems.at(i)->index != -1) {
+ QmlGraphicsListViewAttached *attached = visibleItems.at(i)->attached;
+ attached->setPrevSection(prevSection);
+ createSection(visibleItems.at(i));
+ prevSection = attached->section();
+ }
+ }
+ }
+}
+
+void QmlGraphicsListViewPrivate::updateCurrentSection()
+{
+ if (!sectionCriteria || visibleItems.isEmpty()) {
+ currentSection = QString();
+ return;
+ }
+ int index = 0;
+ while (visibleItems.at(index)->endPosition() < position() && index < visibleItems.count())
+ ++index;
+
+ if (index < visibleItems.count())
+ currentSection = visibleItems.at(index)->attached->section();
+ else
+ currentSection = visibleItems.first()->attached->section();
+}
+
+void QmlGraphicsListViewPrivate::updateCurrent(int modelIndex)
+{
+ Q_Q(QmlGraphicsListView);
+ if (!q->isComponentComplete() || !isValid() || modelIndex < 0 || modelIndex >= model->count()) {
+ if (currentItem) {
+ currentItem->attached->setIsCurrentItem(false);
+ releaseItem(currentItem);
+ currentItem = 0;
+ currentIndex = -1;
+ updateHighlight();
+ emit q->currentIndexChanged();
+ }
+ return;
+ }
+
+ if (currentItem && currentIndex == modelIndex) {
+ updateHighlight();
+ return;
+ }
+ FxListItem *oldCurrentItem = currentItem;
+ currentIndex = modelIndex;
+ currentItem = createItem(modelIndex);
+ if (oldCurrentItem && (!currentItem || oldCurrentItem->item != currentItem->item))
+ oldCurrentItem->attached->setIsCurrentItem(false);
+ if (currentItem) {
+ if (modelIndex == visibleIndex - 1) {
+ // We can calculate exact postion in this case
+ currentItem->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.
+ currentItem->setPosition(positionAt(modelIndex));
+ }
+ currentItem->item->setFocus(true);
+ currentItem->attached->setIsCurrentItem(true);
+ }
+ updateHighlight();
+ emit q->currentIndexChanged();
+ // Release the old current item
+ releaseItem(oldCurrentItem);
+}
+
+void QmlGraphicsListViewPrivate::updateAverage()
+{
+ if (!visibleItems.count())
+ return;
+ qreal sum = 0.0;
+ for (int i = 0; i < visibleItems.count(); ++i)
+ sum += visibleItems.at(i)->size();
+ averageSize = sum / visibleItems.count();
+}
+
+void QmlGraphicsListViewPrivate::updateFooter()
+{
+ Q_Q(QmlGraphicsListView);
+ if (!footer && footerComponent) {
+ QmlGraphicsItem *item = 0;
+ QmlContext *context = new QmlContext(qmlContext(q));
+ QObject *nobj = footerComponent->create(context);
+ if (nobj) {
+ context->setParent(nobj);
+ item = qobject_cast<QmlGraphicsItem *>(nobj);
+ if (!item)
+ delete nobj;
+ } else {
+ delete context;
+ }
+ if (item) {
+ item->setParent(q->viewport());
+ item->setZValue(1);
+ footer = new FxListItem(item, q);
+ }
+ }
+ if (footer) {
+ if (visibleItems.count()) {
+ qreal endPos = endPosition();
+ if (lastVisibleIndex() == model->count()-1) {
+ footer->setPosition(endPos);
+ } else {
+ qreal visiblePos = position() + q->height();
+ if (endPos <= visiblePos || footer->position() < endPos)
+ footer->setPosition(endPos);
+ }
+ } else {
+ footer->setPosition(visiblePos);
+ }
+ }
+}
+
+void QmlGraphicsListViewPrivate::updateHeader()
+{
+ Q_Q(QmlGraphicsListView);
+ if (!header && headerComponent) {
+ QmlGraphicsItem *item = 0;
+ QmlContext *context = new QmlContext(qmlContext(q));
+ QObject *nobj = headerComponent->create(context);
+ if (nobj) {
+ context->setParent(nobj);
+ item = qobject_cast<QmlGraphicsItem *>(nobj);
+ if (!item)
+ delete nobj;
+ } else {
+ delete context;
+ }
+ if (item) {
+ item->setParent(q->viewport());
+ item->setZValue(1);
+ header = new FxListItem(item, q);
+ if (visibleItems.isEmpty())
+ visiblePos = header->size();
+ }
+ }
+ if (header) {
+ if (visibleItems.count()) {
+ qreal startPos = startPosition();
+ if (visibleIndex == 0) {
+ header->setPosition(startPos - header->size());
+ } else {
+ if (position() <= startPos || header->position() > startPos - header->size())
+ header->setPosition(startPos - header->size());
+ }
+ } else {
+ header->setPosition(0);
+ }
+ }
+}
+
+void QmlGraphicsListViewPrivate::fixupPosition()
+{
+ moveReason = Other;
+ if (orient == QmlGraphicsListView::Vertical)
+ fixupY();
+ else
+ fixupX();
+}
+
+void QmlGraphicsListViewPrivate::fixupY()
+{
+ Q_Q(QmlGraphicsListView);
+ if (orient == QmlGraphicsListView::Horizontal)
+ return;
+ if (!q->yflick() || _moveY.timeLine())
+ return;
+
+ int oldDuration = fixupDuration;
+ fixupDuration = moveReason == Mouse ? fixupDuration : 0;
+
+ if (haveHighlightRange && highlightRange == QmlGraphicsListView::StrictlyEnforceRange) {
+ if (currentItem && highlight && currentItem->position() != highlight->position()) {
+ timeline.reset(_moveY);
+ timeline.move(_moveY, -(currentItem->position() - highlightRangeStart), QEasingCurve(QEasingCurve::InOutQuad), fixupDuration);
+ vTime = timeline.time();
+ }
+ } else if (snapMode != QmlGraphicsListView::NoSnap) {
+ if (FxListItem *item = snapItemAt(position())) {
+ qreal pos = qMin(item->position() - highlightRangeStart, -q->maxYExtent());
+ qreal dist = qAbs(_moveY + pos);
+ if (dist > 0) {
+ timeline.reset(_moveY);
+ timeline.move(_moveY, -pos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration);
+ vTime = timeline.time();
+ }
+ }
+ } else {
+ QmlGraphicsFlickablePrivate::fixupY();
+ }
+ fixupDuration = oldDuration;
+}
+
+void QmlGraphicsListViewPrivate::fixupX()
+{
+ Q_Q(QmlGraphicsListView);
+ if (orient == QmlGraphicsListView::Vertical)
+ return;
+ if (!q->xflick() || _moveX.timeLine())
+ return;
+
+ int oldDuration = fixupDuration;
+ fixupDuration = moveReason == Mouse ? fixupDuration : 0;
+
+ if (haveHighlightRange && highlightRange == QmlGraphicsListView::StrictlyEnforceRange) {
+ if (currentItem && highlight && currentItem->position() != highlight->position()) {
+ timeline.reset(_moveX);
+ timeline.move(_moveX, -(currentItem->position() - highlightRangeStart), QEasingCurve(QEasingCurve::InOutQuad), fixupDuration);
+ vTime = timeline.time();
+ }
+ } else if (snapMode != QmlGraphicsListView::NoSnap) {
+ if (FxListItem *item = snapItemAt(position())) {
+ qreal pos = qMin(item->position() - highlightRangeStart, -q->maxXExtent());
+ qreal dist = qAbs(_moveX + pos);
+ if (dist > 0) {
+ timeline.reset(_moveX);
+ timeline.move(_moveX, -pos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration);
+ vTime = timeline.time();
+ }
+ }
+ } else {
+ QmlGraphicsFlickablePrivate::fixupX();
+ }
+ fixupDuration = oldDuration;
+}
+
+void QmlGraphicsListViewPrivate::flickX(qreal velocity)
+{
+ Q_Q(QmlGraphicsListView);
+
+ moveReason = Mouse;
+ if ((!haveHighlightRange || highlightRange != QmlGraphicsListView::StrictlyEnforceRange) && snapMode == QmlGraphicsListView::NoSnap) {
+ QmlGraphicsFlickablePrivate::flickX(velocity);
+ return;
+ }
+ qreal maxDistance = -1;
+ const qreal maxX = q->maxXExtent();
+ const qreal minX = q->minXExtent();
+ // -ve velocity means list is moving up
+ if (velocity > 0) {
+ if (snapMode == QmlGraphicsListView::SnapOneItem) {
+ if (FxListItem *item = firstVisibleItem())
+ maxDistance = qAbs(item->position() + _moveX.value());
+ } else if (_moveX.value() < minX) {
+ maxDistance = qAbs(minX -_moveX.value() + (overShoot?30:0));
+ }
+ if (snapMode != QmlGraphicsListView::SnapToItem && highlightRange != QmlGraphicsListView::StrictlyEnforceRange)
+ flickTargetX = minX;
+ } else {
+ if (snapMode == QmlGraphicsListView::SnapOneItem) {
+ if (FxListItem *item = nextVisibleItem())
+ maxDistance = qAbs(item->position() + _moveX.value());
+ } else if (_moveX.value() > maxX) {
+ maxDistance = qAbs(maxX - _moveX.value()) + (overShoot?30:0);
+ }
+ if (snapMode != QmlGraphicsListView::SnapToItem && highlightRange != QmlGraphicsListView::StrictlyEnforceRange)
+ flickTargetX = maxX;
+ }
+ if (maxDistance > 0 && (snapMode != QmlGraphicsListView::NoSnap || highlightRange == QmlGraphicsListView::StrictlyEnforceRange)) {
+ // 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 (!flicked) {
+ // the initial flick - estimate boundary
+ qreal accel = deceleration;
+ qreal v2 = v * v;
+ qreal maxAccel = v2 / (2.0f * maxDistance);
+ if (maxAccel < accel) {
+ qreal dist = v2 / (accel * 2.0);
+ if (v > 0)
+ dist = -dist;
+ flickTargetX = -snapPosAt(-(_moveX.value() - highlightRangeStart) + dist) + highlightRangeStart;
+ dist = -flickTargetX + _moveX.value();
+ accel = v2 / (2.0f * qAbs(dist));
+ overshootDist = 0.0;
+ } else {
+ flickTargetX = velocity > 0 ? minX : maxX;
+ overshootDist = overShoot ? 30 : 0;
+ }
+ timeline.reset(_moveX);
+ timeline.accel(_moveX, v, accel, maxDistance + overshootDist);
+ timeline.execute(fixupXEvent);
+ flicked = true;
+ emit q->flickingChanged();
+ emit q->flickStarted();
+ correctFlick = true;
+ } else {
+ // reevaluate the target boundary.
+ qreal newtarget = flickTargetX;
+ if (snapMode != QmlGraphicsListView::NoSnap || highlightRange == QmlGraphicsListView::StrictlyEnforceRange)
+ newtarget = -snapPosAt(-(flickTargetX - highlightRangeStart)) + highlightRangeStart;
+ if (velocity < 0 && newtarget < maxX)
+ newtarget = maxX;
+ else if (velocity > 0 && newtarget > minX)
+ newtarget = minX;
+ if (newtarget == flickTargetX) // boundary unchanged - nothing to do
+ return;
+ flickTargetX = newtarget;
+ qreal dist = -newtarget + _moveX.value();
+ if ((v < 0 && dist < 0) || (v > 0 && dist > 0)) {
+ correctFlick = false;
+ timeline.reset(_moveX);
+ fixupX();
+ return;
+ }
+ timeline.reset(_moveX);
+ timeline.accelDistance(_moveX, v, -dist + (v < 0 ? -overshootDist : overshootDist));
+ timeline.execute(fixupXEvent);
+ }
+ } else {
+ correctFlick = false;
+ timeline.reset(_moveX);
+ fixupX();
+ }
+}
+
+void QmlGraphicsListViewPrivate::flickY(qreal velocity)
+{
+ Q_Q(QmlGraphicsListView);
+
+ moveReason = Mouse;
+ if ((!haveHighlightRange || highlightRange != QmlGraphicsListView::StrictlyEnforceRange) && snapMode == QmlGraphicsListView::NoSnap) {
+ QmlGraphicsFlickablePrivate::flickY(velocity);
+ return;
+ }
+ qreal maxDistance = -1;
+ const qreal maxY = q->maxYExtent();
+ const qreal minY = q->minYExtent();
+ // -ve velocity means list is moving up
+ if (velocity > 0) {
+ if (snapMode == QmlGraphicsListView::SnapOneItem) {
+ if (FxListItem *item = firstVisibleItem())
+ maxDistance = qAbs(item->position() + _moveY.value());
+ } else if (_moveY.value() < minY) {
+ maxDistance = qAbs(minY -_moveY.value() + (overShoot?30:0));
+ }
+ if (snapMode != QmlGraphicsListView::SnapToItem && highlightRange != QmlGraphicsListView::StrictlyEnforceRange)
+ flickTargetY = minY;
+ } else {
+ if (snapMode == QmlGraphicsListView::SnapOneItem) {
+ if (FxListItem *item = nextVisibleItem())
+ maxDistance = qAbs(item->position() + _moveY.value());
+ } else if (_moveY.value() > maxY) {
+ maxDistance = qAbs(maxY - _moveY.value()) + (overShoot?30:0);
+ }
+ if (snapMode != QmlGraphicsListView::SnapToItem && highlightRange != QmlGraphicsListView::StrictlyEnforceRange)
+ flickTargetY = maxY;
+ }
+ if (maxDistance > 0 && (snapMode != QmlGraphicsListView::NoSnap || highlightRange == QmlGraphicsListView::StrictlyEnforceRange)) {
+ // 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 (!flicked) {
+ // the initial flick - estimate boundary
+ qreal accel = deceleration;
+ qreal v2 = v * v;
+ qreal maxAccel = v2 / (2.0f * maxDistance);
+ if (maxAccel < accel) {
+ qreal dist = v2 / (accel * 2.0);
+ if (v > 0)
+ dist = -dist;
+ flickTargetY = -snapPosAt(-(_moveY.value() - highlightRangeStart) + dist) + highlightRangeStart;
+ dist = -flickTargetY + _moveY.value();
+ accel = v2 / (2.0f * qAbs(dist));
+ overshootDist = 0.0;
+ } else {
+ flickTargetY = velocity > 0 ? minY : maxY;
+ overshootDist = overShoot ? 30 : 0;
+ }
+ timeline.reset(_moveY);
+ timeline.accel(_moveY, v, accel, maxDistance + overshootDist);
+ timeline.execute(fixupYEvent);
+ flicked = true;
+ emit q->flickingChanged();
+ emit q->flickStarted();
+ correctFlick = true;
+ } else {
+ // reevaluate the target boundary.
+ qreal newtarget = flickTargetY;
+ if (snapMode != QmlGraphicsListView::NoSnap || highlightRange == QmlGraphicsListView::StrictlyEnforceRange)
+ newtarget = -snapPosAt(-(flickTargetY - highlightRangeStart)) + highlightRangeStart;
+ if (velocity < 0 && newtarget < maxY)
+ newtarget = maxY;
+ else if (velocity > 0 && newtarget > minY)
+ newtarget = minY;
+ if (newtarget == flickTargetY) // boundary unchanged - nothing to do
+ return;
+ flickTargetY = newtarget;
+ qreal dist = -newtarget + _moveY.value();
+ if ((v < 0 && dist < 0) || (v > 0 && dist > 0)) {
+ correctFlick = false;
+ timeline.reset(_moveY);
+ fixupY();
+ return;
+ }
+ timeline.reset(_moveY);
+ timeline.accelDistance(_moveY, v, -dist + (v < 0 ? -overshootDist : overshootDist));
+ timeline.execute(fixupYEvent);
+ }
+ } else {
+ correctFlick = false;
+ timeline.reset(_moveY);
+ fixupY();
+ }
+}
+
+//----------------------------------------------------------------------------
+
+/*!
+ \qmlclass ListView QmlGraphicsListView
+ \inherits Flickable
+ \brief The ListView item provides a list view of items provided by a model.
+
+ The model is typically provided by a QAbstractListModel "C++ model object",
+ but can also be created directly in QML. The items are laid out vertically
+ or horizontally and may be flicked to scroll.
+
+ The below example creates a very simple vertical list, using a QML model.
+ \image trivialListView.png
+
+ The user interface defines a delegate to display an item, a highlight,
+ and the ListView which uses the above.
+
+ \snippet doc/src/snippets/declarative/listview/listview.qml 3
+
+ The model is defined as a ListModel using QML:
+ \quotefile doc/src/snippets/declarative/listview/dummydata/ContactModel.qml
+
+ In this case ListModel is a handy way for us to test our UI. In practice
+ the model would be implemented in C++, or perhaps via a SQL data source.
+*/
+
+QmlGraphicsListView::QmlGraphicsListView(QmlGraphicsItem *parent)
+ : QmlGraphicsFlickable(*(new QmlGraphicsListViewPrivate), parent)
+{
+ Q_D(QmlGraphicsListView);
+ d->init();
+}
+
+QmlGraphicsListView::~QmlGraphicsListView()
+{
+ Q_D(QmlGraphicsListView);
+ d->clear();
+ if (d->ownModel)
+ delete d->model;
+ delete d->header;
+ delete d->footer;
+}
+
+/*!
+ \qmlattachedproperty bool 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/highlight.qml 0
+*/
+
+/*!
+ \qmlattachedproperty ListView ListView::view
+ This attached property holds the view that manages this delegate instance.
+
+ It is attached to each instance of the delegate.
+*/
+
+/*!
+ \qmlattachedproperty string ListView::prevSection
+ 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 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 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 below ensures that the animation completes before
+ the item is removed from the list.
+
+ \code
+ Component {
+ id: myDelegate
+ Item {
+ id: wrapper
+ ListView.onRemove: SequentialAnimation {
+ PropertyAction { target: wrapper.ListView; property: "delayRemove"; value: true }
+ NumberAnimation { target: wrapper; property: "scale"; to: 0; duration: 250; easing: "easeInOutQuad" }
+ PropertyAction { target: wrapper.ListView; property: "delayRemove"; value: false }
+ }
+ }
+ }
+ \endcode
+*/
+
+/*!
+ \qmlattachedsignal ListView::onAdd()
+ This attached handler is called immediately after an item is added to the view.
+*/
+
+/*!
+ \qmlattachedsignal ListView::onRemove()
+ This attached handler is called immediately before an item is removed from the view.
+*/
+
+/*!
+ \qmlproperty model ListView::model
+ This property holds the model providing data for the list.
+
+ 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. 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},
+ \l{XmlListModel} or \l{VisualItemModel}.
+
+ \sa {qmlmodels}{Data Models}
+*/
+QVariant QmlGraphicsListView::model() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->modelVariant;
+}
+
+void QmlGraphicsListView::setModel(const QVariant &model)
+{
+ Q_D(QmlGraphicsListView);
+ if (d->model) {
+ disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
+ disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
+ disconnect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));
+ disconnect(d->model, SIGNAL(createdItem(int, QmlGraphicsItem*)), this, SLOT(createdItem(int,QmlGraphicsItem*)));
+ disconnect(d->model, SIGNAL(destroyingItem(QmlGraphicsItem*)), this, SLOT(destroyingItem(QmlGraphicsItem*)));
+ }
+ d->clear();
+ d->modelVariant = model;
+ QObject *object = qvariant_cast<QObject*>(model);
+ QmlGraphicsVisualModel *vim = 0;
+ if (object && (vim = qobject_cast<QmlGraphicsVisualModel *>(object))) {
+ if (d->ownModel) {
+ delete d->model;
+ d->ownModel = false;
+ }
+ d->model = vim;
+ } else {
+ if (!d->ownModel) {
+ d->model = new QmlGraphicsVisualDataModel(qmlContext(this));
+ d->ownModel = true;
+ }
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model))
+ dataModel->setModel(model);
+ }
+ if (d->model) {
+ if (isComponentComplete()) {
+ refill();
+ if (d->currentIndex >= d->model->count() || d->currentIndex < 0) {
+ setCurrentIndex(0);
+ } else {
+ d->moveReason = QmlGraphicsListViewPrivate::SetIndex;
+ d->updateCurrent(d->currentIndex);
+ }
+ }
+ connect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
+ connect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
+ connect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));
+ connect(d->model, SIGNAL(createdItem(int, QmlGraphicsItem*)), this, SLOT(createdItem(int,QmlGraphicsItem*)));
+ connect(d->model, SIGNAL(destroyingItem(QmlGraphicsItem*)), this, SLOT(destroyingItem(QmlGraphicsItem*)));
+ emit countChanged();
+ }
+}
+
+/*!
+ \qmlproperty component 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}.
+
+ Note that the ListView 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/listview/listview.qml 0
+*/
+QmlComponent *QmlGraphicsListView::delegate() const
+{
+ Q_D(const QmlGraphicsListView);
+ if (d->model) {
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model))
+ return dataModel->delegate();
+ }
+
+ return 0;
+}
+
+void QmlGraphicsListView::setDelegate(QmlComponent *delegate)
+{
+ Q_D(QmlGraphicsListView);
+ if (delegate == this->delegate())
+ return;
+ if (!d->ownModel) {
+ d->model = new QmlGraphicsVisualDataModel(qmlContext(this));
+ d->ownModel = true;
+ }
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model)) {
+ dataModel->setDelegate(delegate);
+ if (isComponentComplete()) {
+ for (int i = 0; i < d->visibleItems.count(); ++i)
+ d->releaseItem(d->visibleItems.at(i));
+ d->visibleItems.clear();
+ refill();
+ d->moveReason = QmlGraphicsListViewPrivate::SetIndex;
+ d->updateCurrent(d->currentIndex);
+ }
+ }
+}
+
+/*!
+ \qmlproperty int ListView::currentIndex
+ \qmlproperty Item ListView::currentItem
+
+ \c currentIndex holds the index of the current item.
+ \c currentItem is the current item. Note that the position of the current item
+ may only be approximate until it becomes visible in the view.
+*/
+int QmlGraphicsListView::currentIndex() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->currentIndex;
+}
+
+void QmlGraphicsListView::setCurrentIndex(int index)
+{
+ Q_D(QmlGraphicsListView);
+ if (isComponentComplete() && d->isValid() && index != d->currentIndex && index < d->model->count() && index >= 0) {
+ d->moveReason = QmlGraphicsListViewPrivate::SetIndex;
+ cancelFlick();
+ d->updateCurrent(index);
+ } else {
+ d->currentIndex = index;
+ }
+}
+
+QmlGraphicsItem *QmlGraphicsListView::currentItem()
+{
+ Q_D(QmlGraphicsListView);
+ if (!d->currentItem)
+ return 0;
+ return d->currentItem->item;
+}
+
+/*!
+ \qmlproperty Item ListView::highlightItem
+
+ \c highlightItem holds the highlight item, which was created
+ from the \l highlight component.
+
+ The highlightItem is managed by the view unless
+ \l highlightFollowsCurrentItem is set to false.
+
+ \sa highlight, highlightFollowsCurrentItem
+*/
+QmlGraphicsItem *QmlGraphicsListView::highlightItem()
+{
+ Q_D(QmlGraphicsListView);
+ if (!d->highlight)
+ return 0;
+ return d->highlight->item;
+}
+
+/*!
+ \qmlproperty int ListView::count
+ This property holds the number of items in the view.
+*/
+int QmlGraphicsListView::count() const
+{
+ Q_D(const QmlGraphicsListView);
+ if (d->model)
+ return d->model->count();
+ return 0;
+}
+
+/*!
+ \qmlproperty component ListView::highlight
+ This property holds the component to use as the highlight.
+
+ An instance of the highlight component will be created for each list.
+ The geometry of the resultant component instance will be managed by the list
+ so as to stay with the current item, unless the highlightFollowsCurrentItem
+ property is false.
+
+ The below example demonstrates how to make a simple highlight
+ for a vertical list.
+
+ \snippet doc/src/snippets/declarative/listview/listview.qml 1
+ \image trivialListView.png
+
+ \sa highlightItem, highlightFollowsCurrentItem
+*/
+QmlComponent *QmlGraphicsListView::highlight() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->highlightComponent;
+}
+
+void QmlGraphicsListView::setHighlight(QmlComponent *highlight)
+{
+ Q_D(QmlGraphicsListView);
+ if (highlight != d->highlightComponent) {
+ d->highlightComponent = highlight;
+ d->createHighlight();
+ if (d->currentItem)
+ d->updateHighlight();
+ }
+}
+
+/*!
+ \qmlproperty bool ListView::highlightFollowsCurrentItem
+ This property holds whether the highlight is managed by the view.
+
+ If highlightFollowsCurrentItem is true, the highlight will be moved smoothly
+ to follow the current item. If highlightFollowsCurrentItem is false, the
+ highlight will not be moved by the view, and must be implemented
+ by the highlight. The following example creates a highlight with
+ its motion defined by the spring \l {SpringFollow}:
+
+ \snippet doc/src/snippets/declarative/listview/highlight.qml 1
+
+ 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
+*/
+bool QmlGraphicsListView::highlightFollowsCurrentItem() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->autoHighlight;
+}
+
+void QmlGraphicsListView::setHighlightFollowsCurrentItem(bool autoHighlight)
+{
+ Q_D(QmlGraphicsListView);
+ if (d->autoHighlight != autoHighlight) {
+ d->autoHighlight = autoHighlight;
+ if (d->highlightPosAnimator) {
+ d->highlightPosAnimator->setEnabled(d->autoHighlight);
+ d->highlightSizeAnimator->setEnabled(d->autoHighlight);
+ }
+ d->updateHighlight();
+ }
+}
+
+//###Possibly rename these properties, since they are very useful even without a highlight?
+/*!
+ \qmlproperty real ListView::preferredHighlightBegin
+ \qmlproperty real ListView::preferredHighlightEnd
+ \qmlproperty enumeration ListView::highlightRangeMode
+
+ These properties set the preferred range of the highlight (current item)
+ within the view.
+
+ Note that this is the correct way to influence where the
+ current item ends up when the list scrolls. For example, if you want the
+ currently selected item to be in the middle of the list, then set the
+ highlight range to be where the middle item would go. Then, when the list scrolls,
+ the currently selected item will be the item at that spot. 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.
+
+ If highlightRangeMode is set to \e 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 list
+ or due to a mouse interaction.
+
+ If highlightRangeMode is set to \e 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.
+
+ The default value is \e NoHighlightRange.
+
+ Note that a valid range requires preferredHighlightEnd to be greater
+ than or equal to preferredHighlightBegin.
+*/
+qreal QmlGraphicsListView::preferredHighlightBegin() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->highlightRangeStart;
+}
+
+void QmlGraphicsListView::setPreferredHighlightBegin(qreal start)
+{
+ Q_D(QmlGraphicsListView);
+ d->highlightRangeStart = start;
+ d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd;
+}
+
+qreal QmlGraphicsListView::preferredHighlightEnd() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->highlightRangeEnd;
+}
+
+void QmlGraphicsListView::setPreferredHighlightEnd(qreal end)
+{
+ Q_D(QmlGraphicsListView);
+ d->highlightRangeEnd = end;
+ d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd;
+}
+
+QmlGraphicsListView::HighlightRangeMode QmlGraphicsListView::highlightRangeMode() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->highlightRange;
+}
+
+void QmlGraphicsListView::setHighlightRangeMode(HighlightRangeMode mode)
+{
+ Q_D(QmlGraphicsListView);
+ d->highlightRange = mode;
+ d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd;
+}
+
+/*!
+ \qmlproperty real ListView::spacing
+
+ This property holds the spacing to leave between items.
+*/
+qreal QmlGraphicsListView::spacing() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->spacing;
+}
+
+void QmlGraphicsListView::setSpacing(qreal spacing)
+{
+ Q_D(QmlGraphicsListView);
+ if (spacing != d->spacing) {
+ d->spacing = spacing;
+ d->layout();
+ emit spacingChanged();
+ }
+}
+
+/*!
+ \qmlproperty enumeration ListView::orientation
+ This property holds the orientation of the list.
+
+ Possible values are \c Vertical (default) and \c Horizontal.
+
+ Vertical Example:
+ \image trivialListView.png
+ Horizontal Example:
+ \image ListViewHorizontal.png
+*/
+QmlGraphicsListView::Orientation QmlGraphicsListView::orientation() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->orient;
+}
+
+void QmlGraphicsListView::setOrientation(QmlGraphicsListView::Orientation orientation)
+{
+ Q_D(QmlGraphicsListView);
+ if (d->orient != orientation) {
+ d->orient = orientation;
+ if (d->orient == QmlGraphicsListView::Vertical) {
+ setViewportWidth(-1);
+ setFlickDirection(VerticalFlick);
+ } else {
+ setViewportHeight(-1);
+ setFlickDirection(HorizontalFlick);
+ }
+ d->clear();
+ refill();
+ emit orientationChanged();
+ d->updateCurrent(d->currentIndex);
+ }
+}
+
+/*!
+ \qmlproperty bool ListView::keyNavigationWraps
+ This property holds whether the list wraps key navigation
+
+ If this property is true then key presses to move off of one end of the list will cause the
+ current item to jump to the other end.
+*/
+bool QmlGraphicsListView::isWrapEnabled() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->wrap;
+}
+
+void QmlGraphicsListView::setWrapEnabled(bool wrap)
+{
+ Q_D(QmlGraphicsListView);
+ d->wrap = wrap;
+}
+
+/*!
+ \qmlproperty int ListView::cacheBuffer
+ This property holds the number of off-screen pixels to cache.
+
+ This property determines the number of pixels above the top of the list
+ and below the bottom of the list to cache. Setting this value can make
+ scrolling the list smoother at the expense of additional memory usage.
+*/
+int QmlGraphicsListView::cacheBuffer() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->buffer;
+}
+
+void QmlGraphicsListView::setCacheBuffer(int b)
+{
+ Q_D(QmlGraphicsListView);
+ if (d->buffer != b) {
+ d->buffer = b;
+ if (isComponentComplete()) {
+ d->bufferMode = QmlGraphicsListViewPrivate::BufferBefore | QmlGraphicsListViewPrivate::BufferAfter;
+ refill();
+ }
+ }
+}
+
+/*!
+ \qmlproperty string ListView::section.property
+ \qmlproperty enumeration ListView::section.criteria
+ These properties hold the expression to be evaluated for the section attached property.
+
+ section.property hold the name of the property to use to determine
+ the section the item is in.
+
+ section.criteria holds the criteria to use to get the section. It
+ can be either:
+ \list
+ \o ViewSection.FullString (default) - section is the value of the property.
+ \o ViewSection.FirstCharacter - section is the first character of the property value.
+ \endlist
+
+ Each item in the list has attached properties named \c ListView.section and
+ \c ListView.prevSection. These may be used to place a section header for
+ related items. The example below assumes that the model is sorted by size of
+ pet. The section expression is the size property. If \c ListView.section and
+ \c ListView.prevSection differ, the item will display a section header.
+
+ \snippet examples/declarative/listview/sections.qml 0
+
+ \image ListViewSections.png
+*/
+QmlGraphicsViewSection *QmlGraphicsListView::sectionCriteria()
+{
+ Q_D(QmlGraphicsListView);
+ if (!d->sectionCriteria)
+ d->sectionCriteria = new QmlGraphicsViewSection(this);
+ return d->sectionCriteria;
+}
+
+/*!
+ \qmlproperty string ListView::currentSection
+ This property holds the section that is currently at the beginning of the view.
+*/
+QString QmlGraphicsListView::currentSection() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->currentSection;
+}
+
+/*!
+ \qmlproperty real ListView::highlightMoveSpeed
+ \qmlproperty real ListView::highlightResizeSpeed
+ These properties hold the move and resize animation speed of the highlight delegate.
+
+ highlightFollowsCurrentItem must be true for these properties
+ to have effect.
+
+ The default value for these properties is 400 pixels/second.
+
+ \sa highlightFollowsCurrentItem
+*/
+qreal QmlGraphicsListView::highlightMoveSpeed() const
+{
+ Q_D(const QmlGraphicsListView);\
+ return d->highlightMoveSpeed;
+}
+
+void QmlGraphicsListView::setHighlightMoveSpeed(qreal speed)
+{
+ Q_D(QmlGraphicsListView);\
+ if (d->highlightMoveSpeed != speed) {
+ d->highlightMoveSpeed = speed;
+ if (d->highlightPosAnimator)
+ d->highlightPosAnimator->setVelocity(d->highlightMoveSpeed);
+ emit highlightMoveSpeedChanged();
+ }
+}
+
+qreal QmlGraphicsListView::highlightResizeSpeed() const
+{
+ Q_D(const QmlGraphicsListView);\
+ return d->highlightResizeSpeed;
+}
+
+void QmlGraphicsListView::setHighlightResizeSpeed(qreal speed)
+{
+ Q_D(QmlGraphicsListView);\
+ if (d->highlightResizeSpeed != speed) {
+ d->highlightResizeSpeed = speed;
+ if (d->highlightSizeAnimator)
+ d->highlightSizeAnimator->setVelocity(d->highlightResizeSpeed);
+ emit highlightResizeSpeedChanged();
+ }
+}
+
+/*!
+ \qmlproperty enumeration ListView::snapMode
+
+ This property determines where the view will settle following a drag or flick.
+ The allowed values are:
+
+ \list
+ \o NoSnap (default) - the view will stop anywhere within the visible area.
+ \o SnapToItem - the view will settle with an item aligned with the start of
+ the view.
+ \o SnapOneItem - the view will settle 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
+*/
+QmlGraphicsListView::SnapMode QmlGraphicsListView::snapMode() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->snapMode;
+}
+
+void QmlGraphicsListView::setSnapMode(SnapMode mode)
+{
+ Q_D(QmlGraphicsListView);
+ if (d->snapMode != mode) {
+ d->snapMode = mode;
+ }
+}
+
+QmlComponent *QmlGraphicsListView::footer() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->footerComponent;
+}
+
+void QmlGraphicsListView::setFooter(QmlComponent *footer)
+{
+ Q_D(QmlGraphicsListView);
+ if (d->footerComponent != footer) {
+ if (d->footer) {
+ delete d->footer;
+ d->footer = 0;
+ }
+ d->footerComponent = footer;
+ d->minExtentDirty = true;
+ d->maxExtentDirty = true;
+ d->updateFooter();
+ d->updateViewport();
+ }
+}
+
+QmlComponent *QmlGraphicsListView::header() const
+{
+ Q_D(const QmlGraphicsListView);
+ return d->headerComponent;
+}
+
+void QmlGraphicsListView::setHeader(QmlComponent *header)
+{
+ Q_D(QmlGraphicsListView);
+ if (d->headerComponent != header) {
+ if (d->header) {
+ delete d->header;
+ d->header = 0;
+ }
+ d->headerComponent = header;
+ d->minExtentDirty = true;
+ d->maxExtentDirty = true;
+ d->updateHeader();
+ d->updateFooter();
+ d->updateViewport();
+ }
+}
+
+void QmlGraphicsListView::viewportMoved()
+{
+ Q_D(QmlGraphicsListView);
+ QmlGraphicsFlickable::viewportMoved();
+ d->lazyRelease = true;
+ refill();
+ if (isFlicking() || d->moving)
+ d->moveReason = QmlGraphicsListViewPrivate::Mouse;
+ if (d->moveReason != QmlGraphicsListViewPrivate::SetIndex) {
+ if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange && d->highlight) {
+ // reposition highlight
+ qreal pos = d->highlight->position();
+ if (pos > d->position() + d->highlightRangeEnd - 1 - d->highlight->size())
+ pos = d->position() + d->highlightRangeEnd - 1 - d->highlight->size();
+ if (pos < d->position() + d->highlightRangeStart)
+ pos = d->position() + d->highlightRangeStart;
+ d->highlight->setPosition(pos);
+
+ // update current index
+ int idx = d->snapIndex();
+ if (idx >= 0 && idx != d->currentIndex)
+ d->updateCurrent(idx);
+ }
+ }
+
+ if (d->flicked && 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()) {
+ if (d->velocityY > 0) {
+ const qreal minY = minYExtent();
+ if ((minY - d->_moveY.value() < height()/2 || d->flickTargetY - d->_moveY.value() < height()/2)
+ && minY != d->flickTargetY)
+ d->flickY(-d->verticalVelocity.value());
+ d->bufferMode = QmlGraphicsListViewPrivate::BufferBefore;
+ } else if (d->velocityY < 0) {
+ const qreal maxY = maxYExtent();
+ if ((d->_moveY.value() - maxY < height()/2 || d->_moveY.value() - d->flickTargetY < height()/2)
+ && maxY != d->flickTargetY)
+ d->flickY(-d->verticalVelocity.value());
+ d->bufferMode = QmlGraphicsListViewPrivate::BufferAfter;
+ }
+ }
+
+ if (xflick()) {
+ if (d->velocityX > 0) {
+ const qreal minX = minXExtent();
+ if ((minX - d->_moveX.value() < height()/2 || d->flickTargetX - d->_moveX.value() < height()/2)
+ && minX != d->flickTargetX)
+ d->flickX(-d->horizontalVelocity.value());
+ d->bufferMode = QmlGraphicsListViewPrivate::BufferBefore;
+ } else if (d->velocityX < 0) {
+ const qreal maxX = maxXExtent();
+ if ((d->_moveX.value() - maxX < height()/2 || d->_moveX.value() - d->flickTargetX < height()/2)
+ && maxX != d->flickTargetX)
+ d->flickX(-d->horizontalVelocity.value());
+ d->bufferMode = QmlGraphicsListViewPrivate::BufferAfter;
+ }
+ }
+ d->inFlickCorrection = false;
+ }
+}
+
+qreal QmlGraphicsListView::minYExtent() const
+{
+ Q_D(const QmlGraphicsListView);
+ if (d->orient == QmlGraphicsListView::Horizontal)
+ return QmlGraphicsFlickable::minYExtent();
+ if (d->minExtentDirty) {
+ d->minExtent = -d->startPosition();
+ if (d->header && d->visibleItems.count())
+ d->minExtent += d->header->size();
+ if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange)
+ d->minExtent += d->highlightRangeStart;
+ d->minExtentDirty = false;
+ }
+
+ return d->minExtent;
+}
+
+qreal QmlGraphicsListView::maxYExtent() const
+{
+ Q_D(const QmlGraphicsListView);
+ if (d->orient == QmlGraphicsListView::Horizontal)
+ return height();
+ if (d->maxExtentDirty) {
+ if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange)
+ d->maxExtent = -(d->positionAt(count()-1) - d->highlightRangeEnd);
+ else
+ d->maxExtent = -(d->endPosition() - height() + 1);
+ if (d->footer)
+ d->maxExtent -= d->footer->size();
+ qreal minY = minYExtent();
+ if (d->maxExtent > minY)
+ d->maxExtent = minY;
+ d->maxExtentDirty = false;
+ }
+ return d->maxExtent;
+}
+
+qreal QmlGraphicsListView::minXExtent() const
+{
+ Q_D(const QmlGraphicsListView);
+ if (d->orient == QmlGraphicsListView::Vertical)
+ return QmlGraphicsFlickable::minXExtent();
+ if (d->minExtentDirty) {
+ d->minExtent = -d->startPosition();
+ if (d->header)
+ d->minExtent += d->header->size();
+ if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange)
+ d->minExtent += d->highlightRangeStart;
+ d->minExtentDirty = false;
+ }
+
+ return d->minExtent;
+}
+
+qreal QmlGraphicsListView::maxXExtent() const
+{
+ Q_D(const QmlGraphicsListView);
+ if (d->orient == QmlGraphicsListView::Vertical)
+ return width();
+ if (d->maxExtentDirty) {
+ if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange)
+ d->maxExtent = -(d->positionAt(count()-1) - d->highlightRangeEnd);
+ else
+ d->maxExtent = -(d->endPosition() - width() + 1);
+ if (d->footer)
+ d->maxExtent -= d->footer->size();
+ qreal minX = minXExtent();
+ if (d->maxExtent > minX)
+ d->maxExtent = minX;
+ d->maxExtentDirty = false;
+ }
+
+ return d->maxExtent;
+}
+
+void QmlGraphicsListView::keyPressEvent(QKeyEvent *event)
+{
+ Q_D(QmlGraphicsListView);
+ QmlGraphicsFlickable::keyPressEvent(event);
+ if (event->isAccepted())
+ return;
+
+ if (d->model && d->model->count() && d->interactive) {
+ if ((d->orient == QmlGraphicsListView::Horizontal && event->key() == Qt::Key_Left)
+ || (d->orient == QmlGraphicsListView::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 == QmlGraphicsListView::Horizontal && event->key() == Qt::Key_Right)
+ || (d->orient == QmlGraphicsListView::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();
+}
+
+/*!
+ \qmlmethod ListView::incrementCurrentIndex()
+
+ Increments the current index. The current index will wrap
+ if keyNavigationWraps is true and it is currently at the end.
+*/
+void QmlGraphicsListView::incrementCurrentIndex()
+{
+ Q_D(QmlGraphicsListView);
+ if (currentIndex() < d->model->count() - 1 || d->wrap) {
+ d->moveReason = QmlGraphicsListViewPrivate::SetIndex;
+ int index = currentIndex()+1;
+ cancelFlick();
+ d->updateCurrent(index < d->model->count() ? index : 0);
+ }
+}
+
+/*!
+ \qmlmethod ListView::decrementCurrentIndex()
+
+ Decrements the current index. The current index will wrap
+ if keyNavigationWraps is true and it is currently at the beginning.
+*/
+void QmlGraphicsListView::decrementCurrentIndex()
+{
+ Q_D(QmlGraphicsListView);
+ if (currentIndex() > 0 || d->wrap) {
+ d->moveReason = QmlGraphicsListViewPrivate::SetIndex;
+ int index = currentIndex()-1;
+ cancelFlick();
+ d->updateCurrent(index >= 0 ? index : d->model->count()-1);
+ }
+}
+
+/*!
+ \qmlmethod ListView::positionViewAtIndex(int index)
+
+ Positions the view such that the \a index is at the top (or left for horizontal orientation) of the view.
+ If positioning the view at the index would cause empty space to be displayed at
+ the end of the view, the view will be positioned at the end.
+*/
+void QmlGraphicsListView::positionViewAtIndex(int index)
+{
+ Q_D(QmlGraphicsListView);
+ if (!d->isValid() || index < 0 || index >= d->model->count())
+ return;
+
+ qreal maxExtent = d->orient == QmlGraphicsListView::Vertical ? -maxYExtent() : -maxXExtent();
+ FxListItem *item = d->visibleItem(index);
+ if (item) {
+ // Already created - just move to top of view
+ int pos = qMin(item->position(), maxExtent);
+ d->setPosition(pos);
+ } else {
+ int pos = d->positionAt(index);
+ // save the currently visible items in case any of them end up visible again
+ QList<FxListItem*> oldVisible = d->visibleItems;
+ d->visibleItems.clear();
+ d->visiblePos = pos;
+ d->visibleIndex = index;
+ d->setPosition(pos);
+ // setPosition() will cause refill. Adjust if we have moved beyond range.
+ if (d->position() > maxExtent)
+ d->setPosition(maxExtent);
+ // now release the reference to all the old visible items.
+ for (int i = 0; i < oldVisible.count(); ++i)
+ d->releaseItem(oldVisible.at(i));
+ }
+}
+
+
+void QmlGraphicsListView::componentComplete()
+{
+ Q_D(QmlGraphicsListView);
+ QmlGraphicsFlickable::componentComplete();
+ refill();
+ d->moveReason = QmlGraphicsListViewPrivate::SetIndex;
+ if (d->currentIndex < 0)
+ d->updateCurrent(0);
+ else
+ d->updateCurrent(d->currentIndex);
+ d->fixupPosition();
+}
+
+void QmlGraphicsListView::refill()
+{
+ Q_D(QmlGraphicsListView);
+ d->refill(d->position(), d->position()+d->size()-1);
+}
+
+void QmlGraphicsListView::trackedPositionChanged()
+{
+ Q_D(QmlGraphicsListView);
+ if (!d->trackedItem || !d->currentItem)
+ return;
+ if (!isFlicking() && !d->moving && d->moveReason == QmlGraphicsListViewPrivate::SetIndex) {
+ const qreal trackedPos = d->trackedItem->position();
+ const qreal viewPos = d->position();
+ if (d->haveHighlightRange) {
+ if (d->highlightRange == StrictlyEnforceRange) {
+ qreal pos = viewPos;
+ if (trackedPos > pos + d->highlightRangeEnd - d->trackedItem->size())
+ pos = trackedPos - d->highlightRangeEnd + d->trackedItem->size();
+ if (trackedPos < pos + d->highlightRangeStart)
+ pos = trackedPos - d->highlightRangeStart;
+ d->setPosition(pos);
+ } else {
+ qreal pos = viewPos;
+ if (trackedPos < d->startPosition() + d->highlightRangeStart) {
+ pos = d->startPosition();
+ } else if (d->trackedItem->endPosition() > d->endPosition() - d->size() + d->highlightRangeEnd) {
+ pos = d->endPosition() - d->size();
+ if (pos < d->startPosition())
+ pos = d->startPosition();
+ } else {
+ if (trackedPos < viewPos + d->highlightRangeStart) {
+ pos = trackedPos - d->highlightRangeStart;
+ } else if (trackedPos > viewPos + d->highlightRangeEnd - d->trackedItem->size()) {
+ pos = trackedPos - d->highlightRangeEnd + d->trackedItem->size();
+ }
+ }
+ d->setPosition(pos);
+ }
+ } else {
+ if (trackedPos < viewPos && d->currentItem->position() < viewPos) {
+ d->setPosition(d->currentItem->position() < trackedPos ? trackedPos : d->currentItem->position());
+ } else if (d->trackedItem->endPosition() > viewPos + d->size()
+ && d->currentItem->endPosition() > viewPos + d->size()) {
+ qreal pos;
+ if (d->trackedItem->endPosition() < d->currentItem->endPosition()) {
+ pos = d->trackedItem->endPosition() - d->size();
+ if (d->trackedItem->size() > d->size())
+ pos = trackedPos;
+ } else {
+ pos = d->currentItem->endPosition() - d->size();
+ if (d->currentItem->size() > d->size())
+ pos = d->currentItem->position();
+ }
+ d->setPosition(pos);
+ }
+ }
+ }
+}
+
+void QmlGraphicsListView::itemsInserted(int modelIndex, int count)
+{
+ Q_D(QmlGraphicsListView);
+ d->updateUnrequestedIndexes();
+ d->moveReason = QmlGraphicsListViewPrivate::Other;
+ if (!d->visibleItems.count() || d->model->count() <= 1) {
+ d->layout();
+ d->updateCurrent(qMax(0, qMin(d->currentIndex, d->model->count()-1)));
+ emit countChanged();
+ return;
+ }
+
+ int overlapCount = count;
+ if (!d->mapRangeFromModel(modelIndex, overlapCount)) {
+ int i = d->visibleItems.count() - 1;
+ while (i > 0 && d->visibleItems.at(i)->index == -1)
+ --i;
+ if (d->visibleItems.at(i)->index + 1 == modelIndex) {
+ // Special case of appending an item to the model.
+ modelIndex = d->visibleIndex + d->visibleItems.count();
+ } else {
+ if (modelIndex < d->visibleIndex) {
+ // Insert before visible items
+ d->visibleIndex += count;
+ for (int i = 0; i < d->visibleItems.count(); ++i) {
+ FxListItem *listItem = d->visibleItems.at(i);
+ if (listItem->index != -1 && listItem->index >= modelIndex)
+ listItem->index += count;
+ }
+ }
+ if (d->currentIndex >= modelIndex) {
+ // adjust current item index
+ d->currentIndex += count;
+ if (d->currentItem)
+ d->currentItem->index = d->currentIndex;
+ }
+ d->layout();
+ emit countChanged();
+ return;
+ }
+ }
+
+ // At least some of the added items will be visible
+
+ int index = modelIndex - d->visibleIndex;
+ // index can be the next item past the end of the visible items list (i.e. appended)
+ int pos = index < d->visibleItems.count() ? d->visibleItems.at(index)->position()
+ : d->visibleItems.at(index-1)->endPosition()+d->spacing+1;
+ int initialPos = pos;
+ int diff = 0;
+ QList<FxListItem*> added;
+ bool addedVisible = false;
+ FxListItem *firstVisible = d->firstVisibleItem();
+ if (firstVisible && pos < firstVisible->position()) {
+ // Insert items before the visible item.
+ int insertionIdx = index;
+ int i = 0;
+ int from = d->position() - d->buffer;
+ for (i = count-1; i >= 0 && pos > from; --i) {
+ addedVisible = true;
+ FxListItem *item = d->createItem(modelIndex + i);
+ d->visibleItems.insert(insertionIdx, item);
+ pos -= item->size() + d->spacing;
+ item->setPosition(pos);
+ index++;
+ }
+ if (i >= 0) {
+ // If we didn't insert all our new items - anything
+ // before the current index is not visible - remove it.
+ while (insertionIdx--) {
+ FxListItem *item = d->visibleItems.takeFirst();
+ if (item->index != -1)
+ d->visibleIndex++;
+ d->releaseItem(item);
+ }
+ } else {
+ // adjust pos of items before inserted items.
+ for (int i = insertionIdx-1; i >= 0; i--) {
+ FxListItem *listItem = d->visibleItems.at(i);
+ listItem->setPosition(listItem->position() - (initialPos - pos));
+ }
+ }
+ } else {
+ int i = 0;
+ int to = d->buffer+d->position()+d->size()-1;
+ for (i = 0; i < count && pos <= to; ++i) {
+ addedVisible = true;
+ FxListItem *item = d->createItem(modelIndex + i);
+ d->visibleItems.insert(index, item);
+ item->setPosition(pos);
+ added.append(item);
+ pos += item->size() + d->spacing;
+ ++index;
+ }
+ if (i != count) {
+ // We didn't insert all our new items, which means anything
+ // beyond the current index is not visible - remove it.
+ while (d->visibleItems.count() > index)
+ d->releaseItem(d->visibleItems.takeLast());
+ }
+ diff = pos - initialPos;
+ }
+ if (d->currentIndex >= modelIndex) {
+ // adjust current item index
+ d->currentIndex += count;
+ if (d->currentItem) {
+ d->currentItem->index = d->currentIndex;
+ d->currentItem->setPosition(d->currentItem->position() + diff);
+ }
+ }
+ // Update the indexes of the following visible items.
+ for (; index < d->visibleItems.count(); ++index) {
+ FxListItem *listItem = d->visibleItems.at(index);
+ if (d->currentItem && listItem->item != d->currentItem->item)
+ listItem->setPosition(listItem->position() + diff);
+ if (listItem->index != -1)
+ listItem->index += count;
+ }
+ // everything is in order now - emit add() signal
+ for (int j = 0; j < added.count(); ++j)
+ added.at(j)->attached->emitAdd();
+
+ if (addedVisible)
+ d->layout();
+ emit countChanged();
+}
+
+void QmlGraphicsListView::itemsRemoved(int modelIndex, int count)
+{
+ Q_D(QmlGraphicsListView);
+ d->moveReason = QmlGraphicsListViewPrivate::Other;
+ d->updateUnrequestedIndexes();
+
+ FxListItem *firstVisible = d->firstVisibleItem();
+ int preRemovedSize = 0;
+ bool removedVisible = false;
+ // Remove the items from the visible list, skipping anything already marked for removal
+ QList<FxListItem*>::Iterator it = d->visibleItems.begin();
+ while (it != d->visibleItems.end()) {
+ FxListItem *item = *it;
+ if (item->index == -1 || item->index < modelIndex) {
+ // already removed, or before removed items
+ ++it;
+ } else if (item->index >= modelIndex + count) {
+ // after removed items
+ item->index -= count;
+ ++it;
+ } else {
+ // removed item
+ removedVisible = true;
+ item->attached->emitRemove();
+ if (item->attached->delayRemove()) {
+ item->index = -1;
+ connect(item->attached, SIGNAL(delayRemoveChanged()), this, SLOT(destroyRemoved()), Qt::QueuedConnection);
+ ++it;
+ } else {
+ if (item == firstVisible)
+ firstVisible = 0;
+ if (firstVisible && item->position() < firstVisible->position())
+ preRemovedSize += item->size();
+ it = d->visibleItems.erase(it);
+ d->releaseItem(item);
+ }
+ }
+ }
+
+ if (firstVisible && d->visibleItems.first() != firstVisible)
+ d->visibleItems.first()->setPosition(d->visibleItems.first()->position() + preRemovedSize);
+
+ // fix current
+ if (d->currentIndex >= modelIndex + count) {
+ d->currentIndex -= count;
+ if (d->currentItem)
+ d->currentItem->index -= count;
+ } else if (d->currentIndex >= modelIndex && d->currentIndex < modelIndex + count) {
+ // current item has been removed.
+ d->currentItem->attached->setIsCurrentItem(false);
+ d->releaseItem(d->currentItem);
+ d->currentItem = 0;
+ d->currentIndex = -1;
+ d->updateCurrent(qMin(modelIndex, d->model->count()-1));
+ }
+
+ // update visibleIndex
+ for (it = d->visibleItems.begin(); it != d->visibleItems.end(); ++it) {
+ if ((*it)->index != -1) {
+ d->visibleIndex = (*it)->index;
+ break;
+ }
+ }
+
+ if (removedVisible) {
+ if (d->visibleItems.isEmpty()) {
+ d->visibleIndex = 0;
+ d->visiblePos = d->header ? d->header->size() : 0;
+ d->timeline.clear();
+ d->setPosition(0);
+ if (d->model->count() == 0)
+ update();
+ else
+ refill();
+ } else {
+ // Correct the positioning of the items
+ d->layout();
+ }
+ }
+
+ emit countChanged();
+}
+
+void QmlGraphicsListView::destroyRemoved()
+{
+ Q_D(QmlGraphicsListView);
+ for (QList<FxListItem*>::Iterator it = d->visibleItems.begin();
+ it != d->visibleItems.end();) {
+ FxListItem *listItem = *it;
+ if (listItem->index == -1 && listItem->attached->delayRemove() == false) {
+ d->releaseItem(listItem);
+ it = d->visibleItems.erase(it);
+ } else {
+ ++it;
+ }
+ }
+
+ // Correct the positioning of the items
+ d->layout();
+}
+
+void QmlGraphicsListView::itemsMoved(int from, int to, int count)
+{
+ Q_D(QmlGraphicsListView);
+ d->updateUnrequestedIndexes();
+
+ if (d->visibleItems.isEmpty()) {
+ refill();
+ return;
+ }
+
+ d->moveReason = QmlGraphicsListViewPrivate::Other;
+ FxListItem *firstVisible = d->firstVisibleItem();
+ qreal firstItemPos = firstVisible->position();
+ QHash<int,FxListItem*> moved;
+ int moveBy = 0;
+
+ QList<FxListItem*>::Iterator it = d->visibleItems.begin();
+ while (it != d->visibleItems.end()) {
+ FxListItem *item = *it;
+ if (item->index >= from && item->index < from + count) {
+ // take the items that are moving
+ item->index += (to-from);
+ moved.insert(item->index, item);
+ if (item->position() < firstItemPos)
+ moveBy += item->size();
+ it = d->visibleItems.erase(it);
+ } else {
+ // move everything after the moved items.
+ if (item->index > from && item->index != -1)
+ item->index -= count;
+ ++it;
+ }
+ }
+
+ int remaining = count;
+ int endIndex = d->visibleIndex;
+ it = d->visibleItems.begin();
+ while (it != d->visibleItems.end()) {
+ FxListItem *item = *it;
+ if (remaining && item->index >= to && item->index < to + count) {
+ // place items in the target position, reusing any existing items
+ FxListItem *movedItem = moved.take(item->index);
+ if (!movedItem)
+ movedItem = d->createItem(item->index);
+ if (item->index <= firstVisible->index)
+ moveBy -= movedItem->size();
+ it = d->visibleItems.insert(it, movedItem);
+ ++it;
+ --remaining;
+ } else {
+ if (item->index != -1) {
+ if (item->index >= to) {
+ // update everything after the moved items.
+ item->index += count;
+ }
+ endIndex = item->index;
+ }
+ ++it;
+ }
+ }
+
+ // If we have moved items to the end of the visible items
+ // then add any existing moved items that we have
+ while (FxListItem *item = moved.take(endIndex+1)) {
+ d->visibleItems.append(item);
+ ++endIndex;
+ }
+
+ // Whatever moved items remain are no longer visible items.
+ while (moved.count())
+ d->releaseItem(moved.take(moved.begin().key()));
+
+ // Ensure we don't cause an ugly list scroll.
+ d->visibleItems.first()->setPosition(d->visibleItems.first()->position() + moveBy);
+
+ d->layout();
+}
+
+void QmlGraphicsListView::createdItem(int index, QmlGraphicsItem *item)
+{
+ Q_D(QmlGraphicsListView);
+ if (d->requestedIndex != index) {
+ item->setParentItem(viewport());
+ d->unrequestedItems.insert(item, index);
+ if (d->orient == QmlGraphicsListView::Vertical)
+ item->setY(d->positionAt(index));
+ else
+ item->setX(d->positionAt(index));
+ }
+}
+
+void QmlGraphicsListView::destroyingItem(QmlGraphicsItem *item)
+{
+ Q_D(QmlGraphicsListView);
+ d->unrequestedItems.remove(item);
+}
+
+void QmlGraphicsListView::animStopped()
+{
+ Q_D(QmlGraphicsListView);
+ d->moveReason = QmlGraphicsListViewPrivate::Other;
+ d->bufferMode = QmlGraphicsListViewPrivate::NoBuffer;
+}
+
+QmlGraphicsListViewAttached *QmlGraphicsListView::qmlAttachedProperties(QObject *obj)
+{
+ return new QmlGraphicsListViewAttached(obj);
+}
+
+QML_DEFINE_TYPE(Qt,4,6,ListView,QmlGraphicsListView)
+QML_DEFINE_TYPE(Qt,4,6,ViewSection,QmlGraphicsViewSection)
+
+QT_END_NAMESPACE
+
+#include <qmlgraphicslistview.moc>
diff --git a/src/declarative/graphicsitems/qmlgraphicslistview_p.h b/src/declarative/graphicsitems/qmlgraphicslistview_p.h
new file mode 100644
index 0000000..79d678a
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicslistview_p.h
@@ -0,0 +1,238 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSLISTVIEW_H
+#define QMLGRAPHICSLISTVIEW_H
+
+#include "qmlgraphicsflickable_p.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsViewSection : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(QString property READ property WRITE setProperty NOTIFY changed)
+ Q_PROPERTY(SectionCriteria criteria READ criteria WRITE setCriteria NOTIFY changed)
+ Q_PROPERTY(QmlComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged)
+ Q_ENUMS(SectionCriteria)
+public:
+ QmlGraphicsViewSection(QObject *parent=0) : QObject(parent), m_criteria(FullString), m_delegate(0) {}
+
+ QString property() const { return m_property; }
+ void setProperty(const QString &);
+
+ enum SectionCriteria { FullString, FirstCharacter };
+ SectionCriteria criteria() const { return m_criteria; }
+ void setCriteria(SectionCriteria);
+
+ QmlComponent *delegate() const { return m_delegate; }
+ void setDelegate(QmlComponent *delegate);
+
+ QString sectionString(const QString &value);
+
+Q_SIGNALS:
+ void changed();
+ void delegateChanged();
+
+private:
+ QString m_property;
+ SectionCriteria m_criteria;
+ QmlComponent *m_delegate;
+};
+
+
+class QmlGraphicsVisualModel;
+class QmlGraphicsListViewAttached;
+class QmlGraphicsListViewPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsListView : public QmlGraphicsFlickable
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsListView)
+
+ Q_PROPERTY(QVariant model READ model WRITE setModel)
+ Q_PROPERTY(QmlComponent *delegate READ delegate WRITE setDelegate)
+ Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
+ Q_PROPERTY(QmlGraphicsItem *currentItem READ currentItem NOTIFY currentIndexChanged)
+ Q_PROPERTY(int count READ count NOTIFY countChanged)
+
+ Q_PROPERTY(QmlComponent *highlight READ highlight WRITE setHighlight)
+ Q_PROPERTY(QmlGraphicsItem *highlightItem READ highlightItem NOTIFY highlightChanged)
+ Q_PROPERTY(bool highlightFollowsCurrentItem READ highlightFollowsCurrentItem WRITE setHighlightFollowsCurrentItem)
+ Q_PROPERTY(qreal highlightMoveSpeed READ highlightMoveSpeed WRITE setHighlightMoveSpeed NOTIFY highlightMoveSpeedChanged)
+ Q_PROPERTY(qreal highlightResizeSpeed READ highlightResizeSpeed WRITE setHighlightResizeSpeed NOTIFY highlightResizeSpeedChanged)
+
+ Q_PROPERTY(qreal preferredHighlightBegin READ preferredHighlightBegin WRITE setPreferredHighlightBegin)
+ Q_PROPERTY(qreal preferredHighlightEnd READ preferredHighlightEnd WRITE setPreferredHighlightEnd)
+ Q_PROPERTY(HighlightRangeMode highlightRangeMode READ highlightRangeMode WRITE setHighlightRangeMode)
+
+ Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing NOTIFY spacingChanged)
+ Q_PROPERTY(Orientation orientation READ orientation WRITE setOrientation NOTIFY orientationChanged)
+ Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled)
+ Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer)
+ Q_PROPERTY(QmlGraphicsViewSection *section READ sectionCriteria CONSTANT)
+ Q_PROPERTY(QString currentSection READ currentSection NOTIFY currentSectionChanged)
+
+ Q_PROPERTY(SnapMode snapMode READ snapMode WRITE setSnapMode)
+
+ Q_PROPERTY(QmlComponent *header READ header WRITE setHeader)
+ Q_PROPERTY(QmlComponent *footer READ footer WRITE setFooter)
+
+ Q_ENUMS(HighlightRangeMode)
+ Q_ENUMS(Orientation)
+ Q_ENUMS(SnapMode)
+ Q_CLASSINFO("DefaultProperty", "data")
+
+public:
+ QmlGraphicsListView(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsListView();
+
+ QVariant model() const;
+ void setModel(const QVariant &);
+
+ QmlComponent *delegate() const;
+ void setDelegate(QmlComponent *);
+
+ int currentIndex() const;
+ void setCurrentIndex(int idx);
+
+ QmlGraphicsItem *currentItem();
+ QmlGraphicsItem *highlightItem();
+ int count() const;
+
+ QmlComponent *highlight() const;
+ void setHighlight(QmlComponent *highlight);
+
+ bool highlightFollowsCurrentItem() const;
+ void setHighlightFollowsCurrentItem(bool);
+
+ enum HighlightRangeMode { NoHighlightRange, ApplyRange, StrictlyEnforceRange };
+ HighlightRangeMode highlightRangeMode() const;
+ void setHighlightRangeMode(HighlightRangeMode mode);
+
+ qreal preferredHighlightBegin() const;
+ void setPreferredHighlightBegin(qreal);
+
+ qreal preferredHighlightEnd() const;
+ void setPreferredHighlightEnd(qreal);
+
+ qreal spacing() const;
+ void setSpacing(qreal spacing);
+
+ enum Orientation { Horizontal = Qt::Horizontal, Vertical = Qt::Vertical };
+ Orientation orientation() const;
+ void setOrientation(Orientation);
+
+ bool isWrapEnabled() const;
+ void setWrapEnabled(bool);
+
+ int cacheBuffer() const;
+ void setCacheBuffer(int);
+
+ QmlGraphicsViewSection *sectionCriteria();
+ QString currentSection() const;
+
+ qreal highlightMoveSpeed() const;
+ void setHighlightMoveSpeed(qreal);
+
+ qreal highlightResizeSpeed() const;
+ void setHighlightResizeSpeed(qreal);
+
+ enum SnapMode { NoSnap, SnapToItem, SnapOneItem };
+ SnapMode snapMode() const;
+ void setSnapMode(SnapMode mode);
+
+ QmlComponent *footer() const;
+ void setFooter(QmlComponent *);
+
+ QmlComponent *header() const;
+ void setHeader(QmlComponent *);
+
+ static QmlGraphicsListViewAttached *qmlAttachedProperties(QObject *);
+
+public Q_SLOTS:
+ void incrementCurrentIndex();
+ void decrementCurrentIndex();
+ void positionViewAtIndex(int index);
+
+Q_SIGNALS:
+ void countChanged();
+ void spacingChanged();
+ void orientationChanged();
+ void currentIndexChanged();
+ void currentSectionChanged();
+ void highlightMoveSpeedChanged();
+ void highlightResizeSpeedChanged();
+ void highlightChanged();
+
+protected:
+ virtual void viewportMoved();
+ virtual qreal minYExtent() const;
+ virtual qreal maxYExtent() const;
+ virtual qreal minXExtent() const;
+ virtual qreal maxXExtent() const;
+ virtual void keyPressEvent(QKeyEvent *);
+ virtual void componentComplete();
+
+private Q_SLOTS:
+ void refill();
+ void trackedPositionChanged();
+ void itemsInserted(int index, int count);
+ void itemsRemoved(int index, int count);
+ void itemsMoved(int from, int to, int count);
+ void destroyRemoved();
+ void createdItem(int index, QmlGraphicsItem *item);
+ void destroyingItem(QmlGraphicsItem *item);
+ void animStopped();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPEINFO(QmlGraphicsListView, QML_HAS_ATTACHED_PROPERTIES)
+QML_DECLARE_TYPE(QmlGraphicsListView)
+QML_DECLARE_TYPE(QmlGraphicsViewSection)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicsloader.cpp b/src/declarative/graphicsitems/qmlgraphicsloader.cpp
new file mode 100644
index 0000000..b3486ef
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsloader.cpp
@@ -0,0 +1,488 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsloader_p_p.h"
+
+#include <qmlengine_p.h>
+
+QT_BEGIN_NAMESPACE
+
+QmlGraphicsLoaderPrivate::QmlGraphicsLoaderPrivate()
+ : item(0), component(0), ownComponent(false)
+ , resizeMode(QmlGraphicsLoader::SizeLoaderToItem)
+{
+}
+
+QmlGraphicsLoaderPrivate::~QmlGraphicsLoaderPrivate()
+{
+}
+
+void QmlGraphicsLoaderPrivate::itemGeometryChanged(QmlGraphicsItem *resizeItem, const QRectF &newGeometry, const QRectF &oldGeometry)
+{
+ if (resizeItem == item && resizeMode == QmlGraphicsLoader::SizeLoaderToItem) {
+ _q_updateSize();
+ }
+ QmlGraphicsItemChangeListener::itemGeometryChanged(resizeItem, newGeometry, oldGeometry);
+}
+
+void QmlGraphicsLoaderPrivate::clear()
+{
+ if (ownComponent) {
+ delete component;
+ component = 0;
+ ownComponent = false;
+ }
+ source = QUrl();
+
+ if (item) {
+ if (QmlGraphicsItem *qmlItem = qobject_cast<QmlGraphicsItem*>(item)) {
+ if (resizeMode == QmlGraphicsLoader::SizeLoaderToItem) {
+ QmlGraphicsItemPrivate *p =
+ static_cast<QmlGraphicsItemPrivate *>(QGraphicsItemPrivate::get(qmlItem));
+ p->removeItemChangeListener(this, QmlGraphicsItemPrivate::Geometry);
+ }
+ }
+
+ // We can't delete immediately because our item may have triggered
+ // the Loader to load a different item.
+ item->setVisible(false);
+ item->setParentItem(0);
+ item->deleteLater();
+ item = 0;
+ }
+}
+
+void QmlGraphicsLoaderPrivate::initResize()
+{
+ Q_Q(QmlGraphicsLoader);
+ if (QmlGraphicsItem *qmlItem = qobject_cast<QmlGraphicsItem*>(item)) {
+ if (resizeMode == QmlGraphicsLoader::SizeLoaderToItem) {
+ QmlGraphicsItemPrivate *p =
+ static_cast<QmlGraphicsItemPrivate *>(QGraphicsItemPrivate::get(qmlItem));
+ p->addItemChangeListener(this, QmlGraphicsItemPrivate::Geometry);
+ }
+ } else if (item && item->isWidget()) {
+ QGraphicsWidget *widget = static_cast<QGraphicsWidget*>(item);
+ if (resizeMode == QmlGraphicsLoader::SizeLoaderToItem) {
+ widget->installEventFilter(q);
+ }
+ }
+ _q_updateSize();
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Loader,QmlGraphicsLoader)
+
+/*!
+ \qmlclass Loader QmlGraphicsLoader
+ \inherits Item
+
+ \brief The Loader item allows dynamically loading an Item-based
+ subtree from a QML URL or Component.
+
+ Loader instantiates an item from a component. The component to
+ instantiate may be specified directly by the \c sourceComponent
+ property, or loaded from a URL via the \c source property.
+
+ It is also an effective means of delaying the creation of a component
+ until it is required:
+ \code
+ Loader { id: pageLoader }
+ Rectangle {
+ MouseRegion { anchors.fill: parent; onClicked: pageLoader.source = "Page1.qml" }
+ }
+ \endcode
+
+ If the Loader source is changed, any previous items instantiated
+ will be destroyed. Setting \c source to an empty string
+ will destroy the currently instantiated items, freeing resources
+ and leaving the Loader empty. For example:
+
+ \code
+ pageLoader.source = ""
+ \endcode
+
+ unloads "Page1.qml" and frees resources consumed by it.
+
+ \sa {dynamic-object-creation}{Dynamic Object Creation}
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsLoader
+ \qmlclass Loader
+ */
+
+/*!
+ Create a new QmlGraphicsLoader instance.
+ */
+QmlGraphicsLoader::QmlGraphicsLoader(QmlGraphicsItem *parent)
+ : QmlGraphicsItem(*(new QmlGraphicsLoaderPrivate), parent)
+{
+}
+
+/*!
+ Destroy the loader instance.
+ */
+QmlGraphicsLoader::~QmlGraphicsLoader()
+{
+}
+
+/*!
+ \qmlproperty url Loader::source
+ This property holds the URL of the QML component to
+ instantiate.
+
+ \sa sourceComponent, status, progress
+*/
+QUrl QmlGraphicsLoader::source() const
+{
+ Q_D(const QmlGraphicsLoader);
+ return d->source;
+}
+
+void QmlGraphicsLoader::setSource(const QUrl &url)
+{
+ Q_D(QmlGraphicsLoader);
+ if (d->source == url)
+ return;
+
+ d->clear();
+
+ d->source = url;
+ if (d->source.isEmpty()) {
+ emit sourceChanged();
+ emit statusChanged();
+ emit progressChanged();
+ emit itemChanged();
+ return;
+ }
+
+ d->component = new QmlComponent(qmlEngine(this), d->source, this);
+ d->ownComponent = true;
+ if (!d->component->isLoading()) {
+ d->_q_sourceLoaded();
+ } else {
+ connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)),
+ this, SLOT(_q_sourceLoaded()));
+ connect(d->component, SIGNAL(progressChanged(qreal)),
+ this, SIGNAL(progressChanged()));
+ emit statusChanged();
+ emit progressChanged();
+ emit sourceChanged();
+ emit itemChanged();
+ }
+}
+
+/*!
+ \qmlproperty Component Loader::sourceComponent
+ The sourceComponent 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
+
+ \sa source, progress
+*/
+
+QmlComponent *QmlGraphicsLoader::sourceComponent() const
+{
+ Q_D(const QmlGraphicsLoader);
+ return d->component;
+}
+
+void QmlGraphicsLoader::setSourceComponent(QmlComponent *comp)
+{
+ Q_D(QmlGraphicsLoader);
+ if (comp == d->component)
+ return;
+
+ d->clear();
+
+ d->component = comp;
+ d->ownComponent = false;
+ if (!d->component) {
+ emit sourceChanged();
+ emit statusChanged();
+ emit progressChanged();
+ emit itemChanged();
+ return;
+ }
+
+ if (!d->component->isLoading()) {
+ d->_q_sourceLoaded();
+ } else {
+ connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)),
+ this, SLOT(_q_sourceLoaded()));
+ connect(d->component, SIGNAL(progressChanged(qreal)),
+ this, SIGNAL(progressChanged()));
+ emit progressChanged();
+ emit sourceChanged();
+ emit statusChanged();
+ emit itemChanged();
+ }
+}
+
+void QmlGraphicsLoaderPrivate::_q_sourceLoaded()
+{
+ Q_Q(QmlGraphicsLoader);
+
+ if (component) {
+ QmlContext *ctxt = new QmlContext(qmlContext(q));
+ ctxt->addDefaultObject(q);
+
+ if (!component->errors().isEmpty()) {
+ qWarning() << component->errors();
+ emit q->sourceChanged();
+ emit q->statusChanged();
+ emit q->progressChanged();
+ return;
+ }
+
+ QObject *obj = component->create(ctxt);
+ if (obj) {
+ ctxt->setParent(obj);
+ item = qobject_cast<QGraphicsObject *>(obj);
+ if (item) {
+ if (QmlGraphicsItem* qmlItem = qobject_cast<QmlGraphicsItem *>(item)) {
+ qmlItem->setParentItem(q);
+ } else {
+ item->setParentItem(q);
+ item->setParent(q);
+ }
+// item->setFocus(true);
+ initResize();
+ }
+ } else {
+ delete obj;
+ delete ctxt;
+ source = QUrl();
+ }
+ emit q->sourceChanged();
+ emit q->statusChanged();
+ emit q->progressChanged();
+ emit q->itemChanged();
+ }
+}
+
+/*!
+ \qmlproperty enum Loader::status
+
+ This property holds the status of QML loading. It can be one of:
+ \list
+ \o Null - no QML source has been set
+ \o Ready - the QML source has been loaded
+ \o Loading - the QML source is currently being loaded
+ \o Error - an error occurred while loading the QML source
+ \endlist
+
+ \sa progress
+*/
+
+QmlGraphicsLoader::Status QmlGraphicsLoader::status() const
+{
+ Q_D(const QmlGraphicsLoader);
+
+ if (d->component)
+ return static_cast<QmlGraphicsLoader::Status>(d->component->status());
+
+ if (d->item)
+ return Ready;
+
+ return d->source.isEmpty() ? Null : Error;
+}
+
+/*!
+ \qmlproperty real Loader::progress
+
+ This property holds the progress of QML data loading, from 0.0 (nothing loaded)
+ to 1.0 (finished).
+
+ \sa status
+*/
+qreal QmlGraphicsLoader::progress() const
+{
+ Q_D(const QmlGraphicsLoader);
+
+ if (d->item)
+ return 1.0;
+
+ if (d->component)
+ return d->component->progress();
+
+ return 0.0;
+}
+
+/*!
+ \qmlproperty enum Loader::resizeMode
+
+ This property determines how the Loader or item are resized:
+ \list
+ \o NoResize - no item will be resized
+ \o SizeLoaderToItem - the Loader will be sized to the size of the item, unless the size of the Loader has been otherwise specified.
+ \o SizeItemToLoader - the item will be sized to the size of the Loader.
+ \endlist
+
+ Note that changing from SizeItemToLoader to SizeLoaderToItem
+ after the component is loaded will not return the item or Loader
+ to it's original size. This is due to the item size being adjusted
+ to the Loader size, thereby losing the original size of the item.
+ Future changes to the item's size will affect the loader, however.
+
+ The default resizeMode is SizeLoaderToItem.
+*/
+QmlGraphicsLoader::ResizeMode QmlGraphicsLoader::resizeMode() const
+{
+ Q_D(const QmlGraphicsLoader);
+ return d->resizeMode;
+}
+
+void QmlGraphicsLoader::setResizeMode(ResizeMode mode)
+{
+ Q_D(QmlGraphicsLoader);
+ if (mode == d->resizeMode)
+ return;
+
+ if (QmlGraphicsItem *qmlItem = qobject_cast<QmlGraphicsItem*>(d->item)) {
+ if (d->resizeMode == SizeLoaderToItem) {
+ QmlGraphicsItemPrivate *p =
+ static_cast<QmlGraphicsItemPrivate *>(QGraphicsItemPrivate::get(qmlItem));
+ p->removeItemChangeListener(d, QmlGraphicsItemPrivate::Geometry);
+ }
+ } else if (d->item && d->item->isWidget()) {
+ if (d->resizeMode == SizeLoaderToItem)
+ d->item->removeEventFilter(this);
+ }
+
+ d->resizeMode = mode;
+ d->initResize();
+}
+
+void QmlGraphicsLoaderPrivate::_q_updateSize()
+{
+ Q_Q(QmlGraphicsLoader);
+ if (!item)
+ return;
+ if (QmlGraphicsItem *qmlItem = qobject_cast<QmlGraphicsItem*>(item)) {
+ if (resizeMode == QmlGraphicsLoader::SizeLoaderToItem) {
+ q->setWidth(qmlItem->width());
+ q->setHeight(qmlItem->height());
+ } else if (resizeMode == QmlGraphicsLoader::SizeItemToLoader) {
+ qmlItem->setWidth(q->width());
+ qmlItem->setHeight(q->height());
+ }
+ } else if (item && item->isWidget()) {
+ QGraphicsWidget *widget = static_cast<QGraphicsWidget*>(item);
+ if (resizeMode == QmlGraphicsLoader::SizeLoaderToItem) {
+ QSizeF newSize = widget->size();
+ if (newSize.isValid()) {
+ q->setWidth(newSize.width());
+ q->setHeight(newSize.height());
+ }
+ } else if (resizeMode == QmlGraphicsLoader::SizeItemToLoader) {
+ QSizeF oldSize = widget->size();
+ QSizeF newSize = oldSize;
+ if (q->heightValid())
+ newSize.setHeight(q->height());
+ if (q->widthValid())
+ newSize.setWidth(q->width());
+ if (oldSize != newSize)
+ widget->resize(newSize);
+ }
+ }
+}
+
+/*!
+ \qmlproperty Item Loader::item
+ This property holds the top-level item created from source.
+*/
+QGraphicsObject *QmlGraphicsLoader::item() const
+{
+ Q_D(const QmlGraphicsLoader);
+ return d->item;
+}
+
+void QmlGraphicsLoader::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
+{
+ Q_D(QmlGraphicsLoader);
+ if (newGeometry != oldGeometry) {
+ if (d->resizeMode == SizeItemToLoader) {
+ d->_q_updateSize();
+ }
+ }
+ QmlGraphicsItem::geometryChanged(newGeometry, oldGeometry);
+}
+
+QVariant QmlGraphicsLoader::itemChange(GraphicsItemChange change, const QVariant &value)
+{
+ Q_D(QmlGraphicsLoader);
+ if (change == ItemSceneHasChanged) {
+ if (d->item && d->item->isWidget()) {
+ if (d->resizeMode == SizeLoaderToItem) {
+ d->item->removeEventFilter(this);
+ d->item->installEventFilter(this);
+ }
+ }
+ }
+ return QmlGraphicsItem::itemChange(change, value);
+}
+
+bool QmlGraphicsLoader::eventFilter(QObject *watched, QEvent *e)
+{
+ Q_D(QmlGraphicsLoader);
+ if (watched == d->item && e->type() == QEvent::GraphicsSceneResize) {
+ if (d->item && d->item->isWidget() && d->resizeMode == SizeLoaderToItem) {
+ d->_q_updateSize();
+ }
+ }
+ return QmlGraphicsItem::eventFilter(watched, e);
+}
+
+#include <moc_qmlgraphicsloader_p.cpp>
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsloader_p.h b/src/declarative/graphicsitems/qmlgraphicsloader_p.h
new file mode 100644
index 0000000..87b6a52
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsloader_p.h
@@ -0,0 +1,109 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSLOADER_H
+#define QMLGRAPHICSLOADER_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsLoaderPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsLoader : public QmlGraphicsItem
+{
+ Q_OBJECT
+ Q_ENUMS(Status)
+ Q_ENUMS(ResizeMode)
+
+ Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
+ Q_PROPERTY(QmlComponent *sourceComponent READ sourceComponent WRITE setSourceComponent NOTIFY sourceChanged)
+ Q_PROPERTY(ResizeMode resizeMode READ resizeMode WRITE setResizeMode)
+ Q_PROPERTY(QGraphicsObject *item READ item NOTIFY itemChanged)
+ Q_PROPERTY(Status status READ status NOTIFY statusChanged)
+ Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged)
+
+public:
+ QmlGraphicsLoader(QmlGraphicsItem *parent=0);
+ virtual ~QmlGraphicsLoader();
+
+ QUrl source() const;
+ void setSource(const QUrl &);
+
+ QmlComponent *sourceComponent() const;
+ void setSourceComponent(QmlComponent *);
+
+ enum Status { Null, Ready, Loading, Error };
+ Status status() const;
+ qreal progress() const;
+
+ enum ResizeMode { NoResize, SizeLoaderToItem, SizeItemToLoader };
+ ResizeMode resizeMode() const;
+ void setResizeMode(ResizeMode mode);
+
+ QGraphicsObject *item() const;
+
+Q_SIGNALS:
+ void itemChanged();
+ void sourceChanged();
+ void statusChanged();
+ void progressChanged();
+protected:
+ void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry);
+ QVariant itemChange(GraphicsItemChange change, const QVariant &value);
+ bool eventFilter(QObject *watched, QEvent *e);
+private:
+ Q_DISABLE_COPY(QmlGraphicsLoader)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsLoader)
+ Q_PRIVATE_SLOT(d_func(), void _q_sourceLoaded())
+ Q_PRIVATE_SLOT(d_func(), void _q_updateSize())
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsLoader)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSLOADER_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsloader_p_p.h b/src/declarative/graphicsitems/qmlgraphicsloader_p_p.h
new file mode 100644
index 0000000..7f10eff
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsloader_p_p.h
@@ -0,0 +1,88 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSLOADER_P_H
+#define QMLGRAPHICSLOADER_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 "qmlgraphicsloader_p.h"
+
+#include "qmlgraphicsitem_p.h"
+#include "qmlgraphicsitemchangelistener_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlContext;
+class QmlGraphicsLoaderPrivate : public QmlGraphicsItemPrivate, public QmlGraphicsItemChangeListener
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsLoader)
+
+public:
+ QmlGraphicsLoaderPrivate();
+ ~QmlGraphicsLoaderPrivate();
+
+ void itemGeometryChanged(QmlGraphicsItem *item, const QRectF &newGeometry, const QRectF &oldGeometry);
+ void clear();
+ void initResize();
+
+ QUrl source;
+ QGraphicsObject *item;
+ QmlComponent *component;
+ bool ownComponent : 1;
+ QmlGraphicsLoader::ResizeMode resizeMode;
+
+ void _q_sourceLoaded();
+ void _q_updateSize();
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLGRAPHICSLOADER_P_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsmouseregion.cpp b/src/declarative/graphicsitems/qmlgraphicsmouseregion.cpp
new file mode 100644
index 0000000..bd21e7a
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsmouseregion.cpp
@@ -0,0 +1,653 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsmouseregion_p.h"
+#include "qmlgraphicsmouseregion_p_p.h"
+
+#include "qmlgraphicsevents_p_p.h"
+
+#include <QGraphicsSceneMouseEvent>
+
+QT_BEGIN_NAMESPACE
+static const int PressAndHoldDelay = 800;
+
+QML_DEFINE_TYPE(Qt,4,6,Drag,QmlGraphicsDrag)
+QmlGraphicsDrag::QmlGraphicsDrag(QObject *parent)
+: QObject(parent), _target(0), _axis(XandYAxis), _xmin(0), _xmax(0), _ymin(0), _ymax(0)
+{
+}
+
+QmlGraphicsDrag::~QmlGraphicsDrag()
+{
+}
+
+QmlGraphicsItem *QmlGraphicsDrag::target() const
+{
+ return _target;
+}
+
+void QmlGraphicsDrag::setTarget(QmlGraphicsItem *t)
+{
+ _target = t;
+}
+
+QmlGraphicsDrag::Axis QmlGraphicsDrag::axis() const
+{
+ return _axis;
+}
+
+void QmlGraphicsDrag::setAxis(QmlGraphicsDrag::Axis a)
+{
+ _axis = a;
+}
+
+qreal QmlGraphicsDrag::xmin() const
+{
+ return _xmin;
+}
+
+void QmlGraphicsDrag::setXmin(qreal m)
+{
+ _xmin = m;
+}
+
+qreal QmlGraphicsDrag::xmax() const
+{
+ return _xmax;
+}
+
+void QmlGraphicsDrag::setXmax(qreal m)
+{
+ _xmax = m;
+}
+
+qreal QmlGraphicsDrag::ymin() const
+{
+ return _ymin;
+}
+
+void QmlGraphicsDrag::setYmin(qreal m)
+{
+ _ymin = m;
+}
+
+qreal QmlGraphicsDrag::ymax() const
+{
+ return _ymax;
+}
+
+void QmlGraphicsDrag::setYmax(qreal m)
+{
+ _ymax = m;
+}
+
+QmlGraphicsMouseRegionPrivate::~QmlGraphicsMouseRegionPrivate()
+{
+ delete drag;
+}
+
+
+/*!
+ \qmlclass MouseRegion QmlGraphicsMouseRegion
+ \brief The MouseRegion item enables simple mouse handling.
+ \inherits Item
+
+ A MouseRegion is typically used in conjunction with a visible item,
+ where the MouseRegion effectively 'proxies' mouse handling for that
+ item. For example, we can put a MouseRegion in a Rectangle that changes
+ the Rectangle color to red when clicked:
+ \snippet doc/src/snippets/declarative/mouseregion.qml 0
+
+ Many MouseRegion signals pass a \l {MouseEvent}{mouse} parameter that contains
+ additional information about the mouse event, such as the position, button,
+ and any key modifiers.
+
+ Below we have the previous
+ example extended so as to give a different color when you right click.
+ \snippet doc/src/snippets/declarative/mouseregion.qml 1
+
+ For basic key handling, see the \l {Keys}{Keys attached property}.
+
+ MouseRegion is an invisible item: it is never painted.
+
+ \sa MouseEvent
+*/
+
+/*!
+ \qmlsignal MouseRegion::onEntered()
+
+ This handler is called when the mouse enters the mouse region.
+*/
+
+/*!
+ \qmlsignal MouseRegion::onExited()
+
+ This handler is called when the mouse exists the mouse region.
+*/
+
+/*!
+ \qmlsignal MouseRegion::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.
+*/
+
+/*!
+ \qmlsignal MouseRegion::onClicked(mouse)
+
+ This handler is called when there is a click. A click is defined as a press followed by a release,
+ both inside the MouseRegion (pressing, moving outside the MouseRegion, 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 wasHeld.
+
+ The \e accepted property of the MouseEvent parameter is ignored in this handler.
+*/
+
+/*!
+ \qmlsignal MouseRegion::onPressed(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 MouseRegion
+ will handle the press and all future mouse events until release. The default is to accept
+ the event and not allow other MouseRegions beneath this one to handle the event. If \e accepted
+ is set to false, no further events will be sent to this MouseRegion until the button is next
+ pressed.
+*/
+
+/*!
+ \qmlsignal MouseRegion::onReleased(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 wasHeld.
+
+ The \e accepted property of the MouseEvent parameter is ignored in this handler.
+*/
+
+/*!
+ \qmlsignal MouseRegion::onPressAndHold(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 MouseRegion::onDoubleClicked(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 wasHeld.
+
+ The \e accepted property of the MouseEvent parameter is ignored in this handler.
+*/
+
+QML_DEFINE_TYPE(Qt,4,6,MouseRegion,QmlGraphicsMouseRegion)
+
+/*!
+ \internal
+ \class QmlGraphicsMouseRegion
+ \brief The QmlGraphicsMouseRegion class provides a simple mouse handling abstraction for use within Qml.
+
+ \ingroup group_coreitems
+
+ All QmlGraphicsItem derived classes can do mouse handling but the QmlGraphicsMouseRegion class exposes mouse
+ handling data as properties and tracks flicking and dragging of the mouse.
+
+ A QmlGraphicsMouseRegion object can be instantiated in Qml using the tag \l MouseRegion.
+ */
+QmlGraphicsMouseRegion::QmlGraphicsMouseRegion(QmlGraphicsItem *parent)
+ : QmlGraphicsItem(*(new QmlGraphicsMouseRegionPrivate), parent)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ d->init();
+}
+
+QmlGraphicsMouseRegion::~QmlGraphicsMouseRegion()
+{
+}
+
+/*!
+ \qmlproperty real MouseRegion::mouseX
+ \qmlproperty real MouseRegion::mouseY
+ These properties hold the coordinates of the mouse.
+
+ 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
+ even if the mouse is moved outside the region.
+
+ If hoverEnabled is true then these properties will be valid:
+ \list
+ \i when no button is pressed, but the mouse is within the MouseRegion (containsMouse is true).
+ \i if a button is pressed and held, even if it has since moved out of the region.
+ \endlist
+
+ The coordinates are relative to the MouseRegion.
+*/
+qreal QmlGraphicsMouseRegion::mouseX() const
+{
+ Q_D(const QmlGraphicsMouseRegion);
+ return d->lastPos.x();
+}
+
+qreal QmlGraphicsMouseRegion::mouseY() const
+{
+ Q_D(const QmlGraphicsMouseRegion);
+ return d->lastPos.y();
+}
+
+/*!
+ \qmlproperty bool MouseRegion::enabled
+ This property holds whether the item accepts mouse events.
+*/
+bool QmlGraphicsMouseRegion::isEnabled() const
+{
+ Q_D(const QmlGraphicsMouseRegion);
+ return d->absorb;
+}
+
+void QmlGraphicsMouseRegion::setEnabled(bool a)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ if (a != d->absorb) {
+ d->absorb = a;
+ emit enabledChanged();
+ }
+}
+/*!
+ \qmlproperty MouseButtons MouseRegion::pressedButtons
+ This property holds the mouse buttons currently pressed.
+
+ It contains a bitwise combination of:
+ \list
+ \o Qt.LeftButton
+ \o Qt.RightButton
+ \o Qt.MidButton
+ \endlist
+
+ The code below displays "right" when the right mouse buttons is pressed:
+ \code
+ Text {
+ text: mr.pressedButtons & Qt.RightButton ? "right" : ""
+ horizontalAlignment: Text.AlignHCenter
+ verticalAlignment: Text.AlignVCenter
+ MouseRegion {
+ id: mr
+ acceptedButtons: Qt.LeftButton | Qt.RightButton
+ anchors.fill: parent
+ }
+ }
+ \endcode
+
+ \sa acceptedButtons
+*/
+Qt::MouseButtons QmlGraphicsMouseRegion::pressedButtons() const
+{
+ Q_D(const QmlGraphicsMouseRegion);
+ return d->lastButtons;
+}
+
+void QmlGraphicsMouseRegion::mousePressEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ d->moved = false;
+ if (!d->absorb)
+ QmlGraphicsItem::mousePressEvent(event);
+ else {
+ d->longPress = false;
+ d->saveEvent(event);
+ if (d->drag) {
+ d->dragX = drag()->axis() & QmlGraphicsDrag::XAxis;
+ d->dragY = drag()->axis() & QmlGraphicsDrag::YAxis;
+ }
+ d->dragged = false;
+ setHovered(true);
+ d->start = event->pos();
+ d->startScene = event->scenePos();
+ // we should only start timer if pressAndHold is connected to.
+ if (d->isConnected("pressAndHold(QmlGraphicsMouseEvent*)"))
+ d->pressAndHoldTimer.start(PressAndHoldDelay, this);
+ setKeepMouseGrab(false);
+ event->setAccepted(setPressed(true));
+ }
+}
+
+void QmlGraphicsMouseRegion::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ if (!d->absorb) {
+ QmlGraphicsItem::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) {
+ if (d->dragX) d->startX = drag()->target()->x();
+ if (d->dragY) d->startY = drag()->target()->y();
+ }
+
+ QPointF startLocalPos;
+ QPointF curLocalPos;
+ if (drag()->target()->parent()) {
+ startLocalPos = drag()->target()->parentItem()->mapFromScene(d->startScene);
+ curLocalPos = drag()->target()->parentItem()->mapFromScene(event->scenePos());
+ } else {
+ startLocalPos = d->startScene;
+ curLocalPos = event->scenePos();
+ }
+
+ const int dragThreshold = QApplication::startDragDistance();
+ qreal dx = qAbs(curLocalPos.x() - startLocalPos.x());
+ qreal dy = qAbs(curLocalPos.y() - startLocalPos.y());
+ if ((d->dragX && !(dx < dragThreshold)) || (d->dragY && !(dy < dragThreshold)))
+ d->dragged = true;
+ if (!keepMouseGrab()) {
+ if ((!d->dragY && dy < dragThreshold && d->dragX && dx > dragThreshold)
+ || (!d->dragX && dx < dragThreshold && d->dragY && dy > dragThreshold)
+ || (d->dragX && d->dragY)) {
+ setKeepMouseGrab(true);
+ }
+ }
+
+ if (d->dragX) {
+ qreal x = (curLocalPos.x() - startLocalPos.x()) + d->startX;
+ if (x < drag()->xmin())
+ x = drag()->xmin();
+ else if (x > drag()->xmax())
+ x = drag()->xmax();
+ drag()->target()->setX(x);
+ }
+ if (d->dragY) {
+ qreal y = (curLocalPos.y() - startLocalPos.y()) + d->startY;
+ if (y < drag()->ymin())
+ y = drag()->ymin();
+ else if (y > drag()->ymax())
+ y = drag()->ymax();
+ drag()->target()->setY(y);
+ }
+ }
+ d->moved = true;
+ QmlGraphicsMouseEvent me(d->lastPos.x(), d->lastPos.y(), d->lastButton, d->lastButtons, d->lastModifiers, false, d->longPress);
+ emit positionChanged(&me);
+}
+
+
+void QmlGraphicsMouseRegion::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ if (!d->absorb) {
+ QmlGraphicsItem::mouseReleaseEvent(event);
+ } else {
+ d->saveEvent(event);
+ setPressed(false);
+ // If we don't accept hover, we need to reset containsMouse.
+ if (!acceptHoverEvents())
+ setHovered(false);
+ setKeepMouseGrab(false);
+ }
+}
+
+void QmlGraphicsMouseRegion::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ if (!d->absorb) {
+ QmlGraphicsItem::mouseDoubleClickEvent(event);
+ } else {
+ QmlGraphicsItem::mouseDoubleClickEvent(event);
+ if (event->isAccepted()) {
+ // Only deliver the event if we have accepted the press.
+ d->saveEvent(event);
+ QmlGraphicsMouseEvent me(d->lastPos.x(), d->lastPos.y(), d->lastButton, d->lastButtons, d->lastModifiers, true, false);
+ emit this->doubleClicked(&me);
+ }
+ }
+}
+
+void QmlGraphicsMouseRegion::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ if (!d->absorb)
+ QmlGraphicsItem::hoverEnterEvent(event);
+ else
+ setHovered(true);
+}
+
+void QmlGraphicsMouseRegion::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ if (!d->absorb) {
+ QmlGraphicsItem::hoverEnterEvent(event);
+ } else {
+ d->lastPos = event->pos();
+ QmlGraphicsMouseEvent me(d->lastPos.x(), d->lastPos.y(), Qt::NoButton, d->lastButtons, d->lastModifiers, false, d->longPress);
+ emit positionChanged(&me);
+ }
+}
+
+void QmlGraphicsMouseRegion::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ if (!d->absorb)
+ QmlGraphicsItem::hoverLeaveEvent(event);
+ else
+ setHovered(false);
+}
+
+bool QmlGraphicsMouseRegion::sceneEvent(QEvent *event)
+{
+ bool rv = QmlGraphicsItem::sceneEvent(event);
+ if (event->type() == QEvent::UngrabMouse) {
+ Q_D(QmlGraphicsMouseRegion);
+ if (d->pressed) {
+ // if our mouse grab has been removed (probably by Flickable), fix our
+ // state
+ d->pressed = false;
+ setKeepMouseGrab(false);
+ emit pressedChanged();
+ //emit hoveredChanged();
+ }
+ }
+ return rv;
+}
+
+void QmlGraphicsMouseRegion::timerEvent(QTimerEvent *event)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ if (event->timerId() == d->pressAndHoldTimer.timerId()) {
+ d->pressAndHoldTimer.stop();
+ if (d->pressed && d->dragged == false && d->hovered == true) {
+ d->longPress = true;
+ QmlGraphicsMouseEvent me(d->lastPos.x(), d->lastPos.y(), d->lastButton, d->lastButtons, d->lastModifiers, false, d->longPress);
+ emit pressAndHold(&me);
+ }
+ }
+}
+
+/*!
+ \qmlproperty bool MouseRegion::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.
+*/
+
+/*!
+ \qmlproperty bool MouseRegion::containsMouse
+ This property holds whether the mouse is currently inside the mouse region.
+
+ \warning This property is not updated if the region 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 QmlGraphicsMouseRegion::hovered() const
+{
+ Q_D(const QmlGraphicsMouseRegion);
+ return d->hovered;
+}
+
+/*!
+ \qmlproperty bool MouseRegion::pressed
+ This property holds whether the mouse region is currently pressed.
+*/
+bool QmlGraphicsMouseRegion::pressed() const
+{
+ Q_D(const QmlGraphicsMouseRegion);
+ return d->pressed;
+}
+
+void QmlGraphicsMouseRegion::setHovered(bool h)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ if (d->hovered != h) {
+ d->hovered = h;
+ emit hoveredChanged();
+ d->hovered ? emit entered() : emit exited();
+ }
+}
+
+/*!
+ \qmlproperty Qt::MouseButtons MouseRegion::acceptedButtons
+ This property holds the mouse buttons that the mouse region reacts to.
+
+ The available buttons are:
+ \list
+ \o Qt.LeftButton
+ \o Qt.RightButton
+ \o Qt.MidButton
+ \endlist
+
+ To accept more than one button the flags can be combined with the
+ "|" (or) operator:
+
+ \code
+ MouseRegion { acceptedButtons: Qt.LeftButton | Qt.RightButton }
+ \endcode
+
+ The default is to accept the Left button.
+*/
+Qt::MouseButtons QmlGraphicsMouseRegion::acceptedButtons() const
+{
+ return acceptedMouseButtons();
+}
+
+void QmlGraphicsMouseRegion::setAcceptedButtons(Qt::MouseButtons buttons)
+{
+ if (buttons != acceptedMouseButtons()) {
+ setAcceptedMouseButtons(buttons);
+ emit acceptedButtonsChanged();
+ }
+}
+
+bool QmlGraphicsMouseRegion::setPressed(bool p)
+{
+ Q_D(QmlGraphicsMouseRegion);
+ bool isclick = d->pressed == true && p == false && d->dragged == false && d->hovered == true;
+
+ if (d->pressed != p) {
+ d->pressed = p;
+ QmlGraphicsMouseEvent me(d->lastPos.x(), d->lastPos.y(), d->lastButton, d->lastButtons, d->lastModifiers, isclick, d->longPress);
+ if (d->pressed) {
+ emit positionChanged(&me);
+ emit pressed(&me);
+ } else {
+ emit released(&me);
+ if (isclick)
+ emit clicked(&me);
+ }
+
+ emit pressedChanged();
+ return me.isAccepted();
+ }
+ return false;
+}
+
+QmlGraphicsDrag *QmlGraphicsMouseRegion::drag()
+{
+ Q_D(QmlGraphicsMouseRegion);
+ if (!d->drag)
+ d->drag = new QmlGraphicsDrag;
+ return d->drag;
+}
+
+/*!
+ \qmlproperty Item MouseRegion::drag.target
+ \qmlproperty Axis MouseRegion::drag.axis
+ \qmlproperty real MouseRegion::drag.minimumX
+ \qmlproperty real MouseRegion::drag.maximumX
+ \qmlproperty real MouseRegion::drag.minimumY
+ \qmlproperty real MouseRegion::drag.maximumY
+
+ drag provides a convenient way to make an item draggable.
+
+ \list
+ \i \c target specifies the item to drag.
+ \i \c axis specifies whether dragging can be done horizontally (XAxis), vertically (YAxis), or both (XandYAxis)
+ \i the minimum and maximum properties limit how far the target can be dragged along the corresponding axes.
+ \endlist
+
+ The following example uses drag to reduce the opacity of an image as it moves to the right:
+ \snippet doc/src/snippets/declarative/drag.qml 0
+*/
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsmouseregion_p.h b/src/declarative/graphicsitems/qmlgraphicsmouseregion_p.h
new file mode 100644
index 0000000..0ddad1b
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsmouseregion_p.h
@@ -0,0 +1,177 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSMOUSEREGION_H
+#define QMLGRAPHICSMOUSEREGION_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsDrag : public QObject
+{
+ Q_OBJECT
+
+ Q_ENUMS(Axis)
+ Q_PROPERTY(QmlGraphicsItem *target READ target WRITE setTarget)
+ Q_PROPERTY(Axis axis READ axis WRITE setAxis)
+ Q_PROPERTY(qreal minimumX READ xmin WRITE setXmin)
+ Q_PROPERTY(qreal maximumX READ xmax WRITE setXmax)
+ Q_PROPERTY(qreal minimumY READ ymin WRITE setYmin)
+ Q_PROPERTY(qreal maximumY READ ymax WRITE setYmax)
+ //### consider drag and drop
+
+public:
+ QmlGraphicsDrag(QObject *parent=0);
+ ~QmlGraphicsDrag();
+
+ QmlGraphicsItem *target() const;
+ void setTarget(QmlGraphicsItem *);
+
+ 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);
+
+private:
+ QmlGraphicsItem *_target;
+ Axis _axis;
+ qreal _xmin;
+ qreal _xmax;
+ qreal _ymin;
+ qreal _ymax;
+ Q_DISABLE_COPY(QmlGraphicsDrag)
+};
+
+class QmlGraphicsMouseEvent;
+class QmlGraphicsMouseRegionPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsMouseRegion : public QmlGraphicsItem
+{
+ Q_OBJECT
+
+ Q_PROPERTY(qreal mouseX READ mouseX NOTIFY positionChanged)
+ Q_PROPERTY(qreal mouseY READ mouseY NOTIFY positionChanged)
+ 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 acceptHoverEvents WRITE setAcceptHoverEvents)
+ Q_PROPERTY(QmlGraphicsDrag *drag READ drag) //### add flicking to QmlGraphicsDrag or add a QmlGraphicsFlick ???
+
+public:
+ QmlGraphicsMouseRegion(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsMouseRegion();
+
+ 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);
+
+ QmlGraphicsDrag *drag();
+
+Q_SIGNALS:
+ void hoveredChanged();
+ void pressedChanged();
+ void enabledChanged();
+ void acceptedButtonsChanged();
+ void positionChanged(QmlGraphicsMouseEvent *mouse);
+
+ void pressed(QmlGraphicsMouseEvent *mouse);
+ void pressAndHold(QmlGraphicsMouseEvent *mouse);
+ void released(QmlGraphicsMouseEvent *mouse);
+ void clicked(QmlGraphicsMouseEvent *mouse);
+ void doubleClicked(QmlGraphicsMouseEvent *mouse);
+ void entered();
+ void exited();
+
+protected:
+ void setHovered(bool);
+ bool setPressed(bool);
+
+ void mousePressEvent(QGraphicsSceneMouseEvent *event);
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
+ void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
+ void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
+ void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
+ void hoverMoveEvent(QGraphicsSceneHoverEvent *event);
+ void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
+ bool sceneEvent(QEvent *);
+ void timerEvent(QTimerEvent *event);
+
+private:
+ void handlePress();
+ void handleRelease();
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsMouseRegion)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsMouseRegion)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsDrag)
+QML_DECLARE_TYPE(QmlGraphicsMouseRegion)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSMOUSEREGION_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsmouseregion_p_p.h b/src/declarative/graphicsitems/qmlgraphicsmouseregion_p_p.h
new file mode 100644
index 0000000..0f1b0d4
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsmouseregion_p_p.h
@@ -0,0 +1,117 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSMOUSEREGION_P_H
+#define QMLGRAPHICSMOUSEREGION_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 "qmlgraphicsitem_p.h"
+
+#include <qdatetime.h>
+#include <qbasictimer.h>
+#include <qgraphicssceneevent.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsMouseRegionPrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsMouseRegion)
+
+public:
+ QmlGraphicsMouseRegionPrivate()
+ : absorb(true), hovered(false), pressed(false), longPress(false), drag(0)
+ {
+ }
+
+ ~QmlGraphicsMouseRegionPrivate();
+
+ void init()
+ {
+ Q_Q(QmlGraphicsMouseRegion);
+ q->setAcceptedMouseButtons(Qt::LeftButton);
+ }
+
+ void saveEvent(QGraphicsSceneMouseEvent *event) {
+ lastPos = event->pos();
+ lastButton = event->button();
+ lastButtons = event->buttons();
+ lastModifiers = event->modifiers();
+ }
+
+ bool isConnected(const char *signal) {
+ Q_Q(QmlGraphicsMouseRegion);
+ int idx = QObjectPrivate::get(q)->signalIndex(signal);
+ return QObjectPrivate::get(q)->isSignalConnected(idx);
+ }
+
+ bool absorb : 1;
+ bool hovered : 1;
+ bool pressed : 1;
+ bool longPress : 1;
+ bool moved : 1;
+ bool dragX : 1;
+ bool dragY : 1;
+ bool dragged : 1;
+ QmlGraphicsDrag *drag;
+ QPointF start;
+ QPointF startScene;
+ qreal startX;
+ qreal startY;
+ QPointF lastPos;
+ Qt::MouseButton lastButton;
+ Qt::MouseButtons lastButtons;
+ Qt::KeyboardModifiers lastModifiers;
+ QBasicTimer pressAndHoldTimer;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLGRAPHICSMOUSEREGION_P_H
diff --git a/src/declarative/graphicsitems/qmlgraphicspainteditem.cpp b/src/declarative/graphicsitems/qmlgraphicspainteditem.cpp
new file mode 100644
index 0000000..e50e3e4
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspainteditem.cpp
@@ -0,0 +1,466 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicspainteditem_p.h"
+#include "qmlgraphicspainteditem_p_p.h"
+
+#include <QDebug>
+#include <QPen>
+#include <QFile>
+#include <QEvent>
+#include <QApplication>
+#include <QGraphicsSceneMouseEvent>
+#include <QPainter>
+#include <QPaintEngine>
+#include <qmath.h>
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QmlGraphicsPaintedItem
+ \brief The QmlGraphicsPaintedItem class is an abstract base class for QmlView items that want cached painting.
+ \internal
+
+ This is a convenience class for implementing items that paint their contents
+ using a QPainter. The contents of the item are cached behind the scenes.
+ The dirtyCache() function should be called if the contents change to
+ ensure the cache is refreshed the next time painting occurs.
+
+ To subclass QmlGraphicsPaintedItem, you must reimplement drawContents() to draw
+ the contents of the item.
+*/
+
+/*!
+ \fn void QmlGraphicsPaintedItem::drawContents(QPainter *painter, const QRect &rect)
+
+ This function is called when the cache needs to be refreshed. When
+ sub-classing QmlGraphicsPaintedItem this function should be implemented so as to
+ paint the contents of the item using the given \a painter for the
+ area of the contents specified by \a rect.
+*/
+
+/*!
+ \property QmlGraphicsPaintedItem::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 drawContents() function. This is distinct from the size of the
+ item in regards to height() and width().
+*/
+
+// XXX bug in WebKit - can call repaintRequested and other cache-changing functions from within render!
+static int inpaint=0;
+static int inpaint_clearcache=0;
+
+/*!
+ Marks areas of the cache that intersect with the given \a rect as dirty and
+ in need of being refreshed.
+
+ \sa clearCache()
+*/
+void QmlGraphicsPaintedItem::dirtyCache(const QRect& rect)
+{
+ Q_D(QmlGraphicsPaintedItem);
+ QRect srect(qCeil(rect.x()*d->contentsScale),
+ qCeil(rect.y()*d->contentsScale),
+ qCeil(rect.width()*d->contentsScale),
+ qCeil(rect.height()*d->contentsScale));
+ for (int i=0; i < d->imagecache.count(); ) {
+ QmlGraphicsPaintedItemPrivate::ImageCacheItem *c = d->imagecache[i];
+ QRect isect = (c->area & srect) | c->dirty;
+ if (isect == c->area && !inpaint) {
+ delete d->imagecache.takeAt(i);
+ } else {
+ c->dirty = isect;
+ ++i;
+ }
+ }
+}
+
+/*!
+ Marks the entirety of the contents cache as dirty.
+
+ \sa dirtyCache()
+*/
+void QmlGraphicsPaintedItem::clearCache()
+{
+ if (inpaint) {
+ inpaint_clearcache=1;
+ return;
+ }
+ Q_D(QmlGraphicsPaintedItem);
+ qDeleteAll(d->imagecache);
+ d->imagecache.clear();
+}
+
+/*!
+ Returns the size of the contents.
+
+ \sa setContentsSize()
+*/
+QSize QmlGraphicsPaintedItem::contentsSize() const
+{
+ Q_D(const QmlGraphicsPaintedItem);
+ return d->contentsSize;
+}
+
+/*!
+ Sets the size of the contents to the given \a size.
+
+ \sa contentsSize()
+*/
+void QmlGraphicsPaintedItem::setContentsSize(const QSize &size)
+{
+ Q_D(QmlGraphicsPaintedItem);
+ if (d->contentsSize == size) return;
+ d->contentsSize = size;
+ setImplicitWidth(size.width()*d->contentsScale);
+ setImplicitHeight(size.height()*d->contentsScale);
+ clearCache();
+ update();
+ emit contentsSizeChanged();
+}
+
+qreal QmlGraphicsPaintedItem::contentsScale() const
+{
+ Q_D(const QmlGraphicsPaintedItem);
+ return d->contentsScale;
+}
+
+void QmlGraphicsPaintedItem::setContentsScale(qreal scale)
+{
+ Q_D(QmlGraphicsPaintedItem);
+ if (d->contentsScale == scale) return;
+ d->contentsScale = scale;
+ setImplicitWidth(d->contentsSize.width()*scale);
+ setImplicitHeight(d->contentsSize.height()*scale);
+ clearCache();
+ update();
+ emit contentsScaleChanged();
+}
+
+
+/*!
+ Constructs a new QmlGraphicsPaintedItem with the given \a parent.
+*/
+QmlGraphicsPaintedItem::QmlGraphicsPaintedItem(QmlGraphicsItem *parent)
+ : QmlGraphicsItem(*(new QmlGraphicsPaintedItemPrivate), parent)
+{
+ init();
+}
+
+/*!
+ \internal
+ Constructs a new QmlGraphicsPaintedItem with the given \a parent and
+ initialized private data member \a dd.
+*/
+QmlGraphicsPaintedItem::QmlGraphicsPaintedItem(QmlGraphicsPaintedItemPrivate &dd, QmlGraphicsItem *parent)
+ : QmlGraphicsItem(dd, parent)
+{
+ init();
+}
+
+/*!
+ Destroys the image item.
+*/
+QmlGraphicsPaintedItem::~QmlGraphicsPaintedItem()
+{
+ clearCache();
+}
+
+/*!
+ \internal
+*/
+void QmlGraphicsPaintedItem::init()
+{
+ connect(this,SIGNAL(widthChanged()),this,SLOT(clearCache()));
+ connect(this,SIGNAL(heightChanged()),this,SLOT(clearCache()));
+ connect(this,SIGNAL(visibleChanged()),this,SLOT(clearCache()));
+}
+
+void QmlGraphicsPaintedItem::setCacheFrozen(bool frozen)
+{
+ Q_D(QmlGraphicsPaintedItem);
+ if (d->cachefrozen == frozen)
+ return;
+ d->cachefrozen = frozen;
+ // XXX clear cache?
+}
+
+/*!
+ \reimp
+*/
+void QmlGraphicsPaintedItem::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
+{
+ Q_D(QmlGraphicsPaintedItem);
+ const QRect content(0,0,qCeil(d->contentsSize.width()*d->contentsScale),
+ qCeil(d->contentsSize.height()*d->contentsScale));
+ if (content.width() <= 0 || content.height() <= 0)
+ return;
+
+ ++inpaint;
+
+ const QTransform &x = p->deviceTransform();
+ QTransform xinv = x.inverted();
+ QRegion effectiveClip;
+ QRegion sysClip = p->paintEngine()->systemClip();
+ if (xinv.type() <= QTransform::TxScale && sysClip.numRects() < 5) {
+ // simple transform, region gets no more complicated...
+ effectiveClip = xinv.map(sysClip);
+ } else {
+ // do not make complicated regions...
+ effectiveClip = xinv.mapRect(sysClip.boundingRect());
+ }
+
+ QRegion topaint = p->clipRegion();
+ if (topaint.isEmpty()) {
+ if (effectiveClip.isEmpty())
+ topaint = QRect(0,0,p->device()->width(),p->device()->height());
+ else
+ topaint = effectiveClip;
+ } else if (!effectiveClip.isEmpty()) {
+ topaint &= effectiveClip;
+ }
+
+ topaint &= content;
+ QRegion uncached(content);
+ p->setRenderHints(QPainter::SmoothPixmapTransform, d->smooth);
+
+ int cachesize=0;
+ for (int i=0; i<d->imagecache.count(); ++i) {
+ QRect area = d->imagecache[i]->area;
+ if (topaint.contains(area)) {
+ QRectF target(area.x(), area.y(), area.width(), area.height());
+ if (!d->cachefrozen) {
+ if (!d->imagecache[i]->dirty.isNull() && topaint.contains(d->imagecache[i]->dirty)) {
+ QPainter qp(&d->imagecache[i]->image);
+ qp.setRenderHints(QPainter::HighQualityAntialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform, d->smoothCache);
+ qp.translate(-area.x(), -area.y());
+ qp.scale(d->contentsScale,d->contentsScale);
+ QRect clip = d->imagecache[i]->dirty;
+ QRect sclip(qFloor(clip.x()/d->contentsScale),
+ qFloor(clip.y()/d->contentsScale),
+ qCeil(clip.width()/d->contentsScale+clip.x()/d->contentsScale-qFloor(clip.x()/d->contentsScale)),
+ qCeil(clip.height()/d->contentsScale+clip.y()/d->contentsScale-qFloor(clip.y()/d->contentsScale)));
+ qp.setClipRect(sclip);
+ if (d->fillColor.isValid()){
+ if(d->fillColor.alpha() < 255){
+ // ### Might not work outside of raster paintengine
+ QPainter::CompositionMode prev = qp.compositionMode();
+ qp.setCompositionMode(QPainter::CompositionMode_Source);
+ qp.fillRect(sclip,d->fillColor);
+ qp.setCompositionMode(prev);
+ }else{
+ qp.fillRect(sclip,d->fillColor);
+ }
+ }
+ drawContents(&qp, sclip);
+ d->imagecache[i]->dirty = QRect();
+ }
+ }
+ p->drawPixmap(target.toRect(), d->imagecache[i]->image);
+ topaint -= area;
+ d->imagecache[i]->age=0;
+ } else {
+ d->imagecache[i]->age++;
+ }
+ cachesize += area.width()*area.height();
+ uncached -= area;
+ }
+
+ if (!topaint.isEmpty()) {
+ if (!d->cachefrozen) {
+ // Find a sensible larger area, otherwise will paint lots of tiny images.
+ QRect biggerrect = topaint.boundingRect().adjusted(-64,-64,128,128);
+ cachesize += biggerrect.width() * biggerrect.height();
+ while (d->imagecache.count() && cachesize > d->max_imagecache_size) {
+ int oldest=-1;
+ int age=-1;
+ for (int i=0; i<d->imagecache.count(); ++i) {
+ int a = d->imagecache[i]->age;
+ if (a > age) {
+ oldest = i;
+ age = a;
+ }
+ }
+ cachesize -= d->imagecache[oldest]->area.width()*d->imagecache[oldest]->area.height();
+ uncached += d->imagecache[oldest]->area;
+ delete d->imagecache.takeAt(oldest);
+ }
+ const QRegion bigger = QRegion(biggerrect) & uncached;
+ const QVector<QRect> rects = bigger.rects();
+ for (int i = 0; i < rects.count(); ++i) {
+ const QRect &r = rects.at(i);
+ QPixmap img(r.size());
+ if (d->fillColor.isValid())
+ img.fill(d->fillColor);
+ {
+ QPainter qp(&img);
+ qp.setRenderHints(QPainter::HighQualityAntialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform, d->smoothCache);
+
+ qp.translate(-r.x(),-r.y());
+ qp.scale(d->contentsScale,d->contentsScale);
+ QRect sclip(qFloor(r.x()/d->contentsScale),
+ qFloor(r.y()/d->contentsScale),
+ qCeil(r.width()/d->contentsScale+r.x()/d->contentsScale-qFloor(r.x()/d->contentsScale)),
+ qCeil(r.height()/d->contentsScale+r.y()/d->contentsScale-qFloor(r.y()/d->contentsScale)));
+ drawContents(&qp, sclip);
+ }
+ QmlGraphicsPaintedItemPrivate::ImageCacheItem *newitem = new QmlGraphicsPaintedItemPrivate::ImageCacheItem;
+ newitem->area = r;
+ newitem->image = img;
+ d->imagecache.append(newitem);
+ p->drawPixmap(r, newitem->image);
+ }
+ } else {
+ const QVector<QRect> rects = uncached.rects();
+ for (int i = 0; i < rects.count(); ++i)
+ p->fillRect(rects.at(i), Qt::lightGray);
+ }
+ }
+
+ if (inpaint_clearcache) {
+ clearCache();
+ inpaint_clearcache = 0;
+ }
+
+ --inpaint;
+}
+
+/*!
+ \qmlproperty int PaintedItem::pixelCacheSize
+
+ This property holds the maximum number of pixels of image cache to
+ allow. The default is 0.1 megapixels. The cache will not be larger
+ than the (unscaled) size of the WebView.
+*/
+/*!
+ \property QmlGraphicsPaintedItem::pixelCacheSize
+
+ The maximum number of pixels of image cache to allow. The default
+ is 0.1 megapixels. The cache will not be larger than the (unscaled)
+ size of the QmlGraphicsPaintedItem.
+*/
+int QmlGraphicsPaintedItem::pixelCacheSize() const
+{
+ Q_D(const QmlGraphicsPaintedItem);
+ return d->max_imagecache_size;
+}
+
+void QmlGraphicsPaintedItem::setPixelCacheSize(int pixels)
+{
+ Q_D(QmlGraphicsPaintedItem);
+ if (pixels < d->max_imagecache_size) {
+ int cachesize=0;
+ for (int i=0; i<d->imagecache.count(); ++i) {
+ QRect area = d->imagecache[i]->area;
+ cachesize += area.width()*area.height();
+ }
+ while (d->imagecache.count() && cachesize > pixels) {
+ int oldest=-1;
+ int age=-1;
+ for (int i=0; i<d->imagecache.count(); ++i) {
+ int a = d->imagecache[i]->age;
+ if (a > age) {
+ oldest = i;
+ age = a;
+ }
+ }
+ cachesize -= d->imagecache[oldest]->area.width()*d->imagecache[oldest]->area.height();
+ delete d->imagecache.takeAt(oldest);
+ }
+ }
+ d->max_imagecache_size = pixels;
+}
+
+
+
+/*!
+ \property QmlGraphicsPaintedItem::fillColor
+
+ The color to be used to fill the item prior to calling drawContents().
+ By default, this is Qt::transparent.
+
+ Performance improvements can be achieved if subclasses call this with either an
+ invalid color (QColor()), or an appropriate solid color.
+*/
+void QmlGraphicsPaintedItem::setFillColor(const QColor& c)
+{
+ Q_D(QmlGraphicsPaintedItem);
+ if (d->fillColor == c)
+ return;
+ d->fillColor = c;
+ emit fillColorChanged();
+ update();
+}
+
+QColor QmlGraphicsPaintedItem::fillColor() const
+{
+ Q_D(const QmlGraphicsPaintedItem);
+ return d->fillColor;
+}
+
+/*!
+ \qmlproperty bool PaintedItem::smoothCache
+
+ Controls whether the cached tiles of which the item is composed are
+ rendered smoothly when they are generated.
+
+ This is in addition toe Item::smooth, which controls the smooth painting of
+ the already-painted cached tiles under transformation.
+*/
+bool QmlGraphicsPaintedItem::smoothCache() const
+{
+ Q_D(const QmlGraphicsPaintedItem);
+ return d->smoothCache;
+}
+
+void QmlGraphicsPaintedItem::setSmoothCache(bool on)
+{
+ Q_D(QmlGraphicsPaintedItem);
+ if (d->smoothCache != on) {
+ d->smoothCache = on;
+ clearCache();
+ }
+}
+
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicspainteditem_p.h b/src/declarative/graphicsitems/qmlgraphicspainteditem_p.h
new file mode 100644
index 0000000..ab21f36
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspainteditem_p.h
@@ -0,0 +1,114 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSIMAGEITEM_H
+#define QMLGRAPHICSIMAGEITEM_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsPaintedItemPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsPaintedItem : public QmlGraphicsItem
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QSize contentsSize READ contentsSize WRITE setContentsSize NOTIFY contentsSizeChanged)
+ Q_PROPERTY(QColor fillColor READ fillColor WRITE setFillColor NOTIFY fillColorChanged)
+ Q_PROPERTY(int pixelCacheSize READ pixelCacheSize WRITE setPixelCacheSize)
+ Q_PROPERTY(bool smoothCache READ smoothCache WRITE setSmoothCache)
+ Q_PROPERTY(qreal contentsScale READ contentsScale WRITE setContentsScale NOTIFY contentsScaleChanged)
+
+
+public:
+ QmlGraphicsPaintedItem(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsPaintedItem();
+
+ QSize contentsSize() const;
+ void setContentsSize(const QSize &);
+
+ qreal contentsScale() const;
+ void setContentsScale(qreal);
+
+ int pixelCacheSize() const;
+ void setPixelCacheSize(int pixels);
+
+ bool smoothCache() const;
+ void setSmoothCache(bool on);
+
+ QColor fillColor() const;
+ void setFillColor(const QColor&);
+
+ void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+
+protected:
+ QmlGraphicsPaintedItem(QmlGraphicsPaintedItemPrivate &dd, QmlGraphicsItem *parent);
+
+ virtual void drawContents(QPainter *p, const QRect &) = 0;
+
+ void setCacheFrozen(bool);
+
+Q_SIGNALS:
+ void fillColorChanged();
+ void contentsSizeChanged();
+ void contentsScaleChanged();
+
+protected Q_SLOTS:
+ void dirtyCache(const QRect &);
+ void clearCache();
+
+private:
+ void init();
+ Q_DISABLE_COPY(QmlGraphicsPaintedItem)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsPaintedItem)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsPaintedItem)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicspainteditem_p_p.h b/src/declarative/graphicsitems/qmlgraphicspainteditem_p_p.h
new file mode 100644
index 0000000..6bcc51a
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspainteditem_p_p.h
@@ -0,0 +1,90 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSIMAGEITEM_P_H
+#define QMLGRAPHICSIMAGEITEM_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 "qmlgraphicsitem_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsPaintedItemPrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsPaintedItem)
+
+public:
+ QmlGraphicsPaintedItemPrivate()
+ : max_imagecache_size(100000), contentsScale(1.0), fillColor(Qt::transparent), cachefrozen(false), smoothCache(true)
+ {
+ }
+
+ struct ImageCacheItem {
+ ImageCacheItem() : age(0) {}
+ ~ImageCacheItem() { }
+ int age;
+ QRect area;
+ QRect dirty; // one dirty area (allows optimization of common cases)
+ QPixmap image;
+ };
+
+ QList<ImageCacheItem*> imagecache;
+
+ int max_imagecache_size;
+ QSize contentsSize;
+ qreal contentsScale;
+ QColor fillColor;
+ bool cachefrozen;
+ bool smoothCache;
+};
+
+QT_END_NAMESPACE
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicsparticles.cpp b/src/declarative/graphicsitems/qmlgraphicsparticles.cpp
new file mode 100644
index 0000000..8c5fb4f
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsparticles.cpp
@@ -0,0 +1,1241 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsparticles_p.h"
+
+#include "qmlgraphicsitem_p.h"
+
+#include <qmlpixmapcache_p.h>
+#include <qfxperf_p_p.h>
+#include <qmlanimation_p_p.h>
+
+#include <QNetworkReply>
+#include <QPainter>
+#include <QtGui/qdrawutil.h>
+#include <QVarLengthArray>
+
+#include <stdlib.h>
+#include <math.h>
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#define M_PI_2 (M_PI / 2.)
+#endif
+#ifndef INT_MAX
+#define INT_MAX 2147483647
+#endif
+
+QT_BEGIN_NAMESPACE
+#define PI_SQR 9.8696044
+// parabolic approximation
+inline qreal fastSin(qreal theta)
+{
+ const qreal b = 4 / M_PI;
+ const qreal c = -4 / PI_SQR;
+
+ qreal y = b * theta + c * theta * qAbs(theta);
+ return y;
+}
+
+inline qreal fastCos(qreal theta)
+{
+ theta += M_PI_2;
+ if (theta > M_PI)
+ theta -= 2 * M_PI;
+
+ return fastSin(theta);
+}
+
+class QmlGraphicsParticle
+{
+public:
+ QmlGraphicsParticle(int time) : lifeSpan(1000), fadeOutAge(800)
+ , opacity(0), birthTime(time), x_velocity(0), y_velocity(0)
+ , state(FadeIn), data(0)
+ {
+ }
+
+ int lifeSpan;
+ int fadeOutAge;
+ qreal x;
+ qreal y;
+ qreal opacity;
+ int birthTime;
+ qreal x_velocity;
+ qreal y_velocity;
+ enum State { FadeIn, Solid, FadeOut };
+ State state;
+ void *data;
+};
+
+//---------------------------------------------------------------------------
+
+QML_DEFINE_TYPE(Qt,4,6,ParticleMotion,QmlGraphicsParticleMotion)
+
+/*!
+ \class QmlGraphicsParticleMotion
+ \ingroup group_effects
+ \brief The QmlGraphicsParticleMotion class is the base class for particle motion.
+ \internal
+
+ This class causes the particles to remain static.
+*/
+
+/*!
+ Constructs a QmlGraphicsParticleMotion with parent object \a parent.
+*/
+QmlGraphicsParticleMotion::QmlGraphicsParticleMotion(QObject *parent) :
+ QObject(parent)
+{
+}
+
+/*!
+ Move the \a particle to its new position. \a interval is the number of
+ milliseconds elapsed since it was last moved.
+*/
+void QmlGraphicsParticleMotion::advance(QmlGraphicsParticle &particle, int interval)
+{
+ Q_UNUSED(particle);
+ Q_UNUSED(interval);
+}
+
+/*!
+ The \a particle has just been created. Some motion strategies require
+ additional state information. This can be allocated by this function.
+*/
+void QmlGraphicsParticleMotion::created(QmlGraphicsParticle &particle)
+{
+ Q_UNUSED(particle);
+}
+
+/*!
+ The \a particle is about to be destroyed. Any additional memory
+ that has been allocated for the particle should be freed.
+*/
+void QmlGraphicsParticleMotion::destroy(QmlGraphicsParticle &particle)
+{
+ Q_UNUSED(particle);
+}
+
+/*!
+ \qmlclass ParticleMotionLinear
+ \brief The ParticleMotionLinear object moves particles linearly.
+
+ \sa Particles
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsParticleMotionLinear
+ \ingroup group_effects
+ \brief The QmlGraphicsParticleMotionLinear class moves the particles linearly.
+*/
+
+QML_DEFINE_TYPE(Qt,4,6,ParticleMotionLinear,QmlGraphicsParticleMotionLinear)
+
+void QmlGraphicsParticleMotionLinear::advance(QmlGraphicsParticle &p, int interval)
+{
+ p.x += interval * p.x_velocity;
+ p.y += interval * p.y_velocity;
+}
+
+/*!
+ \qmlclass ParticleMotionGravity
+ \brief The ParticleMotionGravity object moves particles towards a point.
+
+ \sa Particles
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsParticleMotionGravity
+ \ingroup group_effects
+ \brief The QmlGraphicsParticleMotionGravity class moves the particles towards a point.
+*/
+
+QML_DEFINE_TYPE(Qt,4,6,ParticleMotionGravity,QmlGraphicsParticleMotionGravity)
+
+/*!
+ \qmlproperty int ParticleMotionGravity::xattractor
+ \qmlproperty int ParticleMotionGravity::yattractor
+ These properties hold the x and y coordinates of the point attracting the particles.
+*/
+
+/*!
+ \qmlproperty int ParticleMotionGravity::acceleration
+ This property holds the acceleration to apply to the particles.
+*/
+
+/*!
+ \property QmlGraphicsParticleMotionGravity::xattractor
+ \brief the x coordinate of the point attracting the particles.
+*/
+
+/*!
+ \property QmlGraphicsParticleMotionGravity::yattractor
+ \brief the y coordinate of the point attracting the particles.
+*/
+
+/*!
+ \property QmlGraphicsParticleMotionGravity::acceleration
+ \brief the acceleration to apply to the particles.
+*/
+
+void QmlGraphicsParticleMotionGravity::advance(QmlGraphicsParticle &p, int interval)
+{
+ qreal xdiff = p.x - _xAttr;
+ qreal ydiff = p.y - _yAttr;
+
+ qreal xcomp = xdiff / (xdiff + ydiff);
+ qreal ycomp = ydiff / (xdiff + ydiff);
+
+ p.x_velocity += xcomp * _accel * interval;
+ p.y_velocity += ycomp * _accel * interval;
+
+ p.x += interval * p.x_velocity;
+ p.y += interval * p.y_velocity;
+}
+
+/*!
+ \qmlclass ParticleMotionWander
+ \brief The ParticleMotionWander object moves particles in a somewhat random fashion.
+
+ The particles will continue roughly in the original direction, however will randomly
+ drift to each side.
+
+ The code below produces an effect similar to falling snow.
+
+ \qml
+Rectangle {
+ width: 240
+ height: 320
+ color: "black"
+
+ Particles {
+ y: 0
+ width: parent.width
+ height: 30
+ source: "star.png"
+ lifeSpan: 5000
+ count: 50
+ angle: 70
+ angleDeviation: 36
+ velocity: 30
+ velocityDeviation: 10
+ ParticleMotionWander {
+ xvariance: 30
+ pace: 100
+ }
+ }
+}
+ \endqml
+
+ \sa Particles
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsParticleMotionWander
+ \ingroup group_effects
+ \brief The QmlGraphicsParticleMotionWander class moves particles in a somewhat random fashion.
+
+ The particles will continue roughly in the original direction, however will randomly
+ drift to each side.
+*/
+
+/*!
+ \qmlproperty int QmlGraphicsParticleMotionWander::xvariance
+ \qmlproperty int QmlGraphicsParticleMotionWander::yvariance
+
+ These properties set the amount to wander in the x and y directions.
+*/
+
+/*!
+ \qmlproperty int QmlGraphicsParticleMotionWander::pace
+ This property holds how quickly the paricles will move from side to side.
+*/
+
+QML_DEFINE_TYPE(Qt,4,6,ParticleMotionWander,QmlGraphicsParticleMotionWander)
+
+void QmlGraphicsParticleMotionWander::advance(QmlGraphicsParticle &p, int interval)
+{
+ if (!particles)
+ particles = qobject_cast<QmlGraphicsParticles*>(parent());
+ if (particles) {
+ Data *d = (Data*)p.data;
+ if (_xvariance != 0.) {
+ qreal xdiff = p.x_velocity - d->x_targetV;
+ if ((xdiff > d->x_peak && d->x_var > 0.0) || (xdiff < -d->x_peak && d->x_var < 0.0)) {
+ d->x_var = -d->x_var;
+ d->x_peak = _xvariance + _xvariance * qreal(qrand()) / RAND_MAX;
+ }
+ p.x_velocity += d->x_var * interval;
+ }
+ p.x += interval * p.x_velocity;
+
+ if (_yvariance != 0.) {
+ qreal ydiff = p.y_velocity - d->y_targetV;
+ if ((ydiff > d->y_peak && d->y_var > 0.0) || (ydiff < -d->y_peak && d->y_var < 0.0)) {
+ d->y_var = -d->y_var;
+ d->y_peak = _yvariance + _yvariance * qreal(qrand()) / RAND_MAX;
+ }
+ p.y_velocity += d->y_var * interval;
+ }
+ p.y += interval * p.y_velocity;
+ }
+}
+
+void QmlGraphicsParticleMotionWander::created(QmlGraphicsParticle &p)
+{
+ if (!p.data) {
+ Data *d = new Data;
+ p.data = (void*)d;
+ d->x_targetV = p.x_velocity;
+ d->y_targetV = p.y_velocity;
+ d->x_peak = _xvariance;
+ d->y_peak = _yvariance;
+ d->x_var = _pace * qreal(qrand()) / RAND_MAX / 1000.0;
+ d->y_var = _pace * qreal(qrand()) / RAND_MAX / 1000.0;
+ }
+}
+
+void QmlGraphicsParticleMotionWander::destroy(QmlGraphicsParticle &p)
+{
+ if (p.data)
+ delete (Data*)p.data;
+}
+
+//---------------------------------------------------------------------------
+class QmlGraphicsParticlesPainter : public QmlGraphicsItem
+{
+public:
+ QmlGraphicsParticlesPainter(QmlGraphicsParticlesPrivate *p, QmlGraphicsItem* parent)
+ : QmlGraphicsItem(parent), d(p)
+ {
+ setFlag(QGraphicsItem::ItemHasNoContents, false);
+ maxX = minX = maxY = minY = 0;
+ }
+
+ void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+
+ void updateSize();
+
+ qreal maxX;
+ qreal minX;
+ qreal maxY;
+ qreal minY;
+ QmlGraphicsParticlesPrivate* d;
+};
+
+//---------------------------------------------------------------------------
+class QmlGraphicsParticlesPrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsParticles)
+public:
+ QmlGraphicsParticlesPrivate()
+ : count(1), emissionRate(-1), emissionVariance(0.5), lifeSpan(1000)
+ , lifeSpanDev(1000), fadeInDur(200), fadeOutDur(300)
+ , angle(0), angleDev(0), velocity(0), velocityDev(0), emissionCarry(0.)
+ , addParticleTime(0), addParticleCount(0), lastAdvTime(0)
+ , motion(0), pendingPixmapCache(false), clock(this)
+ {
+ }
+
+ ~QmlGraphicsParticlesPrivate()
+ {
+ }
+
+ void init()
+ {
+ Q_Q(QmlGraphicsParticles);
+ paintItem = new QmlGraphicsParticlesPainter(this, q);
+ }
+
+ void tick(int time);
+ void createParticle(int time);
+ void updateOpacity(QmlGraphicsParticle &p, int age);
+
+ QUrl url;
+ QPixmap image;
+ int count;
+ int emissionRate;
+ qreal emissionVariance;
+ int lifeSpan;
+ int lifeSpanDev;
+ int fadeInDur;
+ int fadeOutDur;
+ qreal angle;
+ qreal angleDev;
+ qreal velocity;
+ qreal velocityDev;
+ qreal emissionCarry;
+ int addParticleTime;
+ int addParticleCount;
+ int lastAdvTime;
+ QmlGraphicsParticleMotion *motion;
+ QmlGraphicsParticlesPainter *paintItem;
+
+ bool pendingPixmapCache;
+
+ QList<QPair<int, int> > bursts;//countLeft, emissionRate pairs
+ QList<QmlGraphicsParticle> particles;
+ QTickAnimationProxy<QmlGraphicsParticlesPrivate, &QmlGraphicsParticlesPrivate::tick> clock;
+
+};
+
+void QmlGraphicsParticlesPrivate::tick(int time)
+{
+ Q_Q(QmlGraphicsParticles);
+ if (!motion)
+ motion = new QmlGraphicsParticleMotionLinear(q);
+
+ int oldCount = particles.count();
+ int removed = 0;
+ int interval = time - lastAdvTime;
+ for (int i = 0; i < particles.count(); ) {
+ QmlGraphicsParticle &particle = particles[i];
+ int age = time - particle.birthTime;
+ if (age >= particle.lifeSpan) {
+ QmlGraphicsParticle part = particles.takeAt(i);
+ motion->destroy(part);
+ ++removed;
+ } else {
+ updateOpacity(particle, age);
+ motion->advance(particle, interval);
+ ++i;
+ }
+ }
+
+ if(emissionRate == -1)//Otherwise leave emission to the emission rate
+ while(removed-- && ((count == -1) || particles.count() < count))
+ createParticle(time);
+
+ if (!addParticleTime)
+ addParticleTime = time;
+
+ //Possibly emit new particles
+ if (((count == -1) || particles.count() < count) && emissionRate
+ && !(count==-1 && emissionRate==-1)) {
+ int emissionCount = -1;
+ if (emissionRate != -1){
+ qreal variance = 1.;
+ if (emissionVariance > 0.){
+ variance += (qreal(qrand())/RAND_MAX) * emissionVariance * (qrand()%2?-1.:1.);
+ }
+ qreal emission = emissionRate * (qreal(interval)/1000.);
+ emission = emission * variance + emissionCarry;
+ double tmpDbl;
+ emissionCarry = modf(emission, &tmpDbl);
+ emissionCount = (int)tmpDbl;
+ emissionCount = qMax(0,emissionCount);
+ }
+ while(((count == -1) || particles.count() < count) &&
+ (emissionRate==-1 || emissionCount--))
+ createParticle(time);
+ }
+
+ //Deal with emissions from requested bursts
+ for(int i=0; i<bursts.size(); i++){
+ int emission = 0;
+ if(bursts[i].second == -1){
+ emission = bursts[i].first;
+ }else{
+ qreal variance = 1.;
+ if (emissionVariance > 0.){
+ variance += (qreal(qrand())/RAND_MAX) * emissionVariance * (qrand()%2?-1.:1.);
+ }
+ qreal workingEmission = bursts[i].second * (qreal(interval)/1000.);
+ workingEmission *= variance;
+ emission = (int)workingEmission;
+ emission = qMax(emission, 0);
+ }
+ emission = qMin(emission, bursts[i].first);
+ bursts[i].first -= emission;
+ while(emission--)
+ createParticle(time);
+ }
+ for(int i=bursts.size()-1; i>=0; i--)
+ if(bursts[i].first <= 0)
+ bursts.removeAt(i);
+
+ lastAdvTime = time;
+ paintItem->updateSize();
+ paintItem->update();
+ if (!(oldCount || particles.count()) && (!count || !emissionRate) && bursts.isEmpty()) {
+ lastAdvTime = 0;
+ clock.stop();
+ }
+}
+
+void QmlGraphicsParticlesPrivate::createParticle(int time)
+{
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::CreateParticle> x;
+#endif
+ Q_Q(QmlGraphicsParticles);
+ QmlGraphicsParticle p(time);
+ p.x = q->x() + q->width() * qreal(qrand()) / RAND_MAX - image.width()/2.0;
+ p.y = q->y() + q->height() * qreal(qrand()) / RAND_MAX - image.height()/2.0;
+ p.lifeSpan = lifeSpan;
+ if (lifeSpanDev)
+ p.lifeSpan += int(lifeSpanDev/2 - lifeSpanDev * qreal(qrand()) / RAND_MAX);
+ p.fadeOutAge = p.lifeSpan - fadeOutDur;
+ if (fadeInDur == 0.) {
+ p.state= QmlGraphicsParticle::Solid;
+ p.opacity = 1.0;
+ }
+ qreal a = angle;
+ if (angleDev)
+ a += angleDev/2 - angleDev * qreal(qrand()) / RAND_MAX;
+ if (a > M_PI)
+ a = a - 2 * M_PI;
+ qreal v = velocity;
+ if (velocityDev)
+ v += velocityDev/2 - velocityDev * qreal(qrand()) / RAND_MAX;
+ p.x_velocity = v * fastCos(a);
+ p.y_velocity = v * fastSin(a);
+ particles.append(p);
+ motion->created(particles.last());
+}
+
+void QmlGraphicsParticlesPrivate::updateOpacity(QmlGraphicsParticle &p, int age)
+{
+ switch (p.state) {
+ case QmlGraphicsParticle::FadeIn:
+ if (age <= fadeInDur) {
+ p.opacity = qreal(age) / fadeInDur;
+ break;
+ } else {
+ p.opacity = 1.0;
+ p.state = QmlGraphicsParticle::Solid;
+ // Fall through
+ }
+ case QmlGraphicsParticle::Solid:
+ if (age <= p.fadeOutAge) {
+ break;
+ } else {
+ p.state = QmlGraphicsParticle::FadeOut;
+ // Fall through
+ }
+ case QmlGraphicsParticle::FadeOut:
+ p.opacity = qreal(p.lifeSpan - age) / fadeOutDur;
+ break;
+ }
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Particles,QmlGraphicsParticles)
+
+/*!
+ \qmlclass Particles
+ \brief The Particles object generates and moves particles.
+ \inherits Item
+
+ This element provides preliminary support for particles in QML, and may be heavily changed or removed in later versions.
+
+ The particles created by this object cannot be dealt with directly, they can only be controlled through the parameters of the Particles object. The particles are all the same pixmap, specified by the user.
+
+ The particles are painted relative to the parent of the Particles object. Moving the
+ Particles object will not move the particles already emitted.
+
+ The below example creates two differently behaving particle sources.
+ The top one has particles falling from the top like snow,
+ the lower one has particles expelled up like a fountain.
+
+ \qml
+Rectangle {
+ width: 240
+ height: 320
+ color: "black"
+ Particles {
+ y: 0
+ width: parent.width
+ height: 30
+ source: "star.png"
+ lifeSpan: 5000
+ count: 50
+ angle: 70
+ angleDeviation: 36
+ velocity: 30
+ velocityDeviation: 10
+ ParticleMotionWander {
+ xvariance: 30
+ pace: 100
+ }
+ }
+ Particles {
+ y: 300
+ x: 120
+ width: 1
+ height: 1
+ source: "star.png"
+ lifeSpan: 5000
+ count: 200
+ angle: 270
+ angleDeviation: 45
+ velocity: 50
+ velocityDeviation: 30
+ ParticleMotionGravity {
+ yattractor: 1000
+ xattractor: 0
+ acceleration: 25
+ }
+ }
+}
+ \endqml
+ \image particles.gif
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsParticles
+ \ingroup group_effects
+ \brief The QmlGraphicsParticles class generates and moves particles.
+*/
+
+QmlGraphicsParticles::QmlGraphicsParticles(QmlGraphicsItem *parent)
+ : QmlGraphicsItem(*(new QmlGraphicsParticlesPrivate), parent)
+{
+ Q_D(QmlGraphicsParticles);
+ d->init();
+}
+
+QmlGraphicsParticles::~QmlGraphicsParticles()
+{
+ Q_D(QmlGraphicsParticles);
+ if (d->pendingPixmapCache)
+ QmlPixmapCache::cancel(d->url, this);
+}
+
+/*!
+ \qmlproperty string Particles::src
+ This property holds the URL of the particle image.
+*/
+
+/*!
+ \property QmlGraphicsParticles::source
+ \brief the URL of the particle image.
+*/
+QUrl QmlGraphicsParticles::source() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->url;
+}
+
+void QmlGraphicsParticles::imageLoaded()
+{
+ Q_D(QmlGraphicsParticles);
+ d->pendingPixmapCache = false;
+ QmlPixmapCache::get(d->url, &d->image);
+ d->paintItem->updateSize();
+ d->paintItem->update();
+}
+
+void QmlGraphicsParticles::setSource(const QUrl &name)
+{
+ Q_D(QmlGraphicsParticles);
+
+ if ((d->url.isEmpty() == name.isEmpty()) && name == d->url)
+ return;
+
+ if (d->pendingPixmapCache) {
+ QmlPixmapCache::cancel(d->url, this);
+ d->pendingPixmapCache = false;
+ }
+ if (name.isEmpty()) {
+ d->url = name;
+ d->image = QPixmap();
+ d->paintItem->updateSize();
+ d->paintItem->update();
+ } else {
+ d->url = name;
+ Q_ASSERT(!name.isRelative());
+ QmlPixmapReply::Status status = QmlPixmapCache::get(d->url, &d->image);
+ if (status != QmlPixmapReply::Ready && status != QmlPixmapReply::Error) {
+ QmlPixmapReply *reply = QmlPixmapCache::request(qmlEngine(this), d->url);
+ connect(reply, SIGNAL(finished()), this, SLOT(imageLoaded()));
+ d->pendingPixmapCache = true;
+ } else {
+ //### unify with imageLoaded
+ d->paintItem->updateSize();
+ d->paintItem->update();
+ }
+ }
+ emit sourceChanged();
+}
+
+/*!
+ \qmlproperty int Particles::count
+ This property holds the maximum number of particles
+
+ The particles element emits particles until it has count active
+ particles. When this number is reached, new particles are not emitted until
+ some of the current particles reach theend of their lifespan.
+
+ If count is -1 then there is no maximum number of active particles, and
+ particles will be constantly emitted at the rate specified by emissionRate.
+
+ If both count and emissionRate are set to -1, nothing will be emitted.
+
+*/
+
+/*!
+ \property QmlGraphicsParticles::count
+ \brief the maximum number of particles
+*/
+int QmlGraphicsParticles::count() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->count;
+}
+
+void QmlGraphicsParticles::setCount(int cnt)
+{
+ Q_D(QmlGraphicsParticles);
+ if (cnt == d->count)
+ return;
+
+ int oldCount = d->count;
+ d->count = cnt;
+ d->addParticleTime = 0;
+ d->addParticleCount = d->particles.count();
+ if (!oldCount && d->clock.state() != QAbstractAnimation::Running && d->count && d->emissionRate) {
+ d->clock.start();
+ }
+ d->paintItem->updateSize();
+ d->paintItem->update();
+ emit countChanged();
+}
+
+
+/*!
+ \qmlproperty int Particles::emissionRate
+ This property holds the target number of particles to emit every second.
+
+ The particles element will emit up to emissionRate particles every
+ second. Fewer particles may be emitted per second if the maximum number of
+ particles has been reached.
+
+ If emissionRate is set to -1 there is no limit to the number of
+ particles emitted per second, and particles will be instantly emitted to
+ reach the maximum number of particles specified by count.
+
+ The default value for emissionRate is -1.
+
+ If both count and emissionRate are set to -1, nothing will be emitted.
+*/
+
+/*!
+ \property QmlGraphicsParticles::emissionRate
+ \brief the emission rate of particles
+*/
+int QmlGraphicsParticles::emissionRate() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->emissionRate;
+}
+void QmlGraphicsParticles::setEmissionRate(int er)
+{
+ Q_D(QmlGraphicsParticles);
+ if(er == d->emissionRate)
+ return;
+ d->emissionRate = er;
+ if (d->clock.state() != QAbstractAnimation::Running && d->count && d->emissionRate) {
+ d->clock.start();
+ }
+ emit emissionRateChanged();
+}
+
+/*!
+ \qmlproperty qreal Particles::emissionVariance
+ This property holds how inconsistent the rate of particle emissions are.
+ It is a number between 0 (no variance) and 1 (some variance).
+
+ The expected number of particles emitted per second is emissionRate. If
+ emissionVariance is 0 then particles will be emitted consistently throughout
+ each second to reach that number. If emissionVariance is greater than 0 the
+ rate of particle emission will vary randomly throughout the second, with the
+ consequence that the actual number of particles emitted in one second will
+ vary randomly as well.
+
+ emissionVariance is the maximum deviation from emitting
+ emissionRate particles per second. An emissionVariance of 0 means you should
+ get exactly emissionRate particles emitted per second,
+ and an emissionVariance of 1 means you will get between zero and two times
+ emissionRate particles per second, but you should get emissionRate particles
+ per second on average.
+
+ Note that even with an emissionVariance of 0 there may be some variance due
+ to performance and hardware constraints.
+
+ The default value of emissionVariance is 0.5
+*/
+
+/*!
+ \property QmlGraphicsParticles::emissionVariance
+ \brief how much the particle emission amounts vary per tick
+*/
+
+qreal QmlGraphicsParticles::emissionVariance() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->emissionVariance;
+}
+
+void QmlGraphicsParticles::setEmissionVariance(qreal ev)
+{
+ Q_D(QmlGraphicsParticles);
+ if(d->emissionVariance == ev)
+ return;
+ d->emissionVariance = ev;
+ emit emissionVarianceChanged();
+}
+
+/*!
+ \qmlproperty int Particles::lifeSpan
+ \qmlproperty int Particles::lifeSpanDeviation
+
+ These properties describe the life span of each particle.
+
+ The default lifespan for a particle is 1000ms.
+
+ lifeSpanDeviation randomly varies the lifeSpan up to the specified variation. For
+ example, the following creates particles whose lifeSpan will vary
+ from 150ms to 250ms:
+
+ \qml
+Particles {
+ source: "star.png"
+ lifeSpan: 200
+ lifeSpanDeviation: 100
+}
+ \endqml
+*/
+
+/*!
+ \property QmlGraphicsParticles::lifeSpan
+ \brief the life span of each particle.
+
+ Default value is 1000ms.
+
+ \sa QmlGraphicsParticles::lifeSpanDeviation
+*/
+int QmlGraphicsParticles::lifeSpan() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->lifeSpan;
+}
+
+void QmlGraphicsParticles::setLifeSpan(int ls)
+{
+ Q_D(QmlGraphicsParticles);
+ if(d->lifeSpan == ls)
+ return;
+ d->lifeSpan = ls;
+ emit lifeSpanChanged();
+}
+
+/*!
+ \property QmlGraphicsParticles::lifeSpanDeviation
+ \brief the maximum possible deviation from the set lifeSpan.
+
+ Randomly varies the lifeSpan up to the specified variation. For
+ example, the following creates particles whose lifeSpan will vary
+ from 150ms to 250ms:
+
+\qml
+Particles {
+ source: "star.png"
+ lifeSpan: 200
+ lifeSpanDeviation: 100
+}
+\endqml
+
+ \sa QmlGraphicsParticles::lifeSpan
+*/
+int QmlGraphicsParticles::lifeSpanDeviation() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->lifeSpanDev;
+}
+
+void QmlGraphicsParticles::setLifeSpanDeviation(int dev)
+{
+ Q_D(QmlGraphicsParticles);
+ if(d->lifeSpanDev == dev)
+ return;
+ d->lifeSpanDev = dev;
+ emit lifeSpanDeviationChanged();
+}
+
+/*!
+ \qmlproperty int Particles::fadeInDuration
+ \qmlproperty int Particles::fadeOutDuration
+ These properties hold the time taken to fade the particles in and out.
+
+ By default fade in is 200ms and fade out is 300ms.
+*/
+
+/*!
+ \property QmlGraphicsParticles::fadeInDuration
+ \brief the time taken to fade in the particles.
+
+ Default value is 200ms.
+*/
+int QmlGraphicsParticles::fadeInDuration() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->fadeInDur;
+}
+
+void QmlGraphicsParticles::setFadeInDuration(int dur)
+{
+ Q_D(QmlGraphicsParticles);
+ if (dur < 0.0 || dur == d->fadeInDur)
+ return;
+ d->fadeInDur = dur;
+ emit fadeInDurationChanged();
+}
+
+/*!
+ \property QmlGraphicsParticles::fadeOutDuration
+ \brief the time taken to fade out the particles.
+
+ Default value is 300ms.
+*/
+int QmlGraphicsParticles::fadeOutDuration() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->fadeOutDur;
+}
+
+void QmlGraphicsParticles::setFadeOutDuration(int dur)
+{
+ Q_D(QmlGraphicsParticles);
+ if (dur < 0.0 || d->fadeOutDur == dur)
+ return;
+ d->fadeOutDur = dur;
+ emit fadeOutDurationChanged();
+}
+
+/*!
+ \qmlproperty real Particles::angle
+ \qmlproperty real Particles::angleDeviation
+
+ These properties control particle direction.
+
+ angleDeviation randomly varies the direction up to the specified variation. For
+ example, the following creates particles whose initial direction will
+ vary from 15 degrees to 105 degrees:
+
+ \qml
+Particles {
+ source: "star.png"
+ angle: 60
+ angleDeviation: 90
+}
+ \endqml
+*/
+
+/*!
+ \property QmlGraphicsParticles::angle
+ \brief the initial angle of direction.
+
+ \sa QmlGraphicsParticles::angleDeviation
+*/
+qreal QmlGraphicsParticles::angle() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->angle * 180.0 / M_PI;
+}
+
+void QmlGraphicsParticles::setAngle(qreal angle)
+{
+ Q_D(QmlGraphicsParticles);
+ qreal radAngle = angle * M_PI / 180.0;
+ if(radAngle == d->angle)
+ return;
+ d->angle = radAngle;
+ emit angleChanged();
+}
+
+/*!
+ \property QmlGraphicsParticles::angleDeviation
+ \brief the maximum possible deviation from the set angle.
+
+ Randomly varies the direction up to the specified variation. For
+ example, the following creates particles whose initial direction will
+ vary from 15 degrees to 105 degrees:
+
+\qml
+Particles {
+ source: "star.png"
+ angle: 60
+ angleDeviation: 90
+}
+\endqml
+
+ \sa QmlGraphicsParticles::angle
+*/
+qreal QmlGraphicsParticles::angleDeviation() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->angleDev * 180.0 / M_PI;
+}
+
+void QmlGraphicsParticles::setAngleDeviation(qreal dev)
+{
+ Q_D(QmlGraphicsParticles);
+ qreal radDev = dev * M_PI / 180.0;
+ if(radDev == d->angleDev)
+ return;
+ d->angleDev = radDev;
+ emit angleDeviationChanged();
+}
+
+/*!
+ \qmlproperty real Particles::velocity
+ \qmlproperty real Particles::velocityDeviation
+
+ These properties control the velocity of the particles.
+
+ velocityDeviation randomly varies the velocity up to the specified variation. For
+ example, the following creates particles whose initial velocity will
+ vary from 40 to 60.
+
+ \qml
+Particles {
+ source: "star.png"
+ velocity: 50
+ velocityDeviation: 20
+}
+ \endqml
+*/
+
+/*!
+ \property QmlGraphicsParticles::velocity
+ \brief the initial velocity of the particles.
+
+ \sa QmlGraphicsParticles::velocityDeviation
+*/
+qreal QmlGraphicsParticles::velocity() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->velocity * 1000.0;
+}
+
+void QmlGraphicsParticles::setVelocity(qreal velocity)
+{
+ Q_D(QmlGraphicsParticles);
+ qreal realVel = velocity / 1000.0;
+ if(realVel == d->velocity)
+ return;
+ d->velocity = realVel;
+ emit velocityChanged();
+}
+
+/*!
+ \property QmlGraphicsParticles::velocityDeviation
+ \brief the maximum possible deviation from the set velocity.
+
+ Randomly varies the velocity up to the specified variation. For
+ example, the following creates particles whose initial velocity will
+ vary from 40 to 60.
+
+\qml
+Particles {
+ source: "star.png"
+ velocity: 50
+ velocityDeviation: 20
+}
+\endqml
+
+ \sa QmlGraphicsParticles::velocity
+*/
+qreal QmlGraphicsParticles::velocityDeviation() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->velocityDev * 1000.0;
+}
+
+void QmlGraphicsParticles::setVelocityDeviation(qreal velocity)
+{
+ Q_D(QmlGraphicsParticles);
+ qreal realDev = velocity / 1000.0;
+ if(realDev == d->velocityDev)
+ return;
+ d->velocityDev = realDev;
+ emit velocityDeviationChanged();
+}
+
+/*!
+ \qmlproperty ParticleMotion Particles::motion
+ This property sets the type of motion to apply to the particles.
+
+ When a particle is created it will have an initial direction and velocity.
+ The motion of the particle during its lifeSpan is then influenced by the
+ motion property.
+
+ Default motion is ParticleMotionLinear.
+*/
+
+/*!
+ \property QmlGraphicsParticles::motion
+ \brief sets the type of motion to apply to the particles.
+
+ When a particle is created it will have an initial direction and velocity.
+ The motion of the particle during its lifeSpan is then influenced by the
+ motion property.
+
+ Default motion is QmlGraphicsParticleMotionLinear.
+*/
+QmlGraphicsParticleMotion *QmlGraphicsParticles::motion() const
+{
+ Q_D(const QmlGraphicsParticles);
+ return d->motion;
+}
+
+void QmlGraphicsParticles::setMotion(QmlGraphicsParticleMotion *motion)
+{
+ Q_D(QmlGraphicsParticles);
+ d->motion = motion;
+}
+
+/*!
+ \qmlmethod Particles::burst(int count, int emissionRate)
+
+ Initiates a burst of particles.
+
+ This method takes two arguments. The first argument is the number
+ of particles to emit and the second argument is the emissionRate for the
+ burst. If the second argument is omitted, it is treated as -1. The burst
+ of particles has a separate emissionRate and count to the normal emission of
+ particles. The burst uses the same values as normal emission for all other
+ properties, including emissionVariance.
+
+ The normal emission of particles will continue during the burst, however
+ the particles created by the burst count towards the maximum number used by
+ normal emission. To avoid this behavior, use two Particles elements.
+
+*/
+void QmlGraphicsParticles::burst(int count, int emissionRate)
+{
+ Q_D(QmlGraphicsParticles);
+ d->bursts << qMakePair(count, emissionRate);
+ if (d->clock.state() != QAbstractAnimation::Running)
+ d->clock.start();
+}
+
+void QmlGraphicsParticlesPainter::updateSize()
+{
+ if (!isComponentComplete())
+ return;
+
+ const int parentX = parentItem()->x();
+ const int parentY = parentItem()->y();
+ for (int i = 0; i < d->particles.count(); ++i) {
+ const QmlGraphicsParticle &particle = d->particles.at(i);
+ if(particle.x > maxX)
+ maxX = particle.x;
+ if(particle.x < minX)
+ minX = particle.x;
+ if(particle.y > maxY)
+ maxY = particle.y;
+ if(particle.y < minY)
+ minY = particle.y;
+ }
+
+ int myWidth = (int)(maxX-minX+0.5)+d->image.width();
+ int myX = (int)(minX - parentX);
+ int myHeight = (int)(maxY-minY+0.5)+d->image.height();
+ int myY = (int)(minY - parentY);
+ setWidth(myWidth);
+ setHeight(myHeight);
+ setX(myX);
+ setY(myY);
+}
+
+void QmlGraphicsParticles::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
+{
+ Q_UNUSED(p);
+ //painting is done by the ParticlesPainter, so it can have the right size
+}
+
+void QmlGraphicsParticlesPainter::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
+{
+ if (d->image.isNull() || d->particles.isEmpty())
+ return;
+
+ const int myX = x() + parentItem()->x();
+ const int myY = y() + parentItem()->y();
+
+ QVarLengthArray<QDrawPixmaps::Data, 256> pixmapData;
+ pixmapData.resize(d->particles.count());
+
+ const QRectF sourceRect = d->image.rect();
+ qreal halfPWidth = sourceRect.width()/2.;
+ qreal halfPHeight = sourceRect.height()/2.;
+ for (int i = 0; i < d->particles.count(); ++i) {
+ const QmlGraphicsParticle &particle = d->particles.at(i);
+ pixmapData[i].point = QPointF(particle.x - myX + halfPWidth, particle.y - myY + halfPHeight);
+ pixmapData[i].opacity = particle.opacity;
+
+ //these never change
+ pixmapData[i].rotation = 0;
+ pixmapData[i].scaleX = 1;
+ pixmapData[i].scaleY = 1;
+ pixmapData[i].source = sourceRect;
+ }
+ qDrawPixmaps(p, pixmapData.data(), d->particles.count(), d->image);
+}
+
+void QmlGraphicsParticles::componentComplete()
+{
+ Q_D(QmlGraphicsParticles);
+ QmlGraphicsItem::componentComplete();
+ if (d->count) {
+ d->paintItem->updateSize();
+ d->clock.start();
+ }
+ if (d->lifeSpanDev > d->lifeSpan)
+ d->lifeSpanDev = d->lifeSpan;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsparticles_p.h b/src/declarative/graphicsitems/qmlgraphicsparticles_p.h
new file mode 100644
index 0000000..c34d55b
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsparticles_p.h
@@ -0,0 +1,247 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSPARTICLES_H
+#define QMLGRAPHICSPARTICLES_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsParticle;
+class QmlGraphicsParticles;
+class Q_DECLARATIVE_EXPORT QmlGraphicsParticleMotion : public QObject
+{
+ Q_OBJECT
+public:
+ QmlGraphicsParticleMotion(QObject *parent=0);
+
+ virtual void advance(QmlGraphicsParticle &, int interval);
+ virtual void created(QmlGraphicsParticle &);
+ virtual void destroy(QmlGraphicsParticle &);
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsParticleMotionLinear : public QmlGraphicsParticleMotion
+{
+ Q_OBJECT
+public:
+ QmlGraphicsParticleMotionLinear(QObject *parent=0)
+ : QmlGraphicsParticleMotion(parent) {}
+
+ virtual void advance(QmlGraphicsParticle &, int interval);
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsParticleMotionGravity : public QmlGraphicsParticleMotion
+{
+ Q_OBJECT
+
+ Q_PROPERTY(int xattractor READ xAttractor WRITE setXAttractor)
+ Q_PROPERTY(int yattractor READ yAttractor WRITE setYAttractor)
+ Q_PROPERTY(int acceleration READ acceleration WRITE setAcceleration)
+public:
+ QmlGraphicsParticleMotionGravity(QObject *parent=0)
+ : QmlGraphicsParticleMotion(parent), _xAttr(0), _yAttr(0), _accel(0.00005) {}
+
+ int xAttractor() const { return _xAttr; }
+ void setXAttractor(int x) { _xAttr = x; }
+
+ int yAttractor() const { return _yAttr; }
+ void setYAttractor(int y) { _yAttr = y; }
+
+ int acceleration() const { return int(_accel * 1000000); }
+ void setAcceleration(int accel) { _accel = qreal(accel)/1000000.0; }
+
+ virtual void advance(QmlGraphicsParticle &, int interval);
+
+private:
+ int _xAttr;
+ int _yAttr;
+ qreal _accel;
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsParticleMotionWander : public QmlGraphicsParticleMotion
+{
+ Q_OBJECT
+public:
+ QmlGraphicsParticleMotionWander()
+ : QmlGraphicsParticleMotion(), particles(0), _xvariance(0), _yvariance(0) {}
+
+ virtual void advance(QmlGraphicsParticle &, int interval);
+ virtual void created(QmlGraphicsParticle &);
+ virtual void destroy(QmlGraphicsParticle &);
+
+ struct Data {
+ qreal x_targetV;
+ qreal y_targetV;
+ qreal x_peak;
+ qreal y_peak;
+ qreal x_var;
+ qreal y_var;
+ };
+
+ Q_PROPERTY(int xvariance READ xVariance WRITE setXVariance)
+ int xVariance() const { return int(_xvariance * 1000); }
+ void setXVariance(int var) { _xvariance = var / 1000.0; }
+
+ Q_PROPERTY(int yvariance READ yVariance WRITE setYVariance)
+ int yVariance() const { return int(_yvariance * 1000); }
+ void setYVariance(int var) { _yvariance = var / 1000.0; }
+
+ Q_PROPERTY(int pace READ pace WRITE setPace)
+ int pace() const { return int(_pace * 1000); }
+ void setPace(int pace) { _pace = pace / 1000.0; }
+
+private:
+ QmlGraphicsParticles *particles;
+ qreal _xvariance;
+ qreal _yvariance;
+ qreal _pace;
+};
+
+class QmlGraphicsParticlesPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsParticles : public QmlGraphicsItem
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
+ Q_PROPERTY(int count READ count WRITE setCount NOTIFY countChanged)
+ Q_PROPERTY(int emissionRate READ emissionRate WRITE setEmissionRate NOTIFY emissionRateChanged)
+ Q_PROPERTY(qreal emissionVariance READ emissionVariance WRITE setEmissionVariance NOTIFY emissionVarianceChanged)
+ Q_PROPERTY(int lifeSpan READ lifeSpan WRITE setLifeSpan NOTIFY lifeSpanChanged)
+ Q_PROPERTY(int lifeSpanDeviation READ lifeSpanDeviation WRITE setLifeSpanDeviation NOTIFY lifeSpanDeviationChanged)
+ Q_PROPERTY(int fadeInDuration READ fadeInDuration WRITE setFadeInDuration NOTIFY fadeInDurationChanged)
+ Q_PROPERTY(int fadeOutDuration READ fadeOutDuration WRITE setFadeOutDuration NOTIFY fadeOutDurationChanged)
+ Q_PROPERTY(qreal angle READ angle WRITE setAngle NOTIFY angleChanged)
+ Q_PROPERTY(qreal angleDeviation READ angleDeviation WRITE setAngleDeviation NOTIFY angleDeviationChanged)
+ Q_PROPERTY(qreal velocity READ velocity WRITE setVelocity NOTIFY velocityChanged)
+ Q_PROPERTY(qreal velocityDeviation READ velocityDeviation WRITE setVelocityDeviation NOTIFY velocityDeviationChanged)
+ Q_PROPERTY(QmlGraphicsParticleMotion *motion READ motion WRITE setMotion)
+ Q_CLASSINFO("DefaultProperty", "motion")
+
+public:
+ QmlGraphicsParticles(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsParticles();
+
+ QUrl source() const;
+ void setSource(const QUrl &);
+
+ int count() const;
+ void setCount(int cnt);
+
+ int emissionRate() const;
+ void setEmissionRate(int);
+
+ qreal emissionVariance() const;
+ void setEmissionVariance(qreal);
+
+ int lifeSpan() const;
+ void setLifeSpan(int);
+
+ int lifeSpanDeviation() const;
+ void setLifeSpanDeviation(int);
+
+ int fadeInDuration() const;
+ void setFadeInDuration(int);
+
+ int fadeOutDuration() const;
+ void setFadeOutDuration(int);
+
+ qreal angle() const;
+ void setAngle(qreal);
+
+ qreal angleDeviation() const;
+ void setAngleDeviation(qreal);
+
+ qreal velocity() const;
+ void setVelocity(qreal);
+
+ qreal velocityDeviation() const;
+ void setVelocityDeviation(qreal);
+
+ QmlGraphicsParticleMotion *motion() const;
+ void setMotion(QmlGraphicsParticleMotion *);
+
+ void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+
+public Q_SLOTS:
+ void burst(int count, int emissionRate=-1);
+
+protected:
+ virtual void componentComplete();
+
+Q_SIGNALS:
+ void sourceChanged();
+ void countChanged();
+ void emissionRateChanged();
+ void emissionVarianceChanged();
+ void lifeSpanChanged();
+ void lifeSpanDeviationChanged();
+ void fadeInDurationChanged();
+ void fadeOutDurationChanged();
+ void angleChanged();
+ void angleDeviationChanged();
+ void velocityChanged();
+ void velocityDeviationChanged();
+ void emittingChanged();
+
+private Q_SLOTS:
+ void imageLoaded();
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsParticles)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsParticles)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsParticleMotion)
+QML_DECLARE_TYPE(QmlGraphicsParticleMotionLinear)
+QML_DECLARE_TYPE(QmlGraphicsParticleMotionGravity)
+QML_DECLARE_TYPE(QmlGraphicsParticleMotionWander)
+QML_DECLARE_TYPE(QmlGraphicsParticles)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicspath.cpp b/src/declarative/graphicsitems/qmlgraphicspath.cpp
new file mode 100644
index 0000000..18f27af
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspath.cpp
@@ -0,0 +1,850 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicspath_p.h"
+#include "qmlgraphicspath_p_p.h"
+
+#include <qfxperf_p_p.h>
+
+#include <QSet>
+
+#include <private/qbezier_p.h>
+
+QT_BEGIN_NAMESPACE
+QML_DEFINE_TYPE(Qt,4,6,Path,QmlGraphicsPath)
+QML_DEFINE_NOCREATE_TYPE(QmlGraphicsPathElement)
+QML_DEFINE_NOCREATE_TYPE(QmlGraphicsCurve)
+QML_DEFINE_TYPE(Qt,4,6,PathAttribute,QmlGraphicsPathAttribute)
+QML_DEFINE_TYPE(Qt,4,6,PathPercent,QmlGraphicsPathPercent)
+QML_DEFINE_TYPE(Qt,4,6,PathLine,QmlGraphicsPathLine)
+QML_DEFINE_TYPE(Qt,4,6,PathQuad,QmlGraphicsPathQuad)
+QML_DEFINE_TYPE(Qt,4,6,PathCubic,QmlGraphicsPathCubic)
+
+/*!
+ \qmlclass PathElement QmlGraphicsPathElement
+ \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
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsPathElement
+ \ingroup group_utility
+*/
+
+/*!
+ \qmlclass Path QmlGraphicsPath
+ \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
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsPath
+ \ingroup group_utility
+ \brief The QmlGraphicsPath class defines a path.
+ \sa QmlGraphicsPathView
+*/
+QmlGraphicsPath::QmlGraphicsPath(QObject *parent)
+ : QObject(*(new QmlGraphicsPathPrivate), parent)
+{
+}
+
+QmlGraphicsPath::~QmlGraphicsPath()
+{
+}
+
+/*!
+ \qmlproperty real Path::startX
+ \qmlproperty real Path::startY
+ These properties hold the starting position of the path.
+*/
+qreal QmlGraphicsPath::startX() const
+{
+ Q_D(const QmlGraphicsPath);
+ return d->startX;
+}
+
+void QmlGraphicsPath::setStartX(qreal x)
+{
+ Q_D(QmlGraphicsPath);
+ d->startX = x;
+}
+
+qreal QmlGraphicsPath::startY() const
+{
+ Q_D(const QmlGraphicsPath);
+ return d->startY;
+}
+
+void QmlGraphicsPath::setStartY(qreal y)
+{
+ Q_D(QmlGraphicsPath);
+ d->startY = y;
+}
+
+/*!
+ \qmlproperty bool Path::closed
+ This property holds whether the start and end of the path are identical.
+*/
+bool QmlGraphicsPath::isClosed() const
+{
+ Q_D(const QmlGraphicsPath);
+ return d->closed;
+}
+
+/*!
+ \qmlproperty list<PathElement> 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
+*/
+
+QList<QmlGraphicsPathElement *>* QmlGraphicsPath::pathElements()
+{
+ Q_D(QmlGraphicsPath);
+ return &(d->_pathElements);
+}
+
+void QmlGraphicsPath::interpolate(int idx, const QString &name, qreal value)
+{
+ Q_D(QmlGraphicsPath);
+ if (!idx)
+ return;
+
+ qreal lastValue = 0;
+ qreal lastPercent = 0;
+ int search = idx - 1;
+ while(search >= 0) {
+ const AttributePoint &point = d->_attributePoints.at(search);
+ if (point.values.contains(name)) {
+ lastValue = point.values.value(name);
+ lastPercent = point.origpercent;
+ break;
+ }
+ --search;
+ }
+
+ ++search;
+
+ const AttributePoint &curPoint = d->_attributePoints.at(idx);
+
+ for (int ii = search; ii < idx; ++ii) {
+ AttributePoint &point = d->_attributePoints[ii];
+
+ qreal val = lastValue + (value - lastValue) * (point.origpercent - lastPercent) / (curPoint.origpercent - lastPercent);
+ point.values.insert(name, val);
+ }
+}
+
+void QmlGraphicsPath::endpoint(const QString &name)
+{
+ Q_D(QmlGraphicsPath);
+ 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 QmlGraphicsPath::processPath()
+{
+ Q_D(QmlGraphicsPath);
+
+ d->_pointCache.clear();
+ d->_attributePoints.clear();
+ d->_path = QPainterPath();
+
+ AttributePoint first;
+ for (int ii = 0; ii < d->_attributes.count(); ++ii)
+ first.values[d->_attributes.at(ii)] = 0;
+ d->_attributePoints << first;
+
+ d->_path.moveTo(d->startX, d->startY);
+
+ QmlGraphicsCurve *lastCurve = 0;
+ foreach (QmlGraphicsPathElement *pathElement, d->_pathElements) {
+ if (QmlGraphicsCurve *curve = qobject_cast<QmlGraphicsCurve *>(pathElement)) {
+ curve->addToPath(d->_path);
+ AttributePoint p;
+ p.origpercent = d->_path.length();
+ d->_attributePoints << p;
+ lastCurve = curve;
+ } else if (QmlGraphicsPathAttribute *attribute = qobject_cast<QmlGraphicsPathAttribute *>(pathElement)) {
+ AttributePoint &point = d->_attributePoints.last();
+ point.values[attribute->name()] = attribute->value();
+ interpolate(d->_attributePoints.count() - 1, attribute->name(), attribute->value());
+ } else if (QmlGraphicsPathPercent *percent = qobject_cast<QmlGraphicsPathPercent *>(pathElement)) {
+ AttributePoint &point = d->_attributePoints.last();
+ point.values[QLatin1String("_qfx_percent")] = percent->value();
+ interpolate(d->_attributePoints.count() - 1, QLatin1String("_qfx_percent"), percent->value());
+ }
+ }
+
+ // Fixup end points
+ const AttributePoint &last = d->_attributePoints.last();
+ for (int ii = 0; ii < d->_attributes.count(); ++ii) {
+ if (!last.values.contains(d->_attributes.at(ii)))
+ endpoint(d->_attributes.at(ii));
+ }
+
+ // Adjust percent
+ qreal length = d->_path.length();
+ qreal prevpercent = 0;
+ qreal prevorigpercent = 0;
+ for (int ii = 0; ii < d->_attributePoints.count(); ++ii) {
+ const AttributePoint &point = d->_attributePoints.at(ii);
+ if (point.values.contains(QLatin1String("_qfx_percent"))) { //special string for QmlGraphicsPathPercent
+ if ( ii > 0) {
+ qreal scale = (d->_attributePoints[ii].origpercent/length - prevorigpercent) /
+ (point.values.value(QLatin1String("_qfx_percent"))-prevpercent);
+ d->_attributePoints[ii].scale = scale;
+ }
+ d->_attributePoints[ii].origpercent /= length;
+ d->_attributePoints[ii].percent = point.values.value(QLatin1String("_qfx_percent"));
+ prevorigpercent = d->_attributePoints[ii].origpercent;
+ prevpercent = d->_attributePoints[ii].percent;
+ } else {
+ d->_attributePoints[ii].origpercent /= length;
+ d->_attributePoints[ii].percent = d->_attributePoints[ii].origpercent;
+ }
+ }
+
+ d->closed = lastCurve && d->startX == lastCurve->x() && d->startY == lastCurve->y();
+
+ emit changed();
+}
+
+void QmlGraphicsPath::componentComplete()
+{
+ Q_D(QmlGraphicsPath);
+ QSet<QString> attrs;
+ // First gather up all the attributes
+ foreach (QmlGraphicsPathElement *pathElement, d->_pathElements) {
+ if (QmlGraphicsPathAttribute *attribute =
+ qobject_cast<QmlGraphicsPathAttribute *>(pathElement))
+ attrs.insert(attribute->name());
+ }
+ d->_attributes = attrs.toList();
+
+ processPath();
+
+ foreach (QmlGraphicsPathElement *pathElement, d->_pathElements)
+ connect(pathElement, SIGNAL(changed()), this, SLOT(processPath()));
+}
+
+QPainterPath QmlGraphicsPath::path() const
+{
+ Q_D(const QmlGraphicsPath);
+ return d->_path;
+}
+
+QStringList QmlGraphicsPath::attributes() const
+{
+ Q_D(const QmlGraphicsPath);
+ return d->_attributes;
+}
+#include <QTime>
+
+static inline QBezier nextBezier(const QPainterPath &path, int *from, qreal *bezLength)
+{
+ const int lastElement = path.elementCount() - 1;
+ for (int i=*from; i <= lastElement; ++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;
+ *from = i+1;
+ 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();
+ *from = i+3;
+ return b;
+ }
+ default:
+ break;
+ }
+ }
+ *from = lastElement;
+ *bezLength = 0;
+ return QBezier();
+}
+
+void QmlGraphicsPath::createPointCache() const
+{
+ Q_D(const QmlGraphicsPath);
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::QmlGraphicsPathViewPathCache> pc;
+#endif
+ qreal pathLength = d->_path.length();
+ const int points = int(pathLength*2);
+ const int lastElement = d->_path.elementCount() - 1;
+ d->_pointCache.resize(points+1);
+
+ int currElement = 0;
+ 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 QmlGraphicsPath::pointAt(qreal p) const
+{
+ Q_D(const QmlGraphicsPath);
+ if (d->_pointCache.isEmpty()) {
+ createPointCache();
+ }
+ 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 QmlGraphicsPath::attributeAt(const QString &name, qreal percent) const
+{
+ Q_D(const QmlGraphicsPath);
+ 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 QmlGraphicsCurve::x() const
+{
+ return _x;
+}
+
+void QmlGraphicsCurve::setX(qreal x)
+{
+ if (_x != x) {
+ _x = x;
+ emit changed();
+ }
+}
+
+qreal QmlGraphicsCurve::y() const
+{
+ return _y;
+}
+
+void QmlGraphicsCurve::setY(qreal y)
+{
+ if (_y != y) {
+ _y = y;
+ emit changed();
+ }
+}
+
+/****************************************************************************/
+
+/*!
+ \qmlclass PathAttribute QmlGraphicsPathAttribute
+ \brief The PathAttribute allows setting an attribute at a given position in a Path.
+
+ The PathAttribute object allows attibutes consisting of a name and
+ a value to be specified for the endpoints of path segments. The
+ attributes are exposed to the delegate as
+ \l{qmlintroduction.html#attached-properties} {Attached Properties}.
+ The value of an attribute at any particular point is interpolated
+ from the PathAttributes bounding the 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.scale and
+ PathView.opacity 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
+ \endtable
+
+ \sa Path
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsPathAttribute
+ \ingroup group_utility
+ \brief The QmlGraphicsPathAttribute class allows to set the value of an attribute at a given position in the path.
+
+ \sa QmlGraphicsPath
+*/
+
+
+/*!
+ \qmlproperty string PathAttribute::name
+ the name of the attribute to change.
+*/
+
+/*!
+ the name of the attribute to change.
+*/
+
+QString QmlGraphicsPathAttribute::name() const
+{
+ return _name;
+}
+
+void QmlGraphicsPathAttribute::setName(const QString &name)
+{
+ _name = name;
+}
+
+/*!
+ \qmlproperty string PathAttribute::value
+ the new value of the attribute.
+*/
+
+/*!
+ the new value of the attribute.
+*/
+qreal QmlGraphicsPathAttribute::value() const
+{
+ return _value;
+}
+
+void QmlGraphicsPathAttribute::setValue(qreal value)
+{
+ if (_value != value) {
+ _value = value;
+ emit changed();
+ }
+}
+
+/****************************************************************************/
+
+/*!
+ \qmlclass PathLine QmlGraphicsPathLine
+ \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
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsPathLine
+ \ingroup group_utility
+ \brief The QmlGraphicsPathLine class defines a straight line.
+
+ \sa QmlGraphicsPath
+*/
+
+/*!
+ \qmlproperty real PathLine::x
+ \qmlproperty real PathLine::y
+
+ Defines the end point of the line.
+*/
+
+void QmlGraphicsPathLine::addToPath(QPainterPath &path)
+{
+ path.lineTo(x(), y());
+}
+
+/****************************************************************************/
+
+/*!
+ \qmlclass PathQuad QmlGraphicsPathQuad
+ \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
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsPathQuad
+ \ingroup group_utility
+ \brief The QmlGraphicsPathQuad class defines a quadratic Bezier curve with a control point.
+
+ \sa QmlGraphicsPath
+*/
+
+
+/*!
+ \qmlproperty real PathQuad::x
+ \qmlproperty real PathQuad::y
+
+ Defines the end point of the curve.
+*/
+
+/*!
+ \qmlproperty real PathQuad::controlX
+ \qmlproperty real PathQuad::controlY
+
+ Defines the position of the control point.
+*/
+
+/*!
+ the x position of the control point.
+*/
+qreal QmlGraphicsPathQuad::controlX() const
+{
+ return _controlX;
+}
+
+void QmlGraphicsPathQuad::setControlX(qreal x)
+{
+ if (_controlX != x) {
+ _controlX = x;
+ emit changed();
+ }
+}
+
+
+/*!
+ the y position of the control point.
+*/
+qreal QmlGraphicsPathQuad::controlY() const
+{
+ return _controlY;
+}
+
+void QmlGraphicsPathQuad::setControlY(qreal y)
+{
+ if (_controlY != y) {
+ _controlY = y;
+ emit changed();
+ }
+}
+
+void QmlGraphicsPathQuad::addToPath(QPainterPath &path)
+{
+ path.quadTo(controlX(), controlY(), x(), y());
+}
+
+/****************************************************************************/
+
+/*!
+ \qmlclass PathCubic QmlGraphicsPathCubic
+ \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
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsPathCubic
+ \ingroup group_utility
+ \brief The QmlGraphicsPathCubic class defines a cubic Bezier curve with two control points.
+
+ \sa QmlGraphicsPath
+*/
+
+/*!
+ \qmlproperty real PathCubic::x
+ \qmlproperty real PathCubic::y
+
+ Defines the end point of the curve.
+*/
+
+/*!
+ \qmlproperty real PathCubic::control1X
+ \qmlproperty real PathCubic::control1Y
+
+ Defines the position of the first control point.
+*/
+qreal QmlGraphicsPathCubic::control1X() const
+{
+ return _control1X;
+}
+
+void QmlGraphicsPathCubic::setControl1X(qreal x)
+{
+ if (_control1X != x) {
+ _control1X = x;
+ emit changed();
+ }
+}
+
+qreal QmlGraphicsPathCubic::control1Y() const
+{
+ return _control1Y;
+}
+
+void QmlGraphicsPathCubic::setControl1Y(qreal y)
+{
+ if (_control1Y != y) {
+ _control1Y = y;
+ emit changed();
+ }
+}
+
+/*!
+ \qmlproperty real PathCubic::control2X
+ \qmlproperty real PathCubic::control2Y
+
+ Defines the position of the second control point.
+*/
+qreal QmlGraphicsPathCubic::control2X() const
+{
+ return _control2X;
+}
+
+void QmlGraphicsPathCubic::setControl2X(qreal x)
+{
+ if (_control2X != x) {
+ _control2X = x;
+ emit changed();
+ }
+}
+
+qreal QmlGraphicsPathCubic::control2Y() const
+{
+ return _control2Y;
+}
+
+void QmlGraphicsPathCubic::setControl2Y(qreal y)
+{
+ if (_control2Y != y) {
+ _control2Y = y;
+ emit changed();
+ }
+}
+
+void QmlGraphicsPathCubic::addToPath(QPainterPath &path)
+{
+ path.cubicTo(control1X(), control1Y(), control2X(), control2Y(), x(), y());
+}
+
+/****************************************************************************/
+
+/*!
+ \qmlclass PathPercent QmlGraphicsPathPercent
+ \brief The PathPercent manipulates the way a path is interpreted.
+
+ The examples below show the normal distrubution 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
+ 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
+ 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
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsPathPercent
+ \ingroup group_utility
+ \brief The QmlGraphicsPathPercent class manipulates the way a path is interpreted.
+
+ QmlGraphicsPathPercent allows you to bunch up items (or spread out items) along various
+ segments of a QmlGraphicsPathView's path.
+
+ \sa QmlGraphicsPath
+
+*/
+
+qreal QmlGraphicsPathPercent::value() const
+{
+ return _value;
+}
+
+void QmlGraphicsPathPercent::setValue(qreal value)
+{
+ _value = value;
+}
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicspath_p.h b/src/declarative/graphicsitems/qmlgraphicspath_p.h
new file mode 100644
index 0000000..2b4b0fd
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspath_p.h
@@ -0,0 +1,262 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSPATH_H
+#define QMLGRAPHICSPATH_H
+
+#include "qmlgraphicsitem.h"
+
+#include <qml.h>
+
+#include <QtCore/QObject>
+#include <QtGui/QPainterPath>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+class Q_DECLARATIVE_EXPORT QmlGraphicsPathElement : public QObject
+{
+ Q_OBJECT
+public:
+ QmlGraphicsPathElement(QObject *parent=0) : QObject(parent) {}
+Q_SIGNALS:
+ void changed();
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsPathAttribute : public QmlGraphicsPathElement
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QString name READ name WRITE setName)
+ Q_PROPERTY(qreal value READ value WRITE setValue NOTIFY changed)
+public:
+ QmlGraphicsPathAttribute(QObject *parent=0) : QmlGraphicsPathElement(parent), _value(0) {}
+
+
+ QString name() const;
+ void setName(const QString &name);
+
+ qreal value() const;
+ void setValue(qreal value);
+
+private:
+ QString _name;
+ qreal _value;
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsCurve : public QmlGraphicsPathElement
+{
+ Q_OBJECT
+
+ Q_PROPERTY(qreal x READ x WRITE setX NOTIFY changed)
+ Q_PROPERTY(qreal y READ y WRITE setY NOTIFY changed)
+public:
+ QmlGraphicsCurve(QObject *parent=0) : QmlGraphicsPathElement(parent), _x(0), _y(0) {}
+
+ qreal x() const;
+ void setX(qreal x);
+
+ qreal y() const;
+ void setY(qreal y);
+
+ virtual void addToPath(QPainterPath &) {}
+
+private:
+ qreal _x;
+ qreal _y;
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsPathLine : public QmlGraphicsCurve
+{
+ Q_OBJECT
+public:
+ QmlGraphicsPathLine(QObject *parent=0) : QmlGraphicsCurve(parent) {}
+
+ void addToPath(QPainterPath &path);
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsPathQuad : public QmlGraphicsCurve
+{
+ Q_OBJECT
+
+ Q_PROPERTY(qreal controlX READ controlX WRITE setControlX NOTIFY changed)
+ Q_PROPERTY(qreal controlY READ controlY WRITE setControlY NOTIFY changed)
+public:
+ QmlGraphicsPathQuad(QObject *parent=0) : QmlGraphicsCurve(parent), _controlX(0), _controlY(0) {}
+
+ qreal controlX() const;
+ void setControlX(qreal x);
+
+ qreal controlY() const;
+ void setControlY(qreal y);
+
+ void addToPath(QPainterPath &path);
+
+private:
+ qreal _controlX;
+ qreal _controlY;
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsPathCubic : public QmlGraphicsCurve
+{
+ Q_OBJECT
+
+ Q_PROPERTY(qreal control1X READ control1X WRITE setControl1X NOTIFY changed)
+ Q_PROPERTY(qreal control1Y READ control1Y WRITE setControl1Y NOTIFY changed)
+ Q_PROPERTY(qreal control2X READ control2X WRITE setControl2X NOTIFY changed)
+ Q_PROPERTY(qreal control2Y READ control2Y WRITE setControl2Y NOTIFY changed)
+public:
+ QmlGraphicsPathCubic(QObject *parent=0) : QmlGraphicsCurve(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);
+
+ void addToPath(QPainterPath &path);
+
+private:
+ int _control1X;
+ int _control1Y;
+ int _control2X;
+ int _control2Y;
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsPathPercent : public QmlGraphicsPathElement
+{
+ Q_OBJECT
+ Q_PROPERTY(qreal value READ value WRITE setValue)
+public:
+ QmlGraphicsPathPercent(QObject *parent=0) : QmlGraphicsPathElement(parent) {}
+
+ qreal value() const;
+ void setValue(qreal value);
+
+private:
+ qreal _value;
+};
+
+class QmlGraphicsPathPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsPath : public QObject, public QmlParserStatus
+{
+ Q_OBJECT
+
+ Q_INTERFACES(QmlParserStatus)
+ Q_PROPERTY(QList<QmlGraphicsPathElement *>* pathElements READ pathElements)
+ Q_PROPERTY(qreal startX READ startX WRITE setStartX)
+ Q_PROPERTY(qreal startY READ startY WRITE setStartY)
+ Q_PROPERTY(bool closed READ isClosed NOTIFY changed)
+ Q_CLASSINFO("DefaultProperty", "pathElements")
+ Q_INTERFACES(QmlParserStatus)
+public:
+ QmlGraphicsPath(QObject *parent=0);
+ ~QmlGraphicsPath();
+
+ QList<QmlGraphicsPathElement *>* pathElements();
+
+ qreal startX() const;
+ void setStartX(qreal x);
+
+ qreal startY() const;
+ void setStartY(qreal y);
+
+ bool isClosed() const;
+
+ QPainterPath path() const;
+ QStringList attributes() const;
+ qreal attributeAt(const QString &, qreal) const;
+ QPointF pointAt(qreal) const;
+
+Q_SIGNALS:
+ void changed();
+
+protected:
+ virtual void componentComplete();
+
+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;
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsPath)
+ Q_DECLARE_PRIVATE(QmlGraphicsPath)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsPathElement)
+QML_DECLARE_TYPE(QmlGraphicsPathAttribute)
+QML_DECLARE_TYPE(QmlGraphicsCurve)
+QML_DECLARE_TYPE(QmlGraphicsPathLine)
+QML_DECLARE_TYPE(QmlGraphicsPathQuad)
+QML_DECLARE_TYPE(QmlGraphicsPathCubic)
+QML_DECLARE_TYPE(QmlGraphicsPathPercent)
+QML_DECLARE_TYPE(QmlGraphicsPath)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSPATH_H
diff --git a/src/declarative/graphicsitems/qmlgraphicspath_p_p.h b/src/declarative/graphicsitems/qmlgraphicspath_p_p.h
new file mode 100644
index 0000000..04342a8
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspath_p_p.h
@@ -0,0 +1,81 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSPATH_P_H
+#define QMLGRAPHICSPATH_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 "qmlgraphicspath_p.h"
+
+#include <qml.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+class QmlGraphicsPathPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsPath)
+
+public:
+ QmlGraphicsPathPrivate() : startX(0), startY(0), closed(false) { }
+
+ QPainterPath _path;
+ QList<QmlGraphicsPathElement*> _pathElements;
+ mutable QVector<QPointF> _pointCache;
+ QList<QmlGraphicsPath::AttributePoint> _attributePoints;
+ QStringList _attributes;
+ int startX;
+ int startY;
+ bool closed;
+};
+
+QT_END_NAMESPACE
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicspathview.cpp b/src/declarative/graphicsitems/qmlgraphicspathview.cpp
new file mode 100644
index 0000000..85e87eb
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspathview.cpp
@@ -0,0 +1,971 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicspathview_p.h"
+#include "qmlgraphicspathview_p_p.h"
+
+#include <qmlstate_p.h>
+#include <qmlopenmetaobject_p.h>
+
+#include <QDebug>
+#include <QEvent>
+#include <qlistmodelinterface_p.h>
+#include <QGraphicsSceneEvent>
+
+#include <math.h>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,PathView,QmlGraphicsPathView)
+
+
+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);
+}
+
+
+class QmlGraphicsPathViewAttached : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(bool onPath READ isOnPath NOTIFY onPathChanged)
+public:
+ QmlGraphicsPathViewAttached(QObject *parent)
+ : QObject(parent), mo(new QmlOpenMetaObject(this)), onPath(false)
+ {
+ }
+
+ ~QmlGraphicsPathViewAttached()
+ {
+ QmlGraphicsPathView::attachedProperties.remove(parent());
+ }
+
+ QVariant value(const QByteArray &name) const
+ {
+ return mo->value(name);
+ }
+ void setValue(const QByteArray &name, const QVariant &val)
+ {
+ mo->setValue(name, val);
+ }
+
+ bool isOnPath() const { return onPath; }
+ void setOnPath(bool on) {
+ if (on != onPath) {
+ onPath = on;
+ emit onPathChanged();
+ }
+ }
+
+Q_SIGNALS:
+ void onPathChanged();
+
+private:
+ QmlOpenMetaObject *mo;
+ bool onPath;
+};
+
+
+QmlGraphicsItem *QmlGraphicsPathViewPrivate::getItem(int modelIndex)
+{
+ Q_Q(QmlGraphicsPathView);
+ requestedIndex = modelIndex;
+ QmlGraphicsItem *item = model->item(modelIndex);
+ if (item) {
+ if (QObject *obj = QmlGraphicsPathView::qmlAttachedProperties(item))
+ static_cast<QmlGraphicsPathViewAttached *>(obj)->setOnPath(true);
+ item->setParentItem(q);
+ }
+ requestedIndex = -1;
+ return item;
+}
+
+void QmlGraphicsPathViewPrivate::releaseItem(QmlGraphicsItem *item)
+{
+ if (!item || !model)
+ return;
+ if (QObject *obj = QmlGraphicsPathView::qmlAttachedProperties(item))
+ static_cast<QmlGraphicsPathViewAttached *>(obj)->setOnPath(false);
+ if (model->release(item) == 0) {
+ if (QObject *obj = QmlGraphicsPathView::qmlAttachedProperties(item))
+ static_cast<QmlGraphicsPathViewAttached *>(obj)->setOnPath(false);
+ }
+}
+
+/*!
+ \qmlclass PathView QmlGraphicsPathView
+ \brief The PathView element lays out model-provided items on a path.
+ \inherits Item
+
+ The model is typically provided by a QAbstractListModel "C++ model object", but can also be created directly in QML.
+
+ The items are laid out along a path defined by a \l Path and may be flicked to scroll.
+
+ \snippet doc/src/snippets/declarative/pathview/pathview.qml 0
+
+ \image pathview.gif
+
+ \sa Path
+*/
+
+QmlGraphicsPathView::QmlGraphicsPathView(QmlGraphicsItem *parent)
+ : QmlGraphicsItem(*(new QmlGraphicsPathViewPrivate), parent)
+{
+ Q_D(QmlGraphicsPathView);
+ d->init();
+}
+
+QmlGraphicsPathView::~QmlGraphicsPathView()
+{
+ Q_D(QmlGraphicsPathView);
+ if (d->ownModel)
+ delete d->model;
+}
+
+/*!
+ \qmlattachedproperty bool 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:
+
+ \code
+ Component {
+ Rectangle {
+ visible: PathView.onPath
+ ...
+ }
+ }
+ \endcode
+
+ It is attached to each instance of the delegate.
+*/
+
+/*!
+ \qmlproperty model 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 XML, using the ListModel element.
+
+ \sa {qmlmodels}{Data Models}
+*/
+QVariant QmlGraphicsPathView::model() const
+{
+ Q_D(const QmlGraphicsPathView);
+ return d->modelVariant;
+}
+
+void QmlGraphicsPathView::setModel(const QVariant &model)
+{
+ Q_D(QmlGraphicsPathView);
+ if (d->model) {
+ disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
+ disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
+ disconnect(d->model, SIGNAL(createdItem(int, QmlGraphicsItem*)), this, SLOT(createdItem(int,QmlGraphicsItem*)));
+ for (int i=0; i<d->items.count(); i++){
+ QmlGraphicsItem *p = d->items[i];
+ d->model->release(p);
+ }
+ d->items.clear();
+ }
+
+ d->modelVariant = model;
+ QObject *object = qvariant_cast<QObject*>(model);
+ QmlGraphicsVisualModel *vim = 0;
+ if (object && (vim = qobject_cast<QmlGraphicsVisualModel *>(object))) {
+ if (d->ownModel) {
+ delete d->model;
+ d->ownModel = false;
+ }
+ d->model = vim;
+ } else {
+ if (!d->ownModel) {
+ d->model = new QmlGraphicsVisualDataModel(qmlContext(this));
+ d->ownModel = true;
+ }
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model))
+ dataModel->setModel(model);
+ }
+ if (d->model) {
+ connect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
+ connect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
+ connect(d->model, SIGNAL(createdItem(int, QmlGraphicsItem*)), this, SLOT(createdItem(int,QmlGraphicsItem*)));
+ }
+ d->firstIndex = 0;
+ d->pathOffset = 0;
+ d->regenerate();
+ d->fixOffset();
+}
+
+/*!
+ \qmlproperty int PathView::count
+ This property holds the number of items in the model.
+*/
+int QmlGraphicsPathView::count() const
+{
+ Q_D(const QmlGraphicsPathView);
+ return d->model ? d->model->count() : 0;
+}
+
+/*!
+ \qmlproperty Path PathView::path
+ \default
+ This property holds the path used to lay out the items.
+ For more information see the \l Path documentation.
+*/
+QmlGraphicsPath *QmlGraphicsPathView::path() const
+{
+ Q_D(const QmlGraphicsPathView);
+ return d->path;
+}
+
+void QmlGraphicsPathView::setPath(QmlGraphicsPath *path)
+{
+ Q_D(QmlGraphicsPathView);
+ d->path = path;
+ connect(d->path, SIGNAL(changed()), this, SLOT(refill()));
+ d->regenerate();
+}
+
+/*!
+ \qmlproperty int PathView::currentIndex
+ This property holds the index of the current item.
+*/
+int QmlGraphicsPathView::currentIndex() const
+{
+ Q_D(const QmlGraphicsPathView);
+ return d->currentIndex;
+}
+
+void QmlGraphicsPathView::setCurrentIndex(int idx)
+{
+ Q_D(QmlGraphicsPathView);
+ if (d->model && d->model->count())
+ idx = qAbs(idx % d->model->count());
+ if (d->model && idx != d->currentIndex) {
+ d->currentIndex = idx;
+ if (d->model->count()) {
+ d->snapToCurrent();
+ int itemIndex = (idx - d->firstIndex + d->model->count()) % d->model->count();
+ if (itemIndex < d->items.count())
+ d->items.at(itemIndex)->setFocus(true);
+ }
+ emit currentIndexChanged();
+ }
+}
+
+/*!
+ \qmlproperty real PathView::offset
+
+ The offset specifies how far along the path the items are from their initial positions.
+*/
+qreal QmlGraphicsPathView::offset() const
+{
+ Q_D(const QmlGraphicsPathView);
+ return d->_offset;
+}
+
+void QmlGraphicsPathView::setOffset(qreal offset)
+{
+ Q_D(QmlGraphicsPathView);
+ d->setOffset(offset);
+ d->updateCurrent();
+}
+
+void QmlGraphicsPathViewPrivate::setOffset(qreal o)
+{
+ Q_Q(QmlGraphicsPathView);
+ if (_offset != o) {
+ _offset = qmlMod(o, qreal(100.0));
+ if (_offset < 0)
+ _offset = 100.0 + _offset;
+ q->refill();
+ }
+}
+
+/*!
+ \qmlproperty real PathView::snapPosition
+
+ This property determines the position (0-100) the nearest item will snap to.
+*/
+qreal QmlGraphicsPathView::snapPosition() const
+{
+ Q_D(const QmlGraphicsPathView);
+ return d->snapPos;
+}
+
+void QmlGraphicsPathView::setSnapPosition(qreal pos)
+{
+ Q_D(QmlGraphicsPathView);
+ d->snapPos = pos/100;
+ d->fixOffset();
+}
+
+/*!
+ \qmlproperty real 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 QmlGraphicsPathView::dragMargin() const
+{
+ Q_D(const QmlGraphicsPathView);
+ return d->dragMargin;
+}
+
+void QmlGraphicsPathView::setDragMargin(qreal dragMargin)
+{
+ Q_D(QmlGraphicsPathView);
+ d->dragMargin = dragMargin;
+}
+
+/*!
+ \qmlproperty component 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}.
+
+ 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
+*/
+QmlComponent *QmlGraphicsPathView::delegate() const
+{
+ Q_D(const QmlGraphicsPathView);
+ if (d->model) {
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model))
+ return dataModel->delegate();
+ }
+
+ return 0;
+}
+
+void QmlGraphicsPathView::setDelegate(QmlComponent *c)
+{
+ Q_D(QmlGraphicsPathView);
+ if (!d->ownModel) {
+ d->model = new QmlGraphicsVisualDataModel(qmlContext(this));
+ d->ownModel = true;
+ }
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model)) {
+ dataModel->setDelegate(c);
+ d->regenerate();
+ }
+}
+
+/*!
+ \qmlproperty int PathView::pathItemCount
+ This property holds the number of items visible on the path at any one time
+*/
+int QmlGraphicsPathView::pathItemCount() const
+{
+ Q_D(const QmlGraphicsPathView);
+ return d->pathItems;
+}
+
+void QmlGraphicsPathView::setPathItemCount(int i)
+{
+ Q_D(QmlGraphicsPathView);
+ if (i == d->pathItems)
+ return;
+ d->pathItems = i;
+ d->regenerate();
+}
+
+QPointF QmlGraphicsPathViewPrivate::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 / 10.0;
+
+ return nearPoint;
+}
+
+
+void QmlGraphicsPathView::mousePressEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsPathView);
+ if (!d->items.count())
+ return;
+ QPointF scenePoint = mapToScene(event->pos());
+ int idx = 0;
+ for (; idx < d->items.count(); ++idx) {
+ QRectF rect = d->items.at(idx)->boundingRect();
+ rect = d->items.at(idx)->mapToScene(rect).boundingRect();
+ if (rect.contains(scenePoint))
+ break;
+ }
+ if (idx == d->items.count() && d->dragMargin == 0.) // didn't click on an item
+ return;
+
+ d->startPoint = d->pointNear(event->pos(), &d->startPc);
+ if (idx == d->items.count()) {
+ qreal distance = qAbs(event->pos().x() - d->startPoint.x()) + qAbs(event->pos().y() - d->startPoint.y());
+ if (distance > d->dragMargin)
+ return;
+ }
+
+ d->stealMouse = false;
+ d->lastElapsed = 0;
+ d->lastDist = 0;
+ QmlGraphicsItemPrivate::start(d->lastPosTime);
+ d->tl.clear();
+}
+
+void QmlGraphicsPathView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsPathView);
+ if (d->lastPosTime.isNull())
+ return;
+
+ if (!d->stealMouse) {
+ QPointF delta = event->pos() - d->startPoint;
+ if (qAbs(delta.x()) > QApplication::startDragDistance() && qAbs(delta.y()) > QApplication::startDragDistance())
+ d->stealMouse = true;
+ }
+
+ if (d->stealMouse) {
+ d->moveReason = QmlGraphicsPathViewPrivate::Mouse;
+ qreal newPc;
+ d->pointNear(event->pos(), &newPc);
+ qreal diff = newPc - d->startPc;
+ if (diff) {
+ setOffset(d->_offset + diff);
+
+ if (diff > 50)
+ diff -= 100;
+ else if (diff < -50)
+ diff += 100;
+
+ d->lastElapsed = QmlGraphicsItemPrivate::restart(d->lastPosTime);
+ d->lastDist = diff;
+ d->startPc = newPc;
+ }
+ }
+}
+
+void QmlGraphicsPathView::mouseReleaseEvent(QGraphicsSceneMouseEvent *)
+{
+ Q_D(QmlGraphicsPathView);
+ if (d->lastPosTime.isNull())
+ return;
+
+ qreal elapsed = qreal(d->lastElapsed + QmlGraphicsItemPrivate::elapsed(d->lastPosTime)) / 1000.;
+ qreal velocity = elapsed > 0. ? d->lastDist / elapsed : 0;
+ if (d->model && d->model->count() && qAbs(velocity) > 5) {
+ if (velocity > 100)
+ velocity = 100;
+ else if (velocity < -100)
+ velocity = -100;
+ qreal inc = qmlMod(d->_offset - d->snapPos, qreal(100.0 / d->model->count()));
+ qreal dist = qAbs(velocity/2 - qmlMod(velocity/2, qreal(100.0 / d->model->count()) - inc));
+ d->moveOffset.setValue(d->_offset);
+ d->tl.accel(d->moveOffset, velocity, 10, dist);
+ d->tl.execute(d->fixupOffsetEvent);
+ } else {
+ d->fixOffset();
+ }
+
+ d->lastPosTime = QTime();
+ d->stealMouse = false;
+ ungrabMouse();
+}
+
+bool QmlGraphicsPathView::sendMouseEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsPathView);
+ QGraphicsSceneMouseEvent mouseEvent(event->type());
+ QRectF myRect = mapToScene(QRectF(0, 0, width(), height())).boundingRect();
+ QGraphicsScene *s = scene();
+ QmlGraphicsItem *grabber = s ? qobject_cast<QmlGraphicsItem*>(s->mouseGrabberItem()) : 0;
+ if ((d->stealMouse || myRect.contains(event->scenePos().toPoint())) && (!grabber || !grabber->keepMouseGrab())) {
+ mouseEvent.setAccepted(false);
+ for (int i = 0x1; i <= 0x10; i <<= 1) {
+ if (event->buttons() & i) {
+ Qt::MouseButton button = Qt::MouseButton(i);
+ mouseEvent.setButtonDownPos(button, mapFromScene(event->buttonDownPos(button)));
+ }
+ }
+ mouseEvent.setScenePos(event->scenePos());
+ mouseEvent.setLastScenePos(event->lastScenePos());
+ mouseEvent.setPos(mapFromScene(event->scenePos()));
+ mouseEvent.setLastPos(mapFromScene(event->lastScenePos()));
+
+ switch(mouseEvent.type()) {
+ case QEvent::GraphicsSceneMouseMove:
+ mouseMoveEvent(&mouseEvent);
+ break;
+ case QEvent::GraphicsSceneMousePress:
+ mousePressEvent(&mouseEvent);
+ break;
+ case QEvent::GraphicsSceneMouseRelease:
+ mouseReleaseEvent(&mouseEvent);
+ break;
+ default:
+ break;
+ }
+ grabber = qobject_cast<QmlGraphicsItem*>(s->mouseGrabberItem());
+ if (grabber && d->stealMouse && !grabber->keepMouseGrab() && grabber != this)
+ grabMouse();
+
+ return d->stealMouse;
+ } else if (!d->lastPosTime.isNull()) {
+ d->lastPosTime = QTime();
+ }
+ return false;
+}
+
+bool QmlGraphicsPathView::sceneEventFilter(QGraphicsItem *i, QEvent *e)
+{
+ if (!isVisible())
+ return QmlGraphicsItem::sceneEventFilter(i, e);
+
+ switch (e->type()) {
+ case QEvent::GraphicsSceneMousePress:
+ case QEvent::GraphicsSceneMouseMove:
+ case QEvent::GraphicsSceneMouseRelease:
+ {
+ bool ret = sendMouseEvent(static_cast<QGraphicsSceneMouseEvent *>(e));
+ if (e->type() == QEvent::GraphicsSceneMouseRelease)
+ return ret;
+ break;
+ }
+ default:
+ break;
+ }
+
+ return QmlGraphicsItem::sceneEventFilter(i, e);
+}
+
+void QmlGraphicsPathView::componentComplete()
+{
+ Q_D(QmlGraphicsPathView);
+ QmlGraphicsItem::componentComplete();
+ d->regenerate();
+
+ // move to correct offset
+ if (d->items.count()) {
+ int itemIndex = (d->currentIndex - d->firstIndex + d->model->count()) % d->model->count();
+
+ itemIndex += d->pathOffset;
+ itemIndex %= d->items.count();
+ qreal targetOffset = qmlMod(100 + (d->snapPos*100) - 100.0 * itemIndex / d->items.count(), qreal(100.0));
+
+ if (targetOffset < 0)
+ targetOffset = 100.0 + targetOffset;
+ if (targetOffset != d->_offset) {
+ d->moveOffset.setValue(targetOffset);
+ }
+ }
+}
+
+void QmlGraphicsPathViewPrivate::regenerate()
+{
+ Q_Q(QmlGraphicsPathView);
+ if (!q->isComponentComplete())
+ return;
+
+ for (int i=0; i<items.count(); i++){
+ QmlGraphicsItem *p = items[i];
+ releaseItem(p);
+ }
+ items.clear();
+
+ if (!isValid())
+ return;
+
+ if (firstIndex >= model->count())
+ firstIndex = model->count()-1;
+ if (pathOffset >= model->count())
+ pathOffset = model->count()-1;
+
+ int numItems = pathItems >= 0 ? pathItems : model->count();
+ for (int i=0; i < numItems && i < model->count(); ++i){
+ int index = (i + firstIndex) % model->count();
+ QmlGraphicsItem *item = getItem(index);
+ if (!item) {
+ qWarning() << "PathView: Cannot create item, index" << (i + firstIndex) % model->count();
+ return;
+ }
+ items.append(item);
+ item->setZValue(i);
+ if (currentIndex == index)
+ item->setFocus(true);
+ }
+ q->refill();
+}
+
+void QmlGraphicsPathViewPrivate::updateItem(QmlGraphicsItem *item, qreal percent)
+{
+ if (QObject *obj = QmlGraphicsPathView::qmlAttachedProperties(item)) {
+ foreach(const QString &attr, path->attributes())
+ static_cast<QmlGraphicsPathViewAttached *>(obj)->setValue(attr.toUtf8(), path->attributeAt(attr, percent));
+ }
+ QPointF pf = path->pointAt(percent);
+ item->setX(pf.x() - item->width()*item->scale()/2);
+ item->setY(pf.y() - item->height()*item->scale()/2);
+}
+
+void QmlGraphicsPathView::refill()
+{
+ Q_D(QmlGraphicsPathView);
+ if (!d->isValid() || !isComponentComplete())
+ return;
+
+ QList<qreal> positions;
+ for (int i=0; i<d->items.count(); i++){
+ qreal percent = i * (100. / d->items.count());
+ percent = percent + d->_offset;
+ percent = qmlMod(percent, qreal(100.0));
+ positions << qAbs(percent/100.0);
+ }
+
+ if (d->pathItems==-1) {
+ for (int i=0; i<positions.count(); i++)
+ d->updateItem(d->items.at(i), positions[i]);
+ return;
+ }
+
+ QList<qreal> rotatedPositions;
+ for (int i=0; i<d->items.count(); i++)
+ rotatedPositions << positions[(i + d->pathOffset + d->items.count()) % d->items.count()];
+
+ int wrapIndex= -1;
+ for (int i=0; i<d->items.count()-1; i++) {
+ if (rotatedPositions[i] > rotatedPositions[i+1]){
+ wrapIndex = i;
+ break;
+ }
+ }
+ if (wrapIndex != -1 ){
+ //A wraparound has occured
+ if (wrapIndex < d->items.count()/2){
+ while(wrapIndex-- >= 0){
+ QmlGraphicsItem* p = d->items.takeFirst();
+ d->updateItem(p, 0.0);
+ d->releaseItem(p);
+ d->firstIndex++;
+ d->firstIndex %= d->model->count();
+ int index = (d->firstIndex + d->items.count())%d->model->count();
+ QmlGraphicsItem *item = d->getItem(index);
+ item->setZValue(wrapIndex);
+ if (d->currentIndex == index)
+ item->setFocus(true);
+ d->items << item;
+ d->pathOffset++;
+ d->pathOffset=d->pathOffset % d->items.count();
+ }
+ } else {
+ while(wrapIndex++ < d->items.count()-1){
+ QmlGraphicsItem* p = d->items.takeLast();
+ d->updateItem(p, 1.0);
+ d->releaseItem(p);
+ d->firstIndex--;
+ if (d->firstIndex < 0)
+ d->firstIndex = d->model->count() - 1;
+ QmlGraphicsItem *item = d->getItem(d->firstIndex);
+ item->setZValue(d->firstIndex);
+ if (d->currentIndex == d->firstIndex)
+ item->setFocus(true);
+ d->items.prepend(item);
+ d->pathOffset--;
+ if (d->pathOffset < 0)
+ d->pathOffset = d->items.count() - 1;
+ }
+ }
+ for (int i=0; i<d->items.count(); i++)
+ rotatedPositions[i] = positions[(i + d->pathOffset + d->items.count())
+ % d->items.count()];
+ }
+ for (int i=0; i<d->items.count(); i++)
+ d->updateItem(d->items.at(i), rotatedPositions[i]);
+}
+
+void QmlGraphicsPathView::itemsInserted(int modelIndex, int count)
+{
+ //XXX support animated insertion
+ Q_D(QmlGraphicsPathView);
+ if (!d->isValid() || !isComponentComplete())
+ return;
+ if (d->pathItems == -1) {
+ for (int i = 0; i < count; ++i) {
+ QmlGraphicsItem *item = d->getItem(modelIndex + i);
+ item->setZValue(modelIndex + i);
+ d->items.insert(modelIndex + i, item);
+ }
+ refill();
+ } else {
+ //XXX This is pretty heavy handed until we reference count items.
+ d->regenerate();
+ }
+
+ // make sure the current item is still at the snap position
+ int itemIndex = (d->currentIndex - d->firstIndex + d->model->count())%d->model->count();
+ itemIndex += d->pathOffset;
+ itemIndex %= d->items.count();
+ qreal targetOffset = qmlMod(100 + (d->snapPos*100) - 100.0 * itemIndex / d->items.count(), qreal(100.0));
+
+ if (targetOffset < 0)
+ targetOffset = 100.0 + targetOffset;
+ if (targetOffset != d->_offset)
+ d->moveOffset.setValue(targetOffset);
+}
+
+void QmlGraphicsPathView::itemsRemoved(int modelIndex, int count)
+{
+ //XXX support animated removal
+ Q_D(QmlGraphicsPathView);
+ if (!d->isValid() || !isComponentComplete())
+ return;
+ if (d->pathItems == -1) {
+ for (int i = 0; i < count; ++i) {
+ QmlGraphicsItem* p = d->items.takeAt(modelIndex);
+ d->model->release(p);
+ }
+ d->snapToCurrent();
+ refill();
+ } else {
+ d->regenerate();
+ }
+
+ if (d->model->count() == 0) {
+ d->currentIndex = -1;
+ d->moveOffset.setValue(0);
+ return;
+ }
+
+ // make sure the current item is still at the snap position
+ if (d->currentIndex >= d->model->count())
+ d->currentIndex = d->model->count() - 1;
+ int itemIndex = (d->currentIndex - d->firstIndex + d->model->count())%d->model->count();
+ itemIndex += d->pathOffset;
+ itemIndex %= d->items.count();
+ qreal targetOffset = qmlMod(100 + (d->snapPos*100) - 100.0 * itemIndex / d->items.count(), qreal(100.0));
+
+ if (targetOffset < 0)
+ targetOffset = 100.0 + targetOffset;
+ if (targetOffset != d->_offset)
+ d->moveOffset.setValue(targetOffset);
+}
+
+void QmlGraphicsPathView::createdItem(int index, QmlGraphicsItem *item)
+{
+ Q_D(QmlGraphicsPathView);
+ if (d->requestedIndex != index) {
+ item->setParentItem(this);
+ d->updateItem(item, index < d->firstIndex ? 0.0 : 1.0);
+ }
+}
+
+void QmlGraphicsPathView::destroyingItem(QmlGraphicsItem *item)
+{
+ Q_UNUSED(item);
+}
+
+void QmlGraphicsPathView::ticked()
+{
+ Q_D(QmlGraphicsPathView);
+ d->updateCurrent();
+}
+
+// find the item closest to the snap position
+int QmlGraphicsPathViewPrivate::calcCurrentIndex()
+{
+ int current = -1;
+ if (model && items.count()) {
+ _offset = qmlMod(_offset, qreal(100.0));
+ if (_offset < 0)
+ _offset += 100.0;
+
+ if (pathItems == -1) {
+ qreal delta = qmlMod(_offset - snapPos, qreal(100.0));
+ if (delta < 0)
+ delta = 100.0 + delta;
+ int ii = model->count() - qRound(delta * model->count() / 100);
+ if (ii < 0)
+ ii = 0;
+ current = ii;
+ } else {
+ qreal bestDiff=1e9;
+ int bestI=-1;
+ for (int i=0; i<items.count(); i++){
+ qreal percent = i * (100. / items.count());
+ percent = percent + _offset;
+ percent = qmlMod(percent, qreal(100.0));
+ qreal diff = qAbs(snapPos - (percent/100.0));
+ if (diff < bestDiff){
+ bestDiff = diff;
+ bestI = i;
+ }
+ }
+ int modelIndex = (bestI - pathOffset + items.count())%items.count();
+ modelIndex += firstIndex;
+ current = modelIndex;
+ }
+ current = qAbs(current % model->count());
+ }
+
+ return current;
+}
+
+void QmlGraphicsPathViewPrivate::updateCurrent()
+{
+ Q_Q(QmlGraphicsPathView);
+ if (moveReason != Mouse)
+ return;
+ int idx = calcCurrentIndex();
+ if (model && idx != currentIndex) {
+ currentIndex = idx;
+ int itemIndex = (idx - firstIndex + model->count()) % model->count();
+ if (itemIndex < items.count())
+ items.at(itemIndex)->setFocus(true);
+ emit q->currentIndexChanged();
+ }
+}
+
+void QmlGraphicsPathViewPrivate::fixOffset()
+{
+ Q_Q(QmlGraphicsPathView);
+ if (model && items.count()) {
+ int curr = calcCurrentIndex();
+ if (curr != currentIndex)
+ q->setCurrentIndex(curr);
+ else
+ snapToCurrent();
+ }
+}
+
+void QmlGraphicsPathViewPrivate::snapToCurrent()
+{
+ if (!model || model->count() <= 0)
+ return;
+
+ int itemIndex = (currentIndex - firstIndex + model->count()) % model->count();
+
+ //Rounds is the number of times round to make the current item visible
+ int rounds = itemIndex / items.count();
+ int otherWayRounds = (model->count() - (itemIndex)) / items.count() + 1;
+ if (otherWayRounds < rounds)
+ rounds = -otherWayRounds;
+
+ itemIndex += pathOffset;
+ itemIndex %= items.count();
+ qreal targetOffset = qmlMod(100 + (snapPos*100) - 100.0 * itemIndex / items.count(), qreal(100.0));
+
+ if (targetOffset < 0)
+ targetOffset = 100.0 + targetOffset;
+ if (targetOffset == _offset && rounds == 0)
+ return;
+
+ moveReason = Other;
+ tl.clear();
+ moveOffset.setValue(_offset);
+
+ if (rounds!=0){
+ //Compensate if the targetOffset would bring the target it from off the screen
+ qreal distance = targetOffset - _offset;
+ if (distance <= -50)
+ rounds--;
+ if (distance > 50)
+ rounds++;
+ tl.move(moveOffset, targetOffset + 100.0*(-rounds), QEasingCurve(QEasingCurve::InOutQuad),
+ int(100*items.count()*qMax((qreal)(2.0/items.count()),(qreal)qAbs(rounds))));
+ tl.execute(fixupOffsetEvent);
+ return;
+ }
+
+ if (targetOffset - _offset > 50.0) {
+ qreal distance = 100 - targetOffset + _offset;
+ tl.move(moveOffset, 0.0, QEasingCurve(QEasingCurve::OutQuad), int(200 * _offset / distance));
+ tl.set(moveOffset, 100.0);
+ tl.move(moveOffset, targetOffset, QEasingCurve(QEasingCurve::InQuad), int(200 * (100-targetOffset) / distance));
+ } else if (targetOffset - _offset <= -50.0) {
+ qreal distance = 100 - _offset + targetOffset;
+ tl.move(moveOffset, 100.0, QEasingCurve(QEasingCurve::OutQuad), int(200 * (100-_offset) / distance));
+ tl.set(moveOffset, 0.0);
+ tl.move(moveOffset, targetOffset, QEasingCurve(QEasingCurve::InQuad), int(200 * targetOffset / distance));
+ } else {
+ tl.move(moveOffset, targetOffset, QEasingCurve(QEasingCurve::InOutQuad), 200);
+ }
+}
+
+QHash<QObject*, QObject*> QmlGraphicsPathView::attachedProperties;
+QObject *QmlGraphicsPathView::qmlAttachedProperties(QObject *obj)
+{
+ QObject *rv = attachedProperties.value(obj);
+ if (!rv) {
+ rv = new QmlGraphicsPathViewAttached(obj);
+ attachedProperties.insert(obj, rv);
+ }
+ return rv;
+}
+
+QT_END_NAMESPACE
+
+#include <qmlgraphicspathview.moc>
diff --git a/src/declarative/graphicsitems/qmlgraphicspathview_p.h b/src/declarative/graphicsitems/qmlgraphicspathview_p.h
new file mode 100644
index 0000000..17106a2
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspathview_p.h
@@ -0,0 +1,134 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSPATHVIEW_H
+#define QMLGRAPHICSPATHVIEW_H
+
+#include "qmlgraphicsitem.h"
+#include "qmlgraphicspath_p.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsPathViewPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsPathView : public QmlGraphicsItem
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QVariant model READ model WRITE setModel)
+ Q_PROPERTY(QmlGraphicsPath *path READ path WRITE setPath)
+ Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
+ Q_PROPERTY(qreal offset READ offset WRITE setOffset NOTIFY offsetChanged)
+ Q_PROPERTY(qreal snapPosition READ snapPosition WRITE setSnapPosition)
+ Q_PROPERTY(qreal dragMargin READ dragMargin WRITE setDragMargin)
+ Q_PROPERTY(int count READ count)
+ Q_PROPERTY(QmlComponent *delegate READ delegate WRITE setDelegate)
+ Q_PROPERTY(int pathItemCount READ pathItemCount WRITE setPathItemCount)
+
+public:
+ QmlGraphicsPathView(QmlGraphicsItem *parent=0);
+ virtual ~QmlGraphicsPathView();
+
+ QVariant model() const;
+ void setModel(const QVariant &);
+
+ QmlGraphicsPath *path() const;
+ void setPath(QmlGraphicsPath *);
+
+ int currentIndex() const;
+ void setCurrentIndex(int idx);
+
+ qreal offset() const;
+ void setOffset(qreal offset);
+
+ qreal snapPosition() const;
+ void setSnapPosition(qreal pos);
+
+ qreal dragMargin() const;
+ void setDragMargin(qreal margin);
+
+ int count() const;
+
+ QmlComponent *delegate() const;
+ void setDelegate(QmlComponent *);
+
+ int pathItemCount() const;
+ void setPathItemCount(int);
+
+ static QObject *qmlAttachedProperties(QObject *);
+
+Q_SIGNALS:
+ void currentIndexChanged();
+ void offsetChanged();
+
+protected:
+ void mousePressEvent(QGraphicsSceneMouseEvent *event);
+ void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent *);
+ bool sendMouseEvent(QGraphicsSceneMouseEvent *event);
+ bool sceneEventFilter(QGraphicsItem *, QEvent *);
+ void componentComplete();
+
+private Q_SLOTS:
+ void refill();
+ void ticked();
+ void itemsInserted(int index, int count);
+ void itemsRemoved(int index, int count);
+ void createdItem(int index, QmlGraphicsItem *item);
+ void destroyingItem(QmlGraphicsItem *item);
+
+private:
+ friend class QmlGraphicsPathViewAttached;
+ static QHash<QObject*, QObject*> attachedProperties;
+ Q_DISABLE_COPY(QmlGraphicsPathView)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsPathView)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsPathView)
+QML_DECLARE_TYPEINFO(QmlGraphicsPathView, QML_HAS_ATTACHED_PROPERTIES)
+QT_END_HEADER
+
+#endif // QMLGRAPHICSPATHVIEW_H
diff --git a/src/declarative/graphicsitems/qmlgraphicspathview_p_p.h b/src/declarative/graphicsitems/qmlgraphicspathview_p_p.h
new file mode 100644
index 0000000..18cb205
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspathview_p_p.h
@@ -0,0 +1,144 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSPATHVIEW_P_H
+#define QMLGRAPHICSPATHVIEW_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 "qmlgraphicspathview_p.h"
+
+#include "qmlgraphicsitem_p.h"
+#include "qmlgraphicsvisualitemmodel_p.h"
+
+#include <qml.h>
+#include <qmlanimation_p_p.h>
+
+#include <qdatetime.h>
+
+QT_BEGIN_NAMESPACE
+
+typedef struct PathViewItem{
+ int index;
+ QmlGraphicsItem* item;
+}PathViewItem;
+
+class QmlGraphicsPathViewPrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsPathView)
+
+public:
+ QmlGraphicsPathViewPrivate()
+ : path(0), currentIndex(0), startPc(0), lastDist(0)
+ , lastElapsed(0), stealMouse(false), ownModel(false), activeItem(0)
+ , snapPos(0), dragMargin(0), moveOffset(this, &QmlGraphicsPathViewPrivate::setOffset)
+ , firstIndex(0), pathItems(-1), pathOffset(0), requestedIndex(-1)
+ , moveReason(Other)
+ {
+ fixupOffsetEvent = QmlTimeLineEvent::timeLineEvent<QmlGraphicsPathViewPrivate, &QmlGraphicsPathViewPrivate::fixOffset>(&moveOffset, this);
+ }
+
+ void init()
+ {
+ Q_Q(QmlGraphicsPathView);
+ _offset = 0;
+ q->setAcceptedMouseButtons(Qt::LeftButton);
+ q->setFlag(QGraphicsItem::ItemIsFocusScope);
+ q->setFiltersChildEvents(true);
+ q->connect(&tl, SIGNAL(updated()), q, SLOT(ticked()));
+ }
+
+ QmlGraphicsItem *getItem(int modelIndex);
+ void releaseItem(QmlGraphicsItem *item);
+
+ bool isValid() const {
+ return model && model->count() > 0 && model->isValid() && path;
+ }
+
+ int calcCurrentIndex();
+ void updateCurrent();
+ void fixOffset();
+ void setOffset(qreal offset);
+ void regenerate();
+ void updateItem(QmlGraphicsItem *, qreal);
+ void snapToCurrent();
+ QPointF pointNear(const QPointF &point, qreal *nearPercent=0) const;
+
+ QmlGraphicsPath *path;
+ int currentIndex;
+ qreal startPc;
+ QPointF startPoint;
+ qreal lastDist;
+ int lastElapsed;
+ qreal _offset;
+ bool stealMouse : 1;
+ bool ownModel : 1;
+ QTime lastPosTime;
+ QPointF lastPos;
+ QmlGraphicsItem *activeItem;
+ qreal snapPos;
+ qreal dragMargin;
+ QmlTimeLine tl;
+ QmlTimeLineValueProxy<QmlGraphicsPathViewPrivate> moveOffset;
+ QmlTimeLineEvent fixupOffsetEvent;
+ int firstIndex;
+ int pathItems;
+ int pathOffset;
+ int requestedIndex;
+ QList<QmlGraphicsItem *> items;
+ QGuard<QmlGraphicsVisualModel> model;
+ QVariant modelVariant;
+ enum MovementReason { Other, Key, Mouse };
+ MovementReason moveReason;
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicspositioners.cpp b/src/declarative/graphicsitems/qmlgraphicspositioners.cpp
new file mode 100644
index 0000000..5b081a2
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspositioners.cpp
@@ -0,0 +1,851 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicspositioners_p.h"
+#include "qmlgraphicspositioners_p_p.h"
+
+#include <qml.h>
+#include <qmlstate_p.h>
+#include <qmlstategroup_p.h>
+#include <qmlstateoperations_p.h>
+#include <qfxperf_p_p.h>
+#include <QtCore/qmath.h>
+
+#include <QDebug>
+#include <QCoreApplication>
+
+QT_BEGIN_NAMESPACE
+
+static const QmlGraphicsItemPrivate::ChangeTypes watchedChanges
+ = QmlGraphicsItemPrivate::Geometry
+ | QmlGraphicsItemPrivate::SiblingOrder
+ | QmlGraphicsItemPrivate::Visibility
+ | QmlGraphicsItemPrivate::Opacity
+ | QmlGraphicsItemPrivate::Destroyed;
+
+void QmlGraphicsBasePositionerPrivate::watchChanges(QmlGraphicsItem *other)
+{
+ QmlGraphicsItemPrivate *otherPrivate = static_cast<QmlGraphicsItemPrivate*>(QGraphicsItemPrivate::get(other));
+ otherPrivate->addItemChangeListener(this, watchedChanges);
+}
+
+void QmlGraphicsBasePositionerPrivate::unwatchChanges(QmlGraphicsItem* other)
+{
+ QmlGraphicsItemPrivate *otherPrivate = static_cast<QmlGraphicsItemPrivate*>(QGraphicsItemPrivate::get(other));
+ otherPrivate->removeItemChangeListener(this, watchedChanges);
+}
+
+/*!
+ \internal
+ \class QmlGraphicsBasePositioner
+ \ingroup group_layouts
+ \brief The QmlGraphicsBasePositioner class provides a base for QmlGraphics layouts.
+
+ To create a QmlGraphics Positioner, simply subclass QmlGraphicsBasePositioner and implement
+ doLayout(), which is automatically called when the layout might need
+ updating. In doLayout() use the setX and setY functions from QmlBasePositioner, 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.
+*/
+QmlGraphicsBasePositioner::QmlGraphicsBasePositioner(PositionerType at, QmlGraphicsItem *parent)
+ : QmlGraphicsItem(*(new QmlGraphicsBasePositionerPrivate), parent)
+{
+ Q_D(QmlGraphicsBasePositioner);
+ d->init(at);
+}
+
+QmlGraphicsBasePositioner::QmlGraphicsBasePositioner(QmlGraphicsBasePositionerPrivate &dd, PositionerType at, QmlGraphicsItem *parent)
+ : QmlGraphicsItem(dd, parent)
+{
+ Q_D(QmlGraphicsBasePositioner);
+ d->init(at);
+}
+
+QmlGraphicsBasePositioner::~QmlGraphicsBasePositioner()
+{
+ Q_D(QmlGraphicsBasePositioner);
+ for (int i = 0; i < positionedItems.count(); ++i)
+ d->unwatchChanges(positionedItems.at(i).item);
+ positionedItems.clear();
+}
+
+int QmlGraphicsBasePositioner::spacing() const
+{
+ Q_D(const QmlGraphicsBasePositioner);
+ return d->spacing;
+}
+
+void QmlGraphicsBasePositioner::setSpacing(int s)
+{
+ Q_D(QmlGraphicsBasePositioner);
+ if (s==d->spacing)
+ return;
+ d->spacing = s;
+ prePositioning();
+ emit spacingChanged();
+}
+
+QmlTransition *QmlGraphicsBasePositioner::move() const
+{
+ Q_D(const QmlGraphicsBasePositioner);
+ return d->moveTransition;
+}
+
+void QmlGraphicsBasePositioner::setMove(QmlTransition *mt)
+{
+ Q_D(QmlGraphicsBasePositioner);
+ d->moveTransition = mt;
+}
+
+QmlTransition *QmlGraphicsBasePositioner::add() const
+{
+ Q_D(const QmlGraphicsBasePositioner);
+ return d->addTransition;
+}
+
+void QmlGraphicsBasePositioner::setAdd(QmlTransition *add)
+{
+ Q_D(QmlGraphicsBasePositioner);
+ d->addTransition = add;
+}
+
+void QmlGraphicsBasePositioner::componentComplete()
+{
+ Q_D(QmlGraphicsBasePositioner);
+ QmlGraphicsItem::componentComplete();
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::BasepositionerComponentComplete> cc;
+#endif
+ positionedItems.reserve(d->QGraphicsItemPrivate::children.count());
+ prePositioning();
+}
+
+QVariant QmlGraphicsBasePositioner::itemChange(GraphicsItemChange change,
+ const QVariant &value)
+{
+ Q_D(QmlGraphicsBasePositioner);
+ if (change == ItemChildAddedChange){
+ QGraphicsItem* item = value.value<QGraphicsItem*>();
+ QmlGraphicsItem* child = 0;
+ if(item)
+ child = qobject_cast<QmlGraphicsItem*>(item->toGraphicsObject());
+ if (child)
+ prePositioning();
+ } else if (change == ItemChildRemovedChange) {
+ QGraphicsItem* item = value.value<QGraphicsItem*>();
+ QmlGraphicsItem* child = 0;
+ if(item)
+ child = qobject_cast<QmlGraphicsItem*>(item->toGraphicsObject());
+ if (child) {
+ QmlGraphicsBasePositioner::PositionedItem posItem(child);
+ int idx = positionedItems.find(posItem);
+ if (idx >= 0) {
+ d->unwatchChanges(child);
+ positionedItems.remove(idx);
+ }
+ prePositioning();
+ }
+ }
+
+ return QmlGraphicsItem::itemChange(change, value);
+}
+
+void QmlGraphicsBasePositioner::prePositioning()
+{
+ Q_D(QmlGraphicsBasePositioner);
+ if (!isComponentComplete())
+ return;
+
+ d->queuedPositioning = false;
+ //Need to order children by creation order modified by stacking order
+ QList<QGraphicsItem *> children = d->QGraphicsItemPrivate::children;
+ qSort(children.begin(), children.end(), d->insertionOrder);
+
+ for (int ii = 0; ii < children.count(); ++ii) {
+ QmlGraphicsItem *child = qobject_cast<QmlGraphicsItem *>(children.at(ii));
+ if (!child)
+ continue;
+ PositionedItem *item = 0;
+ PositionedItem posItem(child);
+ int wIdx = positionedItems.find(posItem);
+ if (wIdx < 0) {
+ d->watchChanges(child);
+ positionedItems.append(posItem);
+ item = &positionedItems[positionedItems.count()-1];
+ } else {
+ item = &positionedItems[wIdx];
+ }
+ if (child->opacity() <= 0.0 || !child->isVisible()) {
+ item->isVisible = false;
+ continue;
+ }
+ if (!item->isVisible) {
+ item->isVisible = true;
+ item->isNew = true;
+ } else {
+ item->isNew = false;
+ }
+ }
+ doPositioning();
+ if(d->addTransition || d->moveTransition)
+ finishApplyTransitions();
+ //Set implicit size to the size of its children
+ qreal h = 0.0f;
+ qreal w = 0.0f;
+ for (int i = 0; i < positionedItems.count(); ++i) {
+ const PositionedItem &posItem = positionedItems.at(i);
+ if (posItem.isVisible) {
+ h = qMax(h, posItem.item->y() + posItem.item->height());
+ w = qMax(w, posItem.item->x() + posItem.item->width());
+ }
+ }
+ setImplicitHeight(h);
+ setImplicitWidth(w);
+}
+
+void QmlGraphicsBasePositioner::positionX(int x, const PositionedItem &target)
+{
+ Q_D(QmlGraphicsBasePositioner);
+ if(d->type == Horizontal || d->type == Both){
+ if(!d->addTransition && !d->moveTransition){
+ target.item->setX(x);
+ }else{
+ if(target.isNew)
+ d->addActions << QmlAction(target.item, QLatin1String("x"), QVariant(x));
+ else
+ d->moveActions << QmlAction(target.item, QLatin1String("x"), QVariant(x));
+ }
+ }
+}
+
+void QmlGraphicsBasePositioner::positionY(int y, const PositionedItem &target)
+{
+ Q_D(QmlGraphicsBasePositioner);
+ if(d->type == Vertical || d->type == Both){
+ if(!d->addTransition && !d->moveTransition){
+ target.item->setY(y);
+ }else{
+ if(target.isNew)
+ d->addActions << QmlAction(target.item, QLatin1String("y"), QVariant(y));
+ else
+ d->moveActions << QmlAction(target.item, QLatin1String("y"), QVariant(y));
+ }
+ }
+}
+
+void QmlGraphicsBasePositioner::finishApplyTransitions()
+{
+ Q_D(QmlGraphicsBasePositioner);
+ // 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();
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Column,QmlGraphicsColumn)
+/*!
+ \qmlclass Column QmlGraphicsColumn
+ \brief The Column item lines up 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.
+
+ The below example positions differently shaped rectangles using a Column.
+ \table
+ \row
+ \o \image verticalpositioner_example.png
+ \o
+ \qml
+Column {
+ spacing: 2
+ Rectangle { color: "red"; width: 50; height: 50 }
+ Rectangle { color: "green"; width: 20; height: 50 }
+ Rectangle { color: "blue"; width: 50; height: 20 }
+}
+ \endqml
+ \endtable
+
+ Column also provides for transitions to be set when items are added, moved,
+ or removed in the positioner. Adding and removing apply both to items which are deleted
+ or have their position in the document changed so as to no longer be children of the positioner,
+ as well as to items which have their opacity set to or from zero so as to appear or disappear.
+
+ \table
+ \row
+ \o \image verticalpositioner_transition.gif
+ \o
+ \qml
+Column {
+ spacing: 2
+ remove: ...
+ add: ...
+ move: ...
+ ...
+}
+ \endqml
+ \endtable
+
+ 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, or use anchors on a child of a positioner, then the
+ positioner may exhibit strange behaviour.
+
+*/
+/*!
+ \qmlproperty Transition 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.
+
+ Added 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.
+
+
+*/
+/*!
+ \qmlproperty Transition 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 can happen when other items are added or removed from the positioner, or when items resize themselves.
+
+ \table
+ \row
+ \o \image positioner-move.gif
+ \o
+ \qml
+Column {
+ move: Transition {
+ NumberAnimation {
+ matchProperties: "y"
+ ease: "easeOutBounce"
+ }
+ }
+}
+ \endqml
+ \endtable
+*/
+/*!
+ \qmlproperty int Column::spacing
+
+ spacing is the amount in pixels left empty between each adjacent
+ item, and defaults to 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 top positioner has the default of no spacing,
+ and the bottom positioner has its spacing set to 2.
+
+ \image spacing_a.png
+ \image spacing_b.png
+
+*/
+/*!
+ \internal
+ \class QmlGraphicsColumn
+ \brief The QmlGraphicsColumn class lines up items vertically.
+ \ingroup group_positioners
+*/
+QmlGraphicsColumn::QmlGraphicsColumn(QmlGraphicsItem *parent)
+: QmlGraphicsBasePositioner(Vertical, parent)
+{
+}
+
+static inline bool isInvisible(QmlGraphicsItem *child)
+{
+ return child->opacity() == 0.0 || !child->isVisible() || !child->width() || !child->height();
+}
+
+void QmlGraphicsColumn::doPositioning()
+{
+ int voffset = 0;
+
+ for (int ii = 0; ii < positionedItems.count(); ++ii) {
+ const PositionedItem &child = positionedItems.at(ii);
+ if (!child.item || isInvisible(child.item))
+ continue;
+
+ if(child.item->y() != voffset)
+ positionY(voffset, child);
+
+ voffset += child.item->height();
+ voffset += spacing();
+ }
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Row,QmlGraphicsRow)
+/*!
+ \qmlclass Row QmlGraphicsRow
+ \brief The Row item lines up its children horizontally.
+ \inherits Item
+
+ The Row item positions its child items so that they are
+ horizontally aligned and not overlapping. Spacing can be added between the
+ items, and a margin around all items can also be added. It also provides for
+ transitions to be set when items are added, moved, or removed in the
+ positioner. Adding and removing apply both to items which are deleted or have
+ their position in the document changed so as to no longer be children of the
+ positioner, as well as to items which have their opacity set to or from zero
+ so as to appear or disappear.
+
+ The below example lays out differently shaped rectangles using a Row.
+ \qml
+Row {
+ spacing: 2
+ Rectangle { color: "red"; width: 50; height: 50 }
+ Rectangle { color: "green"; width: 20; height: 50 }
+ Rectangle { color: "blue"; width: 50; height: 20 }
+}
+ \endqml
+ \image horizontalpositioner_example.png
+
+ 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, or use anchors on a child of a positioner, then the
+ positioner may exhibit strange behaviour.
+
+*/
+/*!
+ \qmlproperty Transition Row::add
+ This property holds the transition to apply 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.
+
+ Added 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.
+
+
+*/
+/*!
+ \qmlproperty Transition Row::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 can happen when other items are added or removed from the positioner, or when items resize themselves.
+
+ \qml
+Row {
+ id: positioner
+ move: Transition {
+ NumberAnimation {
+ matchProperties: "x"
+ ease: "easeOutBounce"
+ }
+ }
+}
+ \endqml
+
+*/
+/*!
+ \qmlproperty int Row::spacing
+
+ spacing is the amount in pixels left empty between each adjacent
+ item, and defaults to 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 top positioner has the default of no spacing,
+ and the bottom positioner has its spacing set to 2.
+
+ \image spacing_a.png
+ \image spacing_b.png
+
+*/
+/*!
+ \internal
+ \class QmlGraphicsRow
+ \brief The QmlGraphicsRow class lines up items horizontally.
+ \ingroup group_positioners
+*/
+QmlGraphicsRow::QmlGraphicsRow(QmlGraphicsItem *parent)
+: QmlGraphicsBasePositioner(Horizontal, parent)
+{
+}
+
+void QmlGraphicsRow::doPositioning()
+{
+ int hoffset = 0;
+
+ for (int ii = 0; ii < positionedItems.count(); ++ii) {
+ const PositionedItem &child = positionedItems.at(ii);
+ if (!child.item || isInvisible(child.item))
+ continue;
+
+ if(child.item->x() != hoffset)
+ positionX(hoffset, child);
+
+ hoffset += child.item->width();
+ hoffset += spacing();
+ }
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Grid,QmlGraphicsGrid)
+
+/*!
+ \qmlclass Grid QmlGraphicsGrid
+ \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. Spacing can be added
+ between the items. It also provides for transitions to be set when items are
+ added, moved, or removed in the positioner. Adding and removing apply
+ both to items which are deleted or have their position in the
+ document changed so as to no longer be children of the positioner, as
+ well as to items which have their opacity set to or from zero so
+ as to appear or disappear.
+
+ The Grid defaults to using four columns, and as many rows as
+ are necessary to fit all the child items. The number of rows
+ and/or the number of columns can be constrained by setting the rows
+ or columns properties. The grid positioner calculates a grid with
+ rectangular cells of sufficient size to hold all items, and then
+ places the items in the cells, going across then down, and
+ positioning each item at the (0,0) corner of the cell. The below
+ example demonstrates this.
+
+ \table
+ \row
+ \o \image gridLayout_example.png
+ \o
+ \qml
+Grid {
+ columns: 3
+ spacing: 2
+ Rectangle { color: "red"; width: 50; height: 50 }
+ Rectangle { color: "green"; width: 20; height: 50 }
+ Rectangle { color: "blue"; width: 50; height: 20 }
+ Rectangle { color: "cyan"; width: 50; height: 50 }
+ Rectangle { color: "magenta"; width: 10; height: 10 }
+}
+ \endqml
+ \endtable
+
+ 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, or use anchors on a child of a positioner, then the
+ positioner may exhibit strange behaviour.
+*/
+/*!
+ \qmlproperty Transition Grid::add
+ This property holds the transition to apply when adding an item to the positioner.
+ The transition is only applied to the added item(s).
+ Positioner transitions will only affect the position (x,y) of items.
+
+ Added 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.
+
+
+*/
+/*!
+ \qmlproperty Transition Grid::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 can happen when other items are added or removed from the positioner, or
+ when items resize themselves.
+
+ \qml
+Grid {
+ move: Transition {
+ NumberAnimation {
+ matchProperties: "x,y"
+ ease: "easeOutBounce"
+ }
+ }
+}
+ \endqml
+
+*/
+/*!
+ \qmlproperty int Grid::spacing
+
+ spacing is the amount in pixels left empty between each adjacent
+ item, and defaults to 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 top positioner has the default of no spacing,
+ and the bottom positioner has its spacing set to 2.
+
+ \image spacing_a.png
+ \image spacing_b.png
+
+*/
+/*!
+ \internal
+ \class QmlGraphicsGrid
+ \brief The QmlGraphicsGrid class lays out items in a grid.
+ \ingroup group_layouts
+
+*/
+QmlGraphicsGrid::QmlGraphicsGrid(QmlGraphicsItem *parent) :
+ QmlGraphicsBasePositioner(Both, parent)
+{
+ _columns=-1;
+ _rows=-1;
+}
+
+/*!
+ \qmlproperty int Grid::columns
+ This property holds the number of columns in the grid.
+
+ When the columns property is set the Grid will always have
+ that many columns. Note that if you do not have enough items to
+ fill this many columns some columns will be of zero width.
+*/
+
+/*!
+ \qmlproperty int Grid::rows
+ This property holds the number of rows in the grid.
+
+ When the rows property is set the Grid will always have that
+ many rows. Note that if you do not have enough items to fill this
+ many rows some rows will be of zero width.
+*/
+
+void QmlGraphicsGrid::doPositioning()
+{
+ int c=_columns,r=_rows;//Actual number of rows/columns
+ int numVisible = positionedItems.count();
+ if (_columns==-1 && _rows==-1){
+ c = 4;
+ r = (numVisible+3)/4;
+ }else if (_rows==-1){
+ r = (numVisible+(_columns-1))/_columns;
+ }else if (_columns==-1){
+ c = (numVisible+(_rows-1))/_rows;
+ }
+
+ QList<int> maxColWidth;
+ QList<int> maxRowHeight;
+ int childIndex =0;
+ 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 == positionedItems.count())
+ continue;
+ const PositionedItem &child = positionedItems.at(childIndex++);
+ if (!child.item || isInvisible(child.item))
+ continue;
+ if (child.item->width() > maxColWidth[j])
+ maxColWidth[j] = child.item->width();
+ if (child.item->height() > maxRowHeight[i])
+ maxRowHeight[i] = child.item->height();
+ }
+ }
+
+ int xoffset=0;
+ int yoffset=0;
+ int curRow =0;
+ int curCol =0;
+ for (int i = 0; i < positionedItems.count(); ++i) {
+ const PositionedItem &child = positionedItems.at(i);
+ if (!child.item || isInvisible(child.item))
+ continue;
+ if((child.item->x()!=xoffset)||(child.item->y()!=yoffset)){
+ positionX(xoffset, child);
+ positionY(yoffset, child);
+ }
+ xoffset+=maxColWidth[curCol]+spacing();
+ curCol++;
+ curCol%=c;
+ if (!curCol){
+ yoffset+=maxRowHeight[curRow]+spacing();
+ xoffset=0;
+ curRow++;
+ if (curRow>=r)
+ break;
+ }
+ }
+}
+
+
+QML_DEFINE_TYPE(Qt,4,6,Flow,QmlGraphicsFlow)
+/*!
+ \qmlclass Flow QmlGraphicsFlow
+ \brief The Flow item lines up its children side by side, wrapping as necessary.
+ \inherits Item
+
+
+*/
+/*!
+ \qmlproperty Transition Flow::add
+ This property holds the transition to apply 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.
+
+ Added 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.
+
+
+*/
+/*!
+ \qmlproperty Transition Flow::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 can happen when other items are added or removed from the positioner, or when items resize themselves.
+
+ \qml
+Flow {
+ id: positioner
+ move: Transition {
+ NumberAnimation {
+ matchProperties: "x,y"
+ ease: "easeOutBounce"
+ }
+ }
+}
+ \endqml
+
+*/
+/*!
+ \qmlproperty int Flow::spacing
+
+ spacing is the amount in pixels left empty between each adjacent
+ item, and defaults to 0.
+
+*/
+
+class QmlGraphicsFlowPrivate : public QmlGraphicsBasePositionerPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsFlow)
+
+public:
+ QmlGraphicsFlowPrivate()
+ : QmlGraphicsBasePositionerPrivate(), flow(QmlGraphicsFlow::LeftToRight)
+ {}
+
+ QmlGraphicsFlow::Flow flow;
+};
+
+QmlGraphicsFlow::QmlGraphicsFlow(QmlGraphicsItem *parent)
+: QmlGraphicsBasePositioner(*(new QmlGraphicsFlowPrivate), Both, parent)
+{
+}
+
+/*!
+ \qmlproperty enumeration Flow::flow
+ This property holds the flow of the layout.
+
+ Possible values are \c LeftToRight (default) and \c TopToBottom.
+
+ If \a flow is \c LeftToRight, the items are positioned next to
+ to each other from left to right until the width of the Flow
+ is exceeded, then wrapped to the next line.
+ If \a flow is \c TopToBottom, the 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.
+*/
+QmlGraphicsFlow::Flow QmlGraphicsFlow::flow() const
+{
+ Q_D(const QmlGraphicsFlow);
+ return d->flow;
+}
+
+void QmlGraphicsFlow::setFlow(Flow flow)
+{
+ Q_D(QmlGraphicsFlow);
+ if (d->flow != flow) {
+ d->flow = flow;
+ prePositioning();
+ emit flowChanged();
+ }
+}
+
+void QmlGraphicsFlow::doPositioning()
+{
+ Q_D(QmlGraphicsFlow);
+
+ int hoffset = 0;
+ int voffset = 0;
+ int linemax = 0;
+
+ for (int i = 0; i < positionedItems.count(); ++i) {
+ const PositionedItem &child = positionedItems.at(i);
+ if (!child.item || isInvisible(child.item))
+ continue;
+
+ if (d->flow == LeftToRight) {
+ if (hoffset && hoffset + child.item->width() > width()) {
+ hoffset = 0;
+ voffset += linemax + spacing();
+ linemax = 0;
+ }
+ } else {
+ if (voffset && voffset + child.item->height() > height()) {
+ voffset = 0;
+ hoffset += linemax + spacing();
+ linemax = 0;
+ }
+ }
+
+ if(child.item->x() != hoffset || child.item->y() != voffset){
+ positionX(hoffset, child);
+ positionY(voffset, child);
+ }
+
+ 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()));
+ }
+ }
+}
+
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicspositioners_p.h b/src/declarative/graphicsitems/qmlgraphicspositioners_p.h
new file mode 100644
index 0000000..d6711f6
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspositioners_p.h
@@ -0,0 +1,192 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSLAYOUTS_H
+#define QMLGRAPHICSLAYOUTS_H
+
+#include "qmlgraphicsitem.h"
+
+#include "../util/qmlstate_p.h"
+#include <private/qpodvector_p.h>
+
+#include <QtCore/QObject>
+#include <QtCore/QString>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+class QmlGraphicsBasePositionerPrivate;
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsBasePositioner : public QmlGraphicsItem
+{
+ Q_OBJECT
+
+ Q_PROPERTY(int spacing READ spacing WRITE setSpacing NOTIFY spacingChanged)
+ Q_PROPERTY(QmlTransition *move READ move WRITE setMove)
+ Q_PROPERTY(QmlTransition *add READ add WRITE setAdd)
+public:
+ enum PositionerType { None = 0x0, Horizontal = 0x1, Vertical = 0x2, Both = 0x3 };
+ QmlGraphicsBasePositioner(PositionerType, QmlGraphicsItem *parent);
+ ~QmlGraphicsBasePositioner();
+
+ int spacing() const;
+ void setSpacing(int);
+
+ QmlTransition *move() const;
+ void setMove(QmlTransition *);
+
+ QmlTransition *add() const;
+ void setAdd(QmlTransition *);
+
+protected:
+ QmlGraphicsBasePositioner(QmlGraphicsBasePositionerPrivate &dd, PositionerType at, QmlGraphicsItem *parent);
+ virtual void componentComplete();
+ virtual QVariant itemChange(GraphicsItemChange, const QVariant &);
+ void finishApplyTransitions();
+
+Q_SIGNALS:
+ void spacingChanged();
+
+protected Q_SLOTS:
+ virtual void doPositioning()=0;
+ void prePositioning();
+
+protected:
+ struct PositionedItem {
+ PositionedItem(QmlGraphicsItem *i) : item(i), isNew(false), isVisible(true) {}
+ bool operator==(const PositionedItem &other) const { return other.item == item; }
+ QmlGraphicsItem *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(QmlGraphicsBasePositioner)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsBasePositioner)
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsColumn : public QmlGraphicsBasePositioner
+{
+ Q_OBJECT
+public:
+ QmlGraphicsColumn(QmlGraphicsItem *parent=0);
+protected Q_SLOTS:
+ virtual void doPositioning();
+private:
+ Q_DISABLE_COPY(QmlGraphicsColumn)
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsRow: public QmlGraphicsBasePositioner
+{
+ Q_OBJECT
+public:
+ QmlGraphicsRow(QmlGraphicsItem *parent=0);
+protected Q_SLOTS:
+ virtual void doPositioning();
+private:
+ Q_DISABLE_COPY(QmlGraphicsRow)
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsGrid : public QmlGraphicsBasePositioner
+{
+ Q_OBJECT
+ Q_PROPERTY(int rows READ rows WRITE setRows)
+ Q_PROPERTY(int columns READ columns WRITE setcolumns)
+public:
+ QmlGraphicsGrid(QmlGraphicsItem *parent=0);
+
+ int rows() const {return _rows;}
+ void setRows(const int rows){_rows = rows;}
+
+ int columns() const {return _columns;}
+ void setcolumns(const int columns){_columns = columns;}
+protected Q_SLOTS:
+ virtual void doPositioning();
+
+private:
+ int _rows;
+ int _columns;
+ Q_DISABLE_COPY(QmlGraphicsGrid)
+};
+
+class QmlGraphicsFlowPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsFlow: public QmlGraphicsBasePositioner
+{
+ Q_OBJECT
+ Q_PROPERTY(Flow flow READ flow WRITE setFlow NOTIFY flowChanged)
+public:
+ QmlGraphicsFlow(QmlGraphicsItem *parent=0);
+
+ Q_ENUMS(Flow)
+ enum Flow { LeftToRight, TopToBottom };
+ Flow flow() const;
+ void setFlow(Flow);
+
+Q_SIGNALS:
+ void flowChanged();
+
+protected Q_SLOTS:
+ virtual void doPositioning();
+
+protected:
+ QmlGraphicsFlow(QmlGraphicsFlowPrivate &dd, QmlGraphicsItem *parent);
+private:
+ Q_DISABLE_COPY(QmlGraphicsFlow)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsFlow)
+};
+
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsColumn)
+QML_DECLARE_TYPE(QmlGraphicsRow)
+QML_DECLARE_TYPE(QmlGraphicsGrid)
+QML_DECLARE_TYPE(QmlGraphicsFlow)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicspositioners_p_p.h b/src/declarative/graphicsitems/qmlgraphicspositioners_p_p.h
new file mode 100644
index 0000000..55a31c7
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicspositioners_p_p.h
@@ -0,0 +1,136 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSLAYOUTS_P_H
+#define QMLGRAPHICSLAYOUTS_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 "qmlgraphicspositioners_p.h"
+
+#include "qmlgraphicsitem_p.h"
+
+#include <qmlstate_p.h>
+#include <qmltransitionmanager_p_p.h>
+#include <qmlstateoperations_p.h>
+
+#include <QtCore/QObject>
+#include <QtCore/QString>
+#include <QtCore/QTimer>
+#include <QDebug>
+
+QT_BEGIN_NAMESPACE
+class QmlGraphicsBasePositionerPrivate : public QmlGraphicsItemPrivate, public QmlGraphicsItemChangeListener
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsBasePositioner)
+
+public:
+ QmlGraphicsBasePositionerPrivate()
+ : spacing(0), type(QmlGraphicsBasePositioner::None), moveTransition(0), addTransition(0),
+ queuedPositioning(false)
+ {
+ }
+
+ void init(QmlGraphicsBasePositioner::PositionerType at)
+ {
+ type = at;
+ }
+
+ int spacing;
+ QmlGraphicsBasePositioner::PositionerType type;
+ QmlTransition *moveTransition;
+ QmlTransition *addTransition;
+ QmlStateOperation::ActionList addActions;
+ QmlStateOperation::ActionList moveActions;
+ QmlTransitionManager addTransitionManager;
+ QmlTransitionManager moveTransitionManager;
+
+ void watchChanges(QmlGraphicsItem *other);
+ void unwatchChanges(QmlGraphicsItem* other);
+ bool queuedPositioning;
+
+ virtual void itemSiblingOrderChanged(QmlGraphicsItem* other)
+ {
+ Q_Q(QmlGraphicsBasePositioner);
+ Q_UNUSED(other);
+ if(!queuedPositioning){
+ //Delay is due to many children often being reordered at once
+ //And we only want to reposition them all once
+ QTimer::singleShot(0,q,SLOT(prePositioning()));
+ queuedPositioning = true;
+ }
+ }
+
+ void itemGeometryChanged(QmlGraphicsItem *, const QRectF &newGeometry, const QRectF &oldGeometry)
+ {
+ Q_Q(QmlGraphicsBasePositioner);
+ if (newGeometry.size() != oldGeometry.size())
+ q->prePositioning();
+ }
+ virtual void itemVisibilityChanged(QmlGraphicsItem *)
+ {
+ Q_Q(QmlGraphicsBasePositioner);
+ q->prePositioning();
+ }
+ virtual void itemOpacityChanged(QmlGraphicsItem *)
+ {
+ Q_Q(QmlGraphicsBasePositioner);
+ q->prePositioning();
+ }
+
+ void itemDestroyed(QmlGraphicsItem *item)
+ {
+ Q_Q(QmlGraphicsBasePositioner);
+ q->positionedItems.removeOne(QmlGraphicsBasePositioner::PositionedItem(item));
+ }
+};
+
+QT_END_NAMESPACE
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicsrectangle.cpp b/src/declarative/graphicsitems/qmlgraphicsrectangle.cpp
new file mode 100644
index 0000000..cc09436
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsrectangle.cpp
@@ -0,0 +1,467 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsrectangle_p.h"
+#include "qmlgraphicsrectangle_p_p.h"
+
+#include <QPainter>
+#include <QtCore/qmath.h>
+
+QT_BEGIN_NAMESPACE
+QML_DEFINE_TYPE(Qt,4,6,Pen,QmlGraphicsPen)
+QML_DEFINE_TYPE(Qt,4,6,GradientStop,QmlGraphicsGradientStop)
+QML_DEFINE_TYPE(Qt,4,6,Gradient,QmlGraphicsGradient)
+
+/*!
+ \internal
+ \class QmlGraphicsPen
+ \brief The QmlGraphicsPen class provides a pen used for drawing rectangle borders on a QmlView.
+
+ 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
+*/
+
+void QmlGraphicsPen::setColor(const QColor &c)
+{
+ _color = c;
+ _valid = _color.alpha() ? true : false;
+ emit penChanged();
+}
+
+void QmlGraphicsPen::setWidth(int w)
+{
+ if (_width == w && _valid)
+ return;
+
+ _width = w;
+ _valid = (_width < 1) ? false : true;
+ emit penChanged();
+}
+
+
+/*!
+ \qmlclass GradientStop QmlGraphicsGradientStop
+ \brief The GradientStop item defines the color at a position in a Gradient
+
+ \sa Gradient
+*/
+
+/*!
+ \qmlproperty real GradientStop::position
+ \qmlproperty color GradientStop::color
+
+ Sets a \e color at a \e position in a gradient.
+*/
+
+void QmlGraphicsGradientStop::updateGradient()
+{
+ if (QmlGraphicsGradient *grad = qobject_cast<QmlGraphicsGradient*>(parent()))
+ grad->doUpdate();
+}
+
+/*!
+ \qmlclass Gradient QmlGraphicsGradient
+ \brief The Gradient item defines a gradient fill.
+
+ A gradient is defined by two or more colors, which will be blended seemlessly. The
+ colors are specified at their position in the range 0.0 - 1.0 via
+ the GradientStop item. For example, the following code paints a
+ rectangle with a gradient starting with red, blending to yellow at 1/3 of the
+ size of the rectangle, and ending with Green:
+
+ \table
+ \row
+ \o \image gradient.png
+ \o \quotefile doc/src/snippets/declarative/gradient.qml
+ \endtable
+
+ \sa GradientStop
+*/
+
+/*!
+ \qmlproperty list<GradientStop> Gradient::stops
+ This property holds the gradient stops describing the gradient.
+*/
+
+const QGradient *QmlGraphicsGradient::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 QmlGraphicsGradientStop *stop = m_stops.at(i);
+ m_gradient->setCoordinateMode(QGradient::ObjectBoundingMode);
+ m_gradient->setColorAt(stop->position(), stop->color());
+ }
+ }
+
+ return m_gradient;
+}
+
+void QmlGraphicsGradient::doUpdate()
+{
+ delete m_gradient;
+ m_gradient = 0;
+ emit updated();
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Rectangle,QmlGraphicsRectangle)
+
+/*!
+ \qmlclass Rectangle QmlGraphicsRectangle
+ \brief The Rectangle item allows you to add rectangles to a scene.
+ \inherits Item
+
+ A Rectangle is painted having a solid fill (color) and an optional border.
+ You can also create rounded rectangles using the radius property.
+
+ \qml
+ Rectangle {
+ width: 100
+ height: 100
+ color: "red"
+ border.color: "black"
+ border.width: 5
+ radius: 10
+ }
+ \endqml
+
+ \image declarative-rect.png
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsRectangle
+ \brief The QmlGraphicsRectangle class provides a rectangle item that you can add to a QmlView.
+*/
+QmlGraphicsRectangle::QmlGraphicsRectangle(QmlGraphicsItem *parent)
+ : QmlGraphicsItem(*(new QmlGraphicsRectanglePrivate), parent)
+{
+ Q_D(QmlGraphicsRectangle);
+ d->init();
+ setFlag(QGraphicsItem::ItemHasNoContents, false);
+}
+
+void QmlGraphicsRectangle::doUpdate()
+{
+ Q_D(QmlGraphicsRectangle);
+ d->rectImage = QPixmap();
+ const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0;
+ d->setPaintMargin((pw+1)/2);
+ update();
+}
+
+/*!
+ \qmlproperty int Rectangle::border.width
+ \qmlproperty color 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.
+
+ To keep the border smooth (rather than blurry), odd widths cause the rectangle to be painted at
+ a half-pixel offset;
+*/
+QmlGraphicsPen *QmlGraphicsRectangle::border()
+{
+ Q_D(QmlGraphicsRectangle);
+ return d->getPen();
+}
+
+/*!
+ \qmlproperty Gradient 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.
+
+ \table
+ \row
+ \o \image declarative-rect_gradient.png
+ \o
+ \qml
+ Rectangle { y: 0; width: 80; height: 80; color: "lightsteelblue" }
+ Rectangle { y: 100; width: 80; height: 80
+ gradient: Gradient {
+ GradientStop { position: 0.0; color: "lightsteelblue" }
+ GradientStop { position: 1.0; color: "blue" }
+ }
+ }
+ Rectangle { rotation: 90; x: 80; y: 200; width: 80; height: 80
+ gradient: Gradient {
+ GradientStop { position: 0.0; color: "lightsteelblue" }
+ GradientStop { position: 1.0; color: "blue" }
+ }
+ }
+ // The x offset is needed because the rotation is from the top left corner
+ \endqml
+ \endtable
+
+ If both a gradient and a color are specified, the gradient will be used.
+
+ \sa Gradient, color
+*/
+QmlGraphicsGradient *QmlGraphicsRectangle::gradient() const
+{
+ Q_D(const QmlGraphicsRectangle);
+ return d->gradient;
+}
+
+void QmlGraphicsRectangle::setGradient(QmlGraphicsGradient *gradient)
+{
+ Q_D(QmlGraphicsRectangle);
+ if (d->gradient == gradient)
+ return;
+ if (d->gradient)
+ disconnect(d->gradient, SIGNAL(updated()), this, SLOT(doUpdate()));
+ d->gradient = gradient;
+ if (d->gradient)
+ connect(d->gradient, SIGNAL(updated()), this, SLOT(doUpdate()));
+ update();
+}
+
+
+/*!
+ \qmlproperty real 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 QmlGraphicsRectangle::radius() const
+{
+ Q_D(const QmlGraphicsRectangle);
+ return d->radius;
+}
+
+void QmlGraphicsRectangle::setRadius(qreal radius)
+{
+ Q_D(QmlGraphicsRectangle);
+ if (d->radius == radius)
+ return;
+
+ d->radius = radius;
+ d->rectImage = QPixmap();
+ update();
+ emit radiusChanged();
+}
+
+/*!
+ \qmlproperty color Rectangle::color
+ This property holds the color used to fill the rectangle.
+
+ \qml
+ // green rectangle using hexidecimal notation
+ Rectangle { color: "#00FF00" }
+
+ // steelblue rectangle using SVG color name
+ Rectangle { color: "steelblue" }
+ \endqml
+
+ The default color is white.
+
+ If both a gradient and a color are specified, the gradient will be used.
+*/
+QColor QmlGraphicsRectangle::color() const
+{
+ Q_D(const QmlGraphicsRectangle);
+ return d->color;
+}
+
+void QmlGraphicsRectangle::setColor(const QColor &c)
+{
+ Q_D(QmlGraphicsRectangle);
+ if (d->color == c)
+ return;
+
+ d->color = c;
+ d->rectImage = QPixmap();
+ update();
+ emit colorChanged();
+}
+
+void QmlGraphicsRectangle::generateRoundedRect()
+{
+ Q_D(QmlGraphicsRectangle);
+ if (d->rectImage.isNull()) {
+ const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0;
+ const int radius = qCeil(d->radius); //ensure odd numbered width/height so we get 1-pixel center
+ d->rectImage = QPixmap(radius*2 + 3 + pw*2, radius*2 + 3 + pw*2);
+ d->rectImage.fill(Qt::transparent);
+ QPainter p(&(d->rectImage));
+ p.setRenderHint(QPainter::Antialiasing);
+ if (d->pen && d->pen->isValid()) {
+ QPen pn(QColor(d->pen->color()), d->pen->width());
+ p.setPen(pn);
+ } else {
+ p.setPen(Qt::NoPen);
+ }
+ p.setBrush(d->color);
+ if (pw%2)
+ p.drawRoundedRect(QRectF(qreal(pw)/2+1, qreal(pw)/2+1, d->rectImage.width()-(pw+1), d->rectImage.height()-(pw+1)), d->radius, d->radius);
+ else
+ p.drawRoundedRect(QRectF(qreal(pw)/2, qreal(pw)/2, d->rectImage.width()-pw, d->rectImage.height()-pw), d->radius, d->radius);
+ }
+}
+
+void QmlGraphicsRectangle::generateBorderedRect()
+{
+ Q_D(QmlGraphicsRectangle);
+ if (d->rectImage.isNull()) {
+ const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0;
+ d->rectImage = QPixmap(pw*2 + 3, pw*2 + 3);
+ d->rectImage.fill(Qt::transparent);
+ QPainter p(&(d->rectImage));
+ p.setRenderHint(QPainter::Antialiasing);
+ if (d->pen && d->pen->isValid()) {
+ QPen pn(QColor(d->pen->color()), d->pen->width());
+ pn.setJoinStyle(Qt::MiterJoin);
+ p.setPen(pn);
+ } else {
+ p.setPen(Qt::NoPen);
+ }
+ p.setBrush(d->color);
+ if (pw%2)
+ p.drawRect(QRectF(qreal(pw)/2+1, qreal(pw)/2+1, d->rectImage.width()-(pw+1), d->rectImage.height()-(pw+1)));
+ else
+ p.drawRect(QRectF(qreal(pw)/2, qreal(pw)/2, d->rectImage.width()-pw, d->rectImage.height()-pw));
+ }
+}
+
+void QmlGraphicsRectangle::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
+{
+ Q_D(QmlGraphicsRectangle);
+ if (d->radius > 0 || (d->pen && d->pen->isValid())
+ || (d->gradient && d->gradient->gradient()) ) {
+ drawRect(*p);
+ }
+ else {
+ bool oldAA = p->testRenderHint(QPainter::Antialiasing);
+ if (d->smooth)
+ p->setRenderHints(QPainter::Antialiasing, true);
+ p->fillRect(QRectF(0, 0, width(), height()), d->color);
+ if (d->smooth)
+ p->setRenderHint(QPainter::Antialiasing, oldAA);
+ }
+}
+
+void QmlGraphicsRectangle::drawRect(QPainter &p)
+{
+ Q_D(QmlGraphicsRectangle);
+ if (d->gradient && d->gradient->gradient()) {
+ // XXX This path is still slower than the image path
+ // Image path won't work for gradients though
+ bool oldAA = p.testRenderHint(QPainter::Antialiasing);
+ if (d->smooth)
+ p.setRenderHint(QPainter::Antialiasing);
+ if (d->pen && d->pen->isValid()) {
+ QPen pn(QColor(d->pen->color()), d->pen->width());
+ p.setPen(pn);
+ } else {
+ p.setPen(Qt::NoPen);
+ }
+ p.setBrush(*d->gradient->gradient());
+ if (d->radius > 0.)
+ p.drawRoundedRect(0, 0, width(), height(), d->radius, d->radius);
+ else
+ p.drawRect(0, 0, width(), height());
+ if (d->smooth)
+ p.setRenderHint(QPainter::Antialiasing, oldAA);
+ } else {
+ bool oldAA = p.testRenderHint(QPainter::Antialiasing);
+ bool oldSmooth = p.testRenderHint(QPainter::SmoothPixmapTransform);
+ if (d->smooth)
+ p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth);
+
+ const int pw = d->pen && d->pen->isValid() ? (d->pen->width()+1)/2*2 : 0;
+
+ if (d->radius > 0)
+ generateRoundedRect();
+ else
+ generateBorderedRect();
+
+ int xOffset = (d->rectImage.width()-1)/2;
+ int yOffset = (d->rectImage.height()-1)/2;
+ Q_ASSERT(d->rectImage.width() == 2*xOffset + 1);
+ Q_ASSERT(d->rectImage.height() == 2*yOffset + 1);
+
+ QMargins margins(xOffset, yOffset, xOffset, yOffset);
+ QTileRules rules(Qt::StretchTile, Qt::StretchTile);
+ //NOTE: even though our item may have qreal-based width and height, qDrawBorderPixmap only supports QRects
+ qDrawBorderPixmap(&p, QRect(-pw/2, -pw/2, width()+pw, height()+pw), margins, d->rectImage, d->rectImage.rect(), margins, rules);
+
+ if (d->smooth) {
+ p.setRenderHint(QPainter::Antialiasing, oldAA);
+ p.setRenderHint(QPainter::SmoothPixmapTransform, oldSmooth);
+ }
+ }
+}
+
+/*!
+ \qmlproperty bool 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
+*/
+
+QRectF QmlGraphicsRectangle::boundingRect() const
+{
+ Q_D(const QmlGraphicsRectangle);
+ return QRectF(-d->paintmargin, -d->paintmargin, d->width+d->paintmargin*2, d->height+d->paintmargin*2);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsrectangle_p.h b/src/declarative/graphicsitems/qmlgraphicsrectangle_p.h
new file mode 100644
index 0000000..4f4c1cf
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsrectangle_p.h
@@ -0,0 +1,186 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSRECT_H
+#define QMLGRAPHICSRECT_H
+
+#include "qmlgraphicsitem.h"
+
+#include <QtGui/qbrush.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+class Q_DECLARATIVE_EXPORT QmlGraphicsPen : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(int width READ width WRITE setWidth NOTIFY penChanged)
+ Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY penChanged)
+public:
+ QmlGraphicsPen(QObject *parent=0)
+ : QObject(parent), _width(1), _color("#000000"), _valid(false)
+ {}
+
+ int width() const { return _width; }
+ void setWidth(int w);
+
+ QColor color() const { return _color; }
+ void setColor(const QColor &c);
+
+ bool isValid() { return _valid; };
+
+Q_SIGNALS:
+ void penChanged();
+
+private:
+ int _width;
+ QColor _color;
+ bool _valid;
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsGradientStop : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(qreal position READ position WRITE setPosition)
+ Q_PROPERTY(QColor color READ color WRITE setColor)
+
+public:
+ QmlGraphicsGradientStop(QObject *parent=0) : QObject(parent) {}
+
+ qreal position() const { return m_position; }
+ void setPosition(qreal position) { m_position = position; updateGradient(); }
+
+ QColor color() const { return m_color; }
+ void setColor(const QColor &color) { m_color = color; updateGradient(); }
+
+private:
+ void updateGradient();
+
+private:
+ qreal m_position;
+ QColor m_color;
+};
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsGradient : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QList<QmlGraphicsGradientStop *> *stops READ stops)
+ Q_CLASSINFO("DefaultProperty", "stops")
+
+public:
+ QmlGraphicsGradient(QObject *parent=0) : QObject(parent), m_gradient(0) {}
+ ~QmlGraphicsGradient() { delete m_gradient; }
+
+ QList<QmlGraphicsGradientStop *> *stops() { return &m_stops; }
+
+ const QGradient *gradient() const;
+
+Q_SIGNALS:
+ void updated();
+
+private:
+ void doUpdate();
+
+private:
+ QList<QmlGraphicsGradientStop *> m_stops;
+ mutable QGradient *m_gradient;
+ friend class QmlGraphicsGradientStop;
+};
+
+class QmlGraphicsRectanglePrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsRectangle : public QmlGraphicsItem
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
+ Q_PROPERTY(QmlGraphicsGradient *gradient READ gradient WRITE setGradient)
+ Q_PROPERTY(QmlGraphicsPen * border READ border CONSTANT)
+ Q_PROPERTY(qreal radius READ radius WRITE setRadius NOTIFY radiusChanged)
+public:
+ QmlGraphicsRectangle(QmlGraphicsItem *parent=0);
+
+ QColor color() const;
+ void setColor(const QColor &);
+
+ QmlGraphicsPen *border();
+
+ QmlGraphicsGradient *gradient() const;
+ void setGradient(QmlGraphicsGradient *gradient);
+
+ qreal radius() const;
+ void setRadius(qreal radius);
+
+ QRectF boundingRect() const;
+
+ void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+
+Q_SIGNALS:
+ void colorChanged();
+ void radiusChanged();
+
+private Q_SLOTS:
+ void doUpdate();
+
+private:
+ void generateRoundedRect();
+ void generateBorderedRect();
+ void drawRect(QPainter &painter);
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsRectangle)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsRectangle)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsPen)
+QML_DECLARE_TYPE(QmlGraphicsGradientStop)
+QML_DECLARE_TYPE(QmlGraphicsGradient)
+QML_DECLARE_TYPE(QmlGraphicsRectangle)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSRECT_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsrectangle_p_p.h b/src/declarative/graphicsitems/qmlgraphicsrectangle_p_p.h
new file mode 100644
index 0000000..c4bbbe4
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsrectangle_p_p.h
@@ -0,0 +1,109 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSRECT_P_H
+#define QMLGRAPHICSRECT_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 "qmlgraphicsitem_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsGradient;
+class QmlGraphicsRectangle;
+class QmlGraphicsRectanglePrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsRectangle)
+
+public:
+ QmlGraphicsRectanglePrivate() :
+ color(Qt::white), gradient(0), pen(0), radius(0), paintmargin(0)
+ {
+ }
+
+ ~QmlGraphicsRectanglePrivate()
+ {
+ delete pen;
+ }
+
+ void init()
+ {
+ }
+
+ QColor getColor();
+ QColor color;
+ QmlGraphicsGradient *gradient;
+ QmlGraphicsPen *getPen() {
+ if (!pen) {
+ Q_Q(QmlGraphicsRectangle);
+ pen = new QmlGraphicsPen;
+ QObject::connect(pen, SIGNAL(penChanged()), q, SLOT(doUpdate()));
+ }
+ return pen;
+ }
+ QmlGraphicsPen *pen;
+ qreal radius;
+ qreal paintmargin;
+ QPixmap rectImage;
+
+ void setPaintMargin(qreal margin)
+ {
+ Q_Q(QmlGraphicsRectangle);
+ if (margin == paintmargin)
+ return;
+ q->prepareGeometryChange();
+ paintmargin = margin;
+ }
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLGRAPHICSRECT_P_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsrepeater.cpp b/src/declarative/graphicsitems/qmlgraphicsrepeater.cpp
new file mode 100644
index 0000000..99f0faa
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsrepeater.cpp
@@ -0,0 +1,320 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsrepeater_p.h"
+#include "qmlgraphicsrepeater_p_p.h"
+
+#include "qmlgraphicsvisualitemmodel_p.h"
+
+#include <qmllistaccessor_p.h>
+
+#include <qlistmodelinterface_p.h>
+
+QT_BEGIN_NAMESPACE
+QmlGraphicsRepeaterPrivate::QmlGraphicsRepeaterPrivate()
+: model(0), ownModel(false)
+{
+}
+
+QmlGraphicsRepeaterPrivate::~QmlGraphicsRepeaterPrivate()
+{
+ if (ownModel)
+ delete model;
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Repeater,QmlGraphicsRepeater)
+
+/*!
+ \qmlclass Repeater QmlGraphicsRepeater
+ \inherits Item
+
+ \brief The Repeater item allows you to repeat a component based on a model.
+
+ The Repeater item is used when you want to create a large number of
+ similar items. For each entry in the model, an item is instantiated
+ in a context seeded with data from the model. If the repeater will
+ be instantiating a large number of instances, it may be more efficient to
+ use one of Qt Declarative's \l {xmlViews}{view items}.
+
+ The model may be either an object list, a string list, a number or a Qt model.
+ In each case, the data element and the index is exposed to each instantiated
+ component.
+
+ The index is always exposed as an accessible \c index property.
+ In the case of an object or string list, the data element (of type string
+ or object) is available as the \c modelData property. In the case of a Qt model,
+ all roles are available as named properties just like in the view classes. The
+ following example shows how to use the index property inside the instantiated
+ items.
+
+ \snippet doc/src/snippets/declarative/repeater-index.qml 0
+
+ \image repeater-index.png
+
+ 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 is to allow
+ you to use a Repeater inside a layout. The following QML example shows how
+ the instantiated items would visually appear stacked between the red and
+ blue rectangles.
+
+ \snippet doc/src/snippets/declarative/repeater.qml 0
+
+ \image repeater.png
+
+ The repeater instance continues to own all items it instantiates, even
+ if they are otherwise manipulated. It is illegal to manually remove an item
+ created by the Repeater.
+ */
+
+/*!
+ \internal
+ \class QmlGraphicsRepeater
+ \qmlclass Repeater
+
+ XXX Repeater is very conservative in how it instatiates/deletes items. Also
+ new model entries will not be created and old ones will not be removed.
+ */
+
+/*!
+ Create a new QmlGraphicsRepeater instance.
+ */
+QmlGraphicsRepeater::QmlGraphicsRepeater(QmlGraphicsItem *parent)
+ : QmlGraphicsItem(*(new QmlGraphicsRepeaterPrivate), parent)
+{
+}
+
+/*!
+ Destroy the repeater instance. All items it instantiated are also
+ destroyed.
+ */
+QmlGraphicsRepeater::~QmlGraphicsRepeater()
+{
+}
+
+/*!
+ \qmlproperty any Repeater::model
+
+ The model providing data for the repeater.
+
+ The model may be either an object list, a string list, a number or a Qt model.
+ In each case, the data element and the index is exposed to each instantiated
+ component. The index is always exposed as an accessible \c index property.
+ In the case of an object or string list, the data element (of type string
+ or object) is available as the \c modelData property. In the case of a Qt model,
+ all roles are available as named properties just like in the view classes.
+
+ As a special case the model can also be merely a number. In this case it will
+ create that many instances of the component. They will also be assigned an index
+ based on the order they are created.
+
+ Models can also be created directly in QML, using a \l{ListModel} or \l{XmlListModel}.
+
+ \sa {qmlmodels}{Data Models}
+*/
+QVariant QmlGraphicsRepeater::model() const
+{
+ Q_D(const QmlGraphicsRepeater);
+ return d->dataSource;
+}
+
+void QmlGraphicsRepeater::setModel(const QVariant &model)
+{
+ Q_D(QmlGraphicsRepeater);
+ clear();
+ if (d->model) {
+ disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
+ disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
+ disconnect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));
+ /*
+ disconnect(d->model, SIGNAL(createdItem(int, QmlGraphicsItem*)), this, SLOT(createdItem(int,QmlGraphicsItem*)));
+ disconnect(d->model, SIGNAL(destroyingItem(QmlGraphicsItem*)), this, SLOT(destroyingItem(QmlGraphicsItem*)));
+ */
+ }
+ d->dataSource = model;
+ QObject *object = qvariant_cast<QObject*>(model);
+ QmlGraphicsVisualModel *vim = 0;
+ if (object && (vim = qobject_cast<QmlGraphicsVisualModel *>(object))) {
+ if (d->ownModel) {
+ delete d->model;
+ d->ownModel = false;
+ }
+ d->model = vim;
+ } else {
+ if (!d->ownModel) {
+ d->model = new QmlGraphicsVisualDataModel(qmlContext(this));
+ d->ownModel = true;
+ }
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model))
+ dataModel->setModel(model);
+ }
+ if (d->model) {
+ connect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
+ connect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
+ connect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));
+ /*
+ connect(d->model, SIGNAL(createdItem(int, QmlGraphicsItem*)), this, SLOT(createdItem(int,QmlGraphicsItem*)));
+ connect(d->model, SIGNAL(destroyingItem(QmlGraphicsItem*)), this, SLOT(destroyingItem(QmlGraphicsItem*)));
+ */
+ regenerate();
+ emit countChanged();
+ }
+}
+
+/*!
+ \qmlproperty Component Repeater::delegate
+ \default
+
+ The delegate provides a template defining each item instantiated by the repeater.
+ 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}.
+ */
+QmlComponent *QmlGraphicsRepeater::delegate() const
+{
+ Q_D(const QmlGraphicsRepeater);
+ if (d->model) {
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model))
+ return dataModel->delegate();
+ }
+
+ return 0;
+}
+
+void QmlGraphicsRepeater::setDelegate(QmlComponent *delegate)
+{
+ Q_D(QmlGraphicsRepeater);
+ if (!d->ownModel) {
+ d->model = new QmlGraphicsVisualDataModel(qmlContext(this));
+ d->ownModel = true;
+ }
+ if (QmlGraphicsVisualDataModel *dataModel = qobject_cast<QmlGraphicsVisualDataModel*>(d->model)) {
+ dataModel->setDelegate(delegate);
+ regenerate();
+ }
+}
+
+/*!
+ \qmlproperty int Repeater::count
+
+ This property holds the number of items in the repeater.
+*/
+int QmlGraphicsRepeater::count() const
+{
+ Q_D(const QmlGraphicsRepeater);
+ if (d->model)
+ return d->model->count();
+ return 0;
+}
+
+
+/*!
+ \internal
+ */
+void QmlGraphicsRepeater::componentComplete()
+{
+ QmlGraphicsItem::componentComplete();
+ regenerate();
+}
+
+/*!
+ \internal
+ */
+QVariant QmlGraphicsRepeater::itemChange(GraphicsItemChange change,
+ const QVariant &value)
+{
+ QVariant rv = QmlGraphicsItem::itemChange(change, value);
+ if (change == ItemParentHasChanged) {
+ regenerate();
+ }
+
+ return rv;
+}
+
+void QmlGraphicsRepeater::clear()
+{
+ Q_D(QmlGraphicsRepeater);
+ if (d->model) {
+ foreach (QmlGraphicsItem *item, d->deletables) {
+ item->setParentItem(this);
+ d->model->release(item);
+ }
+ }
+ d->deletables.clear();
+}
+
+/*!
+ \internal
+ */
+void QmlGraphicsRepeater::regenerate()
+{
+ Q_D(QmlGraphicsRepeater);
+
+ clear();
+
+ if (!d->model || !d->model->count() || !d->model->isValid() || !parentItem() || !isComponentComplete())
+ return;
+
+ for (int ii = 0; ii < count(); ++ii) {
+ QmlGraphicsItem *item = d->model->item(ii);
+ if (item) {
+ item->setParent(parentItem());
+ item->stackBefore(this);
+ d->deletables << item;
+ }
+ }
+}
+
+void QmlGraphicsRepeater::itemsInserted(int, int)
+{
+ regenerate();
+}
+
+void QmlGraphicsRepeater::itemsRemoved(int, int)
+{
+ regenerate();
+}
+
+void QmlGraphicsRepeater::itemsMoved(int,int,int)
+{
+ regenerate();
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsrepeater_p.h b/src/declarative/graphicsitems/qmlgraphicsrepeater_p.h
new file mode 100644
index 0000000..61f82d7
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsrepeater_p.h
@@ -0,0 +1,102 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSREPEATER_H
+#define QMLGRAPHICSREPEATER_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsRepeaterPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsRepeater : public QmlGraphicsItem
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QVariant model READ model WRITE setModel)
+ Q_PROPERTY(QmlComponent *delegate READ delegate WRITE setDelegate)
+ Q_PROPERTY(int count READ count NOTIFY countChanged)
+ Q_CLASSINFO("DefaultProperty", "delegate")
+
+public:
+ QmlGraphicsRepeater(QmlGraphicsItem *parent=0);
+ virtual ~QmlGraphicsRepeater();
+
+ QVariant model() const;
+ void setModel(const QVariant &);
+
+ QmlComponent *delegate() const;
+ void setDelegate(QmlComponent *);
+
+ int count() const;
+
+Q_SIGNALS:
+ void countChanged();
+
+private:
+ void clear();
+ void regenerate();
+
+protected:
+ virtual void componentComplete();
+ QVariant itemChange(GraphicsItemChange change, const QVariant &value);
+
+private Q_SLOTS:
+ void itemsInserted(int,int);
+ void itemsRemoved(int,int);
+ void itemsMoved(int,int,int);
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsRepeater)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsRepeater)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsRepeater)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSREPEATER_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsrepeater_p_p.h b/src/declarative/graphicsitems/qmlgraphicsrepeater_p_p.h
new file mode 100644
index 0000000..e6d7bfd
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsrepeater_p_p.h
@@ -0,0 +1,82 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSREPEATER_P_H
+#define QMLGRAPHICSREPEATER_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 "qmlgraphicsrepeater_p.h"
+
+#include "qmlgraphicsitem_p.h"
+
+#include <QPointer>
+
+QT_BEGIN_NAMESPACE
+
+class QmlContext;
+class QmlGraphicsVisualModel;
+class QmlGraphicsRepeaterPrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsRepeater)
+
+public:
+ QmlGraphicsRepeaterPrivate();
+ ~QmlGraphicsRepeaterPrivate();
+
+ QmlGraphicsVisualModel *model;
+ QVariant dataSource;
+ bool ownModel;
+
+ QList<QPointer<QmlGraphicsItem> > deletables;
+};
+
+QT_END_NAMESPACE
+#endif // QMLGRAPHICSREPEATER_P_H
diff --git a/src/declarative/graphicsitems/qmlgraphicsscalegrid.cpp b/src/declarative/graphicsitems/qmlgraphicsscalegrid.cpp
new file mode 100644
index 0000000..f50b79b
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsscalegrid.cpp
@@ -0,0 +1,213 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsscalegrid_p_p.h"
+
+#include <qml.h>
+
+#include <QBuffer>
+#include <QDebug>
+
+QT_BEGIN_NAMESPACE
+/*!
+ \internal
+ \class QmlGraphicsScaleGrid
+ \brief The QmlGraphicsScaleGrid class allows you to specify a 3x3 grid to use in scaling an image.
+*/
+QML_DEFINE_NOCREATE_TYPE(QmlGraphicsScaleGrid)
+
+QmlGraphicsScaleGrid::QmlGraphicsScaleGrid(QObject *parent) : QObject(parent), _left(0), _top(0), _right(0), _bottom(0)
+{
+}
+
+QmlGraphicsScaleGrid::~QmlGraphicsScaleGrid()
+{
+}
+
+bool QmlGraphicsScaleGrid::isNull() const
+{
+ return !_left && !_top && !_right && !_bottom;
+}
+
+void QmlGraphicsScaleGrid::setLeft(int pos)
+{
+ if (_left != pos) {
+ _left = pos;
+ emit borderChanged();
+ }
+}
+
+void QmlGraphicsScaleGrid::setTop(int pos)
+{
+ if (_top != pos) {
+ _top = pos;
+ emit borderChanged();
+ }
+}
+
+void QmlGraphicsScaleGrid::setRight(int pos)
+{
+ if (_right != pos) {
+ _right = pos;
+ emit borderChanged();
+ }
+}
+
+void QmlGraphicsScaleGrid::setBottom(int pos)
+{
+ if (_bottom != pos) {
+ _bottom = pos;
+ emit borderChanged();
+ }
+}
+
+QmlGraphicsGridScaledImage::QmlGraphicsGridScaledImage()
+: _l(-1), _r(-1), _t(-1), _b(-1),
+ _h(QmlGraphicsBorderImage::Stretch), _v(QmlGraphicsBorderImage::Stretch)
+{
+}
+
+QmlGraphicsGridScaledImage::QmlGraphicsGridScaledImage(const QmlGraphicsGridScaledImage &o)
+: _l(o._l), _r(o._r), _t(o._t), _b(o._b), _h(o._h), _v(o._v), _pix(o._pix)
+{
+}
+
+QmlGraphicsGridScaledImage &QmlGraphicsGridScaledImage::operator=(const QmlGraphicsGridScaledImage &o)
+{
+ _l = o._l;
+ _r = o._r;
+ _t = o._t;
+ _b = o._b;
+ _h = o._h;
+ _v = o._v;
+ _pix = o._pix;
+ return *this;
+}
+
+QmlGraphicsGridScaledImage::QmlGraphicsGridScaledImage(QIODevice *data)
+: _l(-1), _r(-1), _t(-1), _b(-1), _h(QmlGraphicsBorderImage::Stretch), _v(QmlGraphicsBorderImage::Stretch)
+{
+ int l = -1;
+ int r = -1;
+ int t = -1;
+ int b = -1;
+ QString imgFile;
+
+ while(!data->atEnd()) {
+ QString line = QString::fromUtf8(data->readLine().trimmed());
+ if (line.isEmpty() || line.startsWith(QLatin1Char('#')))
+ continue;
+
+ QStringList list = line.split(QLatin1Char(':'));
+ if (list.count() != 2)
+ return;
+
+ list[0] = list[0].trimmed();
+ list[1] = list[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;
+}
+
+QmlGraphicsBorderImage::TileMode QmlGraphicsGridScaledImage::stringToRule(const QString &s)
+{
+ if (s == QLatin1String("Stretch"))
+ return QmlGraphicsBorderImage::Stretch;
+ if (s == QLatin1String("Repeat"))
+ return QmlGraphicsBorderImage::Repeat;
+ if (s == QLatin1String("Round"))
+ return QmlGraphicsBorderImage::Round;
+
+ qWarning() << "Unknown tile rule specified. Using Stretch";
+ return QmlGraphicsBorderImage::Stretch;
+}
+
+bool QmlGraphicsGridScaledImage::isValid() const
+{
+ return _l >= 0;
+}
+
+int QmlGraphicsGridScaledImage::gridLeft() const
+{
+ return _l;
+}
+
+int QmlGraphicsGridScaledImage::gridRight() const
+{
+ return _r;
+}
+
+int QmlGraphicsGridScaledImage::gridTop() const
+{
+ return _t;
+}
+
+int QmlGraphicsGridScaledImage::gridBottom() const
+{
+ return _b;
+}
+
+QString QmlGraphicsGridScaledImage::pixmapUrl() const
+{
+ return _pix;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicsscalegrid_p_p.h b/src/declarative/graphicsitems/qmlgraphicsscalegrid_p_p.h
new file mode 100644
index 0000000..88938a7
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsscalegrid_p_p.h
@@ -0,0 +1,133 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSSCALEGRID_H
+#define QMLGRAPHICSSCALEGRID_H
+
+#include "qmlgraphicsborderimage_p.h"
+
+#include "../util/qmlpixmapcache_p.h"
+#include <qml.h>
+
+#include <QtCore/QString>
+#include <QtCore/QObject>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsScaleGrid : 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:
+ QmlGraphicsScaleGrid(QObject *parent=0);
+ ~QmlGraphicsScaleGrid();
+
+ 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_EXPORT QmlGraphicsGridScaledImage
+{
+public:
+ QmlGraphicsGridScaledImage();
+ QmlGraphicsGridScaledImage(const QmlGraphicsGridScaledImage &);
+ QmlGraphicsGridScaledImage(QIODevice*);
+ QmlGraphicsGridScaledImage &operator=(const QmlGraphicsGridScaledImage &);
+ bool isValid() const;
+ int gridLeft() const;
+ int gridRight() const;
+ int gridTop() const;
+ int gridBottom() const;
+ QmlGraphicsBorderImage::TileMode horizontalTileRule() const { return _h; }
+ QmlGraphicsBorderImage::TileMode verticalTileRule() const { return _v; }
+
+ QString pixmapUrl() const;
+
+private:
+ static QmlGraphicsBorderImage::TileMode stringToRule(const QString &);
+
+private:
+ int _l;
+ int _r;
+ int _t;
+ int _b;
+ QmlGraphicsBorderImage::TileMode _h;
+ QmlGraphicsBorderImage::TileMode _v;
+ QString _pix;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsScaleGrid)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSSCALEGRID_H
diff --git a/src/declarative/graphicsitems/qmlgraphicstext.cpp b/src/declarative/graphicsitems/qmlgraphicstext.cpp
new file mode 100644
index 0000000..b13fb7c
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicstext.cpp
@@ -0,0 +1,927 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicstext_p.h"
+#include "qmlgraphicstext_p_p.h"
+#include <qmlstyledtext_p.h>
+
+#include <qfxperf_p_p.h>
+
+#include <QTextLayout>
+#include <QTextLine>
+#include <QTextDocument>
+#include <QTextCursor>
+#include <QGraphicsSceneMouseEvent>
+#include <QPainter>
+#include <QAbstractTextDocumentLayout>
+#include <qmath.h>
+
+QT_BEGIN_NAMESPACE
+QML_DEFINE_TYPE(Qt,4,6,Text,QmlGraphicsText)
+
+/*!
+ \qmlclass Text QmlGraphicsText
+ \brief The Text item allows you to add formatted text to a scene.
+ \inherits Item
+
+ It can display both plain and rich text. For example:
+
+ \qml
+ Text { text: "Hello World!"; font.family: "Helvetica"; font.pointSize: 24; color: "red" }
+ 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 \c wrap is set, it will always
+ prefer width to height (all text will be placed on a single line).
+
+ The \c elide property can alternatively be used to fit a single line of
+ plain text to a set width.
+
+ Text provides read-only text. For editable text, see \l TextEdit.
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsText
+ \qmlclass Text
+ \ingroup group_coreitems
+
+ \brief The QmlGraphicsText class provides a formatted text item that you can add to a QmlView.
+
+ Text was designed for read-only text; it does not allow for any text editing.
+ It can display both plain and rich text. For example:
+
+ \qml
+ Text { text: "Hello World!"; font.family: "Helvetica"; font.pointSize: 24; color: "red" }
+ Text { text: "<b>Hello</b> <i>World!</i>" }
+ \endqml
+
+ \image 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 \c wrap is set, it will always
+ prefer width to height (all text will be placed on a single line).
+
+ The \c elide property can alternatively be used to fit a line of plain text to a set width.
+
+ A QmlGraphicsText object can be instantiated in Qml using the tag \c Text.
+*/
+QmlGraphicsText::QmlGraphicsText(QmlGraphicsItem *parent)
+ : QmlGraphicsItem(*(new QmlGraphicsTextPrivate), parent)
+{
+ setAcceptedMouseButtons(Qt::LeftButton);
+ setFlag(QGraphicsItem::ItemHasNoContents, false);
+}
+
+QmlGraphicsText::~QmlGraphicsText()
+{
+}
+
+
+QmlGraphicsTextPrivate::~QmlGraphicsTextPrivate()
+{
+}
+
+/*!
+ \qmlproperty string Text::font.family
+ \qmlproperty bool Text::font.bold
+ \qmlproperty bool Text::font.italic
+ \qmlproperty bool Text::font.underline
+ \qmlproperty real Text::font.pointSize
+ \qmlproperty int Text::font.pixelSize
+
+ Set the Text's font attributes.
+*/
+QFont QmlGraphicsText::font() const
+{
+ Q_D(const QmlGraphicsText);
+ return d->font;
+}
+
+void QmlGraphicsText::setFont(const QFont &font)
+{
+ Q_D(QmlGraphicsText);
+ if (d->font == font)
+ return;
+
+ d->font = font;
+
+ d->updateLayout();
+ d->markImgDirty();
+ emit fontChanged(d->font);
+}
+
+void QmlGraphicsText::setText(const QString &n)
+{
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::QmlGraphicsText_setText> st;
+#endif
+ Q_D(QmlGraphicsText);
+ if (d->text == n)
+ return;
+
+ d->richText = d->format == RichText || (d->format == AutoText && Qt::mightBeRichText(n));
+ if (d->richText) {
+ if (!d->doc) {
+ d->doc = new QTextDocument(this);
+ d->doc->setDocumentMargin(0);
+ }
+ d->doc->setHtml(n);
+ }
+
+ d->text = n;
+ d->updateLayout();
+ d->markImgDirty();
+ emit textChanged(d->text);
+}
+
+/*!
+ \qmlproperty string 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 rich text. This determination is made using Qt::mightBeRichText().
+*/
+QString QmlGraphicsText::text() const
+{
+ Q_D(const QmlGraphicsText);
+ return d->text;
+}
+
+void QmlGraphicsText::setColor(const QColor &color)
+{
+ Q_D(QmlGraphicsText);
+ if (d->color == color)
+ return;
+
+ d->color = color;
+ d->markImgDirty();
+ emit colorChanged(d->color);
+}
+
+/*!
+ \qmlproperty color Text::color
+
+ The text color.
+
+ \qml
+ //green text using hexadecimal notation
+ Text { color: "#00FF00"; ... }
+
+ //steelblue text using SVG color name
+ Text { color: "steelblue"; ... }
+ \endqml
+*/
+
+QColor QmlGraphicsText::color() const
+{
+ Q_D(const QmlGraphicsText);
+ return d->color;
+}
+
+/*!
+ \qmlproperty enumeration Text::style
+
+ Set an additional text style.
+
+ Supported text styles are \c Normal, \c Outline, \c Raised and \c Sunken.
+
+ \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
+*/
+QmlGraphicsText::TextStyle QmlGraphicsText::style() const
+{
+ Q_D(const QmlGraphicsText);
+ return d->style;
+}
+
+void QmlGraphicsText::setStyle(QmlGraphicsText::TextStyle style)
+{
+ Q_D(QmlGraphicsText);
+ if (d->style == style)
+ return;
+
+ d->style = style;
+ d->markImgDirty();
+ emit styleChanged(d->style);
+}
+
+void QmlGraphicsText::setStyleColor(const QColor &color)
+{
+ Q_D(QmlGraphicsText);
+ if (d->styleColor == color)
+ return;
+
+ d->styleColor = color;
+ d->markImgDirty();
+ emit styleColorChanged(d->styleColor);
+}
+
+/*!
+ \qmlproperty color 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.
+ */
+QColor QmlGraphicsText::styleColor() const
+{
+ Q_D(const QmlGraphicsText);
+ return d->styleColor;
+}
+
+/*!
+ \qmlproperty enumeration Text::horizontalAlignment
+ \qmlproperty enumeration Text::verticalAlignment
+
+ Sets the horizontal and vertical alignment of the text within the Text items
+ width and height. By default, the text is top-left aligned.
+
+ The valid values for \c horizontalAlignment are \c AlignLeft, \c AlignRight and
+ \c AlignHCenter. The valid values for \c verticalAlignment are \c AlignTop, \c AlignBottom
+ and \c AlignVCenter.
+*/
+QmlGraphicsText::HAlignment QmlGraphicsText::hAlign() const
+{
+ Q_D(const QmlGraphicsText);
+ return d->hAlign;
+}
+
+void QmlGraphicsText::setHAlign(HAlignment align)
+{
+ Q_D(QmlGraphicsText);
+ if (d->hAlign == align)
+ return;
+
+ d->hAlign = align;
+ emit horizontalAlignmentChanged(align);
+}
+
+QmlGraphicsText::VAlignment QmlGraphicsText::vAlign() const
+{
+ Q_D(const QmlGraphicsText);
+ return d->vAlign;
+}
+
+void QmlGraphicsText::setVAlign(VAlignment align)
+{
+ Q_D(QmlGraphicsText);
+ if (d->vAlign == align)
+ return;
+
+ d->vAlign = align;
+ emit verticalAlignmentChanged(align);
+}
+
+/*!
+ \qmlproperty bool Text::wrap
+
+ 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.
+
+ Wrapping is done on word boundaries (i.e. it is a "word-wrap"). If the text cannot be
+ word-wrapped to the specified width it will be partially drawn outside of the item's bounds.
+ If this is undesirable then enable clipping on the item (Item::clip).
+
+ Wrapping is off by default.
+*/
+//### Future may provide choice of wrap modes, such as QTextOption::WrapAtWordBoundaryOrAnywhere
+bool QmlGraphicsText::wrap() const
+{
+ Q_D(const QmlGraphicsText);
+ return d->wrap;
+}
+
+void QmlGraphicsText::setWrap(bool w)
+{
+ Q_D(QmlGraphicsText);
+ if (w == d->wrap)
+ return;
+
+ d->wrap = w;
+
+ d->updateLayout();
+ d->markImgDirty();
+ emit wrapChanged(d->wrap);
+}
+
+/*!
+ \qmlproperty enumeration Text::textFormat
+
+ The way the text property should be displayed.
+
+ Supported text formats are \c AutoText, \c PlainText, \c RichText and \c StyledText
+
+ The default is AutoText. If the text format is AutoText the text element
+ will automatically determine whether the text should be treated as
+ rich text. This determination is made using Qt::mightBeRichText().
+
+ StyledText is an optimized format supporting some basic text
+ styling markup, in the style of html 3.2:
+
+ \code
+ <font size="4" color="#ff0000">font size and color</font>
+ <b>bold</b>
+ <i>italic</i>
+ <br>
+ &gt; &lt; &amp;
+ \endcode
+
+ \c StyledText parser is strict, requiring tags to be correctly nested.
+
+ \table
+ \row
+ \o
+ \qml
+Column {
+ TextEdit {
+ font.pointSize: 24
+ text: "<b>Hello</b> <i>World!</i>"
+ }
+ TextEdit {
+ font.pointSize: 24
+ textFormat: "RichText"
+ text: "<b>Hello</b> <i>World!</i>"
+ }
+ TextEdit {
+ font.pointSize: 24
+ textFormat: "PlainText"
+ text: "<b>Hello</b> <i>World!</i>"
+ }
+}
+ \endqml
+ \o \image declarative-textformat.png
+ \endtable
+*/
+
+QmlGraphicsText::TextFormat QmlGraphicsText::textFormat() const
+{
+ Q_D(const QmlGraphicsText);
+ return d->format;
+}
+
+void QmlGraphicsText::setTextFormat(TextFormat format)
+{
+ Q_D(QmlGraphicsText);
+ if (format == d->format)
+ return;
+ d->format = format;
+ bool wasRich = d->richText;
+ d->richText = format == RichText || (format == AutoText && Qt::mightBeRichText(d->text));
+
+ if (wasRich && !d->richText) {
+ //### delete control? (and vice-versa below)
+ d->updateLayout();
+ d->markImgDirty();
+ } else if (!wasRich && d->richText) {
+ if (!d->doc) {
+ d->doc = new QTextDocument(this);
+ d->doc->setDocumentMargin(0);
+ }
+ d->doc->setHtml(d->text);
+ d->updateLayout();
+ d->markImgDirty();
+ }
+
+ emit textFormatChanged(d->format);
+}
+
+/*!
+ \qmlproperty enumeration 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 wrap enabled or with rich text.
+
+ Eliding can be \c ElideNone (the default), \c ElideLeft, \c ElideMiddle, or \c ElideRight.
+
+ If the text is a multi-length string, and the mode is not \c 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"}).
+*/
+QmlGraphicsText::TextElideMode QmlGraphicsText::elideMode() const
+{
+ Q_D(const QmlGraphicsText);
+ return d->elideMode;
+}
+
+void QmlGraphicsText::setElideMode(QmlGraphicsText::TextElideMode mode)
+{
+ Q_D(QmlGraphicsText);
+ if (mode == d->elideMode)
+ return;
+
+ d->elideMode = mode;
+
+ d->updateLayout();
+ d->markImgDirty();
+ emit elideModeChanged(d->elideMode);
+}
+
+void QmlGraphicsText::geometryChanged(const QRectF &newGeometry,
+ const QRectF &oldGeometry)
+{
+ Q_D(QmlGraphicsText);
+ if (newGeometry.width() != oldGeometry.width()) {
+ if (d->wrap || d->elideMode != QmlGraphicsText::ElideNone) {
+ //re-elide if needed
+ if (d->singleline && d->elideMode != QmlGraphicsText::ElideNone &&
+ isComponentComplete() && widthValid()) {
+
+ QFontMetrics fm(d->font);
+ QString tmp = fm.elidedText(d->text,(Qt::TextElideMode)d->elideMode,width()); // XXX still worth layout...?
+ d->layout.setText(tmp);
+ }
+
+ d->imgDirty = true;
+ d->updateSize();
+ }
+ }
+ QmlGraphicsItem::geometryChanged(newGeometry, oldGeometry);
+}
+
+void QmlGraphicsTextPrivate::updateLayout()
+{
+ Q_Q(QmlGraphicsText);
+ if (q->isComponentComplete()) {
+ //setup instance of QTextLayout for all cases other than richtext
+ if (!richText) {
+ layout.clearLayout();
+ layout.setFont(font);
+ if (format != QmlGraphicsText::StyledText) {
+ QString tmp = text;
+ tmp.replace(QLatin1Char('\n'), QChar::LineSeparator);
+ singleline = !tmp.contains(QChar::LineSeparator);
+ if (singleline && elideMode != QmlGraphicsText::ElideNone && q->widthValid()) {
+ QFontMetrics fm(font);
+ tmp = fm.elidedText(tmp,(Qt::TextElideMode)elideMode,q->width()); // XXX still worth layout...?
+ }
+ layout.setText(tmp);
+ } else {
+ singleline = false;
+ QmlStyledText::parse(text, layout);
+ }
+ }
+ updateSize();
+ } else {
+ dirty = true;
+ }
+}
+
+void QmlGraphicsTextPrivate::updateSize()
+{
+ Q_Q(QmlGraphicsText);
+ if (q->isComponentComplete()) {
+ QFontMetrics fm(font);
+ if (text.isEmpty()) {
+ q->setImplicitHeight(fm.height());
+ return;
+ }
+
+ int dy = q->height();
+ QSize size(0, 0);
+
+ //setup instance of QTextLayout for all cases other than richtext
+ if (!richText) {
+ size = setupTextLayout(&layout);
+ cachedLayoutSize = size;
+ dy -= size.height();
+ } else {
+ singleline = false; // richtext can't elide or be optimized for single-line case
+ doc->setDefaultFont(font);
+ QTextOption option((Qt::Alignment)int(hAlign | vAlign));
+ if (wrap)
+ option.setWrapMode(QTextOption::WordWrap);
+ else
+ option.setWrapMode(QTextOption::NoWrap);
+ doc->setDefaultTextOption(option);
+ if (wrap && !q->heightValid() && 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();
+ }
+ int yoff = 0;
+
+ if (q->heightValid()) {
+ if (vAlign == QmlGraphicsText::AlignBottom)
+ yoff = dy;
+ else if (vAlign == QmlGraphicsText::AlignVCenter)
+ yoff = dy/2;
+ }
+ q->setBaselineOffset(fm.ascent() + yoff);
+
+ //### need to comfirm cost of always setting these for richText
+ q->setImplicitWidth(richText ? (int)doc->idealWidth() : size.width());
+ q->setImplicitHeight(richText ? (int)doc->size().height() : size.height());
+ } else {
+ dirty = true;
+ }
+}
+
+// ### text layout handling should be profiled and optimized as needed
+// what about QStackTextEngine engine(tmp, d->font.font()); QTextLayout textLayout(&engine);
+
+void QmlGraphicsTextPrivate::drawOutline()
+{
+ QPixmap img = QPixmap(imgStyleCache.width()+2,imgStyleCache.height()+2);
+ img.fill(Qt::transparent);
+
+ QPainter ppm(&img);
+
+ QPoint pos(imgCache.rect().topLeft());
+ pos += QPoint(-1, 0);
+ ppm.drawPixmap(pos, imgStyleCache);
+ pos += QPoint(2, 0);
+ ppm.drawPixmap(pos, imgStyleCache);
+ pos += QPoint(-1, -1);
+ ppm.drawPixmap(pos, imgStyleCache);
+ pos += QPoint(0, 2);
+ ppm.drawPixmap(pos, imgStyleCache);
+
+ pos += QPoint(0, -1);
+ ppm.drawPixmap(pos, imgCache);
+ ppm.end();
+
+ imgCache = img;
+}
+
+void QmlGraphicsTextPrivate::drawOutline(int yOffset)
+{
+ QPixmap img = QPixmap(imgStyleCache.width()+2,imgStyleCache.height()+2);
+ img.fill(Qt::transparent);
+
+ QPainter ppm(&img);
+
+ QPoint pos(imgCache.rect().topLeft());
+ pos += QPoint(0, yOffset);
+ ppm.drawPixmap(pos, imgStyleCache);
+
+ pos += QPoint(0, -yOffset);
+ ppm.drawPixmap(pos, imgCache);
+ ppm.end();
+
+ imgCache = img;
+}
+
+QSize QmlGraphicsTextPrivate::setupTextLayout(QTextLayout *layout)
+{
+ Q_Q(QmlGraphicsText);
+ layout->setCacheEnabled(true);
+
+ int height = 0;
+ qreal widthUsed = 0;
+ qreal lineWidth = 0;
+
+ //set manual width
+ if ((wrap || elideMode != QmlGraphicsText::ElideNone) && q->widthValid())
+ lineWidth = q->width();
+
+ layout->beginLayout();
+
+ while (1) {
+ QTextLine line = layout->createLine();
+ if (!line.isValid())
+ break;
+
+ if ((wrap || elideMode != QmlGraphicsText::ElideNone) && q->widthValid())
+ line.setLineWidth(lineWidth);
+ }
+ layout->endLayout();
+
+ int x = 0;
+ for (int i = 0; i < layout->lineCount(); ++i) {
+ QTextLine line = layout->lineAt(i);
+ widthUsed = qMax(widthUsed, line.naturalTextWidth());
+ line.setPosition(QPointF(0, height));
+ height += int(line.height());
+
+ if (!cache) {
+ if (hAlign == QmlGraphicsText::AlignLeft) {
+ x = 0;
+ } else if (hAlign == QmlGraphicsText::AlignRight) {
+ x = q->width() - (int)line.naturalTextWidth();
+ } else if (hAlign == QmlGraphicsText::AlignHCenter) {
+ x = (q->width() - (int)line.naturalTextWidth()) / 2;
+ }
+ line.setPosition(QPoint(x, (int)line.y()));
+ }
+ }
+
+ return QSize(qCeil(widthUsed), height);
+}
+
+QPixmap QmlGraphicsTextPrivate::wrappedTextImage(bool drawStyle)
+{
+ //do layout
+ QSize size = cachedLayoutSize;
+
+ int x = 0;
+ for (int i = 0; i < layout.lineCount(); ++i) {
+ QTextLine line = layout.lineAt(i);
+ if (hAlign == QmlGraphicsText::AlignLeft) {
+ x = 0;
+ } else if (hAlign == QmlGraphicsText::AlignRight) {
+ x = size.width() - (int)line.naturalTextWidth();
+ } else if (hAlign == QmlGraphicsText::AlignHCenter) {
+ x = (size.width() - (int)line.naturalTextWidth()) / 2;
+ }
+ line.setPosition(QPoint(x, (int)line.y()));
+ }
+
+ //paint text
+ QPixmap img(size);
+ if (!size.isEmpty()) {
+ img.fill(Qt::transparent);
+ QPainter p(&img);
+ drawWrappedText(&p, QPointF(0,0), drawStyle);
+ }
+ return img;
+}
+
+void QmlGraphicsTextPrivate::drawWrappedText(QPainter *p, const QPointF &pos, bool drawStyle)
+{
+ if (drawStyle)
+ p->setPen(styleColor);
+ else
+ p->setPen(color);
+ p->setFont(font);
+ layout.draw(p, pos);
+}
+
+QPixmap QmlGraphicsTextPrivate::richTextImage(bool drawStyle)
+{
+ QSize size = doc->size().toSize();
+
+ //paint text
+ QPixmap img(size);
+ img.fill(Qt::transparent);
+ QPainter p(&img);
+
+ QAbstractTextDocumentLayout::PaintContext context;
+
+ if (drawStyle) {
+ context.palette.setColor(QPalette::Text, styleColor);
+ // ### Do we really want this?
+ QTextOption colorOption;
+ colorOption.setFlags(QTextOption::SuppressColors);
+ doc->setDefaultTextOption(colorOption);
+ } else {
+ context.palette.setColor(QPalette::Text, color);
+ }
+ doc->documentLayout()->draw(&p, context);
+ if (drawStyle)
+ doc->setDefaultTextOption(QTextOption());
+ return img;
+}
+
+void QmlGraphicsTextPrivate::checkImgCache()
+{
+ if (!imgDirty)
+ return;
+
+ bool empty = text.isEmpty();
+ if (empty) {
+ imgCache = QPixmap();
+ imgStyleCache = QPixmap();
+ } else if (richText) {
+ imgCache = richTextImage(false);
+ if (style != QmlGraphicsText::Normal)
+ imgStyleCache = richTextImage(true); //### should use styleColor
+ } else {
+ imgCache = wrappedTextImage(false);
+ if (style != QmlGraphicsText::Normal)
+ imgStyleCache = wrappedTextImage(true); //### should use styleColor
+ }
+ if (!empty)
+ switch (style) {
+ case QmlGraphicsText::Outline:
+ drawOutline();
+ break;
+ case QmlGraphicsText::Sunken:
+ drawOutline(-1);
+ break;
+ case QmlGraphicsText::Raised:
+ drawOutline(1);
+ break;
+ default:
+ break;
+ }
+
+ imgDirty = false;
+}
+
+void QmlGraphicsText::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
+{
+ Q_D(QmlGraphicsText);
+
+ if (d->cache || d->richText || d->style != Normal) {
+ d->checkImgCache();
+ if (d->imgCache.isNull())
+ return;
+
+ bool oldAA = p->testRenderHint(QPainter::Antialiasing);
+ bool oldSmooth = p->testRenderHint(QPainter::SmoothPixmapTransform);
+ if (d->smooth)
+ p->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth);
+
+ int w = width();
+ int h = height();
+
+ int x = 0;
+ int y = 0;
+
+ switch (d->hAlign) {
+ case AlignLeft:
+ x = 0;
+ break;
+ case AlignRight:
+ x = w - d->imgCache.width();
+ break;
+ case AlignHCenter:
+ x = (w - d->imgCache.width()) / 2;
+ break;
+ }
+
+ switch (d->vAlign) {
+ case AlignTop:
+ y = 0;
+ break;
+ case AlignBottom:
+ y = h - d->imgCache.height();
+ break;
+ case AlignVCenter:
+ y = (h - d->imgCache.height()) / 2;
+ break;
+ }
+
+ bool needClip = !clip() && (d->imgCache.width() > width() ||
+ d->imgCache.height() > height());
+
+ if (needClip) {
+ p->save();
+ p->setClipRect(boundingRect(), Qt::IntersectClip);
+ }
+ p->drawPixmap(x, y, d->imgCache);
+ if (needClip)
+ p->restore();
+
+ if (d->smooth) {
+ p->setRenderHint(QPainter::Antialiasing, oldAA);
+ p->setRenderHint(QPainter::SmoothPixmapTransform, oldSmooth);
+ }
+ } else {
+ int h = height();
+ int y = 0;
+
+ switch (d->vAlign) {
+ case AlignTop:
+ y = 0;
+ break;
+ case AlignBottom:
+ y = h - d->cachedLayoutSize.height();
+ break;
+ case AlignVCenter:
+ y = (h - d->cachedLayoutSize.height()) / 2;
+ break;
+ }
+ bool needClip = !clip() && (d->cachedLayoutSize.width() > width() ||
+ d->cachedLayoutSize.height() > height());
+
+ if (needClip) {
+ p->save();
+ p->setClipRect(boundingRect(), Qt::IntersectClip);
+ }
+ d->drawWrappedText(p, QPointF(0,y), false);
+ if (needClip)
+ p->restore();
+ }
+}
+
+/*!
+ \qmlproperty bool Text::smooth
+
+ Set this property if you want the text 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.
+*/
+
+void QmlGraphicsText::componentComplete()
+{
+ Q_D(QmlGraphicsText);
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::TextComponentComplete> cc;
+#endif
+ QmlGraphicsItem::componentComplete();
+ if (d->dirty) {
+ d->updateLayout();
+ d->dirty = false;
+ }
+}
+
+/*!
+ \overload
+ Handles the given mouse \a event.
+ */
+void QmlGraphicsText::mousePressEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsText);
+
+ if (!d->richText || !d->doc || d->doc->documentLayout()->anchorAt(event->pos()).isEmpty()) {
+ event->setAccepted(false);
+ d->activeLink = QString();
+ } else {
+ d->activeLink = d->doc->documentLayout()->anchorAt(event->pos());
+ }
+
+ // ### may malfunction if two of the same links are clicked & dragged onto each other)
+
+ if (!event->isAccepted())
+ QmlGraphicsItem::mousePressEvent(event);
+
+}
+
+/*!
+ \qmlsignal Text::linkActivated(link)
+
+ This handler is called when the user clicks on a link embedded in the text.
+*/
+
+/*!
+ \overload
+ Handles the given mouse \a event.
+ */
+void QmlGraphicsText::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsText);
+
+ // ### confirm the link, and send a signal out
+ if (d->richText && d->doc && d->activeLink == d->doc->documentLayout()->anchorAt(event->pos()))
+ emit linkActivated(d->activeLink);
+ else
+ event->setAccepted(false);
+
+ if (!event->isAccepted())
+ QmlGraphicsItem::mouseReleaseEvent(event);
+}
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicstext_p.h b/src/declarative/graphicsitems/qmlgraphicstext_p.h
new file mode 100644
index 0000000..8fa2e65
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicstext_p.h
@@ -0,0 +1,160 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSTEXT_H
+#define QMLGRAPHICSTEXT_H
+
+#include "qmlgraphicsitem.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+class QmlGraphicsTextPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsText : public QmlGraphicsItem
+{
+ Q_OBJECT
+ Q_ENUMS(HAlignment)
+ Q_ENUMS(VAlignment)
+ Q_ENUMS(TextStyle)
+ Q_ENUMS(TextFormat)
+ Q_ENUMS(TextElideMode)
+
+ 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 NOTIFY horizontalAlignmentChanged)
+ Q_PROPERTY(VAlignment verticalAlignment READ vAlign WRITE setVAlign NOTIFY verticalAlignmentChanged)
+ Q_PROPERTY(bool wrap READ wrap WRITE setWrap NOTIFY wrapChanged) //### there are several wrap modes in Qt
+ Q_PROPERTY(TextFormat textFormat READ textFormat WRITE setTextFormat NOTIFY textFormatChanged)
+ Q_PROPERTY(TextElideMode elide READ elideMode WRITE setElideMode NOTIFY elideModeChanged) //### elideMode?
+
+public:
+ QmlGraphicsText(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsText();
+
+ enum HAlignment { AlignLeft = Qt::AlignLeft,
+ AlignRight = Qt::AlignRight,
+ AlignHCenter = Qt::AlignHCenter };
+ 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 };
+
+ 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);
+
+ VAlignment vAlign() const;
+ void setVAlign(VAlignment align);
+
+ bool wrap() const;
+ void setWrap(bool w);
+
+ TextFormat textFormat() const;
+ void setTextFormat(TextFormat format);
+
+ TextElideMode elideMode() const;
+ void setElideMode(TextElideMode);
+
+ void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+
+ virtual void componentComplete();
+
+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 wrapChanged(bool wrap);
+ void textFormatChanged(TextFormat textFormat);
+ void elideModeChanged(TextElideMode mode);
+
+protected:
+ void mousePressEvent(QGraphicsSceneMouseEvent *event);
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
+ virtual void geometryChanged(const QRectF &newGeometry,
+ const QRectF &oldGeometry);
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsText)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsText)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsText)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicstext_p_p.h b/src/declarative/graphicsitems/qmlgraphicstext_p_p.h
new file mode 100644
index 0000000..1e29e58
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicstext_p_p.h
@@ -0,0 +1,127 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSTEXT_P_H
+#define QMLGRAPHICSTEXT_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 "qmlgraphicsitem.h"
+#include "qmlgraphicsitem_p.h"
+
+#include <qml.h>
+
+#include <QtGui/qtextlayout.h>
+
+QT_BEGIN_NAMESPACE
+
+class QTextLayout;
+class QTextDocument;
+
+class QmlGraphicsTextPrivate : public QmlGraphicsItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsText)
+public:
+ QmlGraphicsTextPrivate()
+ : color((QRgb)0), style(QmlGraphicsText::Normal), imgDirty(true),
+ hAlign(QmlGraphicsText::AlignLeft), vAlign(QmlGraphicsText::AlignTop), elideMode(QmlGraphicsText::ElideNone),
+ dirty(true), wrap(false), richText(false), singleline(false), cache(true), doc(0),
+ format(QmlGraphicsText::AutoText)
+ {
+#ifdef QML_NO_TEXT_CACHE
+ cache = false;
+#endif
+ }
+
+ ~QmlGraphicsTextPrivate();
+
+ void updateSize();
+ void updateLayout();
+ void markImgDirty() {
+ Q_Q(QmlGraphicsText);
+ imgDirty = true;
+ if (q->isComponentComplete())
+ q->update();
+ }
+ void checkImgCache();
+
+ void drawOutline();
+ void drawOutline(int yOffset);
+
+ QPixmap wrappedTextImage(bool drawStyle);
+ void drawWrappedText(QPainter *p, const QPointF &pos, bool drawStyle);
+ QPixmap richTextImage(bool drawStyle);
+ QSize setupTextLayout(QTextLayout *layout);
+
+ QString text;
+ QFont font;
+ QColor color;
+ QmlGraphicsText::TextStyle style;
+ QColor styleColor;
+ QString activeLink;
+ bool imgDirty;
+ QPixmap imgCache;
+ QPixmap imgStyleCache;
+ QmlGraphicsText::HAlignment hAlign;
+ QmlGraphicsText::VAlignment vAlign;
+ QmlGraphicsText::TextElideMode elideMode;
+ bool dirty:1;
+ bool wrap:1;
+ bool richText:1;
+ bool singleline:1;
+ bool cache:1;
+ QTextDocument *doc;
+ QTextLayout layout;
+ QSize cachedLayoutSize;
+ QmlGraphicsText::TextFormat format;
+};
+
+QT_END_NAMESPACE
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicstextedit.cpp b/src/declarative/graphicsitems/qmlgraphicstextedit.cpp
new file mode 100644
index 0000000..fc80258
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicstextedit.cpp
@@ -0,0 +1,1035 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicstextedit_p.h"
+#include "qmlgraphicstextedit_p_p.h"
+
+#include "qmlgraphicsevents_p_p.h"
+
+#include <qfxperf_p_p.h>
+
+#include <QTextLayout>
+#include <QTextLine>
+#include <QTextDocument>
+#include <QGraphicsSceneMouseEvent>
+#include <QDebug>
+#include <QPainter>
+
+#include <private/qtextcontrol_p.h>
+
+QT_BEGIN_NAMESPACE
+QML_DEFINE_TYPE(Qt,4,6,TextEdit,QmlGraphicsTextEdit)
+
+/*!
+ \qmlclass TextEdit QmlGraphicsTextEdit
+ \brief The TextEdit item allows you to add editable formatted text to a scene.
+
+ It can display both plain and rich text. For example:
+
+ \qml
+TextEdit {
+ id: edit
+ text: "<b>Hello</b> <i>World!</i>"
+ focus: true
+ font.family: "Helvetica"
+ font.pointSize: 20
+ color: "blue"
+ width: 240
+}
+ \endqml
+
+ \image declarative-textedit.gif
+
+ \sa Text
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsTextEdit
+ \qmlclass TextEdit
+ \ingroup group_coreitems
+
+ \brief The QmlGraphicsTextEdit class provides an editable formatted text item that you can add to a QmlView.
+
+ It can display both plain and rich text.
+
+ \image declarative-textedit.png
+
+ A QmlGraphicsTextEdit object can be instantiated in Qml using the tag \c &lt;TextEdit&gt;.
+*/
+
+/*!
+ Constructs a new QmlGraphicsTextEdit.
+*/
+QmlGraphicsTextEdit::QmlGraphicsTextEdit(QmlGraphicsItem *parent)
+: QmlGraphicsPaintedItem(*(new QmlGraphicsTextEditPrivate), parent)
+{
+ Q_D(QmlGraphicsTextEdit);
+ d->init();
+}
+
+QString QmlGraphicsTextEdit::text() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+
+ if (d->richText)
+ return d->document->toHtml();
+ else
+ return d->document->toPlainText();
+}
+
+/*!
+ \qmlproperty string TextEdit::font.family
+ \qmlproperty bool TextEdit::font.bold
+ \qmlproperty bool TextEdit::font.italic
+ \qmlproperty bool TextEdit::font.underline
+ \qmlproperty real TextEdit::font.pointSize
+ \qmlproperty int TextEdit::font.pixelSize
+
+ Set the TextEdit's font attributes.
+*/
+
+/*!
+ \qmlproperty string 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 QmlGraphicsTextEdit::setText(const QString &text)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (QmlGraphicsTextEdit::text() == text)
+ return;
+ d->text = text;
+ d->richText = d->format == RichText || (d->format == AutoText && Qt::mightBeRichText(text));
+ if (d->richText) {
+ d->control->setHtml(text);
+ } else {
+ d->control->setPlainText(text);
+ }
+ q_textChanged();
+}
+
+/*!
+ \qmlproperty enumeration TextEdit::textFormat
+
+ The way the text property should be displayed.
+
+ Supported text formats are \c AutoText, \c PlainText and \c RichText.
+
+ The default is AutoText. 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().
+
+ \table
+ \row
+ \o
+ \qml
+Column {
+ TextEdit {
+ font.pointSize: 24
+ text: "<b>Hello</b> <i>World!</i>"
+ }
+ TextEdit {
+ font.pointSize: 24
+ textFormat: "RichText"
+ text: "<b>Hello</b> <i>World!</i>"
+ }
+ TextEdit {
+ font.pointSize: 24
+ textFormat: "PlainText"
+ text: "<b>Hello</b> <i>World!</i>"
+ }
+}
+ \endqml
+ \o \image declarative-textformat.png
+ \endtable
+*/
+QmlGraphicsTextEdit::TextFormat QmlGraphicsTextEdit::textFormat() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->format;
+}
+
+void QmlGraphicsTextEdit::setTextFormat(TextFormat format)
+{
+ Q_D(QmlGraphicsTextEdit);
+ 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) {
+ d->control->setHtml(d->text);
+ updateSize();
+ }
+ d->format = format;
+ emit textFormatChanged(d->format);
+}
+
+QFont QmlGraphicsTextEdit::font() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->font;
+}
+
+void QmlGraphicsTextEdit::setFont(const QFont &font)
+{
+ Q_D(QmlGraphicsTextEdit);
+ d->font = font;
+
+ clearCache();
+ d->document->setDefaultFont(d->font);
+ if(d->cursor){
+ d->cursor->setHeight(QFontMetrics(d->font).height());
+ moveCursorDelegate();
+ }
+ updateSize();
+ update();
+}
+
+/*!
+ \qmlproperty color TextEdit::color
+
+ The text color.
+
+ \qml
+// green text using hexadecimal notation
+TextEdit { color: "#00FF00"; ... }
+
+// steelblue text using SVG color name
+TextEdit { color: "steelblue"; ... }
+ \endqml
+*/
+QColor QmlGraphicsTextEdit::color() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->color;
+}
+
+void QmlGraphicsTextEdit::setColor(const QColor &color)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (d->color == color)
+ return;
+
+ clearCache();
+ d->color = color;
+ QPalette pal = d->control->palette();
+ pal.setColor(QPalette::Text, color);
+ d->control->setPalette(pal);
+ update();
+ emit colorChanged(d->color);
+}
+
+/*!
+ \qmlproperty color TextEdit::selectionColor
+
+ The text highlight color, used behind selections.
+*/
+QColor QmlGraphicsTextEdit::selectionColor() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->selectionColor;
+}
+
+void QmlGraphicsTextEdit::setSelectionColor(const QColor &color)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (d->selectionColor == color)
+ return;
+
+ clearCache();
+ d->selectionColor = color;
+ QPalette pal = d->control->palette();
+ pal.setColor(QPalette::Highlight, color);
+ d->control->setPalette(pal);
+ update();
+ emit selectionColorChanged(d->selectionColor);
+}
+
+/*!
+ \qmlproperty color TextEdit::selectedTextColor
+
+ The selected text color, used in selections.
+*/
+QColor QmlGraphicsTextEdit::selectedTextColor() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->selectedTextColor;
+}
+
+void QmlGraphicsTextEdit::setSelectedTextColor(const QColor &color)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (d->selectedTextColor == color)
+ return;
+
+ clearCache();
+ d->selectedTextColor = color;
+ QPalette pal = d->control->palette();
+ pal.setColor(QPalette::HighlightedText, color);
+ d->control->setPalette(pal);
+ update();
+ emit selectedTextColorChanged(d->selectedTextColor);
+}
+
+/*!
+ \qmlproperty enumeration TextEdit::horizontalAlignment
+ \qmlproperty enumeration TextEdit::verticalAlignment
+
+ Sets the horizontal and vertical alignment of the text within the TextEdit items
+ width and height. By default, the text is top-left aligned.
+
+ The valid values for \c horizontalAlignment are \c AlignLeft, \c AlignRight and
+ \c AlignHCenter. The valid values for \c verticalAlignment are \c AlignTop, \c AlignBottom
+ and \c AlignVCenter.
+*/
+QmlGraphicsTextEdit::HAlignment QmlGraphicsTextEdit::hAlign() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->hAlign;
+}
+
+void QmlGraphicsTextEdit::setHAlign(QmlGraphicsTextEdit::HAlignment alignment)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (alignment == d->hAlign)
+ return;
+ d->hAlign = alignment;
+ d->updateDefaultTextOption();
+ updateSize();
+ emit horizontalAlignmentChanged(d->hAlign);
+}
+
+QmlGraphicsTextEdit::VAlignment QmlGraphicsTextEdit::vAlign() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->vAlign;
+}
+
+void QmlGraphicsTextEdit::setVAlign(QmlGraphicsTextEdit::VAlignment alignment)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (alignment == d->vAlign)
+ return;
+ d->vAlign = alignment;
+ d->updateDefaultTextOption();
+ updateSize();
+ emit verticalAlignmentChanged(d->vAlign);
+}
+
+bool QmlGraphicsTextEdit::wrap() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->wrap;
+}
+
+/*!
+ \qmlproperty bool TextEdit::wrap
+
+ 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.
+
+ Wrapping is done on word boundaries (i.e. it is a "word-wrap"). Wrapping is off by default.
+*/
+void QmlGraphicsTextEdit::setWrap(bool w)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (w == d->wrap)
+ return;
+ d->wrap = w;
+ d->updateDefaultTextOption();
+ updateSize();
+ emit wrapChanged(d->wrap);
+}
+
+/*!
+ \qmlproperty bool TextEdit::cursorVisible
+ If true the text edit shows a cursor.
+
+ This property is set and unset when the text edit gets focus, but it can also
+ be set directly (useful, for example, if a KeyProxy might forward keys to it).
+*/
+bool QmlGraphicsTextEdit::isCursorVisible() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->cursorVisible;
+}
+
+void QmlGraphicsTextEdit::setCursorVisible(bool on)
+{
+ Q_D(QmlGraphicsTextEdit);
+ 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, 0));
+ emit cursorVisibleChanged(d->cursorVisible);
+}
+
+/*!
+ \qmlproperty int TextEdit::cursorPosition
+ The position of the cursor in the TextEdit.
+*/
+int QmlGraphicsTextEdit::cursorPosition() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->control->textCursor().position();
+}
+
+void QmlGraphicsTextEdit::setCursorPosition(int pos)
+{
+ Q_D(QmlGraphicsTextEdit);
+ QTextCursor cursor = d->control->textCursor();
+ if (cursor.position() == pos)
+ return;
+ cursor.setPosition(pos);
+ d->control->setTextCursor(cursor);
+}
+
+/*!
+ \qmlproperty Component 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 QmlGraphicsItem or
+ QmlGraphicsItem derived item.
+*/
+QmlComponent* QmlGraphicsTextEdit::cursorDelegate() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->cursorComponent;
+}
+
+void QmlGraphicsTextEdit::setCursorDelegate(QmlComponent* c)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if(d->cursorComponent){
+ if(d->cursor){
+ disconnect(d->control, SIGNAL(cursorPositionChanged()),
+ this, SLOT(moveCursorDelegate()));
+ d->control->setCursorWidth(-1);
+ dirtyCache(cursorRect());
+ 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 QmlGraphicsTextEdit::loadCursorDelegate()
+{
+ Q_D(QmlGraphicsTextEdit);
+ if(d->cursorComponent->isLoading())
+ return;
+ d->cursor = qobject_cast<QmlGraphicsItem*>(d->cursorComponent->create(qmlContext(this)));
+ if(d->cursor){
+ connect(d->control, SIGNAL(cursorPositionChanged()),
+ this, SLOT(moveCursorDelegate()));
+ d->control->setCursorWidth(0);
+ dirtyCache(cursorRect());
+ d->cursor->setParentItem(this);
+ d->cursor->setHeight(QFontMetrics(d->font).height());
+ moveCursorDelegate();
+ }else{
+ qWarning() << QLatin1String("Error loading cursor delegate for TextEdit:") + objectName();
+ }
+}
+
+/*!
+ \qmlproperty int TextEdit::selectionStart
+
+ The cursor position before the first character in the current selection.
+ Setting this and selectionEnd allows you to specify a selection in the
+ text edit.
+
+ Note that if selectionStart == selectionEnd then there is no current
+ selection. If you attempt to set selectionStart to a value outside of
+ the current text, selectionStart will not be changed.
+
+ \sa selectionEnd, cursorPosition, selectedText
+*/
+int QmlGraphicsTextEdit::selectionStart() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->control->textCursor().selectionStart();
+}
+
+void QmlGraphicsTextEdit::setSelectionStart(int s)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if(d->lastSelectionStart == s || s < 0 || s > text().length())
+ return;
+ d->lastSelectionStart = s;
+ d->updateSelection();// Will emit the relevant signals
+}
+
+/*!
+ \qmlproperty int TextEdit::selectionEnd
+
+ The cursor position after the last character in the current selection.
+ Setting this and selectionStart allows you to specify a selection in the
+ text edit.
+
+ Note that if selectionStart == selectionEnd then there is no current
+ selection. If you attempt to set selectionEnd to a value outside of
+ the current text, selectionEnd will not be changed.
+
+ \sa selectionStart, cursorPosition, selectedText
+*/
+int QmlGraphicsTextEdit::selectionEnd() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->control->textCursor().selectionEnd();
+}
+
+void QmlGraphicsTextEdit::setSelectionEnd(int s)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if(d->lastSelectionEnd == s || s < 0 || s > text().length())
+ return;
+ d->lastSelectionEnd = s;
+ d->updateSelection();// Will emit the relevant signals
+}
+
+/*!
+ \qmlproperty string 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 QmlGraphicsTextEdit::selectedText() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->control->textCursor().selectedText();
+}
+
+/*!
+ \qmlproperty bool TextEdit::focusOnPress
+
+ Whether the TextEdit should gain focus on a mouse press. By default this is
+ set to true.
+*/
+bool QmlGraphicsTextEdit::focusOnPress() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->focusOnPress;
+}
+
+void QmlGraphicsTextEdit::setFocusOnPress(bool on)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (d->focusOnPress == on)
+ return;
+ d->focusOnPress = on;
+ emit focusOnPressChanged(d->focusOnPress);
+}
+
+/*!
+ \qmlproperty bool TextEdit::persistentSelection
+
+ Whether the TextEdit should keep the selection visible when it loses focus to another
+ item in the scene. By default this is set to true;
+*/
+bool QmlGraphicsTextEdit::persistentSelection() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->persistentSelection;
+}
+
+void QmlGraphicsTextEdit::setPersistentSelection(bool on)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (d->persistentSelection == on)
+ return;
+ d->persistentSelection = on;
+ emit persistentSelectionChanged(d->persistentSelection);
+}
+
+qreal QmlGraphicsTextEdit::textMargin() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->textMargin;
+}
+
+void QmlGraphicsTextEdit::setTextMargin(qreal margin)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (d->textMargin == margin)
+ return;
+ d->textMargin = margin;
+ d->document->setDocumentMargin(d->textMargin);
+ emit textMarginChanged(d->textMargin);
+}
+
+void QmlGraphicsTextEdit::geometryChanged(const QRectF &newGeometry,
+ const QRectF &oldGeometry)
+{
+ if (newGeometry.width() != oldGeometry.width())
+ updateSize();
+ QmlGraphicsPaintedItem::geometryChanged(newGeometry, oldGeometry);
+}
+
+/*!
+ Ensures any delayed caching or data loading the class
+ needs to performed is complete.
+*/
+void QmlGraphicsTextEdit::componentComplete()
+{
+ Q_D(QmlGraphicsTextEdit);
+ QmlGraphicsPaintedItem::componentComplete();
+ if (d->dirty) {
+ updateSize();
+ d->dirty = false;
+ }
+}
+
+/*!
+ \qmlproperty bool TextEdit::readOnly
+
+ Whether the user an 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 QmlGraphicsTextEdit::setReadOnly(bool r)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (r == isReadOnly())
+ return;
+
+
+ Qt::TextInteractionFlags flags = Qt::NoTextInteraction;
+ if (r) {
+ flags = Qt::TextSelectableByMouse;
+ } else {
+ flags = Qt::TextEditorInteraction;
+ }
+ d->control->setTextInteractionFlags(flags);
+ if (!r)
+ d->control->moveCursor(QTextCursor::End);
+
+ emit readOnlyChanged(r);
+}
+
+bool QmlGraphicsTextEdit::isReadOnly() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return !(d->control->textInteractionFlags() & Qt::TextEditable);
+}
+
+/*!
+ Sets how the text edit should interact with user input to the given
+ \a flags.
+*/
+void QmlGraphicsTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags)
+{
+ Q_D(QmlGraphicsTextEdit);
+ d->control->setTextInteractionFlags(flags);
+}
+
+/*!
+ Returns the flags specifying how the text edit should interact
+ with user input.
+*/
+Qt::TextInteractionFlags QmlGraphicsTextEdit::textInteractionFlags() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->control->textInteractionFlags();
+}
+
+/*!
+ Returns the rectangle where the text cursor is rendered
+ within the text edit.
+*/
+QRect QmlGraphicsTextEdit::cursorRect() const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->control->cursorRect().toRect();
+}
+
+
+/*!
+\overload
+Handles the given \a event.
+*/
+bool QmlGraphicsTextEdit::event(QEvent *event)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (event->type() == QEvent::ShortcutOverride) {
+ d->control->processEvent(event, QPointF(0, 0));
+ return event->isAccepted();
+ }
+ return QmlGraphicsPaintedItem::event(event);
+}
+
+/*!
+\overload
+Handles the given key \a event.
+*/
+void QmlGraphicsTextEdit::keyPressEvent(QKeyEvent *event)
+{
+ Q_D(QmlGraphicsTextEdit);
+ d->control->processEvent(event, QPointF(0, 0));
+
+ if (!event->isAccepted())
+ QmlGraphicsPaintedItem::keyPressEvent(event);
+}
+
+/*!
+\overload
+Handles the given key \a event.
+*/
+void QmlGraphicsTextEdit::keyReleaseEvent(QKeyEvent *event)
+{
+ Q_D(QmlGraphicsTextEdit);
+ d->control->processEvent(event, QPointF(0, 0));
+ if (!event->isAccepted())
+ QmlGraphicsPaintedItem::keyReleaseEvent(event);
+}
+
+/*!
+ \overload
+ Handles changing of the focus property. Focus is applied to the control
+ even if the edit does not have active focus. This is because things
+ like KeyProxy can give the behavior of focus even when hasFocus() isn't
+ true.
+*/
+void QmlGraphicsTextEdit::focusChanged(bool hasFocus)
+{
+ setCursorVisible(hasFocus);
+ QmlGraphicsItem::focusChanged(hasFocus);
+}
+
+/*!
+ Causes all text to be selected.
+*/
+void QmlGraphicsTextEdit::selectAll()
+{
+ Q_D(QmlGraphicsTextEdit);
+ d->control->selectAll();
+}
+
+/*!
+\overload
+Handles the given mouse \a event.
+*/
+void QmlGraphicsTextEdit::mousePressEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (d->focusOnPress){
+ QGraphicsItem *p = parentItem();//###Is there a better way to find my focus scope?
+ while(p) {
+ if(p->flags() & QGraphicsItem::ItemIsFocusScope){
+ p->setFocus();
+ break;
+ }
+ p = p->parentItem();
+ }
+ setFocus(true);
+ }
+ d->control->processEvent(event, QPointF(0, 0));
+ if (!event->isAccepted())
+ QmlGraphicsPaintedItem::mousePressEvent(event);
+}
+
+/*!
+\overload
+Handles the given mouse \a event.
+*/
+void QmlGraphicsTextEdit::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsTextEdit);
+ QWidget *widget = event->widget();
+ if (widget && (d->control->textInteractionFlags() & Qt::TextEditable) && boundingRect().contains(event->pos()))
+ qt_widget_private(widget)->handleSoftwareInputPanel(event->button(), d->focusOnPress);
+
+ d->control->processEvent(event, QPointF(0, 0));
+ if (!event->isAccepted())
+ QmlGraphicsPaintedItem::mousePressEvent(event);
+}
+
+/*!
+\overload
+Handles the given mouse \a event.
+*/
+void QmlGraphicsTextEdit::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsTextEdit);
+ d->control->processEvent(event, QPointF(0, 0));
+ if (!event->isAccepted())
+ QmlGraphicsPaintedItem::mouseDoubleClickEvent(event);
+}
+
+/*!
+\overload
+Handles the given mouse \a event.
+*/
+void QmlGraphicsTextEdit::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsTextEdit);
+ d->control->processEvent(event, QPointF(0, 0));
+ if (!event->isAccepted())
+ QmlGraphicsPaintedItem::mousePressEvent(event);
+}
+
+/*!
+\overload
+Handles the given input method \a event.
+*/
+void QmlGraphicsTextEdit::inputMethodEvent(QInputMethodEvent *event)
+{
+ Q_D(QmlGraphicsTextEdit);
+ d->control->processEvent(event, QPointF(0, 0));
+}
+
+/*!
+\overload
+Returns the value of the given \a property.
+*/
+QVariant QmlGraphicsTextEdit::inputMethodQuery(Qt::InputMethodQuery property) const
+{
+ Q_D(const QmlGraphicsTextEdit);
+ return d->control->inputMethodQuery(property);
+}
+
+/*!
+Draws the contents of the text edit using the given \a painter within
+the given \a bounds.
+*/
+void QmlGraphicsTextEdit::drawContents(QPainter *painter, const QRect &bounds)
+{
+ Q_D(QmlGraphicsTextEdit);
+
+ painter->setRenderHint(QPainter::TextAntialiasing, true);
+
+ d->control->drawContents(painter, bounds);
+}
+
+void QmlGraphicsTextEdit::updateImgCache(const QRectF &r)
+{
+ dirtyCache(r.toRect());
+ emit update();
+}
+
+/*!
+ \qmlproperty bool TextEdit::smooth
+
+ Set this property if you want the text 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.
+*/
+
+void QmlGraphicsTextEditPrivate::init()
+{
+ Q_Q(QmlGraphicsTextEdit);
+
+ q->setSmooth(smooth);
+ q->setAcceptedMouseButtons(Qt::LeftButton);
+ q->setFlag(QGraphicsItem::ItemHasNoContents, false);
+ q->setFlag(QGraphicsItem::ItemAcceptsInputMethod);
+
+ control = new QTextControl(q);
+ control->setIgnoreUnusedNavigationEvents(true);
+
+ QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(updateImgCache(QRectF)));
+
+ 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()));
+
+ document = control->document();
+ document->setDefaultFont(font);
+ document->setDocumentMargin(textMargin);
+ document->setUndoRedoEnabled(false); // flush undo buffer.
+ document->setUndoRedoEnabled(true);
+ updateDefaultTextOption();
+}
+
+void QmlGraphicsTextEdit::q_textChanged()
+{
+ updateSize();
+ emit textChanged(text());
+}
+
+void QmlGraphicsTextEdit::moveCursorDelegate()
+{
+ Q_D(QmlGraphicsTextEdit);
+ if(!d->cursor)
+ return;
+ QRectF cursorRect = d->control->cursorRect();
+ d->cursor->setX(cursorRect.x());
+ d->cursor->setY(cursorRect.y());
+}
+
+void QmlGraphicsTextEditPrivate::updateSelection()
+{
+ Q_Q(QmlGraphicsTextEdit);
+ QTextCursor cursor = control->textCursor();
+ bool startChange = (lastSelectionStart != cursor.selectionStart());
+ bool endChange = (lastSelectionEnd != cursor.selectionEnd());
+ //### Is it worth calculating a more minimal set of movements?
+ 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();
+ startChange = (lastSelectionStart != control->textCursor().selectionStart());
+ endChange = (lastSelectionEnd != control->textCursor().selectionEnd());
+ if(startChange || endChange)
+ qWarning() << "QmlGraphicsTextEditPrivate::updateSelection() has failed you.";
+}
+
+void QmlGraphicsTextEdit::updateSelectionMarkers()
+{
+ Q_D(QmlGraphicsTextEdit);
+ 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();
+ }
+}
+
+//### 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 QmlGraphicsTextEdit::updateSize()
+{
+ Q_D(QmlGraphicsTextEdit);
+ if (isComponentComplete()) {
+ QFontMetrics fm = QFontMetrics(d->font);
+ int dy = height();
+ // ### assumes that if the width is set, the text will fill to edges
+ // ### (unless wrap is false, then clipping will occur)
+ if (widthValid())
+ d->document->setTextWidth(width());
+ dy -= (int)d->document->size().height();
+
+ int yoff = 0;
+ if (heightValid()) {
+ if (d->vAlign == AlignBottom)
+ yoff = dy;
+ else if (d->vAlign == AlignVCenter)
+ yoff = dy/2;
+ }
+ setBaselineOffset(fm.ascent() + yoff + d->textMargin);
+
+ //### need to comfirm cost of always setting these
+ int newWidth = (int)d->document->idealWidth();
+ d->document->setTextWidth(newWidth); // ### QTextDoc> Alignment will not work unless textWidth is set. Does Text need this line as well?
+ int cursorWidth = 1;
+ if(d->cursor)
+ cursorWidth = d->cursor->width();
+ newWidth += cursorWidth;
+ if(!d->document->isEmpty())
+ newWidth += 3;// ### Need a better way of accounting for space between char and cursor
+ // ### Setting the implicitWidth triggers another updateSize(), and unless there are bindings nothing has changed.
+ setImplicitWidth(newWidth);
+ setImplicitHeight(d->text.isEmpty() ? fm.height() : (int)d->document->size().height());
+
+ setContentsSize(QSize(width(), height()));
+ } else {
+ d->dirty = true;
+ }
+ emit update();
+}
+
+void QmlGraphicsTextEditPrivate::updateDefaultTextOption()
+{
+ QTextOption opt = document->defaultTextOption();
+ int oldAlignment = opt.alignment();
+ opt.setAlignment((Qt::Alignment)(int)(hAlign | vAlign));
+
+ QTextOption::WrapMode oldWrapMode = opt.wrapMode();
+
+ if (wrap)
+ opt.setWrapMode(QTextOption::WordWrap);
+ else
+ opt.setWrapMode(QTextOption::NoWrap);
+
+ if (oldWrapMode == opt.wrapMode() && oldAlignment == opt.alignment())
+ return;
+ document->setDefaultTextOption(opt);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/graphicsitems/qmlgraphicstextedit_p.h b/src/declarative/graphicsitems/qmlgraphicstextedit_p.h
new file mode 100644
index 0000000..e95b077
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicstextedit_p.h
@@ -0,0 +1,240 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSTEXTEDIT_H
+#define QMLGRAPHICSTEXTEDIT_H
+
+#include "qmlgraphicstext_p.h"
+#include "qmlgraphicspainteditem_p.h"
+
+#include <QtGui/qtextdocument.h>
+#include <QtGui/qtextoption.h>
+#include <QtGui/qtextcursor.h>
+#include <QtGui/qtextformat.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+
+class QmlGraphicsTextEditPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsTextEdit : public QmlGraphicsPaintedItem
+{
+ Q_OBJECT
+ Q_ENUMS(VAlignment)
+ Q_ENUMS(HAlignment)
+ Q_ENUMS(TextFormat)
+
+ 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 NOTIFY horizontalAlignmentChanged)
+ Q_PROPERTY(VAlignment verticalAlignment READ vAlign WRITE setVAlign NOTIFY verticalAlignmentChanged)
+ Q_PROPERTY(bool wrap READ wrap WRITE setWrap NOTIFY wrapChanged) //### other wrap modes
+ 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(QmlComponent* cursorDelegate READ cursorDelegate WRITE setCursorDelegate NOTIFY cursorDelegateChanged)
+ Q_PROPERTY(int selectionStart READ selectionStart WRITE setSelectionStart NOTIFY selectionStartChanged)
+ Q_PROPERTY(int selectionEnd READ selectionEnd WRITE setSelectionEnd NOTIFY selectionEndChanged)
+ Q_PROPERTY(QString selectedText READ selectedText NOTIFY selectionChanged)
+ Q_PROPERTY(bool focusOnPress READ focusOnPress WRITE setFocusOnPress NOTIFY focusOnPressChanged)
+ 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)
+
+public:
+ QmlGraphicsTextEdit(QmlGraphicsItem *parent=0);
+
+ enum HAlignment {
+ AlignLeft = Qt::AlignLeft,
+ AlignRight = Qt::AlignRight,
+ AlignHCenter = Qt::AlignHCenter
+ };
+
+ enum VAlignment {
+ AlignTop = Qt::AlignTop,
+ AlignBottom = Qt::AlignBottom,
+ AlignVCenter = Qt::AlignVCenter
+ };
+
+ enum TextFormat {
+ PlainText = Qt::PlainText,
+ RichText = Qt::RichText,
+ AutoText = Qt::AutoText
+ };
+
+ 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);
+
+ VAlignment vAlign() const;
+ void setVAlign(VAlignment align);
+
+ bool wrap() const;
+ void setWrap(bool w);
+
+ bool isCursorVisible() const;
+ void setCursorVisible(bool on);
+
+ int cursorPosition() const;
+ void setCursorPosition(int pos);
+
+ QmlComponent* cursorDelegate() const;
+ void setCursorDelegate(QmlComponent*);
+
+ int selectionStart() const;
+ void setSelectionStart(int);
+
+ int selectionEnd() const;
+ void setSelectionEnd(int);
+
+ QString selectedText() const;
+
+ bool focusOnPress() const;
+ void setFocusOnPress(bool on);
+
+ bool persistentSelection() const;
+ void setPersistentSelection(bool on);
+
+ qreal textMargin() const;
+ void setTextMargin(qreal margin);
+
+ virtual void componentComplete();
+
+ /* FROM EDIT */
+ void setReadOnly(bool);
+ bool isReadOnly() const;
+
+ void setTextInteractionFlags(Qt::TextInteractionFlags flags);
+ Qt::TextInteractionFlags textInteractionFlags() const;
+
+ QRect cursorRect() const;
+
+ QVariant inputMethodQuery(Qt::InputMethodQuery property) const;
+
+Q_SIGNALS:
+ void textChanged(const QString &);
+ void cursorPositionChanged();
+ 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 wrapChanged(bool isWrapped);
+ void textFormatChanged(TextFormat textFormat);
+ void readOnlyChanged(bool isReadOnly);
+ void cursorVisibleChanged(bool isCursorVisible);
+ void cursorDelegateChanged();
+ void focusOnPressChanged(bool focusIsPressed);
+ void persistentSelectionChanged(bool isPersistentSelection);
+ void textMarginChanged(qreal textMargin);
+
+public Q_SLOTS:
+ void selectAll();
+
+private Q_SLOTS:
+ void updateImgCache(const QRectF &rect);
+ void q_textChanged();
+ void updateSelectionMarkers();
+ void moveCursorDelegate();
+ void loadCursorDelegate();
+
+private:
+ void updateSize();
+
+protected:
+ virtual void geometryChanged(const QRectF &newGeometry,
+ const QRectF &oldGeometry);
+
+ bool event(QEvent *);
+ void keyPressEvent(QKeyEvent *);
+ void keyReleaseEvent(QKeyEvent *);
+
+ void focusChanged(bool);
+
+ // mouse filter?
+ void mousePressEvent(QGraphicsSceneMouseEvent *event);
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
+ void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
+ void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
+
+ void inputMethodEvent(QInputMethodEvent *e);
+
+ void drawContents(QPainter *, const QRect &);
+private:
+ Q_DISABLE_COPY(QmlGraphicsTextEdit)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsTextEdit)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsTextEdit)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicstextedit_p_p.h b/src/declarative/graphicsitems/qmlgraphicstextedit_p_p.h
new file mode 100644
index 0000000..8914bfd
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicstextedit_p_p.h
@@ -0,0 +1,113 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSTEXTEDIT_P_H
+#define QMLGRAPHICSTEXTEDIT_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 "qmlgraphicsitem.h"
+#include "qmlgraphicspainteditem_p_p.h"
+
+#include <qml.h>
+
+QT_BEGIN_NAMESPACE
+class QTextLayout;
+class QTextDocument;
+class QTextControl;
+class QmlGraphicsTextEditPrivate : public QmlGraphicsPaintedItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsTextEdit)
+
+public:
+ QmlGraphicsTextEditPrivate()
+ : color("black"), imgDirty(true), hAlign(QmlGraphicsTextEdit::AlignLeft), vAlign(QmlGraphicsTextEdit::AlignTop),
+ dirty(false), wrap(false), richText(false), cursorVisible(false), focusOnPress(true),
+ persistentSelection(true), textMargin(0.0), lastSelectionStart(0), lastSelectionEnd(0),
+ cursorComponent(0), cursor(0), format(QmlGraphicsTextEdit::AutoText), document(0)
+ {
+ }
+
+ void init();
+
+ void updateDefaultTextOption();
+ void relayoutDocument();
+ void updateSelection();
+
+ QString text;
+ QFont font;
+ QColor color;
+ QColor selectionColor;
+ QColor selectedTextColor;
+ QString style;
+ QColor styleColor;
+ bool imgDirty;
+ QPixmap imgCache;
+ QPixmap imgStyleCache;
+ QmlGraphicsTextEdit::HAlignment hAlign;
+ QmlGraphicsTextEdit::VAlignment vAlign;
+ bool dirty;
+ bool wrap;
+ bool richText;
+ bool cursorVisible;
+ bool focusOnPress;
+ bool persistentSelection;
+ qreal textMargin;
+ int lastSelectionStart;
+ int lastSelectionEnd;
+ QmlComponent* cursorComponent;
+ QmlGraphicsItem* cursor;
+ QmlGraphicsTextEdit::TextFormat format;
+ QTextDocument *document;
+ QTextControl *control;
+};
+
+QT_END_NAMESPACE
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicstextinput.cpp b/src/declarative/graphicsitems/qmlgraphicstextinput.cpp
new file mode 100644
index 0000000..6d79c7a
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicstextinput.cpp
@@ -0,0 +1,916 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicstextinput_p.h"
+#include "qmlgraphicstextinput_p_p.h"
+
+#include <qmlinfo.h>
+
+#include <QValidator>
+#include <QApplication>
+#include <QFontMetrics>
+#include <QPainter>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,TextInput,QmlGraphicsTextInput);
+QML_DEFINE_NOCREATE_TYPE(QValidator);
+QML_DEFINE_TYPE(Qt,4,6,QIntValidator,QIntValidator);
+QML_DEFINE_TYPE(Qt,4,6,QDoubleValidator,QDoubleValidator);
+QML_DEFINE_TYPE(Qt,4,6,QRegExpValidator,QRegExpValidator);
+
+/*!
+ \qmlclass TextInput QmlGraphicsTextInput
+ The TextInput item allows you to add an editable line of text to a scene.
+
+ TextInput can only display a single line of text, and can only display
+ plain text. However it can provide addition input constraints on the text.
+
+ Input constraints include setting a QValidator, an input mask, or a
+ maximum input length.
+*/
+QmlGraphicsTextInput::QmlGraphicsTextInput(QmlGraphicsItem* parent)
+ : QmlGraphicsPaintedItem(*(new QmlGraphicsTextInputPrivate), parent)
+{
+ Q_D(QmlGraphicsTextInput);
+ d->init();
+}
+
+QmlGraphicsTextInput::~QmlGraphicsTextInput()
+{
+}
+
+/*!
+ \qmlproperty string TextInput::text
+
+ The text in the TextInput.
+*/
+
+QString QmlGraphicsTextInput::text() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->control->text();
+}
+
+void QmlGraphicsTextInput::setText(const QString &s)
+{
+ Q_D(QmlGraphicsTextInput);
+ if(s == text())
+ return;
+ d->control->setText(s);
+ //emit textChanged();
+}
+
+/*!
+ \qmlproperty string TextInput::font.family
+ \qmlproperty bool TextInput::font.bold
+ \qmlproperty bool TextInput::font.italic
+ \qmlproperty bool TextInput::font.underline
+ \qmlproperty real TextInput::font.pointSize
+ \qmlproperty int TextInput::font.pixelSize
+
+ Set the TextInput's font attributes.
+*/
+QFont QmlGraphicsTextInput::font() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->font;
+}
+
+void QmlGraphicsTextInput::setFont(const QFont &font)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (d->font == font)
+ return;
+
+ d->font = font;
+
+ d->control->setFont(d->font);
+ if(d->cursorItem){
+ d->cursorItem->setHeight(QFontMetrics(d->font).height());
+ moveCursor();
+ }
+ updateSize();
+ emit fontChanged(d->font);
+}
+
+/*!
+ \qmlproperty color TextInput::color
+
+ The text color.
+*/
+QColor QmlGraphicsTextInput::color() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->color;
+}
+
+void QmlGraphicsTextInput::setColor(const QColor &c)
+{
+ Q_D(QmlGraphicsTextInput);
+ d->color = c;
+}
+
+
+/*!
+ \qmlproperty color TextInput::selectionColor
+
+ The text highlight color, used behind selections.
+*/
+QColor QmlGraphicsTextInput::selectionColor() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->selectionColor;
+}
+
+void QmlGraphicsTextInput::setSelectionColor(const QColor &color)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (d->selectionColor == color)
+ return;
+
+ d->selectionColor = color;
+ QPalette p = d->control->palette();
+ p.setColor(QPalette::Highlight, d->selectionColor);
+ d->control->setPalette(p);
+ emit selectionColorChanged(color);
+}
+
+/*!
+ \qmlproperty color TextInput::selectedTextColor
+
+ The highlighted text color, used in selections.
+*/
+QColor QmlGraphicsTextInput::selectedTextColor() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->selectedTextColor;
+}
+
+void QmlGraphicsTextInput::setSelectedTextColor(const QColor &color)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (d->selectedTextColor == color)
+ return;
+
+ d->selectedTextColor = color;
+ QPalette p = d->control->palette();
+ p.setColor(QPalette::HighlightedText, d->selectedTextColor);
+ d->control->setPalette(p);
+ emit selectedTextColorChanged(color);
+}
+
+/*!
+ \qmlproperty enumeration TextInput::horizontalAlignment
+
+ Sets the horizontal alignment of the text within the TextInput item's
+ width and height. By default, the text is left aligned.
+
+ 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 AlignLeft, \c AlignRight and
+ \c AlignHCenter.
+*/
+QmlGraphicsTextInput::HAlignment QmlGraphicsTextInput::hAlign() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->hAlign;
+}
+
+void QmlGraphicsTextInput::setHAlign(HAlignment align)
+{
+ Q_D(QmlGraphicsTextInput);
+ if(align == d->hAlign)
+ return;
+ d->hAlign = align;
+ emit horizontalAlignmentChanged(d->hAlign);
+}
+
+bool QmlGraphicsTextInput::isReadOnly() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->control->isReadOnly();
+}
+
+void QmlGraphicsTextInput::setReadOnly(bool ro)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (d->control->isReadOnly() == ro)
+ return;
+
+ d->control->setReadOnly(ro);
+
+ emit readOnlyChanged(ro);
+}
+
+int QmlGraphicsTextInput::maxLength() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->control->maxLength();
+}
+
+void QmlGraphicsTextInput::setMaxLength(int ml)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (d->control->maxLength() == ml)
+ return;
+
+ d->control->setMaxLength(ml);
+
+ emit maximumLengthChanged(ml);
+}
+
+/*!
+ \qmlproperty bool TextInput::cursorVisible
+ Set to true when the TextInput shows a cursor.
+
+ This property is set and unset when the TextInput gets 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 the 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 focus.
+*/
+bool QmlGraphicsTextInput::isCursorVisible() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->cursorVisible;
+}
+
+void QmlGraphicsTextInput::setCursorVisible(bool on)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (d->cursorVisible == on)
+ return;
+ d->cursorVisible = on;
+ d->control->setCursorBlinkPeriod(on?QApplication::cursorFlashTime():0);
+ //d->control should emit the cursor update regions
+ emit cursorVisibleChanged(d->cursorVisible);
+}
+
+/*!
+ \qmlproperty int TextInput::cursorPosition
+ The position of the cursor in the TextInput.
+*/
+int QmlGraphicsTextInput::cursorPosition() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->control->cursor();
+}
+void QmlGraphicsTextInput::setCursorPosition(int cp)
+{
+ Q_D(QmlGraphicsTextInput);
+ d->control->moveCursor(cp);
+}
+
+/*!
+ \internal
+
+ Returns a Rect which encompasses the cursor, but which may be larger than is
+ required. Ignores custom cursor delegates.
+*/
+QRect QmlGraphicsTextInput::cursorRect() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->control->cursorRect();
+}
+
+/*!
+ \qmlproperty int TextInput::selectionStart
+
+ The cursor position before the first character in the current selection.
+ Setting this and selectionEnd allows you to specify a selection in the
+ text edit.
+
+ Note that if selectionStart == selectionEnd then there is no current
+ selection. If you attempt to set selectionStart to a value outside of
+ the current text, selectionStart will not be changed.
+
+ \sa selectionEnd, cursorPosition, selectedText
+*/
+int QmlGraphicsTextInput::selectionStart() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->lastSelectionStart;
+}
+
+void QmlGraphicsTextInput::setSelectionStart(int s)
+{
+ Q_D(QmlGraphicsTextInput);
+ if(d->lastSelectionStart == s || s < 0 || s > text().length())
+ return;
+ d->lastSelectionStart = s;
+ d->control->setSelection(s, d->lastSelectionEnd - s);
+}
+
+/*!
+ \qmlproperty int TextInput::selectionEnd
+
+ The cursor position after the last character in the current selection.
+ Setting this and selectionStart allows you to specify a selection in the
+ text edit.
+
+ Note that if selectionStart == selectionEnd then there is no current
+ selection. If you attempt to set selectionEnd to a value outside of
+ the current text, selectionEnd will not be changed.
+
+ \sa selectionStart, cursorPosition, selectedText
+*/
+int QmlGraphicsTextInput::selectionEnd() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->lastSelectionEnd;
+}
+
+void QmlGraphicsTextInput::setSelectionEnd(int s)
+{
+ Q_D(QmlGraphicsTextInput);
+ if(d->lastSelectionEnd == s || s < 0 || s > text().length())
+ return;
+ d->lastSelectionEnd = s;
+ d->control->setSelection(d->lastSelectionStart, s - d->lastSelectionStart);
+}
+
+/*!
+ \qmlproperty string 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.
+
+ \qml
+ myTextInput.text.toString().substring(myTextInput.selectionStart,
+ myTextInput.selectionEnd);
+ \endqml
+*/
+QString QmlGraphicsTextInput::selectedText() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->control->selectedText();
+}
+
+/*!
+ \qmlproperty bool TextInput::focusOnPress
+
+ Whether the TextInput should gain focus on a mouse press. By default this is
+ set to true.
+*/
+bool QmlGraphicsTextInput::focusOnPress() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->focusOnPress;
+}
+
+void QmlGraphicsTextInput::setFocusOnPress(bool b)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (d->focusOnPress == b)
+ return;
+
+ d->focusOnPress = b;
+
+ emit focusOnPressChanged(d->focusOnPress);
+}
+
+/*!
+ \qmlproperty QValidator* TextInput::validator
+
+ Allows you to set a QValidator 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 QIntValidator, QDoubleValidator and
+ QRegExpValidator. For details, refer to their C++ documentation and remember
+ that all Q_PROPERTIES are accessible from Qml. A brief usage guide follows:
+
+ QIntValidator and QDoubleValidator both are controllable through two properties,
+ top and bottom. The difference is that for QIntValidator the top and bottom properties
+ should be integers, and for QDoubleValidator they should be doubles. QRegExpValidator
+ has a single string property, regExp, which should be set to the regular expression to
+ be used for validation. An example of using validators is shown below, which allows
+ input of integers between 11 and 31 into the text input:
+
+ \code
+ import Qt 4.6
+ TextInput{
+ validator: QIntValidator{bottom: 11; top: 31;}
+ focus: true
+ }
+ \endcode
+
+ \sa acceptableInput, inputMask
+*/
+QValidator* QmlGraphicsTextInput::validator() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ //###const cast isn't good, but needed for property system?
+ return const_cast<QValidator*>(d->control->validator());
+}
+
+void QmlGraphicsTextInput::setValidator(QValidator* v)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (d->control->validator() == v)
+ return;
+
+ d->control->setValidator(v);
+ if(!d->control->hasAcceptableInput()){
+ d->oldValidity = false;
+ emit acceptableInputChanged();
+ }
+
+ emit validatorChanged();
+}
+
+/*!
+ \qmlproperty string 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 QmlGraphicsTextInput::inputMask() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->control->inputMask();
+}
+
+void QmlGraphicsTextInput::setInputMask(const QString &im)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (d->control->inputMask() == im)
+ return;
+
+ d->control->setInputMask(im);
+ emit inputMaskChanged(d->control->inputMask());
+}
+
+/*!
+ \qmlproperty bool 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 QmlGraphicsTextInput::hasAcceptableInput() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->control->hasAcceptableInput();
+}
+
+/*!
+ \qmlproperty TextInput.EchoMode TextInput::echoMode
+
+ Specifies how the text should be displayed in the TextInput.
+ The default is Normal, which displays the text as it is. Other values
+ are Password, which displays asterixes instead of characters, NoEcho,
+ which displays nothing, and PasswordEchoOnEdit, which displays all but the
+ current character as asterixes.
+
+*/
+QmlGraphicsTextInput::EchoMode QmlGraphicsTextInput::echoMode() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return (QmlGraphicsTextInput::EchoMode)d->control->echoMode();
+}
+
+void QmlGraphicsTextInput::setEchoMode(QmlGraphicsTextInput::EchoMode echo)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (echoMode() == echo)
+ return;
+
+ d->control->setEchoMode((uint)echo);
+ emit echoModeChanged(echoMode());
+}
+
+/*!
+ \qmlproperty Component 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 QmlGraphicsItem or
+ QmlGraphicsItem derived item.
+*/
+QmlComponent* QmlGraphicsTextInput::cursorDelegate() const
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->cursorComponent;
+}
+
+void QmlGraphicsTextInput::setCursorDelegate(QmlComponent* c)
+{
+ Q_D(QmlGraphicsTextInput);
+ if (d->cursorComponent == c)
+ return;
+
+ d->cursorComponent = c;
+ if(!c){
+ //note that the components are owned by something else
+ disconnect(d->control, SIGNAL(cursorPositionChanged(int, int)),
+ this, SLOT(moveCursor()));
+ delete d->cursorItem;
+ }else{
+ d->startCreatingCursor();
+ }
+
+ emit cursorDelegateChanged();
+}
+
+void QmlGraphicsTextInputPrivate::startCreatingCursor()
+{
+ Q_Q(QmlGraphicsTextInput);
+ q->connect(control, SIGNAL(cursorPositionChanged(int, int)),
+ q, SLOT(moveCursor()));
+ if(cursorComponent->isReady()){
+ q->createCursor();
+ }else if(cursorComponent->isLoading()){
+ q->connect(cursorComponent, SIGNAL(statusChanged(int)),
+ q, SLOT(createCursor()));
+ }else{//isError
+ qmlInfo(q) << QmlGraphicsTextInput::tr("Could not load cursor delegate");
+ qWarning() << cursorComponent->errors();
+ }
+}
+
+void QmlGraphicsTextInput::createCursor()
+{
+ Q_D(QmlGraphicsTextInput);
+ if(d->cursorComponent->isError()){
+ qmlInfo(this) << tr("Could not load cursor delegate");
+ qWarning() << d->cursorComponent->errors();
+ return;
+ }
+
+ if(!d->cursorComponent->isReady())
+ return;
+
+ if(d->cursorItem)
+ delete d->cursorItem;
+ d->cursorItem = qobject_cast<QmlGraphicsItem*>(d->cursorComponent->create());
+ if(!d->cursorItem){
+ qmlInfo(this) << tr("Could not instantiate cursor delegate");
+ //The failed instantiation should print its own error messages
+ return;
+ }
+
+ d->cursorItem->setParentItem(this);
+ d->cursorItem->setX(d->control->cursorToX());
+ d->cursorItem->setHeight(d->control->height());
+}
+
+void QmlGraphicsTextInput::moveCursor()
+{
+ Q_D(QmlGraphicsTextInput);
+ if(!d->cursorItem)
+ return;
+ d->cursorItem->setX(d->control->cursorToX() - d->hscroll);
+}
+
+int QmlGraphicsTextInput::xToPos(int x)
+{
+ Q_D(const QmlGraphicsTextInput);
+ return d->control->xToPos(x - d->hscroll);
+}
+
+void QmlGraphicsTextInput::focusChanged(bool hasFocus)
+{
+ Q_D(QmlGraphicsTextInput);
+ d->focused = hasFocus;
+ setCursorVisible(hasFocus);
+ QmlGraphicsItem::focusChanged(hasFocus);
+}
+
+void QmlGraphicsTextInput::keyPressEvent(QKeyEvent* ev)
+{
+ Q_D(QmlGraphicsTextInput);
+ if((d->control->cursor() == 0 && ev->key() == Qt::Key_Left)
+ || (d->control->cursor() == d->control->text().length()
+ && ev->key() == Qt::Key_Right)){
+ //ignore when moving off the end
+ ev->ignore();
+ }else{
+ d->control->processKeyEvent(ev);
+ }
+ if (!ev->isAccepted())
+ QmlGraphicsPaintedItem::keyPressEvent(ev);
+}
+
+void QmlGraphicsTextInput::mousePressEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsTextInput);
+ if(d->focusOnPress){
+ QGraphicsItem *p = parentItem();//###Is there a better way to find my focus scope?
+ while(p) {
+ if(p->flags() & QGraphicsItem::ItemIsFocusScope){
+ p->setFocus();
+ break;
+ }
+ p = p->parentItem();
+ }
+ setFocus(true);
+ }
+ d->control->processEvent(event);
+}
+
+/*!
+\overload
+Handles the given mouse \a event.
+*/
+void QmlGraphicsTextInput::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsTextInput);
+ QWidget *widget = event->widget();
+ if (widget && !d->control->isReadOnly() && boundingRect().contains(event->pos()))
+ qt_widget_private(widget)->handleSoftwareInputPanel(event->button(), d->focusOnPress);
+ d->control->processEvent(event);
+}
+
+bool QmlGraphicsTextInput::event(QEvent* ev)
+{
+ Q_D(QmlGraphicsTextInput);
+ //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::GraphicsSceneMousePress:
+ case QEvent::GraphicsSceneMouseRelease:
+ break;
+ default:
+ handled = d->control->processEvent(ev);
+ }
+ if(!handled)
+ return QmlGraphicsPaintedItem::event(ev);
+ return true;
+}
+
+void QmlGraphicsTextInput::geometryChanged(const QRectF &newGeometry,
+ const QRectF &oldGeometry)
+{
+ if (newGeometry.width() != oldGeometry.width())
+ updateSize();
+ QmlGraphicsPaintedItem::geometryChanged(newGeometry, oldGeometry);
+}
+
+void QmlGraphicsTextInput::drawContents(QPainter *p, const QRect &r)
+{
+ Q_D(QmlGraphicsTextInput);
+ p->setRenderHint(QPainter::TextAntialiasing, true);
+ p->save();
+ p->setPen(QPen(d->color));
+ int flags = QLineControl::DrawText;
+ if(!isReadOnly() && d->cursorVisible && !d->cursorItem)
+ flags |= QLineControl::DrawCursor;
+ if (d->control->hasSelectedText()){
+ flags |= QLineControl::DrawSelections;
+ }
+
+ QPoint offset = QPoint(0,0);
+ if(d->hAlign != AlignLeft){
+ QFontMetrics fm = QFontMetrics(d->font);
+ //###Is this using bearing appropriately?
+ int minLB = qMax(0, -fm.minLeftBearing());
+ int minRB = qMax(0, -fm.minRightBearing());
+ int widthUsed = qRound(d->control->naturalTextWidth()) + 1 + minRB;
+ int hOffset = 0;
+ if(d->hAlign == AlignRight){
+ hOffset = width() - widthUsed;
+ }else if(d->hAlign == AlignHCenter){
+ hOffset = (width() - widthUsed) / 2;
+ }
+ hOffset -= minLB;
+ offset = QPoint(hOffset, 0);
+ }
+ QRect clipRect = r;
+ d->control->draw(p, offset, clipRect, flags);
+
+ p->restore();
+}
+
+/*!
+\overload
+Returns the value of the given \a property.
+*/
+QVariant QmlGraphicsTextInput::inputMethodQuery(Qt::InputMethodQuery property) const
+{
+ Q_D(const QmlGraphicsTextInput);
+ switch(property) {
+ case Qt::ImFont:
+ return font();
+ case Qt::ImCursorPosition:
+ return QVariant(d->control->cursor());
+ case Qt::ImSurroundingText:
+ return QVariant(text());
+ 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();
+ }
+}
+
+void QmlGraphicsTextInput::selectAll()
+{
+ Q_D(QmlGraphicsTextInput);
+ d->control->setSelection(0, d->control->text().length());
+}
+
+
+/*!
+ \qmlproperty bool TextInput::smooth
+
+ Set this property if you want the text 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.
+*/
+
+void QmlGraphicsTextInputPrivate::init()
+{
+ Q_Q(QmlGraphicsTextInput);
+ control->setCursorWidth(1);
+ control->setPasswordCharacter(QLatin1Char('*'));
+ control->setLayoutDirection(Qt::LeftToRight);
+ q->setSmooth(smooth);
+ q->setAcceptedMouseButtons(Qt::LeftButton);
+ q->setFlag(QGraphicsItem::ItemHasNoContents, false);
+ q->setFlag(QGraphicsItem::ItemAcceptsInputMethod);
+ q->connect(control, SIGNAL(cursorPositionChanged(int,int)),
+ q, SLOT(cursorPosChanged()));
+ q->connect(control, SIGNAL(selectionChanged()),
+ q, SLOT(selectionChanged()));
+ q->connect(control, SIGNAL(textChanged(const QString &)),
+ q, SLOT(q_textChanged()));
+ q->connect(control, SIGNAL(accepted()),
+ q, SIGNAL(accepted()));
+ q->connect(control, SIGNAL(updateNeeded(QRect)),
+ q, SLOT(updateRect(QRect)));
+ q->connect(control, SIGNAL(cursorPositionChanged(int,int)),
+ q, SLOT(updateRect()));//TODO: Only update rect between pos's
+ q->connect(control, SIGNAL(selectionChanged()),
+ q, SLOT(updateRect()));//TODO: Only update rect in selection
+ //Note that above TODOs probably aren't that big a savings
+ q->updateSize();
+ oldValidity = control->hasAcceptableInput();
+ lastSelectionStart = 0;
+ lastSelectionEnd = 0;
+}
+
+void QmlGraphicsTextInput::cursorPosChanged()
+{
+ Q_D(QmlGraphicsTextInput);
+ emit cursorPositionChanged();
+
+ 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 QmlGraphicsTextInput::selectionChanged()
+{
+ Q_D(QmlGraphicsTextInput);
+ 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 QmlGraphicsTextInput::q_textChanged()
+{
+ Q_D(QmlGraphicsTextInput);
+ updateSize();
+ emit textChanged();
+ if(hasAcceptableInput() != d->oldValidity){
+ d->oldValidity = hasAcceptableInput();
+ emit acceptableInputChanged();
+ }
+}
+
+void QmlGraphicsTextInput::updateRect(const QRect &r)
+{
+ if(r == QRect())
+ clearCache();
+ else
+ dirtyCache(r);
+ update();
+}
+
+void QmlGraphicsTextInput::updateSize(bool needsRedraw)
+{
+ Q_D(QmlGraphicsTextInput);
+ int w = width();
+ int h = height();
+ setImplicitHeight(d->control->height());
+ int cursorWidth = d->control->cursorWidth();
+ if(d->cursorItem)
+ cursorWidth = d->cursorItem->width();
+ //### Is QFontMetrics too slow?
+ QFontMetricsF fm(d->font);
+ setImplicitWidth(fm.width(d->control->displayText())+cursorWidth);
+ setContentsSize(QSize(width(), height()));//Repaints if changed
+ if(w==width() && h==height() && needsRedraw){
+ clearCache();
+ update();
+ }
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/graphicsitems/qmlgraphicstextinput_p.h b/src/declarative/graphicsitems/qmlgraphicstextinput_p.h
new file mode 100644
index 0000000..4708381
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicstextinput_p.h
@@ -0,0 +1,230 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSTEXTINPUT_H
+#define QMLGRAPHICSTEXTINPUT_H
+
+#include "qmlgraphicstext_p.h"
+#include "qmlgraphicspainteditem_p.h"
+
+#include <QGraphicsSceneMouseEvent>
+#include <QIntValidator>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsTextInputPrivate;
+class QValidator;
+class Q_DECLARATIVE_EXPORT QmlGraphicsTextInput : public QmlGraphicsPaintedItem
+{
+ Q_OBJECT
+ Q_ENUMS(HAlignment)
+ Q_ENUMS(EchoMode)
+
+ 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 NOTIFY horizontalAlignmentChanged)
+
+ 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 cursorRect READ cursorRect NOTIFY cursorPositionChanged)
+ Q_PROPERTY(QmlComponent *cursorDelegate READ cursorDelegate WRITE setCursorDelegate NOTIFY cursorDelegateChanged)
+ Q_PROPERTY(int selectionStart READ selectionStart WRITE setSelectionStart NOTIFY selectionStartChanged)
+ Q_PROPERTY(int selectionEnd READ selectionEnd WRITE setSelectionEnd NOTIFY selectionEndChanged)
+ Q_PROPERTY(QString selectedText READ selectedText NOTIFY selectedTextChanged)
+
+ Q_PROPERTY(int maximumLength READ maxLength WRITE setMaxLength NOTIFY maximumLengthChanged)
+ Q_PROPERTY(QValidator* validator READ validator WRITE setValidator NOTIFY validatorChanged)
+ Q_PROPERTY(QString inputMask READ inputMask WRITE setInputMask NOTIFY inputMaskChanged)
+ Q_PROPERTY(Qt::InputMethodHints inputMethodHints READ inputMethodHints WRITE setInputMethodHints)
+
+ Q_PROPERTY(bool acceptableInput READ hasAcceptableInput NOTIFY acceptableInputChanged)
+ Q_PROPERTY(EchoMode echoMode READ echoMode WRITE setEchoMode NOTIFY echoModeChanged)
+ Q_PROPERTY(bool focusOnPress READ focusOnPress WRITE setFocusOnPress NOTIFY focusOnPressChanged)
+
+public:
+ QmlGraphicsTextInput(QmlGraphicsItem* parent=0);
+ ~QmlGraphicsTextInput();
+
+ enum EchoMode {//To match QLineEdit::EchoMode
+ Normal,
+ NoEcho,
+ Password,
+ PasswordEchoOnEdit
+ };
+
+ enum HAlignment {
+ AlignLeft = Qt::AlignLeft,
+ AlignRight = Qt::AlignRight,
+ AlignHCenter = Qt::AlignHCenter
+ };
+
+ //### Should we have this function, x based properties,
+ //### or copy TextEdit with x instead of QTextCursor?
+ Q_INVOKABLE int xToPos(int x);
+
+ 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);
+
+ bool isReadOnly() const;
+ void setReadOnly(bool);
+
+ bool isCursorVisible() const;
+ void setCursorVisible(bool on);
+
+ int cursorPosition() const;
+ void setCursorPosition(int cp);
+
+ QRect cursorRect() const;
+
+ int selectionStart() const;
+ void setSelectionStart(int);
+
+ int selectionEnd() const;
+ void setSelectionEnd(int);
+
+ QString selectedText() const;
+
+ int maxLength() const;
+ void setMaxLength(int ml);
+
+ QValidator * validator() const;
+ void setValidator(QValidator* v);
+
+ QString inputMask() const;
+ void setInputMask(const QString &im);
+
+ EchoMode echoMode() const;
+ void setEchoMode(EchoMode echo);
+
+ QmlComponent* cursorDelegate() const;
+ void setCursorDelegate(QmlComponent*);
+
+ bool focusOnPress() const;
+ void setFocusOnPress(bool);
+
+ bool hasAcceptableInput() const;
+
+ void drawContents(QPainter *p,const QRect &r);
+ QVariant inputMethodQuery(Qt::InputMethodQuery property) const;
+
+Q_SIGNALS:
+ void textChanged();
+ void cursorPositionChanged();
+ 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 focusOnPressChanged(bool focusOnPress);
+
+protected:
+ virtual void geometryChanged(const QRectF &newGeometry,
+ const QRectF &oldGeometry);
+
+ void mousePressEvent(QGraphicsSceneMouseEvent *event);
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
+ void keyPressEvent(QKeyEvent* ev);
+ bool event(QEvent *e);
+
+ void focusChanged(bool hasFocus);
+
+public Q_SLOTS:
+ void selectAll();
+
+private Q_SLOTS:
+ void updateSize(bool needsRedraw = true);
+ void q_textChanged();
+ void selectionChanged();
+ void createCursor();
+ void moveCursor();
+ void cursorPosChanged();
+ void updateRect(const QRect &r = QRect());
+
+private:
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsTextInput)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsTextInput)
+QML_DECLARE_TYPE(QValidator)
+QML_DECLARE_TYPE(QIntValidator)
+QML_DECLARE_TYPE(QDoubleValidator)
+QML_DECLARE_TYPE(QRegExpValidator)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSTEXTINPUT_H
diff --git a/src/declarative/graphicsitems/qmlgraphicstextinput_p_p.h b/src/declarative/graphicsitems/qmlgraphicstextinput_p_p.h
new file mode 100644
index 0000000..9eb6e07
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicstextinput_p_p.h
@@ -0,0 +1,114 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSTEXTINPUT_P_H
+#define QMLGRAPHICSTEXTINPUT_P_H
+
+#include "qmlgraphicstextinput_p.h"
+
+#include "qmlgraphicspainteditem_p_p.h"
+
+#include <qml.h>
+
+#include <QPointer>
+
+#include <private/qlinecontrol_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.
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsTextInputPrivate : public QmlGraphicsPaintedItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsTextInput)
+public:
+ QmlGraphicsTextInputPrivate() : control(new QLineControl(QString())),
+ color((QRgb)0), style(QmlGraphicsText::Normal),
+ styleColor((QRgb)0), hAlign(QmlGraphicsTextInput::AlignLeft),
+ hscroll(0), oldScroll(0), focused(false), focusOnPress(true),
+ cursorVisible(false)
+ {
+ }
+
+ ~QmlGraphicsTextInputPrivate()
+ {
+ delete control;
+ }
+
+ void init();
+ void startCreatingCursor();
+
+ QLineControl* control;
+
+ QFont font;
+ QColor color;
+ QColor selectionColor;
+ QColor selectedTextColor;
+ QmlGraphicsText::TextStyle style;
+ QColor styleColor;
+ QmlGraphicsTextInput::HAlignment hAlign;
+ QPointer<QmlComponent> cursorComponent;
+ QPointer<QmlGraphicsItem> cursorItem;
+
+ int lastSelectionStart;
+ int lastSelectionEnd;
+ int oldHeight;
+ int oldWidth;
+ bool oldValidity;
+ int hscroll;
+ int oldScroll;
+ bool focused;
+ bool focusOnPress;
+ bool cursorVisible;
+};
+
+QT_END_NAMESPACE
+
+#endif
+
diff --git a/src/declarative/graphicsitems/qmlgraphicsvisualitemmodel.cpp b/src/declarative/graphicsitems/qmlgraphicsvisualitemmodel.cpp
new file mode 100644
index 0000000..2fc143d
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsvisualitemmodel.cpp
@@ -0,0 +1,1155 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicsvisualitemmodel_p.h"
+
+#include "qmlgraphicsitem.h"
+
+#include <qmlcontext.h>
+#include <qmlengine.h>
+#include <qmlexpression.h>
+#include <qmlpackage_p.h>
+#include <qmlopenmetaobject_p.h>
+#include <qmllistaccessor_p.h>
+#include <qmlinfo.h>
+#include <qmldeclarativedata_p.h>
+#include <qmlpropertycache_p.h>
+#include <qmlguard_p.h>
+
+#include <qlistmodelinterface_p.h>
+#include <qhash.h>
+#include <qlist.h>
+#include <qmetaobjectbuilder_p.h>
+#include <QtCore/qdebug.h>
+
+#include <private/qobject_p.h>
+
+QML_DECLARE_TYPE(QListModelInterface)
+
+QT_BEGIN_NAMESPACE
+
+class QmlGraphicsVisualItemModelAttached : public QObject
+{
+ Q_OBJECT
+
+public:
+ QmlGraphicsVisualItemModelAttached(QObject *parent)
+ : QObject(parent), m_index(0) {}
+ ~QmlGraphicsVisualItemModelAttached() {
+ 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 QmlGraphicsVisualItemModelAttached *properties(QObject *obj) {
+ QmlGraphicsVisualItemModelAttached *rv = attachedProperties.value(obj);
+ if (!rv) {
+ rv = new QmlGraphicsVisualItemModelAttached(obj);
+ attachedProperties.insert(obj, rv);
+ }
+ return rv;
+ }
+
+Q_SIGNALS:
+ void indexChanged();
+
+public:
+ int m_index;
+
+ static QHash<QObject*, QmlGraphicsVisualItemModelAttached*> attachedProperties;
+};
+
+QHash<QObject*, QmlGraphicsVisualItemModelAttached*> QmlGraphicsVisualItemModelAttached::attachedProperties;
+
+
+class QmlGraphicsVisualItemModelPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsVisualItemModel)
+public:
+ QmlGraphicsVisualItemModelPrivate() : QObjectPrivate(), children(this) {}
+
+ struct ItemList : public QmlConcreteList<QmlGraphicsItem *>
+ {
+ ItemList(QmlGraphicsVisualItemModelPrivate *m) : QmlConcreteList<QmlGraphicsItem *>(), model(m) {}
+
+ void append(QmlGraphicsItem *item);
+
+ QmlGraphicsVisualItemModelPrivate *model;
+ };
+
+ void itemAppended() {
+ Q_Q(QmlGraphicsVisualItemModel);
+ QmlGraphicsVisualItemModelAttached *attached = QmlGraphicsVisualItemModelAttached::properties(children.last());
+ attached->setIndex(children.count()-1);
+ emit q->itemsInserted(children.count()-1, 1);
+ emit q->countChanged();
+ }
+
+ void emitChildrenChanged() {
+ Q_Q(QmlGraphicsVisualItemModel);
+ emit q->childrenChanged();
+ }
+ ItemList children;
+};
+
+
+/*!
+ \qmlclass VisualItemModel QmlGraphicsVisualItemModel
+ \brief The VisualItemModel allows items to be provided to a view.
+
+ The children of the VisualItemModel are provided in a model which
+ can be used in a view. Note that no delegate should be
+ provided to a view since the VisualItemModel contains the
+ visual delegate (items).
+
+ An item can determine its index within the
+ model via the VisualItemModel.index attached property.
+
+ The example below places three colored rectangles in a ListView.
+ \code
+ Item {
+ 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
+*/
+QmlGraphicsVisualItemModel::QmlGraphicsVisualItemModel()
+ : QmlGraphicsVisualModel(*(new QmlGraphicsVisualItemModelPrivate))
+{
+}
+
+QmlList<QmlGraphicsItem *> *QmlGraphicsVisualItemModel::children()
+{
+ Q_D(QmlGraphicsVisualItemModel);
+ return &(d->children);
+}
+
+/*!
+ \qmlproperty int VisualItemModel::count
+
+ The number of items in the model. This property is readonly.
+*/
+int QmlGraphicsVisualItemModel::count() const
+{
+ Q_D(const QmlGraphicsVisualItemModel);
+ return d->children.count();
+}
+
+bool QmlGraphicsVisualItemModel::isValid() const
+{
+ return true;
+}
+
+QmlGraphicsItem *QmlGraphicsVisualItemModel::item(int index, bool)
+{
+ Q_D(QmlGraphicsVisualItemModel);
+ return d->children.at(index);
+}
+
+QmlGraphicsVisualModel::ReleaseFlags QmlGraphicsVisualItemModel::release(QmlGraphicsItem *)
+{
+ // Nothing to do
+ return 0;
+}
+
+void QmlGraphicsVisualItemModel::completeItem()
+{
+ // Nothing to do
+}
+
+QString QmlGraphicsVisualItemModel::stringValue(int index, const QString &name)
+{
+ Q_D(QmlGraphicsVisualItemModel);
+ if (index < 0 || index >= d->children.count())
+ return QString();
+ return QmlEngine::contextForObject(d->children.at(index))->contextProperty(name).toString();
+}
+
+QVariant QmlGraphicsVisualItemModel::evaluate(int index, const QString &expression, QObject *objectContext)
+{
+ Q_D(QmlGraphicsVisualItemModel);
+ if (index < 0 || index >= d->children.count())
+ return QVariant();
+ QmlContext *ccontext = qmlContext(this);
+ QmlContext *ctxt = new QmlContext(ccontext);
+ ctxt->addDefaultObject(d->children.at(index));
+ QmlExpression e(ctxt, expression, objectContext);
+ e.setTrackChange(false);
+ QVariant value = e.value();
+ delete ctxt;
+ return value;
+}
+
+int QmlGraphicsVisualItemModel::indexOf(QmlGraphicsItem *item, QObject *) const
+{
+ Q_D(const QmlGraphicsVisualItemModel);
+ return d->children.indexOf(item);
+}
+
+void QmlGraphicsVisualItemModelPrivate::ItemList::append(QmlGraphicsItem *item)
+{
+ QmlConcreteList<QmlGraphicsItem*>::append(item);
+ item->QObject::setParent(model->q_ptr);
+ model->itemAppended();
+
+ model->emitChildrenChanged();
+}
+
+QmlGraphicsVisualItemModelAttached *QmlGraphicsVisualItemModel::qmlAttachedProperties(QObject *obj)
+{
+ return QmlGraphicsVisualItemModelAttached::properties(obj);
+}
+
+//============================================================================
+
+class VDMDelegateDataType : public QmlOpenMetaObjectType
+{
+public:
+ VDMDelegateDataType(const QMetaObject *base, QmlEngine *engine) : QmlOpenMetaObjectType(base, engine) {}
+
+ void propertyCreated(int, QMetaPropertyBuilder &prop) {
+ prop.setWritable(false);
+ }
+};
+
+class QmlGraphicsVisualDataModelParts;
+class QmlGraphicsVisualDataModelData;
+class QmlGraphicsVisualDataModelPrivate : public QObjectPrivate
+{
+public:
+ QmlGraphicsVisualDataModelPrivate(QmlContext *);
+
+ static QmlGraphicsVisualDataModelPrivate *get(QmlGraphicsVisualDataModel *m) {
+ return static_cast<QmlGraphicsVisualDataModelPrivate *>(QObjectPrivate::get(m));
+ }
+
+ QmlGuard<QListModelInterface> m_listModelInterface;
+ QmlGuard<QAbstractItemModel> m_abstractItemModel;
+ QmlGuard<QmlGraphicsVisualDataModel> m_visualItemModel;
+ QString m_part;
+
+ QmlComponent *m_delegate;
+ QmlContext *m_context;
+ QList<int> m_roles;
+ QHash<QByteArray,int> m_roleNames;
+ void ensureRoles() {
+ if (m_roleNames.isEmpty()) {
+ if (m_listModelInterface) {
+ m_roles = m_listModelInterface->roles();
+ for (int ii = 0; ii < m_roles.count(); ++ii)
+ m_roleNames.insert(m_listModelInterface->toString(m_roles.at(ii)).toUtf8(), m_roles.at(ii));
+ if (m_roles.count() == 1)
+ m_roleNames.insert("modelData", m_roles.at(0));
+ } else if (m_abstractItemModel) {
+ for (QHash<int,QByteArray>::const_iterator it = m_abstractItemModel->roleNames().begin();
+ it != m_abstractItemModel->roleNames().end(); ++it) {
+ m_roles.append(it.key());
+ m_roleNames.insert(*it, it.key());
+ }
+ if (m_roles.count() == 1)
+ m_roleNames.insert("modelData", m_roles.at(0));
+ } else if (m_listAccessor) {
+ m_roleNames.insert("modelData", 0);
+ if (m_listAccessor->type() == QmlListAccessor::Instance) {
+ if (QObject *object = m_listAccessor->at(0).value<QObject*>()) {
+ int count = object->metaObject()->propertyCount();
+ for (int ii = 1; ii < count; ++ii) {
+ const QMetaProperty &prop = object->metaObject()->property(ii);
+ m_roleNames.insert(prop.name(), 0);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ void createMetaData() {
+ if (!m_metaDataCreated) {
+ ensureRoles();
+ QHash<QByteArray, int>::const_iterator it = m_roleNames.begin();
+ while (it != m_roleNames.end()) {
+ m_delegateDataType->createProperty(it.key());
+ ++it;
+ }
+ m_metaDataCreated = true;
+ }
+ }
+
+ struct ObjectRef {
+ ObjectRef(QObject *object=0) : obj(object), ref(1) {}
+ QObject *obj;
+ int ref;
+ };
+ class Cache : public QHash<int, ObjectRef> {
+ public:
+ QObject *getItem(int index) {
+ QObject *item = 0;
+ QHash<int,ObjectRef>::iterator it = find(index);
+ if (it != end()) {
+ (*it).ref++;
+ item = (*it).obj;
+ }
+ return item;
+ }
+ QObject *item(int index) {
+ QObject *item = 0;
+ QHash<int, ObjectRef>::const_iterator it = find(index);
+ if (it != end())
+ item = (*it).obj;
+ return item;
+ }
+ void insertItem(int index, QObject *obj) {
+ insert(index, ObjectRef(obj));
+ }
+ bool releaseItem(QObject *obj) {
+ QHash<int, ObjectRef>::iterator it = begin();
+ for (; it != end(); ++it) {
+ ObjectRef &objRef = *it;
+ if (objRef.obj == obj) {
+ if (--objRef.ref == 0) {
+ erase(it);
+ return true;
+ }
+ break;
+ }
+ }
+ return false;
+ }
+ };
+
+ int modelCount() const {
+ if (m_visualItemModel)
+ return m_visualItemModel->count();
+ if (m_listModelInterface)
+ return m_listModelInterface->count();
+ if (m_abstractItemModel)
+ return m_abstractItemModel->rowCount();
+ if (m_listAccessor)
+ return m_listAccessor->count();
+ return 0;
+ }
+
+ Cache m_cache;
+ QHash<QObject *, QmlPackage*> m_packaged;
+
+ QmlGraphicsVisualDataModelParts *m_parts;
+ friend class QmlGraphicsVisualItemParts;
+
+ VDMDelegateDataType *m_delegateDataType;
+ friend class QmlGraphicsVisualDataModelData;
+ bool m_metaDataCreated;
+ bool m_metaDataCacheable;
+
+ QmlGraphicsVisualDataModelData *data(QObject *item);
+
+ QVariant m_modelVariant;
+ QmlListAccessor *m_listAccessor;
+};
+
+class QmlGraphicsVisualDataModelDataMetaObject : public QmlOpenMetaObject
+{
+public:
+ QmlGraphicsVisualDataModelDataMetaObject(QObject *parent, QmlOpenMetaObjectType *type)
+ : QmlOpenMetaObject(parent, type) {}
+
+ virtual QVariant initialValue(int);
+ virtual int createProperty(const char *, const char *);
+
+private:
+ friend class QmlGraphicsVisualDataModelData;
+ QHash<int,int> roleToProp;
+};
+
+class QmlGraphicsVisualDataModelData : public QObject
+{
+Q_OBJECT
+public:
+ QmlGraphicsVisualDataModelData(int index, QmlGraphicsVisualDataModel *model);
+ ~QmlGraphicsVisualDataModelData();
+
+ Q_PROPERTY(int index READ index NOTIFY indexChanged)
+ int index() const;
+ void setIndex(int index);
+
+ int propForRole(int) const;
+ void setValue(int, const QVariant &);
+
+Q_SIGNALS:
+ void indexChanged();
+
+private:
+ friend class QmlGraphicsVisualDataModelDataMetaObject;
+ int m_index;
+ QmlGuard<QmlGraphicsVisualDataModel> m_model;
+ QmlGraphicsVisualDataModelDataMetaObject *m_meta;
+};
+
+int QmlGraphicsVisualDataModelData::propForRole(int id) const
+{
+ QHash<int,int>::const_iterator it = m_meta->roleToProp.find(id);
+ if (it != m_meta->roleToProp.end())
+ return m_meta->roleToProp[id];
+ return -1;
+}
+
+void QmlGraphicsVisualDataModelData::setValue(int id, const QVariant &val)
+{
+ m_meta->setValue(id, val);
+}
+
+int QmlGraphicsVisualDataModelDataMetaObject::createProperty(const char *name, const char *type)
+{
+ QmlGraphicsVisualDataModelData *data =
+ static_cast<QmlGraphicsVisualDataModelData *>(object());
+
+ if (!data->m_model)
+ return -1;
+
+ QmlGraphicsVisualDataModelPrivate *model = QmlGraphicsVisualDataModelPrivate::get(data->m_model);
+
+ if ((!model->m_listModelInterface || !model->m_abstractItemModel) && model->m_listAccessor) {
+ if (model->m_listAccessor->type() == QmlListAccessor::QmlList
+ || model->m_listAccessor->type() == QmlListAccessor::QListPtr) {
+ model->ensureRoles();
+ QObject *object = model->m_listAccessor->at(data->m_index).value<QObject*>();
+ if (object && object->property(name).isValid())
+ return QmlOpenMetaObject::createProperty(name, type);
+ }
+ }
+ return -1;
+}
+
+QVariant QmlGraphicsVisualDataModelDataMetaObject::initialValue(int propId)
+{
+ QmlGraphicsVisualDataModelData *data =
+ static_cast<QmlGraphicsVisualDataModelData *>(object());
+
+ Q_ASSERT(data->m_model);
+ QmlGraphicsVisualDataModelPrivate *model = QmlGraphicsVisualDataModelPrivate::get(data->m_model);
+
+ QByteArray propName = name(propId);
+ if ((!model->m_listModelInterface || !model->m_abstractItemModel) && model->m_listAccessor) {
+ if (propName == "modelData") {
+ if (model->m_listAccessor->type() == QmlListAccessor::Instance) {
+ QObject *object = model->m_listAccessor->at(0).value<QObject*>();
+ return object->metaObject()->property(1).read(object); // the first property after objectName
+ }
+ return model->m_listAccessor->at(data->m_index);
+ } else {
+ // return any property of a single object instance.
+ QObject *object = model->m_listAccessor->at(data->m_index).value<QObject*>();
+ return object->property(propName);
+ }
+ } else if (model->m_listModelInterface) {
+ model->ensureRoles();
+ QHash<QByteArray,int>::const_iterator it = model->m_roleNames.find(propName);
+ if (it != model->m_roleNames.end()) {
+ roleToProp.insert(*it, propId);
+ QVariant value = model->m_listModelInterface->data(data->m_index, *it);
+ return value;
+ } else if (model->m_roles.count() == 1 && propName == "modelData") {
+ //for compatability with other lists, assign modelData if there is only a single role
+ roleToProp.insert(model->m_roles.first(), propId);
+ QVariant value = model->m_listModelInterface->data(data->m_index, model->m_roles.first());
+ return value;
+ }
+ } else if (model->m_abstractItemModel) {
+ model->ensureRoles();
+ QHash<QByteArray,int>::const_iterator it = model->m_roleNames.find(propName);
+ if (it != model->m_roleNames.end()) {
+ roleToProp.insert(*it, propId);
+ QModelIndex index = model->m_abstractItemModel->index(data->m_index, 0);
+ return model->m_abstractItemModel->data(index, *it);
+ }
+ }
+ Q_ASSERT(!"Can never be reached");
+ return QVariant();
+}
+
+QmlGraphicsVisualDataModelData::QmlGraphicsVisualDataModelData(int index,
+ QmlGraphicsVisualDataModel *model)
+: m_index(index), m_model(model),
+m_meta(new QmlGraphicsVisualDataModelDataMetaObject(this, QmlGraphicsVisualDataModelPrivate::get(model)->m_delegateDataType))
+{
+ QmlGraphicsVisualDataModelPrivate *modelPriv = QmlGraphicsVisualDataModelPrivate::get(model);
+ if (modelPriv->m_metaDataCacheable) {
+ if (!modelPriv->m_metaDataCreated)
+ modelPriv->createMetaData();
+ m_meta->setCached(true);
+ }
+}
+
+QmlGraphicsVisualDataModelData::~QmlGraphicsVisualDataModelData()
+{
+}
+
+int QmlGraphicsVisualDataModelData::index() const
+{
+ return m_index;
+}
+
+// This is internal only - it should not be set from qml
+void QmlGraphicsVisualDataModelData::setIndex(int index)
+{
+ m_index = index;
+ emit indexChanged();
+}
+
+//---------------------------------------------------------------------------
+
+class QmlGraphicsVisualDataModelPartsMetaObject : public QmlOpenMetaObject
+{
+public:
+ QmlGraphicsVisualDataModelPartsMetaObject(QObject *parent)
+ : QmlOpenMetaObject(parent) {}
+
+ virtual void propertyCreated(int, QMetaPropertyBuilder &);
+ virtual QVariant initialValue(int);
+};
+
+class QmlGraphicsVisualDataModelParts : public QObject
+{
+Q_OBJECT
+public:
+ QmlGraphicsVisualDataModelParts(QmlGraphicsVisualDataModel *parent);
+
+private:
+ friend class QmlGraphicsVisualDataModelPartsMetaObject;
+ QmlGraphicsVisualDataModel *model;
+};
+
+void QmlGraphicsVisualDataModelPartsMetaObject::propertyCreated(int, QMetaPropertyBuilder &prop)
+{
+ prop.setWritable(false);
+}
+
+QVariant QmlGraphicsVisualDataModelPartsMetaObject::initialValue(int id)
+{
+ QmlGraphicsVisualDataModel *m = new QmlGraphicsVisualDataModel;
+ m->setParent(object());
+ m->setPart(QString::fromUtf8(name(id)));
+ m->setModel(QVariant::fromValue(static_cast<QmlGraphicsVisualDataModelParts *>(object())->model));
+
+ QVariant var = QVariant::fromValue((QObject *)m);
+ return var;
+}
+
+QmlGraphicsVisualDataModelParts::QmlGraphicsVisualDataModelParts(QmlGraphicsVisualDataModel *parent)
+: QObject(parent), model(parent)
+{
+ new QmlGraphicsVisualDataModelPartsMetaObject(this);
+}
+
+QmlGraphicsVisualDataModelPrivate::QmlGraphicsVisualDataModelPrivate(QmlContext *ctxt)
+: m_listModelInterface(0), m_abstractItemModel(0), m_visualItemModel(0), m_delegate(0)
+, m_context(ctxt), m_parts(0), m_delegateDataType(0), m_metaDataCreated(false)
+, m_metaDataCacheable(false), m_listAccessor(0)
+{
+}
+
+QmlGraphicsVisualDataModelData *QmlGraphicsVisualDataModelPrivate::data(QObject *item)
+{
+ QmlGraphicsVisualDataModelData *dataItem =
+ item->findChild<QmlGraphicsVisualDataModelData *>();
+ Q_ASSERT(dataItem);
+ return dataItem;
+}
+
+//---------------------------------------------------------------------------
+
+QmlGraphicsVisualDataModel::QmlGraphicsVisualDataModel()
+: QmlGraphicsVisualModel(*(new QmlGraphicsVisualDataModelPrivate(0)))
+{
+}
+
+QmlGraphicsVisualDataModel::QmlGraphicsVisualDataModel(QmlContext *ctxt)
+: QmlGraphicsVisualModel(*(new QmlGraphicsVisualDataModelPrivate(ctxt)))
+{
+}
+
+QmlGraphicsVisualDataModel::~QmlGraphicsVisualDataModel()
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ if (d->m_listAccessor)
+ delete d->m_listAccessor;
+ if (d->m_delegateDataType)
+ d->m_delegateDataType->release();
+}
+
+QVariant QmlGraphicsVisualDataModel::model() const
+{
+ Q_D(const QmlGraphicsVisualDataModel);
+ return d->m_modelVariant;
+}
+
+void QmlGraphicsVisualDataModel::setModel(const QVariant &model)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ delete d->m_listAccessor;
+ 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(const QModelIndex &,int,int)),
+ this, SLOT(_q_rowsInserted(const QModelIndex &,int,int)));
+ QObject::disconnect(d->m_abstractItemModel, SIGNAL(rowsRemoved(const QModelIndex &,int,int)),
+ this, SLOT(_q_rowsRemoved(const QModelIndex &,int,int)));
+ QObject::disconnect(d->m_abstractItemModel, SIGNAL(dataChanged(const QModelIndex&,const QModelIndex&)),
+ this, SLOT(_q_dataChanged(const QModelIndex&,const QModelIndex&)));
+ QObject::disconnect(d->m_abstractItemModel, SIGNAL(rowsMoved(const QModelIndex&,int,int,const QModelIndex&,int)),
+ this, SLOT(_q_rowsMoved(const QModelIndex&,int,int,const QModelIndex&,int)));
+ } else if (d->m_visualItemModel) {
+ QObject::disconnect(d->m_visualItemModel, SIGNAL(itemsInserted(int,int)),
+ this, SIGNAL(itemsInserted(int,int)));
+ QObject::disconnect(d->m_visualItemModel, SIGNAL(itemsRemoved(int,int)),
+ this, SIGNAL(itemsRemoved(int,int)));
+ QObject::disconnect(d->m_visualItemModel, SIGNAL(itemsMoved(int,int,int)),
+ this, SIGNAL(itemsMoved(int,int,int)));
+ QObject::disconnect(d->m_visualItemModel, SIGNAL(createdPackage(int,QmlPackage*)),
+ this, SLOT(_q_createdPackage(int,QmlPackage*)));
+ QObject::disconnect(d->m_visualItemModel, SIGNAL(destroyingPackage(QmlPackage*)),
+ this, SLOT(_q_destroyingPackage(QmlPackage*)));
+ d->m_visualItemModel = 0;
+ }
+
+ d->m_roles.clear();
+ d->m_roleNames.clear();
+ if (d->m_delegateDataType)
+ d->m_delegateDataType->release();
+ d->m_metaDataCreated = 0;
+ d->m_metaDataCacheable = false;
+ d->m_delegateDataType = new VDMDelegateDataType(&QmlGraphicsVisualDataModelData::staticMetaObject, d->m_context?d->m_context->engine():qmlEngine(this));
+
+ 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)));
+ d->m_metaDataCacheable = true;
+ if (d->m_delegate && d->m_listModelInterface->count())
+ emit itemsInserted(0, d->m_listModelInterface->count());
+ return;
+ } else if (object && (d->m_abstractItemModel = qobject_cast<QAbstractItemModel *>(object))) {
+ QObject::connect(d->m_abstractItemModel, SIGNAL(rowsInserted(const QModelIndex &,int,int)),
+ this, SLOT(_q_rowsInserted(const QModelIndex &,int,int)));
+ QObject::connect(d->m_abstractItemModel, SIGNAL(rowsRemoved(const QModelIndex &,int,int)),
+ this, SLOT(_q_rowsRemoved(const QModelIndex &,int,int)));
+ QObject::connect(d->m_abstractItemModel, SIGNAL(dataChanged(const QModelIndex&,const QModelIndex&)),
+ this, SLOT(_q_dataChanged(const QModelIndex&,const QModelIndex&)));
+ QObject::connect(d->m_abstractItemModel, SIGNAL(rowsMoved(const QModelIndex&,int,int,const QModelIndex&,int)),
+ this, SLOT(_q_rowsMoved(const QModelIndex&,int,int,const QModelIndex&,int)));
+ d->m_metaDataCacheable = true;
+ return;
+ }
+ if ((d->m_visualItemModel = qvariant_cast<QmlGraphicsVisualDataModel *>(model))) {
+ QObject::connect(d->m_visualItemModel, SIGNAL(itemsInserted(int,int)),
+ this, SIGNAL(itemsInserted(int,int)));
+ QObject::connect(d->m_visualItemModel, SIGNAL(itemsRemoved(int,int)),
+ this, SIGNAL(itemsRemoved(int,int)));
+ QObject::connect(d->m_visualItemModel, SIGNAL(itemsMoved(int,int,int)),
+ this, SIGNAL(itemsMoved(int,int,int)));
+ QObject::connect(d->m_visualItemModel, SIGNAL(createdPackage(int,QmlPackage*)),
+ this, SLOT(_q_createdPackage(int,QmlPackage*)));
+ QObject::connect(d->m_visualItemModel, SIGNAL(destroyingPackage(QmlPackage*)),
+ this, SLOT(_q_destroyingPackage(QmlPackage*)));
+ return;
+ }
+ d->m_listAccessor = new QmlListAccessor;
+ d->m_listAccessor->setList(model, d->m_context?d->m_context->engine():qmlEngine(this));
+ if (d->m_listAccessor->type() != QmlListAccessor::QmlList && d->m_listAccessor->type() != QmlListAccessor::QListPtr)
+ d->m_metaDataCacheable = true;
+ if (d->m_delegate && d->modelCount()) {
+ emit itemsInserted(0, d->modelCount());
+ emit countChanged();
+ }
+}
+
+QmlComponent *QmlGraphicsVisualDataModel::delegate() const
+{
+ Q_D(const QmlGraphicsVisualDataModel);
+ if (d->m_visualItemModel)
+ return d->m_visualItemModel->delegate();
+ return d->m_delegate;
+}
+
+void QmlGraphicsVisualDataModel::setDelegate(QmlComponent *delegate)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ bool wasValid = d->m_delegate != 0;
+ d->m_delegate = delegate;
+ if (!wasValid && d->modelCount() && d->m_delegate) {
+ emit itemsInserted(0, d->modelCount());
+ emit countChanged();
+ }
+ if (wasValid && !d->m_delegate && d->modelCount()) {
+ emit itemsRemoved(0, d->modelCount());
+ emit countChanged();
+ }
+}
+
+QString QmlGraphicsVisualDataModel::part() const
+{
+ Q_D(const QmlGraphicsVisualDataModel);
+ return d->m_part;
+}
+
+void QmlGraphicsVisualDataModel::setPart(const QString &part)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ d->m_part = part;
+}
+
+int QmlGraphicsVisualDataModel::count() const
+{
+ Q_D(const QmlGraphicsVisualDataModel);
+ return d->modelCount();
+}
+
+QmlGraphicsItem *QmlGraphicsVisualDataModel::item(int index, bool complete)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ if (d->m_visualItemModel)
+ return d->m_visualItemModel->item(index, d->m_part.toUtf8(), complete);
+ return item(index, QByteArray(), complete);
+}
+
+/*
+ Returns ReleaseStatus flags.
+*/
+QmlGraphicsVisualDataModel::ReleaseFlags QmlGraphicsVisualDataModel::release(QmlGraphicsItem *item)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ if (d->m_visualItemModel)
+ return d->m_visualItemModel->release(item);
+
+ ReleaseFlags stat = 0;
+ QObject *obj = item;
+ bool inPackage = false;
+
+ QHash<QObject*,QmlPackage*>::iterator it = d->m_packaged.find(item);
+ if (it != d->m_packaged.end()) {
+ QmlPackage *package = *it;
+ d->m_packaged.erase(it);
+ if (d->m_packaged.contains(item))
+ stat |= Referenced;
+ inPackage = true;
+ obj = package; // fall through and delete
+ }
+
+ if (d->m_cache.releaseItem(obj)) {
+ if (inPackage) {
+ emit destroyingPackage(qobject_cast<QmlPackage*>(obj));
+ } else {
+ item->setVisible(false);
+ static_cast<QGraphicsItem*>(item)->setParentItem(0);
+ }
+ stat |= Destroyed;
+ obj->deleteLater();
+ } else if (!inPackage) {
+ stat |= Referenced;
+ }
+
+ return stat;
+}
+
+QObject *QmlGraphicsVisualDataModel::parts()
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ if (!d->m_parts)
+ d->m_parts = new QmlGraphicsVisualDataModelParts(this);
+ return d->m_parts;
+}
+
+QmlGraphicsItem *QmlGraphicsVisualDataModel::item(int index, const QByteArray &viewId, bool complete)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ if (d->m_visualItemModel)
+ return d->m_visualItemModel->item(index, viewId, complete);
+
+ if (d->modelCount() <= 0 || !d->m_delegate)
+ return 0;
+
+ QObject *nobj = d->m_cache.getItem(index);
+ if (!nobj) {
+ QmlContext *ccontext = d->m_context;
+ if (!ccontext) ccontext = qmlContext(this);
+ QmlContext *ctxt = new QmlContext(ccontext);
+ QmlGraphicsVisualDataModelData *data = new QmlGraphicsVisualDataModelData(index, this);
+ ctxt->setContextProperty(QLatin1String("model"), data);
+ ctxt->addDefaultObject(data);
+ nobj = d->m_delegate->beginCreate(ctxt);
+ if (complete)
+ d->m_delegate->completeCreate();
+ if (nobj) {
+ ctxt->setParent(nobj);
+ data->setParent(nobj);
+ d->m_cache.insertItem(index, nobj);
+ if (QmlPackage *package = qobject_cast<QmlPackage *>(nobj))
+ emit createdPackage(index, package);
+ } else {
+ delete data;
+ delete ctxt;
+ qWarning() << d->m_delegate->errors();
+ }
+ }
+ QmlGraphicsItem *item = qobject_cast<QmlGraphicsItem *>(nobj);
+ if (!item) {
+ QmlPackage *package = qobject_cast<QmlPackage *>(nobj);
+ if (package) {
+ QObject *o = package->part(QString::fromUtf8(viewId));
+ item = qobject_cast<QmlGraphicsItem *>(o);
+ if (item)
+ d->m_packaged.insertMulti(item, package);
+ }
+ }
+ if (!item) {
+ d->m_cache.releaseItem(nobj);
+ qmlInfo(d->m_delegate) << QmlGraphicsVisualDataModel::tr("Delegate component must be Item type.");
+ }
+
+ return item;
+}
+
+void QmlGraphicsVisualDataModel::completeItem()
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ if (d->m_visualItemModel) {
+ d->m_visualItemModel->completeItem();
+ return;
+ }
+
+ d->m_delegate->completeCreate();
+}
+
+QString QmlGraphicsVisualDataModel::stringValue(int index, const QString &name)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ if (d->m_visualItemModel)
+ return d->m_visualItemModel->stringValue(index, name);
+
+ if ((!d->m_listModelInterface && !d->m_abstractItemModel) || !d->m_delegate)
+ return QString();
+
+ QString val;
+ QObject *data = 0;
+ bool tempData = false;
+
+ if (QObject *nobj = d->m_cache.item(index))
+ data = d->data(nobj);
+ if (!data) {
+ data = new QmlGraphicsVisualDataModelData(index, this);
+ tempData = true;
+ }
+
+ QmlDeclarativeData *ddata = QmlDeclarativeData::get(data);
+ if (ddata && ddata->propertyCache) {
+ QmlPropertyCache::Data *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();
+ }
+
+ if (tempData)
+ delete data;
+
+ return val;
+}
+
+QVariant QmlGraphicsVisualDataModel::evaluate(int index, const QString &expression, QObject *objectContext)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ if (d->m_visualItemModel)
+ return d->m_visualItemModel->evaluate(index, expression, objectContext);
+
+ if ((!d->m_listModelInterface && !d->m_abstractItemModel) || !d->m_delegate)
+ return QVariant();
+
+ QVariant value;
+ QObject *nobj = d->m_cache.item(index);
+ if (nobj) {
+ QmlGraphicsItem *item = qobject_cast<QmlGraphicsItem *>(nobj);
+ if (item) {
+ QmlExpression e(qmlContext(item), expression, objectContext);
+ e.setTrackChange(false);
+ value = e.value();
+ }
+ } else {
+ QmlContext *ccontext = d->m_context;
+ if (!ccontext) ccontext = qmlContext(this);
+ QmlContext *ctxt = new QmlContext(ccontext);
+ QmlGraphicsVisualDataModelData *data = new QmlGraphicsVisualDataModelData(index, this);
+ ctxt->addDefaultObject(data);
+ QmlExpression e(ctxt, expression, objectContext);
+ e.setTrackChange(false);
+ value = e.value();
+ delete data;
+ delete ctxt;
+ }
+
+ return value;
+}
+
+int QmlGraphicsVisualDataModel::indexOf(QmlGraphicsItem *item, QObject *) const
+{
+ QVariant val = QmlEngine::contextForObject(item)->contextProperty(QLatin1String("index"));
+ return val.toInt();
+ return -1;
+}
+
+void QmlGraphicsVisualDataModel::_q_itemsChanged(int index, int count,
+ const QList<int> &roles)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ // XXX - highly inefficient
+ for (int ii = index; ii < index + count; ++ii) {
+
+ if (QObject *item = d->m_cache.item(ii)) {
+ QmlGraphicsVisualDataModelData *data = d->data(item);
+
+ for (int roleIdx = 0; roleIdx < roles.count(); ++roleIdx) {
+ int role = roles.at(roleIdx);
+ int propId = data->propForRole(role);
+ if (propId != -1) {
+ if (d->m_listModelInterface) {
+ data->setValue(propId, d->m_listModelInterface->data(ii, QList<int>() << role).value(role));
+ } else if (d->m_abstractItemModel) {
+ QModelIndex index = d->m_abstractItemModel->index(ii, 0);
+ data->setValue(propId, d->m_abstractItemModel->data(index, role));
+ }
+ }
+ }
+ }
+ }
+}
+
+void QmlGraphicsVisualDataModel::_q_itemsInserted(int index, int count)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ // XXX - highly inefficient
+ QHash<int,QmlGraphicsVisualDataModelPrivate::ObjectRef> items;
+ for (QHash<int,QmlGraphicsVisualDataModelPrivate::ObjectRef>::Iterator iter = d->m_cache.begin();
+ iter != d->m_cache.end(); ) {
+
+ if (iter.key() >= index) {
+ QmlGraphicsVisualDataModelPrivate::ObjectRef objRef = *iter;
+ int index = iter.key() + count;
+ iter = d->m_cache.erase(iter);
+
+ items.insert(index, objRef);
+
+ QmlGraphicsVisualDataModelData *data = d->data(objRef.obj);
+ data->setIndex(index);
+ } else {
+ ++iter;
+ }
+ }
+ d->m_cache.unite(items);
+
+ emit itemsInserted(index, count);
+ emit countChanged();
+}
+
+void QmlGraphicsVisualDataModel::_q_itemsRemoved(int index, int count)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ // XXX - highly inefficient
+ QHash<int, QmlGraphicsVisualDataModelPrivate::ObjectRef> items;
+ for (QHash<int, QmlGraphicsVisualDataModelPrivate::ObjectRef>::Iterator iter = d->m_cache.begin();
+ iter != d->m_cache.end(); ) {
+ if (iter.key() >= index && iter.key() < index + count) {
+ QmlGraphicsVisualDataModelPrivate::ObjectRef objRef = *iter;
+ iter = d->m_cache.erase(iter);
+ items.insertMulti(-1, objRef); //XXX perhaps better to maintain separately
+ QmlGraphicsVisualDataModelData *data = d->data(objRef.obj);
+ data->setIndex(-1);
+ } else if (iter.key() >= index + count) {
+ QmlGraphicsVisualDataModelPrivate::ObjectRef objRef = *iter;
+ int index = iter.key() - count;
+ iter = d->m_cache.erase(iter);
+ items.insert(index, objRef);
+ QmlGraphicsVisualDataModelData *data = d->data(objRef.obj);
+ data->setIndex(index);
+ } else {
+ ++iter;
+ }
+ }
+
+ d->m_cache.unite(items);
+ emit itemsRemoved(index, count);
+ emit countChanged();
+}
+
+void QmlGraphicsVisualDataModel::_q_itemsMoved(int from, int to, int count)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ // XXX - highly inefficient
+ QHash<int,QmlGraphicsVisualDataModelPrivate::ObjectRef> items;
+ for (QHash<int,QmlGraphicsVisualDataModelPrivate::ObjectRef>::Iterator iter = d->m_cache.begin();
+ iter != d->m_cache.end(); ) {
+
+ if (iter.key() >= from && iter.key() < from + count) {
+ QmlGraphicsVisualDataModelPrivate::ObjectRef objRef = *iter;
+ int index = iter.key() - from + to;
+ iter = d->m_cache.erase(iter);
+
+ items.insert(index, objRef);
+
+ QmlGraphicsVisualDataModelData *data = d->data(objRef.obj);
+ data->setIndex(index);
+ } else {
+ ++iter;
+ }
+ }
+ for (QHash<int,QmlGraphicsVisualDataModelPrivate::ObjectRef>::Iterator iter = d->m_cache.begin();
+ iter != d->m_cache.end(); ) {
+
+ int diff = from > to ? count : -count;
+ if (iter.key() >= qMin(from,to) && iter.key() < qMax(from+count,to+count)) {
+ QmlGraphicsVisualDataModelPrivate::ObjectRef objRef = *iter;
+ int index = iter.key() + diff;
+ iter = d->m_cache.erase(iter);
+
+ items.insert(index, objRef);
+
+ QmlGraphicsVisualDataModelData *data = d->data(objRef.obj);
+ data->setIndex(index);
+ } else {
+ ++iter;
+ }
+ }
+ d->m_cache.unite(items);
+
+ emit itemsMoved(from, to, count);
+}
+
+void QmlGraphicsVisualDataModel::_q_rowsInserted(const QModelIndex &parent, int begin, int end)
+{
+ if (!parent.isValid())
+ _q_itemsInserted(begin, end - begin + 1);
+}
+
+void QmlGraphicsVisualDataModel::_q_rowsRemoved(const QModelIndex &parent, int begin, int end)
+{
+ if (!parent.isValid())
+ _q_itemsRemoved(begin, end - begin + 1);
+}
+
+void QmlGraphicsVisualDataModel::_q_rowsMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)
+{
+ const int count = sourceEnd - sourceStart + 1;
+ if (!destinationParent.isValid() && !sourceParent.isValid()) {
+ _q_itemsMoved(sourceStart, destinationRow, count);
+ } else if (!sourceParent.isValid()) {
+ _q_itemsRemoved(sourceStart, count);
+ } else if (!destinationParent.isValid()) {
+ _q_itemsInserted(destinationRow, count);
+ }
+}
+
+void QmlGraphicsVisualDataModel::_q_dataChanged(const QModelIndex &begin, const QModelIndex &end)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ if (!begin.parent().isValid())
+ _q_itemsChanged(begin.row(), end.row() - begin.row() + 1, d->m_roles);
+}
+
+void QmlGraphicsVisualDataModel::_q_createdPackage(int index, QmlPackage *package)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ emit createdItem(index, qobject_cast<QmlGraphicsItem*>(package->part(d->m_part)));
+}
+
+void QmlGraphicsVisualDataModel::_q_destroyingPackage(QmlPackage *package)
+{
+ Q_D(QmlGraphicsVisualDataModel);
+ emit destroyingItem(qobject_cast<QmlGraphicsItem*>(package->part(d->m_part)));
+}
+
+QML_DEFINE_NOCREATE_TYPE(QmlGraphicsVisualModel);
+QML_DEFINE_TYPE(Qt,4,6,VisualItemModel,QmlGraphicsVisualItemModel)
+QML_DEFINE_TYPE(Qt,4,6,VisualDataModel,QmlGraphicsVisualDataModel)
+
+QT_END_NAMESPACE
+
+#include <qmlgraphicsvisualitemmodel.moc>
diff --git a/src/declarative/graphicsitems/qmlgraphicsvisualitemmodel_p.h b/src/declarative/graphicsitems/qmlgraphicsvisualitemmodel_p.h
new file mode 100644
index 0000000..ef849b0
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicsvisualitemmodel_p.h
@@ -0,0 +1,207 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSVISUALDATAMODEL_H
+#define QMLGRAPHICSVISUALDATAMODEL_H
+
+#include <qml.h>
+
+#include <QtCore/qobject.h>
+#include <QtCore/qabstractitemmodel.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+/*****************************************************************************
+ *****************************************************************************
+ XXX Experimental
+ *****************************************************************************
+*****************************************************************************/
+
+class QmlGraphicsItem;
+class QmlComponent;
+class QmlPackage;
+class QmlGraphicsVisualDataModelPrivate;
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsVisualModel : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(int count READ count NOTIFY countChanged)
+
+public:
+ QmlGraphicsVisualModel() {}
+ virtual ~QmlGraphicsVisualModel() {}
+
+ enum ReleaseFlag { Referenced = 0x01, Destroyed = 0x02 };
+ Q_DECLARE_FLAGS(ReleaseFlags, ReleaseFlag)
+
+ virtual int count() const = 0;
+ virtual bool isValid() const = 0;
+ virtual QmlGraphicsItem *item(int index, bool complete=true) = 0;
+ virtual ReleaseFlags release(QmlGraphicsItem *item) = 0;
+ virtual void completeItem() = 0;
+ virtual QVariant evaluate(int index, const QString &expression, QObject *objectContext) = 0;
+ virtual QString stringValue(int, const QString &) { return QString(); }
+
+ virtual int indexOf(QmlGraphicsItem *item, QObject *objectContext) const = 0;
+
+Q_SIGNALS:
+ void countChanged();
+ void itemsInserted(int index, int count);
+ void itemsRemoved(int index, int count);
+ void itemsMoved(int from, int to, int count);
+ void createdItem(int index, QmlGraphicsItem *item);
+ void destroyingItem(QmlGraphicsItem *item);
+
+protected:
+ QmlGraphicsVisualModel(QObjectPrivate &dd, QObject *parent = 0)
+ : QObject(dd, parent) {}
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsVisualModel)
+};
+
+class QmlGraphicsVisualItemModelAttached;
+class QmlGraphicsVisualItemModelPrivate;
+class Q_DECLARATIVE_EXPORT QmlGraphicsVisualItemModel : public QmlGraphicsVisualModel
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlGraphicsVisualItemModel)
+
+ Q_PROPERTY(QmlList<QmlGraphicsItem *>* children READ children NOTIFY childrenChanged DESIGNABLE false)
+ Q_CLASSINFO("DefaultProperty", "children")
+
+public:
+ QmlGraphicsVisualItemModel();
+ virtual ~QmlGraphicsVisualItemModel() {}
+
+ virtual int count() const;
+ virtual bool isValid() const;
+ virtual QmlGraphicsItem *item(int index, bool complete=true);
+ virtual ReleaseFlags release(QmlGraphicsItem *item);
+ virtual void completeItem();
+ virtual QString stringValue(int index, const QString &role);
+ virtual QVariant evaluate(int index, const QString &expression, QObject *objectContext);
+
+ virtual int indexOf(QmlGraphicsItem *item, QObject *objectContext) const;
+
+ QmlList<QmlGraphicsItem *> *children();
+
+ static QmlGraphicsVisualItemModelAttached *qmlAttachedProperties(QObject *obj);
+
+Q_SIGNALS:
+ void childrenChanged();
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsVisualItemModel)
+};
+
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsVisualDataModel : public QmlGraphicsVisualModel
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlGraphicsVisualDataModel)
+
+ Q_PROPERTY(QVariant model READ model WRITE setModel)
+ Q_PROPERTY(QmlComponent *delegate READ delegate WRITE setDelegate)
+ Q_PROPERTY(QString part READ part WRITE setPart)
+ Q_PROPERTY(QObject *parts READ parts CONSTANT)
+ Q_CLASSINFO("DefaultProperty", "delegate")
+public:
+ QmlGraphicsVisualDataModel();
+ QmlGraphicsVisualDataModel(QmlContext *);
+ virtual ~QmlGraphicsVisualDataModel();
+
+ QVariant model() const;
+ void setModel(const QVariant &);
+
+ QmlComponent *delegate() const;
+ void setDelegate(QmlComponent *);
+
+ QString part() const;
+ void setPart(const QString &);
+
+ int count() const;
+ bool isValid() const { return delegate() != 0; }
+ QmlGraphicsItem *item(int index, bool complete=true);
+ QmlGraphicsItem *item(int index, const QByteArray &, bool complete=true);
+ ReleaseFlags release(QmlGraphicsItem *item);
+ void completeItem();
+ virtual QString stringValue(int index, const QString &role);
+ QVariant evaluate(int index, const QString &expression, QObject *objectContext);
+
+ int indexOf(QmlGraphicsItem *item, QObject *objectContext) const;
+
+ QObject *parts();
+
+Q_SIGNALS:
+ void createdPackage(int index, QmlPackage *package);
+ void destroyingPackage(QmlPackage *package);
+
+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_createdPackage(int index, QmlPackage *package);
+ void _q_destroyingPackage(QmlPackage *package);
+
+private:
+ Q_DISABLE_COPY(QmlGraphicsVisualDataModel)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsVisualModel)
+QML_DECLARE_TYPE(QmlGraphicsVisualItemModel)
+QML_DECLARE_TYPEINFO(QmlGraphicsVisualItemModel, QML_HAS_ATTACHED_PROPERTIES)
+QML_DECLARE_TYPE(QmlGraphicsVisualDataModel)
+
+QT_END_HEADER
+
+#endif // QMLGRAPHICSVISUALDATAMODEL_H
diff --git a/src/declarative/graphicsitems/qmlgraphicswebview.cpp b/src/declarative/graphicsitems/qmlgraphicswebview.cpp
new file mode 100644
index 0000000..85fd0d7
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicswebview.cpp
@@ -0,0 +1,1351 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlgraphicswebview_p.h"
+#include "qmlgraphicswebview_p_p.h"
+
+#include "qmlgraphicspainteditem_p_p.h"
+
+#include <qml.h>
+#include <qmlengine.h>
+#include <qmlstate_p.h>
+
+#include <QDebug>
+#include <QPen>
+#include <QFile>
+#include <QEvent>
+#include <QMouseEvent>
+#include <QKeyEvent>
+#include <QBasicTimer>
+#include <QApplication>
+#include <QGraphicsSceneMouseEvent>
+#include <QtWebKit/QWebPage>
+#include <QtWebKit/QWebFrame>
+#include <QtWebKit/QWebElement>
+#include <QtWebKit/QWebSettings>
+#include <qlistmodelinterface_p.h>
+
+QT_BEGIN_NAMESPACE
+QML_DEFINE_TYPE(Qt,4,6,WebView,QmlGraphicsWebView)
+QML_DEFINE_NOCREATE_TYPE(QAction)
+
+static const int MAX_DOUBLECLICK_TIME=500; // XXX need better gesture system
+
+QML_DEFINE_NOCREATE_TYPE(QmlGraphicsWebSettings)
+
+class QmlGraphicsWebViewPrivate : public QmlGraphicsPaintedItemPrivate
+{
+ Q_DECLARE_PUBLIC(QmlGraphicsWebView)
+
+public:
+ QmlGraphicsWebViewPrivate()
+ : QmlGraphicsPaintedItemPrivate(), page(0), preferredwidth(0), preferredheight(0),
+ progress(1.0), status(QmlGraphicsWebView::Null), pending(PendingNone),
+ newWindowComponent(0), newWindowParent(0),
+ pressTime(400),
+ windowObjects(this),
+ rendering(true)
+ {
+ }
+
+ QUrl url; // page url might be different if it has not loaded yet
+ QWebPage *page;
+
+ int preferredwidth, preferredheight;
+ qreal progress;
+ QmlGraphicsWebView::Status status;
+ QString statusText;
+ enum { PendingNone, PendingUrl, PendingHtml, PendingContent } pending;
+ QUrl pending_url;
+ QString pending_string;
+ QByteArray pending_data;
+ mutable QmlGraphicsWebSettings settings;
+ QmlComponent *newWindowComponent;
+ QmlGraphicsItem *newWindowParent;
+
+ QBasicTimer pressTimer;
+ QPoint pressPoint;
+ int pressTime; // milliseconds before it's a "hold"
+
+ void updateWindowObjects();
+ class WindowObjectList : public QmlConcreteList<QObject *>
+ {
+ public:
+ WindowObjectList(QmlGraphicsWebViewPrivate *p)
+ : priv(p) {}
+ virtual void append(QObject *v) {
+ QmlConcreteList<QObject *>::append(v);
+ priv->updateWindowObjects();
+ }
+ private:
+ QmlGraphicsWebViewPrivate *priv;
+ } windowObjects;
+
+ bool rendering;
+};
+
+/*!
+ \qmlclass WebView QmlGraphicsWebView
+ \brief The WebView item allows you to add web content to a canvas.
+ \inherits Item
+
+ A WebView renders web content based on a URL.
+
+ If the width and height of the item is not set, they will
+ dynamically adjust to a size appropriate for the content.
+ This width may be large for typical online web pages.
+
+ If the preferredWidth is set, the width will be this amount or larger,
+ usually laying out the web content to fit the preferredWidth.
+
+ \qml
+ WebView {
+ url: "http://www.nokia.com"
+ width: 490
+ height: 400
+ scale: 0.5
+ smooth: false
+ smoothCache: true
+ }
+ \endqml
+
+ \image webview.png
+
+ The item includes no scrolling, scaling,
+ toolbars, etc., those must be implemented around WebView. See the WebBrowser example
+ for a demonstration of this.
+*/
+
+/*!
+ \internal
+ \class QmlGraphicsWebView
+ \brief The QmlGraphicsWebView class allows you to add web content to a QmlView.
+
+ A WebView renders web content base on a URL.
+
+ \image webview.png
+
+ The item includes no scrolling, scaling,
+ toolbars, etc., those must be implemented around WebView. See the WebBrowser example
+ for a demonstration of this.
+
+ A QmlGraphicsWebView object can be instantiated in Qml using the tag \l WebView.
+*/
+
+QmlGraphicsWebView::QmlGraphicsWebView(QmlGraphicsItem *parent)
+ : QmlGraphicsPaintedItem(*(new QmlGraphicsWebViewPrivate), parent)
+{
+ init();
+}
+
+QmlGraphicsWebView::~QmlGraphicsWebView()
+{
+ Q_D(QmlGraphicsWebView);
+ delete d->page;
+}
+
+void QmlGraphicsWebView::init()
+{
+ Q_D(QmlGraphicsWebView);
+
+ setAcceptHoverEvents(true);
+ setAcceptedMouseButtons(Qt::LeftButton);
+ setFlag(QGraphicsItem::ItemHasNoContents, false);
+
+ d->page = 0;
+}
+
+void QmlGraphicsWebView::componentComplete()
+{
+ QmlGraphicsPaintedItem::componentComplete();
+ Q_D(QmlGraphicsWebView);
+ switch (d->pending) {
+ case QmlGraphicsWebViewPrivate::PendingUrl:
+ setUrl(d->pending_url);
+ break;
+ case QmlGraphicsWebViewPrivate::PendingHtml:
+ setHtml(d->pending_string, d->pending_url);
+ break;
+ case QmlGraphicsWebViewPrivate::PendingContent:
+ setContent(d->pending_data, d->pending_string, d->pending_url);
+ break;
+ default:
+ break;
+ }
+ d->pending = QmlGraphicsWebViewPrivate::PendingNone;
+ d->updateWindowObjects();
+}
+
+QmlGraphicsWebView::Status QmlGraphicsWebView::status() const
+{
+ Q_D(const QmlGraphicsWebView);
+ return d->status;
+}
+
+
+/*!
+ \qmlproperty real WebView::progress
+ This property holds the progress of loading the current URL, from 0 to 1.
+
+ If you just want to know when progress gets to 1, use
+ WebView::onLoadFinished() or WebView::onLoadFailed() instead.
+*/
+qreal QmlGraphicsWebView::progress() const
+{
+ Q_D(const QmlGraphicsWebView);
+ return d->progress;
+}
+
+void QmlGraphicsWebView::doLoadStarted()
+{
+ Q_D(QmlGraphicsWebView);
+
+ if (!d->url.isEmpty()) {
+ d->status = Loading;
+ emit statusChanged(d->status);
+ }
+ emit loadStarted();
+}
+
+void QmlGraphicsWebView::doLoadProgress(int p)
+{
+ Q_D(QmlGraphicsWebView);
+ if (d->progress == p/100.0)
+ return;
+ d->progress = p/100.0;
+ emit progressChanged();
+}
+
+void QmlGraphicsWebView::pageUrlChanged()
+{
+ Q_D(QmlGraphicsWebView);
+
+ page()->setViewportSize(QSize(
+ d->preferredwidth>0 ? d->preferredwidth : width(),
+ d->preferredheight>0 ? d->preferredheight : height()));
+ expandToWebPage();
+
+ if ((d->url.isEmpty() && page()->mainFrame()->url() != QUrl(QLatin1String("about:blank")))
+ || (d->url != page()->mainFrame()->url() && !page()->mainFrame()->url().isEmpty()))
+ {
+ d->url = page()->mainFrame()->url();
+ if (d->url == QUrl(QLatin1String("about:blank")))
+ d->url = QUrl();
+ emit urlChanged();
+ }
+}
+
+void QmlGraphicsWebView::doLoadFinished(bool ok)
+{
+ Q_D(QmlGraphicsWebView);
+
+ if (title().isEmpty())
+ pageUrlChanged(); // XXX bug 232556 - pages with no title never get urlChanged()
+
+ if (ok) {
+ d->status = d->url.isEmpty() ? Null : Ready;
+ emit loadFinished();
+ } else {
+ d->status = Error;
+ emit loadFailed();
+ }
+ emit statusChanged(d->status);
+}
+
+/*!
+ \qmlproperty url WebView::url
+ This property holds the URL to the page displayed in this item. It can be set,
+ but also can change spontaneously (eg. because of network redirection).
+
+ If the url is empty, the page is blank.
+
+ The url is always absolute (QML will resolve relative URL strings in the context
+ of the containing QML document).
+*/
+QUrl QmlGraphicsWebView::url() const
+{
+ Q_D(const QmlGraphicsWebView);
+ return d->url;
+}
+
+void QmlGraphicsWebView::setUrl(const QUrl &url)
+{
+ Q_D(QmlGraphicsWebView);
+ if (url == d->url)
+ return;
+
+ if (isComponentComplete()) {
+ d->url = url;
+ page()->setViewportSize(QSize(
+ d->preferredwidth>0 ? d->preferredwidth : width(),
+ d->preferredheight>0 ? d->preferredheight : height()));
+ QUrl seturl = url;
+ if (seturl.isEmpty())
+ seturl = QUrl(QLatin1String("about:blank"));
+
+ Q_ASSERT(!seturl.isRelative());
+
+ page()->mainFrame()->load(seturl);
+
+ emit urlChanged();
+ } else {
+ d->pending = d->PendingUrl;
+ d->pending_url = url;
+ }
+}
+
+/*!
+ \qmlproperty int WebView::preferredWidth
+ This property holds the ideal width for displaying the current URL.
+*/
+int QmlGraphicsWebView::preferredWidth() const
+{
+ Q_D(const QmlGraphicsWebView);
+ return d->preferredwidth;
+}
+
+void QmlGraphicsWebView::setPreferredWidth(int iw)
+{
+ Q_D(QmlGraphicsWebView);
+ if (d->preferredwidth == iw) return;
+ d->preferredwidth = iw;
+ //expandToWebPage();
+ emit preferredWidthChanged();
+}
+
+/*!
+ \qmlproperty int WebView::preferredHeight
+ This property holds the ideal height for displaying the current URL.
+ This only affects the area zoomed by heuristicZoom().
+*/
+int QmlGraphicsWebView::preferredHeight() const
+{
+ Q_D(const QmlGraphicsWebView);
+ return d->preferredheight;
+}
+void QmlGraphicsWebView::setPreferredHeight(int ih)
+{
+ Q_D(QmlGraphicsWebView);
+ if (d->preferredheight == ih) return;
+ d->preferredheight = ih;
+ emit preferredHeightChanged();
+}
+
+/*!
+ \qmlmethod bool WebView::evaluateJavaScript(string)
+
+ Evaluates the \a scriptSource JavaScript inside the context of the
+ main web frame, and returns the result of the last executed statement.
+
+ Note that this JavaScript does \e not have any access to QML objects
+ except as made available as windowObjects.
+*/
+QVariant QmlGraphicsWebView::evaluateJavaScript(const QString &scriptSource)
+{
+ return this->page()->mainFrame()->evaluateJavaScript(scriptSource);
+}
+
+void QmlGraphicsWebView::focusChanged(bool hasFocus)
+{
+ QFocusEvent e(hasFocus ? QEvent::FocusIn : QEvent::FocusOut);
+ page()->event(&e);
+ QmlGraphicsItem::focusChanged(hasFocus);
+}
+
+void QmlGraphicsWebView::initialLayout()
+{
+ // nothing useful to do at this point
+}
+
+void QmlGraphicsWebView::noteContentsSizeChanged(const QSize&)
+{
+ expandToWebPage();
+}
+
+void QmlGraphicsWebView::expandToWebPage()
+{
+ Q_D(QmlGraphicsWebView);
+ QSize cs = page()->mainFrame()->contentsSize();
+ if (cs.width() < d->preferredwidth)
+ cs.setWidth(d->preferredwidth);
+ if (cs.height() < d->preferredheight)
+ cs.setHeight(d->preferredheight);
+ if (widthValid())
+ cs.setWidth(width());
+ if (heightValid())
+ cs.setHeight(height());
+ if (cs != page()->viewportSize()) {
+ page()->setViewportSize(cs);
+ }
+ if (cs != contentsSize())
+ setContentsSize(cs);
+}
+
+void QmlGraphicsWebView::geometryChanged(const QRectF &newGeometry,
+ const QRectF &oldGeometry)
+{
+ if (newGeometry.size() != oldGeometry.size())
+ expandToWebPage();
+ QmlGraphicsPaintedItem::geometryChanged(newGeometry, oldGeometry);
+}
+
+void QmlGraphicsWebView::paintPage(const QRect& r)
+{
+ dirtyCache(r);
+ update();
+}
+
+/*!
+ \qmlproperty list<object> WebView::javaScriptWindowObjects
+
+ This property is a list of object that are available from within
+ the webview's JavaScript context.
+
+ The \a object will be inserted as a child of the frame's window
+ object, under the name given by the attached property \c WebView.windowObjectName.
+
+ \qml
+ WebView {
+ javaScriptWindowObjects: Object {
+ WebView.windowObjectName: "coordinates"
+ }
+ }
+ \endqml
+
+ Properties of the object will be exposed as JavaScript properties and slots as
+ JavaScript methods.
+
+ If Javascript is not enabled for this page, then this property does nothing.
+*/
+QmlList<QObject *> *QmlGraphicsWebView::javaScriptWindowObjects()
+{
+ Q_D(QmlGraphicsWebView);
+ return &d->windowObjects;
+}
+
+class QmlGraphicsWebViewAttached : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(QString windowObjectName READ windowObjectName WRITE setWindowObjectName)
+public:
+ QmlGraphicsWebViewAttached(QObject *parent)
+ : QObject(parent)
+ {
+ }
+
+ QString windowObjectName() const
+ {
+ return m_windowObjectName;
+ }
+
+ void setWindowObjectName(const QString &n)
+ {
+ m_windowObjectName = n;
+ }
+
+private:
+ QString m_windowObjectName;
+};
+
+QmlGraphicsWebViewAttached *QmlGraphicsWebView::qmlAttachedProperties(QObject *o)
+{
+ return new QmlGraphicsWebViewAttached(o);
+}
+
+void QmlGraphicsWebViewPrivate::updateWindowObjects()
+{
+ Q_Q(QmlGraphicsWebView);
+ if (!q->isComponentComplete() || !page)
+ return;
+
+ for (int ii = 0; ii < windowObjects.count(); ++ii) {
+ QObject *object = windowObjects.at(ii);
+ QmlGraphicsWebViewAttached *attached = static_cast<QmlGraphicsWebViewAttached *>(qmlAttachedPropertiesObject<QmlGraphicsWebView>(object));
+ if (attached && !attached->windowObjectName().isEmpty()) {
+ page->mainFrame()->addToJavaScriptWindowObject(attached->windowObjectName(), object);
+ }
+ }
+}
+
+bool QmlGraphicsWebView::renderingEnabled() const
+{
+ Q_D(const QmlGraphicsWebView);
+ return d->rendering;
+}
+
+void QmlGraphicsWebView::setRenderingEnabled(bool enabled)
+{
+ Q_D(QmlGraphicsWebView);
+ if (d->rendering == enabled)
+ return;
+ d->rendering = enabled;
+ setCacheFrozen(!enabled);
+ if (enabled)
+ clearCache();
+}
+
+
+void QmlGraphicsWebView::drawContents(QPainter *p, const QRect &r)
+{
+ Q_D(QmlGraphicsWebView);
+ if (d->rendering)
+ page()->mainFrame()->render(p,r);
+}
+
+QMouseEvent *QmlGraphicsWebView::sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *e)
+{
+ QEvent::Type t;
+ switch(e->type()) {
+ default:
+ case QEvent::GraphicsSceneMousePress:
+ t = QEvent::MouseButtonPress;
+ break;
+ case QEvent::GraphicsSceneMouseRelease:
+ t = QEvent::MouseButtonRelease;
+ break;
+ case QEvent::GraphicsSceneMouseMove:
+ t = QEvent::MouseMove;
+ break;
+ case QGraphicsSceneEvent::GraphicsSceneMouseDoubleClick:
+ t = QEvent::MouseButtonDblClick;
+ break;
+ }
+
+ QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), e->button(), e->buttons(), 0);
+ return me;
+}
+
+QMouseEvent *QmlGraphicsWebView::sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *e)
+{
+ QEvent::Type t = QEvent::MouseMove;
+
+ QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), Qt::NoButton, Qt::NoButton, 0);
+
+ return me;
+}
+
+
+/*!
+ \qmlsignal WebView::onDoubleClick(clickx,clicky)
+
+ The WebView does not pass double-click events to the web engine, but rather
+ emits this signals.
+*/
+
+void QmlGraphicsWebView::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
+{
+ QMouseEvent *me = sceneMouseEventToMouseEvent(event);
+ emit doubleClick(me->x(),me->y());
+ delete me;
+}
+
+/*!
+ \qmlmethod bool WebView::heuristicZoom(clickX,clickY,maxzoom)
+
+ Finds a zoom that:
+ \list
+ \i shows a whole item
+ \i includes (\a clickX, \a clickY)
+ \i fits into the preferredWidth and preferredHeight
+ \i zooms by no more than \a maxzoom
+ \i is more than 10% above the current zoom
+ \endlist
+
+ If such a zoom exists, emits zoomTo(zoom,centerX,centerY) and returns true; otherwise,
+ no signal is emitted and returns false.
+*/
+bool QmlGraphicsWebView::heuristicZoom(int clickX, int clickY, qreal maxzoom)
+{
+ Q_D(QmlGraphicsWebView);
+ if (contentsScale() >= maxzoom/zoomFactor())
+ return false;
+ qreal ozf = contentsScale();
+ QRect showarea = elementAreaAt(clickX, clickY, d->preferredwidth/maxzoom, d->preferredheight/maxzoom);
+ qreal z = qMin(qreal(d->preferredwidth)/showarea.width(),qreal(d->preferredheight)/showarea.height());
+ if (z > maxzoom/zoomFactor())
+ z = maxzoom/zoomFactor();
+ if (z/ozf > 1.2) {
+ QRectF r(showarea.left()*z, showarea.top()*z, showarea.width()*z, showarea.height()*z);
+ emit zoomTo(z,r.x()+r.width()/2, r.y()+r.height()/2);
+ return true;
+ } else {
+ return false;
+ }
+}
+
+/*!
+ \qmlproperty int WebView::pressGrabTime
+
+ The number of milliseconds the user must press before the WebView
+ starts passing move events through to the web engine (rather than
+ letting other QML elements such as a Flickable take them).
+
+ Defaults to 400ms. Set to 0 to always grab and pass move events to
+ the web engine.
+*/
+int QmlGraphicsWebView::pressGrabTime() const
+{
+ Q_D(const QmlGraphicsWebView);
+ return d->pressTime;
+}
+
+void QmlGraphicsWebView::setPressGrabTime(int ms)
+{
+ Q_D(QmlGraphicsWebView);
+ d->pressTime = ms;
+}
+
+void QmlGraphicsWebView::mousePressEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsWebView);
+
+ setFocus (true);
+ QMouseEvent *me = sceneMouseEventToMouseEvent(event);
+
+ d->pressPoint = me->pos();
+ if (d->pressTime) {
+ d->pressTimer.start(d->pressTime,this);
+ setKeepMouseGrab(false);
+ } else {
+ grabMouse();
+ setKeepMouseGrab(true);
+ }
+
+ page()->event(me);
+ event->setAccepted(
+/*
+ It is not correct to send the press event upwards, if it is not accepted by WebKit
+ e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit
+ Might be a bug in WebKit, though
+ */
+#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835
+ true
+#else
+ me->isAccepted()
+#endif
+ );
+ delete me;
+ if (!event->isAccepted()) {
+ QmlGraphicsPaintedItem::mousePressEvent(event);
+ }
+}
+
+void QmlGraphicsWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsWebView);
+
+ QMouseEvent *me = sceneMouseEventToMouseEvent(event);
+ page()->event(me);
+ d->pressTimer.stop();
+ event->setAccepted(
+/*
+ It is not correct to send the press event upwards, if it is not accepted by WebKit
+ e.g. push button does not work, if done so as QGraphicsScene will not send all the events to WebKit
+ */
+#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835
+ true
+#else
+ me->isAccepted()
+#endif
+ );
+ delete me;
+ if (!event->isAccepted()) {
+ QmlGraphicsPaintedItem::mouseReleaseEvent(event);
+ }
+ setKeepMouseGrab(false);
+ ungrabMouse();
+}
+
+void QmlGraphicsWebView::timerEvent(QTimerEvent *event)
+{
+ Q_D(QmlGraphicsWebView);
+ if (event->timerId() == d->pressTimer.timerId()) {
+ d->pressTimer.stop();
+ grabMouse();
+ setKeepMouseGrab(true);
+ }
+}
+
+void QmlGraphicsWebView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+{
+ Q_D(QmlGraphicsWebView);
+
+ QMouseEvent *me = sceneMouseEventToMouseEvent(event);
+ if (d->pressTimer.isActive()) {
+ if ((me->pos() - d->pressPoint).manhattanLength() > QApplication::startDragDistance()) {
+ d->pressTimer.stop();
+ }
+ }
+ if (keepMouseGrab()) {
+ page()->event(me);
+ event->setAccepted(
+/*
+ It is not correct to send the press event upwards, if it is not accepted by WebKit
+ e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit
+ Might be a bug in WebKit, though
+ */
+#if 1 // QT_VERSION <= 0x040500 // XXX see bug 230835
+ true
+#else
+ me->isAccepted()
+#endif
+ );
+ }
+ delete me;
+ if (!event->isAccepted())
+ QmlGraphicsPaintedItem::mouseMoveEvent(event);
+
+}
+void QmlGraphicsWebView::hoverMoveEvent (QGraphicsSceneHoverEvent * event)
+{
+ QMouseEvent *me = sceneHoverMoveEventToMouseEvent(event);
+ page()->event(me);
+ event->setAccepted(
+#if QT_VERSION <= 0x040500 // XXX see bug 230835
+ true
+#else
+ me->isAccepted()
+#endif
+ );
+ delete me;
+ if (!event->isAccepted())
+ QmlGraphicsPaintedItem::hoverMoveEvent(event);
+}
+
+void QmlGraphicsWebView::keyPressEvent(QKeyEvent* event)
+{
+ page()->event(event);
+ if (!event->isAccepted())
+ QmlGraphicsPaintedItem::keyPressEvent(event);
+}
+
+void QmlGraphicsWebView::keyReleaseEvent(QKeyEvent* event)
+{
+ page()->event(event);
+ if (!event->isAccepted())
+ QmlGraphicsPaintedItem::keyReleaseEvent(event);
+}
+
+bool QmlGraphicsWebView::sceneEvent(QEvent *event)
+{
+ if (event->type() == QEvent::KeyPress) {
+ QKeyEvent *k = static_cast<QKeyEvent *>(event);
+ if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
+ if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
+ page()->event(event);
+ if (event->isAccepted())
+ return true;
+ }
+ }
+ }
+ return QmlGraphicsPaintedItem::sceneEvent(event);
+}
+
+
+/*!
+ \qmlproperty action WebView::back
+ This property holds the action for causing the previous URL in the history to be displayed.
+*/
+QAction *QmlGraphicsWebView::backAction() const
+{
+ return page()->action(QWebPage::Back);
+}
+
+/*!
+ \qmlproperty action WebView::forward
+ This property holds the action for causing the next URL in the history to be displayed.
+*/
+QAction *QmlGraphicsWebView::forwardAction() const
+{
+ return page()->action(QWebPage::Forward);
+}
+
+/*!
+ \qmlproperty action WebView::reload
+ This property holds the action for reloading with the current URL
+*/
+QAction *QmlGraphicsWebView::reloadAction() const
+{
+ return page()->action(QWebPage::Reload);
+}
+
+/*!
+ \qmlproperty action WebView::stop
+ This property holds the action for stopping loading with the current URL
+*/
+QAction *QmlGraphicsWebView::stopAction() const
+{
+ return page()->action(QWebPage::Stop);
+}
+
+/*!
+ \qmlproperty real WebView::title
+ This property holds the title of the web page currently viewed
+
+ By default, this property contains an empty string.
+*/
+QString QmlGraphicsWebView::title() const
+{
+ return page()->mainFrame()->title();
+}
+
+
+
+/*!
+ \qmlproperty pixmap WebView::icon
+ This property holds the icon associated with the web page currently viewed
+*/
+QPixmap QmlGraphicsWebView::icon() const
+{
+ return page()->mainFrame()->icon().pixmap(QSize(256,256));
+}
+
+
+/*!
+ \qmlproperty real WebView::zoomFactor
+ This property holds the multiplier used to scale the contents of a Web page.
+*/
+void QmlGraphicsWebView::setZoomFactor(qreal factor)
+{
+ Q_D(QmlGraphicsWebView);
+ if (factor == page()->mainFrame()->zoomFactor())
+ return;
+
+ page()->mainFrame()->setZoomFactor(factor);
+ page()->setViewportSize(QSize(
+ d->preferredwidth>0 ? d->preferredwidth*factor : width()*factor,
+ d->preferredheight>0 ? d->preferredheight*factor : height()*factor));
+ expandToWebPage();
+
+ emit zoomFactorChanged();
+}
+
+qreal QmlGraphicsWebView::zoomFactor() const
+{
+ return page()->mainFrame()->zoomFactor();
+}
+
+/*!
+ \qmlproperty string WebView::statusText
+
+ This property is the current status suggested by the current web page. In a web browser,
+ such status is often shown in some kind of status bar.
+*/
+void QmlGraphicsWebView::setStatusText(const QString& s)
+{
+ Q_D(QmlGraphicsWebView);
+ d->statusText = s;
+ emit statusTextChanged();
+}
+
+void QmlGraphicsWebView::windowObjectCleared()
+{
+ Q_D(QmlGraphicsWebView);
+ d->updateWindowObjects();
+}
+
+QString QmlGraphicsWebView::statusText() const
+{
+ Q_D(const QmlGraphicsWebView);
+ return d->statusText;
+}
+
+QWebPage *QmlGraphicsWebView::page() const
+{
+ Q_D(const QmlGraphicsWebView);
+
+ if (!d->page) {
+ QmlGraphicsWebView *self = const_cast<QmlGraphicsWebView*>(this);
+ QWebPage *wp = new QmlGraphicsWebPage(self);
+
+ // QML items don't default to having a background,
+ // even though most we pages will set one anyway.
+ QPalette pal = QApplication::palette();
+ pal.setBrush(QPalette::Base, QColor::fromRgbF(0, 0, 0, 0));
+ wp->setPalette(pal);
+
+ wp->setNetworkAccessManager(qmlEngine(this)->networkAccessManager());
+
+ self->setPage(wp);
+
+ return wp;
+ }
+
+ return d->page;
+}
+
+
+// The QObject interface to settings().
+/*!
+ \qmlproperty string WebView::settings.standardFontFamily
+ \qmlproperty string WebView::settings.fixedFontFamily
+ \qmlproperty string WebView::settings.serifFontFamily
+ \qmlproperty string WebView::settings.sansSerifFontFamily
+ \qmlproperty string WebView::settings.cursiveFontFamily
+ \qmlproperty string WebView::settings.fantasyFontFamily
+
+ \qmlproperty int WebView::settings.minimumFontSize
+ \qmlproperty int WebView::settings.minimumLogicalFontSize
+ \qmlproperty int WebView::settings.defaultFontSize
+ \qmlproperty int WebView::settings.defaultFixedFontSize
+
+ \qmlproperty bool WebView::settings.autoLoadImages
+ \qmlproperty bool WebView::settings.javascriptEnabled
+ \qmlproperty bool WebView::settings.javaEnabled
+ \qmlproperty bool WebView::settings.pluginsEnabled
+ \qmlproperty bool WebView::settings.privateBrowsingEnabled
+ \qmlproperty bool WebView::settings.javascriptCanOpenWindows
+ \qmlproperty bool WebView::settings.javascriptCanAccessClipboard
+ \qmlproperty bool WebView::settings.developerExtrasEnabled
+ \qmlproperty bool WebView::settings.linksIncludedInFocusChain
+ \qmlproperty bool WebView::settings.zoomTextOnly
+ \qmlproperty bool WebView::settings.printElementBackgrounds
+ \qmlproperty bool WebView::settings.offlineStorageDatabaseEnabled
+ \qmlproperty bool WebView::settings.offlineWebApplicationCacheEnabled
+ \qmlproperty bool WebView::settings.localStorageDatabaseEnabled
+ \qmlproperty bool WebView::settings.localContentCanAccessRemoteUrls
+
+ These properties give access to the settings controlling the web view.
+
+ See QWebSettings for details of these properties.
+
+ \qml
+ WebView {
+ settings.pluginsEnabled: true
+ settings.standardFontFamily: "Arial"
+ ...
+ }
+ \endqml
+*/
+QmlGraphicsWebSettings *QmlGraphicsWebView::settingsObject() const
+{
+ Q_D(const QmlGraphicsWebView);
+ d->settings.s = page()->settings();
+ return &d->settings;
+}
+
+void QmlGraphicsWebView::setPage(QWebPage *page)
+{
+ Q_D(QmlGraphicsWebView);
+ if (d->page == page)
+ return;
+ if (d->page) {
+ if (d->page->parent() == this) {
+ delete d->page;
+ } else {
+ d->page->disconnect(this);
+ }
+ }
+ d->page = page;
+ d->page->setViewportSize(QSize(
+ d->preferredwidth>0 ? d->preferredwidth : width(),
+ d->preferredheight>0 ? d->preferredheight : height()));
+ d->page->mainFrame()->setScrollBarPolicy(Qt::Horizontal,Qt::ScrollBarAlwaysOff);
+ d->page->mainFrame()->setScrollBarPolicy(Qt::Vertical,Qt::ScrollBarAlwaysOff);
+ connect(d->page,SIGNAL(repaintRequested(QRect)),this,SLOT(paintPage(QRect)));
+ connect(d->page->mainFrame(),SIGNAL(urlChanged(QUrl)),this,SLOT(pageUrlChanged()));
+ connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString)));
+ connect(d->page->mainFrame(), SIGNAL(iconChanged()), this, SIGNAL(iconChanged()));
+ connect(d->page->mainFrame(), SIGNAL(contentsSizeChanged(QSize)), this, SLOT(noteContentsSizeChanged(QSize)));
+ connect(d->page->mainFrame(), SIGNAL(initialLayoutCompleted()), this, SLOT(initialLayout()));
+
+ connect(d->page,SIGNAL(loadStarted()),this,SLOT(doLoadStarted()));
+ connect(d->page,SIGNAL(loadProgress(int)),this,SLOT(doLoadProgress(int)));
+ connect(d->page,SIGNAL(loadFinished(bool)),this,SLOT(doLoadFinished(bool)));
+ connect(d->page,SIGNAL(statusBarMessage(QString)),this,SLOT(setStatusText(QString)));
+
+ connect(d->page->mainFrame(),SIGNAL(javaScriptWindowObjectCleared()),this,SLOT(windowObjectCleared()));
+}
+
+/*!
+ \qmlsignal WebView::onLoadStarted()
+
+ This handler is called when the web engine begins loading
+ a page. Later, WebView::onLoadFinished() or WebView::onLoadFailed()
+ will be emitted.
+*/
+
+/*!
+ \qmlsignal WebView::onLoadFinished()
+
+ This handler is called when the web engine \e successfully
+ finishes loading a page, including any component content
+ (WebView::onLoadFailed() will be emitted otherwise).
+
+ \sa progress
+*/
+
+/*!
+ \qmlsignal WebView::onLoadFailed()
+
+ This handler is called when the web engine fails loading
+ a page or any component content
+ (WebView::onLoadFinished() will be emitted on success).
+*/
+
+void QmlGraphicsWebView::load(const QNetworkRequest &request,
+ QNetworkAccessManager::Operation operation,
+ const QByteArray &body)
+{
+ page()->mainFrame()->load(request, operation, body);
+}
+
+QString QmlGraphicsWebView::html() const
+{
+ return page()->mainFrame()->toHtml();
+}
+
+/*!
+ \qmlproperty string WebView::html
+ This property holds HTML text set directly
+
+ The html property can be set as a string.
+
+ \qml
+ WebView {
+ html: "<p>This is <b>HTML</b>."
+ }
+ \endqml
+*/
+void QmlGraphicsWebView::setHtml(const QString &html, const QUrl &baseUrl)
+{
+ Q_D(QmlGraphicsWebView);
+ page()->setViewportSize(QSize(
+ d->preferredwidth>0 ? d->preferredwidth : width(),
+ d->preferredheight>0 ? d->preferredheight : height()));
+ if (isComponentComplete())
+ page()->mainFrame()->setHtml(html, baseUrl);
+ else {
+ d->pending = d->PendingHtml;
+ d->pending_url = baseUrl;
+ d->pending_string = html;
+ }
+}
+
+void QmlGraphicsWebView::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl)
+{
+ Q_D(QmlGraphicsWebView);
+ page()->setViewportSize(QSize(
+ d->preferredwidth>0 ? d->preferredwidth : width(),
+ d->preferredheight>0 ? d->preferredheight : height()));
+
+ if (isComponentComplete())
+ page()->mainFrame()->setContent(data,mimeType,qmlContext(this)->resolvedUrl(baseUrl));
+ else {
+ d->pending = d->PendingContent;
+ d->pending_url = baseUrl;
+ d->pending_string = mimeType;
+ d->pending_data = data;
+ }
+}
+
+QWebHistory *QmlGraphicsWebView::history() const
+{
+ return page()->history();
+}
+
+QWebSettings *QmlGraphicsWebView::settings() const
+{
+ return page()->settings();
+}
+
+QmlGraphicsWebView *QmlGraphicsWebView::createWindow(QWebPage::WebWindowType type)
+{
+ Q_D(QmlGraphicsWebView);
+ switch (type) {
+ case QWebPage::WebBrowserWindow: {
+ if (!d->newWindowComponent && d->newWindowParent)
+ qWarning("WebView::newWindowComponent not set - WebView::newWindowParent ignored");
+ else if (d->newWindowComponent && !d->newWindowParent)
+ qWarning("WebView::newWindowParent not set - WebView::newWindowComponent ignored");
+ else if (d->newWindowComponent && d->newWindowParent) {
+ QmlGraphicsWebView *webview = 0;
+ QmlContext *windowContext = new QmlContext(qmlContext(this));
+
+ QObject *nobj = d->newWindowComponent->create(windowContext);
+ if (nobj) {
+ windowContext->setParent(nobj);
+ QmlGraphicsItem *item = qobject_cast<QmlGraphicsItem *>(nobj);
+ if (!item) {
+ delete nobj;
+ } else {
+ webview = item->findChild<QmlGraphicsWebView*>();
+ if (!webview) {
+ delete item;
+ } else {
+ item->setParent(d->newWindowParent);
+ }
+ }
+ } else {
+ delete windowContext;
+ }
+
+ return webview;
+ }
+ }
+ break;
+ case QWebPage::WebModalDialog: {
+ // Not supported
+ }
+ }
+ return 0;
+}
+
+/*!
+ \qmlproperty component WebView::newWindowComponent
+
+ This property holds the component to use for new windows.
+ The component must have a WebView somewhere in its structure.
+
+ When the web engine requests a new window, it will be an instance of
+ this component.
+
+ The parent of the new window is set by newWindowParent. It must be set.
+*/
+QmlComponent *QmlGraphicsWebView::newWindowComponent() const
+{
+ Q_D(const QmlGraphicsWebView);
+ return d->newWindowComponent;
+}
+
+void QmlGraphicsWebView::setNewWindowComponent(QmlComponent *newWindow)
+{
+ Q_D(QmlGraphicsWebView);
+ delete d->newWindowComponent;
+ d->newWindowComponent = newWindow;
+}
+
+
+/*!
+ \qmlproperty item WebView::newWindowParent
+
+ The parent item for new windows.
+
+ \sa newWindowComponent
+*/
+QmlGraphicsItem *QmlGraphicsWebView::newWindowParent() const
+{
+ Q_D(const QmlGraphicsWebView);
+ return d->newWindowParent;
+}
+
+void QmlGraphicsWebView::setNewWindowParent(QmlGraphicsItem *parent)
+{
+ Q_D(QmlGraphicsWebView);
+ delete d->newWindowParent;
+ d->newWindowParent = parent;
+}
+
+/*!
+ Returns the area of the largest element at position (\a x,\a y) that is no larger
+ than \a maxwidth by \a maxheight pixels.
+
+ May return an area larger in the case when no smaller element is at the position.
+*/
+QRect QmlGraphicsWebView::elementAreaAt(int x, int y, int maxwidth, int maxheight) const
+{
+ QWebHitTestResult hit = page()->mainFrame()->hitTestContent(QPoint(x,y));
+ QRect rv = hit.boundingRect();
+ QWebElement element = hit.enclosingBlockElement();
+ if (maxwidth<=0) maxwidth = INT_MAX;
+ if (maxheight<=0) maxheight = INT_MAX;
+ while (!element.parent().isNull() && element.geometry().width() <= maxwidth && element.geometry().height() <= maxheight) {
+ rv = element.geometry();
+ element = element.parent();
+ }
+ return rv;
+}
+
+/*!
+ \internal
+ \class QmlGraphicsWebPage
+ \brief The QmlGraphicsWebPage class is a QWebPage that can create QML plugins.
+
+ \sa QmlGraphicsWebView
+*/
+QmlGraphicsWebPage::QmlGraphicsWebPage(QmlGraphicsWebView *parent) :
+ QWebPage(parent)
+{
+}
+
+QmlGraphicsWebPage::~QmlGraphicsWebPage()
+{
+}
+
+void QmlGraphicsWebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID)
+{
+ qWarning() << sourceID << ':' << lineNumber << ':' << message;
+}
+
+QString QmlGraphicsWebPage::chooseFile(QWebFrame *originatingFrame, const QString& oldFile)
+{
+ // Not supported (it's modal)
+ Q_UNUSED(originatingFrame)
+ Q_UNUSED(oldFile)
+ return oldFile;
+}
+
+void QmlGraphicsWebPage::javaScriptAlert(QWebFrame *originatingFrame, const QString& msg)
+{
+ Q_UNUSED(originatingFrame)
+ emit viewItem()->alert(msg);
+}
+
+bool QmlGraphicsWebPage::javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg)
+{
+ // Not supported (it's modal)
+ Q_UNUSED(originatingFrame)
+ Q_UNUSED(msg)
+ return false;
+}
+
+bool QmlGraphicsWebPage::javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result)
+{
+ // Not supported (it's modal)
+ Q_UNUSED(originatingFrame)
+ Q_UNUSED(msg)
+ Q_UNUSED(defaultValue)
+ Q_UNUSED(result)
+ return false;
+}
+
+
+/*
+ Qt WebKit does not understand non-QWidget plugins, so dummy widgets
+ are created, parented to a single dummy tool window.
+
+ The requirements for QML object plugins are input to the Qt WebKit
+ non-QWidget plugin support, which will obsolete this kludge.
+*/
+class QWidget_Dummy_Plugin : public QWidget
+{
+ Q_OBJECT
+public:
+ static QWidget *dummy_shared_parent()
+ {
+ static QWidget *dsp = 0;
+ if (!dsp) {
+ dsp = new QWidget(0,Qt::Tool);
+ dsp->setGeometry(-10000,-10000,0,0);
+ dsp->show();
+ }
+ return dsp;
+ }
+ QWidget_Dummy_Plugin(const QUrl& url, QmlGraphicsWebView *view, const QStringList &paramNames, const QStringList &paramValues) :
+ QWidget(dummy_shared_parent()),
+ propertyNames(paramNames),
+ propertyValues(paramValues),
+ webview(view)
+ {
+ QmlEngine *engine = qmlEngine(webview);
+ component = new QmlComponent(engine, url, this);
+ item = 0;
+ if (component->isLoading())
+ connect(component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(qmlLoaded()));
+ else
+ qmlLoaded();
+ }
+
+public Q_SLOTS:
+ void qmlLoaded()
+ {
+ if (component->isError()) {
+ // ### Could instead give these errors to the WebView to handle.
+ qWarning() << component->errors();
+ return;
+ }
+ item = qobject_cast<QmlGraphicsItem*>(component->create(qmlContext(webview)));
+ item->setParent(webview);
+ QString jsObjName;
+ for (int i=0; i<propertyNames.count(); ++i) {
+ if (propertyNames[i] != QLatin1String("type") && propertyNames[i] != QLatin1String("data")) {
+ item->setProperty(propertyNames[i].toUtf8(),propertyValues[i]);
+ if (propertyNames[i] == QLatin1String("objectname"))
+ jsObjName = propertyValues[i];
+ }
+ }
+ if (!jsObjName.isNull()) {
+ QWebFrame *f = webview->page()->mainFrame();
+ f->addToJavaScriptWindowObject(jsObjName, item);
+ }
+ resizeEvent(0);
+ delete component;
+ component = 0;
+ }
+ void resizeEvent(QResizeEvent*)
+ {
+ if (item) {
+ item->setX(x());
+ item->setY(y());
+ item->setWidth(width());
+ item->setHeight(height());
+ }
+ }
+
+private:
+ QmlComponent *component;
+ QmlGraphicsItem *item;
+ QStringList propertyNames, propertyValues;
+ QmlGraphicsWebView *webview;
+};
+
+QmlGraphicsWebView *QmlGraphicsWebPage::viewItem()
+{
+ return static_cast<QmlGraphicsWebView*>(parent());
+}
+
+QObject *QmlGraphicsWebPage::createPlugin(const QString &, const QUrl &url, const QStringList &paramNames, const QStringList &paramValues)
+{
+ QUrl comp = qmlContext(viewItem())->resolvedUrl(url);
+ return new QWidget_Dummy_Plugin(comp,viewItem(),paramNames,paramValues);
+}
+
+QWebPage *QmlGraphicsWebPage::createWindow(WebWindowType type)
+{
+ QmlGraphicsWebView *newView = viewItem()->createWindow(type);
+ if (newView)
+ return newView->page();
+ return 0;
+}
+
+QT_END_NAMESPACE
+
+#include <qmlgraphicswebview.moc>
diff --git a/src/declarative/graphicsitems/qmlgraphicswebview_p.h b/src/declarative/graphicsitems/qmlgraphicswebview_p.h
new file mode 100644
index 0000000..f5edb7a
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicswebview_p.h
@@ -0,0 +1,257 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSWEBVIEW_H
+#define QMLGRAPHICSWEBVIEW_H
+
+#include "qmlgraphicspainteditem_p.h"
+
+#include <QtGui/QAction>
+#include <QtCore/QUrl>
+#include <QtNetwork/qnetworkaccessmanager.h>
+#include <QtWebKit/QWebPage>
+
+QT_BEGIN_HEADER
+
+class QWebHistory;
+class QWebSettings;
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+class QmlGraphicsWebViewPrivate;
+class QNetworkRequest;
+class QmlGraphicsWebView;
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsWebPage : public QWebPage
+{
+ Q_OBJECT
+public:
+ explicit QmlGraphicsWebPage(QmlGraphicsWebView *parent);
+ ~QmlGraphicsWebPage();
+protected:
+ QObject *createPlugin(const QString &classid, const QUrl &url, const QStringList &paramNames, const QStringList &paramValues);
+ QWebPage *createWindow(WebWindowType type);
+ void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID);
+ QString chooseFile(QWebFrame *originatingFrame, const QString& oldFile);
+ void javaScriptAlert(QWebFrame *originatingFrame, const QString& msg);
+ bool javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg);
+ bool javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result);
+
+private:
+ QmlGraphicsWebView *viewItem();
+};
+
+
+class QmlGraphicsWebViewAttached;
+class QmlGraphicsWebSettings;
+
+//### TODO: browser plugins
+
+class Q_DECLARATIVE_EXPORT QmlGraphicsWebView : public QmlGraphicsPaintedItem
+{
+ Q_OBJECT
+
+ Q_ENUMS(Status SelectionMode)
+
+ Q_PROPERTY(QString title READ title NOTIFY titleChanged)
+ Q_PROPERTY(QPixmap icon READ icon NOTIFY iconChanged)
+ Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor NOTIFY zoomFactorChanged)
+ Q_PROPERTY(QString statusText READ statusText NOTIFY statusTextChanged)
+
+ Q_PROPERTY(QString html READ html WRITE setHtml)
+
+ Q_PROPERTY(int pressGrabTime READ pressGrabTime WRITE setPressGrabTime)
+
+ Q_PROPERTY(int preferredWidth READ preferredWidth WRITE setPreferredWidth NOTIFY preferredWidthChanged)
+ Q_PROPERTY(int preferredHeight READ preferredHeight WRITE setPreferredHeight NOTIFY preferredHeightChanged)
+ Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged)
+ Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged)
+ Q_PROPERTY(Status status READ status NOTIFY statusChanged)
+
+ Q_PROPERTY(QAction* reload READ reloadAction CONSTANT)
+ Q_PROPERTY(QAction* back READ backAction CONSTANT)
+ Q_PROPERTY(QAction* forward READ forwardAction CONSTANT)
+ Q_PROPERTY(QAction* stop READ stopAction CONSTANT)
+
+ Q_PROPERTY(QmlGraphicsWebSettings* settings READ settingsObject CONSTANT)
+
+ Q_PROPERTY(QmlList<QObject *>* javaScriptWindowObjects READ javaScriptWindowObjects CONSTANT)
+
+ Q_PROPERTY(QmlComponent* newWindowComponent READ newWindowComponent WRITE setNewWindowComponent)
+ Q_PROPERTY(QmlGraphicsItem* newWindowParent READ newWindowParent WRITE setNewWindowParent)
+
+ Q_PROPERTY(bool renderingEnabled READ renderingEnabled WRITE setRenderingEnabled)
+
+public:
+ QmlGraphicsWebView(QmlGraphicsItem *parent=0);
+ ~QmlGraphicsWebView();
+
+ QUrl url() const;
+ void setUrl(const QUrl &);
+
+ QString title() const;
+
+ QPixmap icon() const;
+
+ qreal zoomFactor() const;
+ void setZoomFactor(qreal);
+ Q_INVOKABLE bool heuristicZoom(int clickX, int clickY, qreal maxzoom);
+ QRect elementAreaAt(int x, int y, int minwidth, int minheight) const;
+
+ int pressGrabTime() const;
+ void setPressGrabTime(int);
+
+ int preferredWidth() const;
+ void setPreferredWidth(int);
+ int preferredHeight() const;
+ void setPreferredHeight(int);
+
+ enum Status { Null, Ready, Loading, Error };
+ Status status() const;
+ qreal progress() const;
+ QString statusText() const;
+
+ QAction *reloadAction() const;
+ QAction *backAction() const;
+ QAction *forwardAction() const;
+ QAction *stopAction() const;
+
+ QWebPage *page() const;
+ void setPage(QWebPage *page);
+
+ void load(const QNetworkRequest &request,
+ QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation,
+ const QByteArray &body = QByteArray());
+
+ QString html() const;
+
+ void setHtml(const QString &html, const QUrl &baseUrl = QUrl());
+ void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl());
+
+ QWebHistory *history() const;
+ QWebSettings *settings() const;
+ QmlGraphicsWebSettings *settingsObject() const;
+
+ bool renderingEnabled() const;
+ void setRenderingEnabled(bool);
+
+ QmlList<QObject *> *javaScriptWindowObjects();
+
+ static QmlGraphicsWebViewAttached *qmlAttachedProperties(QObject *);
+
+ QmlComponent *newWindowComponent() const;
+ void setNewWindowComponent(QmlComponent *newWindow);
+ QmlGraphicsItem *newWindowParent() const;
+ void setNewWindowParent(QmlGraphicsItem *newWindow);
+
+Q_SIGNALS:
+ void preferredWidthChanged();
+ void preferredHeightChanged();
+ void urlChanged();
+ void progressChanged();
+ void statusChanged(Status);
+ void titleChanged(const QString&);
+ void iconChanged();
+ void statusTextChanged();
+ void zoomFactorChanged();
+
+ void loadStarted();
+ void loadFinished();
+ void loadFailed();
+
+ void doubleClick(int clickX, int clickY);
+
+ void zoomTo(qreal zoom, int centerX, int centerY);
+
+ void alert(const QString& message);
+
+public Q_SLOTS:
+ QVariant evaluateJavaScript(const QString&);
+
+private Q_SLOTS:
+ void expandToWebPage();
+ void paintPage(const QRect&);
+ void doLoadStarted();
+ void doLoadProgress(int p);
+ void doLoadFinished(bool ok);
+ void setStatusText(const QString&);
+ void windowObjectCleared();
+ void pageUrlChanged();
+ void noteContentsSizeChanged(const QSize&);
+ void initialLayout();
+
+protected:
+ void drawContents(QPainter *, const QRect &);
+
+ void mousePressEvent(QGraphicsSceneMouseEvent *event);
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
+ void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
+ void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
+ void timerEvent(QTimerEvent *event);
+ void hoverMoveEvent (QGraphicsSceneHoverEvent * event);
+ void keyPressEvent(QKeyEvent* event);
+ void keyReleaseEvent(QKeyEvent* event);
+ virtual void geometryChanged(const QRectF &newGeometry,
+ const QRectF &oldGeometry);
+ virtual void focusChanged(bool);
+ virtual bool sceneEvent(QEvent *event);
+ QmlGraphicsWebView *createWindow(QWebPage::WebWindowType type);
+
+private:
+ void init();
+ virtual void componentComplete();
+ Q_DISABLE_COPY(QmlGraphicsWebView)
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsWebView)
+ QMouseEvent *sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *);
+ QMouseEvent *sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *);
+ friend class QmlGraphicsWebPage;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsWebView)
+QML_DECLARE_TYPEINFO(QmlGraphicsWebView, QML_HAS_ATTACHED_PROPERTIES)
+QML_DECLARE_TYPE(QAction)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/graphicsitems/qmlgraphicswebview_p_p.h b/src/declarative/graphicsitems/qmlgraphicswebview_p_p.h
new file mode 100644
index 0000000..5659059
--- /dev/null
+++ b/src/declarative/graphicsitems/qmlgraphicswebview_p_p.h
@@ -0,0 +1,151 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGRAPHICSWEBVIEW_P_H
+#define QMLGRAPHICSWEBVIEW_P_H
+
+#include <qml.h>
+
+#include <QtWebKit/QWebPage>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsWebSettings : public QObject {
+ Q_OBJECT
+
+ Q_PROPERTY(QString standardFontFamily READ standardFontFamily WRITE setStandardFontFamily)
+ Q_PROPERTY(QString fixedFontFamily READ fixedFontFamily WRITE setFixedFontFamily)
+ Q_PROPERTY(QString serifFontFamily READ serifFontFamily WRITE setSerifFontFamily)
+ Q_PROPERTY(QString sansSerifFontFamily READ sansSerifFontFamily WRITE setSansSerifFontFamily)
+ Q_PROPERTY(QString cursiveFontFamily READ cursiveFontFamily WRITE setCursiveFontFamily)
+ Q_PROPERTY(QString fantasyFontFamily READ fantasyFontFamily WRITE setFantasyFontFamily)
+
+ Q_PROPERTY(int minimumFontSize READ minimumFontSize WRITE setMinimumFontSize)
+ Q_PROPERTY(int minimumLogicalFontSize READ minimumLogicalFontSize WRITE setMinimumLogicalFontSize)
+ Q_PROPERTY(int defaultFontSize READ defaultFontSize WRITE setDefaultFontSize)
+ Q_PROPERTY(int defaultFixedFontSize READ defaultFixedFontSize WRITE setDefaultFixedFontSize)
+
+ Q_PROPERTY(bool autoLoadImages READ autoLoadImages WRITE setAutoLoadImages)
+ Q_PROPERTY(bool javascriptEnabled READ javascriptEnabled WRITE setJavascriptEnabled)
+ Q_PROPERTY(bool javaEnabled READ javaEnabled WRITE setJavaEnabled)
+ Q_PROPERTY(bool pluginsEnabled READ pluginsEnabled WRITE setPluginsEnabled)
+ Q_PROPERTY(bool privateBrowsingEnabled READ privateBrowsingEnabled WRITE setPrivateBrowsingEnabled)
+ Q_PROPERTY(bool javascriptCanOpenWindows READ javascriptCanOpenWindows WRITE setJavascriptCanOpenWindows)
+ Q_PROPERTY(bool javascriptCanAccessClipboard READ javascriptCanAccessClipboard WRITE setJavascriptCanAccessClipboard)
+ Q_PROPERTY(bool developerExtrasEnabled READ developerExtrasEnabled WRITE setDeveloperExtrasEnabled)
+ Q_PROPERTY(bool linksIncludedInFocusChain READ linksIncludedInFocusChain WRITE setLinksIncludedInFocusChain)
+ Q_PROPERTY(bool zoomTextOnly READ zoomTextOnly WRITE setZoomTextOnly)
+ Q_PROPERTY(bool printElementBackgrounds READ printElementBackgrounds WRITE setPrintElementBackgrounds)
+ Q_PROPERTY(bool offlineStorageDatabaseEnabled READ offlineStorageDatabaseEnabled WRITE setOfflineStorageDatabaseEnabled)
+ Q_PROPERTY(bool offlineWebApplicationCacheEnabled READ offlineWebApplicationCacheEnabled WRITE setOfflineWebApplicationCacheEnabled)
+ Q_PROPERTY(bool localStorageDatabaseEnabled READ localStorageDatabaseEnabled WRITE setLocalStorageDatabaseEnabled)
+ Q_PROPERTY(bool localContentCanAccessRemoteUrls READ localContentCanAccessRemoteUrls WRITE setLocalContentCanAccessRemoteUrls)
+
+public:
+ QmlGraphicsWebSettings() {}
+
+ QString standardFontFamily() const { return s->fontFamily(QWebSettings::StandardFont); }
+ void setStandardFontFamily(const QString& f) { s->setFontFamily(QWebSettings::StandardFont,f); }
+ QString fixedFontFamily() const { return s->fontFamily(QWebSettings::FixedFont); }
+ void setFixedFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FixedFont,f); }
+ QString serifFontFamily() const { return s->fontFamily(QWebSettings::SerifFont); }
+ void setSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SerifFont,f); }
+ QString sansSerifFontFamily() const { return s->fontFamily(QWebSettings::SansSerifFont); }
+ void setSansSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SansSerifFont,f); }
+ QString cursiveFontFamily() const { return s->fontFamily(QWebSettings::CursiveFont); }
+ void setCursiveFontFamily(const QString& f) { s->setFontFamily(QWebSettings::CursiveFont,f); }
+ QString fantasyFontFamily() const { return s->fontFamily(QWebSettings::FantasyFont); }
+ void setFantasyFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FantasyFont,f); }
+
+ int minimumFontSize() const { return s->fontSize(QWebSettings::MinimumFontSize); }
+ void setMinimumFontSize(int size) { s->setFontSize(QWebSettings::MinimumFontSize,size); }
+ int minimumLogicalFontSize() const { return s->fontSize(QWebSettings::MinimumLogicalFontSize); }
+ void setMinimumLogicalFontSize(int size) { s->setFontSize(QWebSettings::MinimumLogicalFontSize,size); }
+ int defaultFontSize() const { return s->fontSize(QWebSettings::DefaultFontSize); }
+ void setDefaultFontSize(int size) { s->setFontSize(QWebSettings::DefaultFontSize,size); }
+ int defaultFixedFontSize() const { return s->fontSize(QWebSettings::DefaultFixedFontSize); }
+ void setDefaultFixedFontSize(int size) { s->setFontSize(QWebSettings::DefaultFixedFontSize,size); }
+
+ bool autoLoadImages() const { return s->testAttribute(QWebSettings::AutoLoadImages); }
+ void setAutoLoadImages(bool on) { s->setAttribute(QWebSettings::AutoLoadImages, on); }
+ bool javascriptEnabled() const { return s->testAttribute(QWebSettings::JavascriptEnabled); }
+ void setJavascriptEnabled(bool on) { s->setAttribute(QWebSettings::JavascriptEnabled, on); }
+ bool javaEnabled() const { return s->testAttribute(QWebSettings::JavaEnabled); }
+ void setJavaEnabled(bool on) { s->setAttribute(QWebSettings::JavaEnabled, on); }
+ bool pluginsEnabled() const { return s->testAttribute(QWebSettings::PluginsEnabled); }
+ void setPluginsEnabled(bool on) { s->setAttribute(QWebSettings::PluginsEnabled, on); }
+ bool privateBrowsingEnabled() const { return s->testAttribute(QWebSettings::PrivateBrowsingEnabled); }
+ void setPrivateBrowsingEnabled(bool on) { s->setAttribute(QWebSettings::PrivateBrowsingEnabled, on); }
+ bool javascriptCanOpenWindows() const { return s->testAttribute(QWebSettings::JavascriptCanOpenWindows); }
+ void setJavascriptCanOpenWindows(bool on) { s->setAttribute(QWebSettings::JavascriptCanOpenWindows, on); }
+ bool javascriptCanAccessClipboard() const { return s->testAttribute(QWebSettings::JavascriptCanAccessClipboard); }
+ void setJavascriptCanAccessClipboard(bool on) { s->setAttribute(QWebSettings::JavascriptCanAccessClipboard, on); }
+ bool developerExtrasEnabled() const { return s->testAttribute(QWebSettings::DeveloperExtrasEnabled); }
+ void setDeveloperExtrasEnabled(bool on) { s->setAttribute(QWebSettings::DeveloperExtrasEnabled, on); }
+ bool linksIncludedInFocusChain() const { return s->testAttribute(QWebSettings::LinksIncludedInFocusChain); }
+ void setLinksIncludedInFocusChain(bool on) { s->setAttribute(QWebSettings::LinksIncludedInFocusChain, on); }
+ bool zoomTextOnly() const { return s->testAttribute(QWebSettings::ZoomTextOnly); }
+ void setZoomTextOnly(bool on) { s->setAttribute(QWebSettings::ZoomTextOnly, on); }
+ bool printElementBackgrounds() const { return s->testAttribute(QWebSettings::PrintElementBackgrounds); }
+ void setPrintElementBackgrounds(bool on) { s->setAttribute(QWebSettings::PrintElementBackgrounds, on); }
+ bool offlineStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::OfflineStorageDatabaseEnabled); }
+ void setOfflineStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, on); }
+ bool offlineWebApplicationCacheEnabled() const { return s->testAttribute(QWebSettings::OfflineWebApplicationCacheEnabled); }
+ void setOfflineWebApplicationCacheEnabled(bool on) { s->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, on); }
+ bool localStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::LocalStorageDatabaseEnabled); }
+ void setLocalStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, on); }
+ bool localContentCanAccessRemoteUrls() const { return s->testAttribute(QWebSettings::LocalContentCanAccessRemoteUrls); }
+ void setLocalContentCanAccessRemoteUrls(bool on) { s->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, on); }
+
+ QWebSettings *s;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlGraphicsWebSettings)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/qml/parser/parser.pri b/src/declarative/qml/parser/parser.pri
new file mode 100644
index 0000000..4530479
--- /dev/null
+++ b/src/declarative/qml/parser/parser.pri
@@ -0,0 +1,21 @@
+INCLUDEPATH += $$PWD
+
+HEADERS += \
+ $$PWD/qmljsast_p.h \
+ $$PWD/qmljsastfwd_p.h \
+ $$PWD/qmljsastvisitor_p.h \
+ $$PWD/qmljsengine_p.h \
+ $$PWD/qmljsgrammar_p.h \
+ $$PWD/qmljslexer_p.h \
+ $$PWD/qmljsmemorypool_p.h \
+ $$PWD/qmljsnodepool_p.h \
+ $$PWD/qmljsparser_p.h \
+ $$PWD/qmljsglobal_p.h
+
+SOURCES += \
+ $$PWD/qmljsast.cpp \
+ $$PWD/qmljsastvisitor.cpp \
+ $$PWD/qmljsengine_p.cpp \
+ $$PWD/qmljsgrammar.cpp \
+ $$PWD/qmljslexer.cpp \
+ $$PWD/qmljsparser.cpp
diff --git a/src/declarative/qml/parser/qmljs.g b/src/declarative/qml/parser/qmljs.g
new file mode 100644
index 0000000..90949d5
--- /dev/null
+++ b/src/declarative/qml/parser/qmljs.g
@@ -0,0 +1,3075 @@
+----------------------------------------------------------------------------
+--
+-- 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-ONLY$
+-- GNU Lesser General Public License Usage
+-- This file may be used under the terms of the GNU Lesser
+-- General Public License version 2.1 as published by the Free Software
+-- Foundation and appearing in the file LICENSE.LGPL included in the
+-- packaging of this file. Please review the following information to
+-- ensure the GNU Lesser General Public License version 2.1 requirements
+-- will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+--
+-- If you have questions regarding the use of this file, please contact
+-- Nokia at qt-info@nokia.com.
+-- $QT_END_LICENSE$
+--
+----------------------------------------------------------------------------
+
+%parser QmlJSGrammar
+%decl qmljsparser_p.h
+%impl qmljsparser.cpp
+%expect 2
+%expect-rr 2
+
+%token T_AND "&" T_AND_AND "&&" T_AND_EQ "&="
+%token T_BREAK "break" T_CASE "case" T_CATCH "catch"
+%token T_COLON ":" T_COMMA ";" T_CONTINUE "continue"
+%token T_DEFAULT "default" T_DELETE "delete" T_DIVIDE_ "/"
+%token T_DIVIDE_EQ "/=" T_DO "do" T_DOT "."
+%token T_ELSE "else" T_EQ "=" T_EQ_EQ "=="
+%token T_EQ_EQ_EQ "===" T_FINALLY "finally" T_FOR "for"
+%token T_FUNCTION "function" T_GE ">=" T_GT ">"
+%token T_GT_GT ">>" T_GT_GT_EQ ">>=" T_GT_GT_GT ">>>"
+%token T_GT_GT_GT_EQ ">>>=" T_IDENTIFIER "identifier" T_IF "if"
+%token T_IN "in" T_INSTANCEOF "instanceof" T_LBRACE "{"
+%token T_LBRACKET "[" T_LE "<=" T_LPAREN "("
+%token T_LT "<" T_LT_LT "<<" T_LT_LT_EQ "<<="
+%token T_MINUS "-" T_MINUS_EQ "-=" T_MINUS_MINUS "--"
+%token T_NEW "new" T_NOT "!" T_NOT_EQ "!="
+%token T_NOT_EQ_EQ "!==" T_NUMERIC_LITERAL "numeric literal" T_OR "|"
+%token T_OR_EQ "|=" T_OR_OR "||" T_PLUS "+"
+%token T_PLUS_EQ "+=" T_PLUS_PLUS "++" T_QUESTION "?"
+%token T_RBRACE "}" T_RBRACKET "]" T_REMAINDER "%"
+%token T_REMAINDER_EQ "%=" T_RETURN "return" T_RPAREN ")"
+%token T_SEMICOLON ";" T_AUTOMATIC_SEMICOLON T_STAR "*"
+%token T_STAR_EQ "*=" T_STRING_LITERAL "string literal"
+%token T_PROPERTY "property" T_SIGNAL "signal" T_READONLY "readonly"
+%token T_SWITCH "switch" T_THIS "this" T_THROW "throw"
+%token T_TILDE "~" T_TRY "try" T_TYPEOF "typeof"
+%token T_VAR "var" T_VOID "void" T_WHILE "while"
+%token T_WITH "with" T_XOR "^" T_XOR_EQ "^="
+%token T_NULL "null" T_TRUE "true" T_FALSE "false"
+%token T_CONST "const"
+%token T_DEBUGGER "debugger"
+%token T_RESERVED_WORD "reserved word"
+%token T_MULTILINE_STRING_LITERAL "multiline string literal"
+%token T_COMMENT "comment"
+
+--- context keywords.
+%token T_PUBLIC "public"
+%token T_IMPORT "import"
+%token T_AS "as"
+
+--- feed tokens
+%token T_FEED_UI_PROGRAM
+%token T_FEED_UI_OBJECT_MEMBER
+%token T_FEED_JS_STATEMENT
+%token T_FEED_JS_EXPRESSION
+%token T_FEED_JS_SOURCE_ELEMENT
+%token T_FEED_JS_PROGRAM
+
+%nonassoc SHIFT_THERE
+%nonassoc T_IDENTIFIER T_COLON T_SIGNAL T_PROPERTY T_READONLY
+%nonassoc REDUCE_HERE
+
+%start TopLevel
+
+/./****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtCore/QtDebug>
+#include <QtGui/QApplication>
+
+#include <string.h>
+
+#include "qmljsengine_p.h"
+#include "qmljslexer_p.h"
+#include "qmljsast_p.h"
+#include "qmljsnodepool_p.h"
+
+./
+
+/:/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+//
+// This file is automatically generated from qmljs.g.
+// Changes will be lost.
+//
+
+#ifndef QMLJSPARSER_P_H
+#define QMLJSPARSER_P_H
+
+#include "qmljsglobal_p.h"
+#include "qmljsgrammar_p.h"
+#include "qmljsast_p.h"
+#include "qmljsengine_p.h"
+
+#include <QtCore/QList>
+#include <QtCore/QString>
+
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS {
+
+class Engine;
+class NameId;
+
+class QML_PARSER_EXPORT Parser: protected $table
+{
+public:
+ union Value {
+ int ival;
+ double dval;
+ NameId *sval;
+ AST::ArgumentList *ArgumentList;
+ AST::CaseBlock *CaseBlock;
+ AST::CaseClause *CaseClause;
+ AST::CaseClauses *CaseClauses;
+ AST::Catch *Catch;
+ AST::DefaultClause *DefaultClause;
+ AST::ElementList *ElementList;
+ AST::Elision *Elision;
+ AST::ExpressionNode *Expression;
+ AST::Finally *Finally;
+ AST::FormalParameterList *FormalParameterList;
+ AST::FunctionBody *FunctionBody;
+ AST::FunctionDeclaration *FunctionDeclaration;
+ AST::Node *Node;
+ AST::PropertyName *PropertyName;
+ AST::PropertyNameAndValueList *PropertyNameAndValueList;
+ AST::SourceElement *SourceElement;
+ AST::SourceElements *SourceElements;
+ AST::Statement *Statement;
+ AST::StatementList *StatementList;
+ AST::Block *Block;
+ AST::VariableDeclaration *VariableDeclaration;
+ AST::VariableDeclarationList *VariableDeclarationList;
+
+ AST::UiProgram *UiProgram;
+ AST::UiImportList *UiImportList;
+ AST::UiImport *UiImport;
+ AST::UiParameterList *UiParameterList;
+ AST::UiPublicMember *UiPublicMember;
+ AST::UiObjectDefinition *UiObjectDefinition;
+ AST::UiObjectInitializer *UiObjectInitializer;
+ AST::UiObjectBinding *UiObjectBinding;
+ AST::UiScriptBinding *UiScriptBinding;
+ AST::UiArrayBinding *UiArrayBinding;
+ AST::UiObjectMember *UiObjectMember;
+ AST::UiObjectMemberList *UiObjectMemberList;
+ AST::UiArrayMemberList *UiArrayMemberList;
+ AST::UiQualifiedId *UiQualifiedId;
+ AST::UiSignature *UiSignature;
+ AST::UiFormalList *UiFormalList;
+ AST::UiFormal *UiFormal;
+ };
+
+public:
+ Parser(Engine *engine);
+ ~Parser();
+
+ // parse a UI program
+ bool parse() { return parse(T_FEED_UI_PROGRAM); }
+ bool parseStatement() { return parse(T_FEED_JS_STATEMENT); }
+ bool parseExpression() { return parse(T_FEED_JS_EXPRESSION); }
+ bool parseSourceElement() { return parse(T_FEED_JS_SOURCE_ELEMENT); }
+ bool parseUiObjectMember() { return parse(T_FEED_UI_OBJECT_MEMBER); }
+ bool parseProgram() { return parse(T_FEED_JS_PROGRAM); }
+
+ AST::UiProgram *ast() const
+ { return AST::cast<AST::UiProgram *>(program); }
+
+ AST::Statement *statement() const
+ {
+ if (! program)
+ return 0;
+
+ return program->statementCast();
+ }
+
+ AST::ExpressionNode *expression() const
+ {
+ if (! program)
+ return 0;
+
+ return program->expressionCast();
+ }
+
+ AST::UiObjectMember *uiObjectMember() const
+ {
+ if (! program)
+ return 0;
+
+ return program->uiObjectMemberCast();
+ }
+
+ AST::Node *rootNode() const
+ { return program; }
+
+ QList<DiagnosticMessage> diagnosticMessages() const
+ { return diagnostic_messages; }
+
+ inline DiagnosticMessage diagnosticMessage() const
+ {
+ foreach (const DiagnosticMessage &d, diagnostic_messages) {
+ if (! d.kind == DiagnosticMessage::Warning)
+ return d;
+ }
+
+ return DiagnosticMessage();
+ }
+
+ inline QString errorMessage() const
+ { return diagnosticMessage().message; }
+
+ inline int errorLineNumber() const
+ { return diagnosticMessage().loc.startLine; }
+
+ inline int errorColumnNumber() const
+ { return diagnosticMessage().loc.startColumn; }
+
+protected:
+ bool parse(int startToken);
+
+ void reallocateStack();
+
+ inline Value &sym(int index)
+ { return sym_stack [tos + index - 1]; }
+
+ inline AST::SourceLocation &loc(int index)
+ { return location_stack [tos + index - 1]; }
+
+ AST::UiQualifiedId *reparseAsQualifiedId(AST::ExpressionNode *expr);
+
+protected:
+ Engine *driver;
+ int tos;
+ int stack_size;
+ Value *sym_stack;
+ int *state_stack;
+ AST::SourceLocation *location_stack;
+
+ AST::Node *program;
+
+ // error recovery
+ enum { TOKEN_BUFFER_SIZE = 3 };
+
+ struct SavedToken {
+ int token;
+ double dval;
+ AST::SourceLocation loc;
+ };
+
+ double yylval;
+ AST::SourceLocation yylloc;
+ AST::SourceLocation yyprevlloc;
+
+ SavedToken token_buffer[TOKEN_BUFFER_SIZE];
+ SavedToken *first_token;
+ SavedToken *last_token;
+
+ QList<DiagnosticMessage> diagnostic_messages;
+};
+
+} // end of namespace QmlJS
+
+
+:/
+
+
+/.
+
+#include "qmljsparser_p.h"
+#include <QVarLengthArray>
+
+//
+// This file is automatically generated from qmljs.g.
+// Changes will be lost.
+//
+
+using namespace QmlJS;
+
+QT_QML_BEGIN_NAMESPACE
+
+void Parser::reallocateStack()
+{
+ if (! stack_size)
+ stack_size = 128;
+ else
+ stack_size <<= 1;
+
+ sym_stack = reinterpret_cast<Value*> (qRealloc(sym_stack, stack_size * sizeof(Value)));
+ state_stack = reinterpret_cast<int*> (qRealloc(state_stack, stack_size * sizeof(int)));
+ location_stack = reinterpret_cast<AST::SourceLocation*> (qRealloc(location_stack, stack_size * sizeof(AST::SourceLocation)));
+}
+
+inline static bool automatic(Engine *driver, int token)
+{
+ return token == $table::T_RBRACE
+ || token == 0
+ || driver->lexer()->prevTerminator();
+}
+
+
+Parser::Parser(Engine *engine):
+ driver(engine),
+ tos(0),
+ stack_size(0),
+ sym_stack(0),
+ state_stack(0),
+ location_stack(0),
+ first_token(0),
+ last_token(0)
+{
+}
+
+Parser::~Parser()
+{
+ if (stack_size) {
+ qFree(sym_stack);
+ qFree(state_stack);
+ qFree(location_stack);
+ }
+}
+
+static inline AST::SourceLocation location(Lexer *lexer)
+{
+ AST::SourceLocation loc;
+ loc.offset = lexer->tokenOffset();
+ loc.length = lexer->tokenLength();
+ loc.startLine = lexer->startLineNo();
+ loc.startColumn = lexer->startColumnNo();
+ return loc;
+}
+
+AST::UiQualifiedId *Parser::reparseAsQualifiedId(AST::ExpressionNode *expr)
+{
+ QVarLengthArray<NameId *, 4> nameIds;
+ QVarLengthArray<AST::SourceLocation, 4> locations;
+
+ AST::ExpressionNode *it = expr;
+ while (AST::FieldMemberExpression *m = AST::cast<AST::FieldMemberExpression *>(it)) {
+ nameIds.append(m->name);
+ locations.append(m->identifierToken);
+ it = m->base;
+ }
+
+ if (AST::IdentifierExpression *idExpr = AST::cast<AST::IdentifierExpression *>(it)) {
+ AST::UiQualifiedId *q = makeAstNode<AST::UiQualifiedId>(driver->nodePool(), idExpr->name);
+ q->identifierToken = idExpr->identifierToken;
+
+ AST::UiQualifiedId *currentId = q;
+ for (int i = nameIds.size() - 1; i != -1; --i) {
+ currentId = makeAstNode<AST::UiQualifiedId>(driver->nodePool(), currentId, nameIds[i]);
+ currentId->identifierToken = locations[i];
+ }
+
+ return currentId->finish();
+ }
+
+ return 0;
+}
+
+bool Parser::parse(int startToken)
+{
+ Lexer *lexer = driver->lexer();
+ bool hadErrors = false;
+ int yytoken = -1;
+ int action = 0;
+
+ token_buffer[0].token = startToken;
+ first_token = &token_buffer[0];
+ last_token = &token_buffer[1];
+
+ tos = -1;
+ program = 0;
+
+ do {
+ if (++tos == stack_size)
+ reallocateStack();
+
+ state_stack[tos] = action;
+
+ _Lcheck_token:
+ if (yytoken == -1 && -TERMINAL_COUNT != action_index[action]) {
+ yyprevlloc = yylloc;
+
+ if (first_token == last_token) {
+ yytoken = lexer->lex();
+ yylval = lexer->dval();
+ yylloc = location(lexer);
+ } else {
+ yytoken = first_token->token;
+ yylval = first_token->dval;
+ yylloc = first_token->loc;
+ ++first_token;
+ }
+ }
+
+ action = t_action(action, yytoken);
+ if (action > 0) {
+ if (action != ACCEPT_STATE) {
+ yytoken = -1;
+ sym(1).dval = yylval;
+ loc(1) = yylloc;
+ } else {
+ --tos;
+ return ! hadErrors;
+ }
+ } else if (action < 0) {
+ const int r = -action - 1;
+ tos -= rhs[r];
+
+ switch (r) {
+./
+
+--------------------------------------------------------------------------------------------------------
+-- Declarative UI
+--------------------------------------------------------------------------------------------------------
+
+TopLevel: T_FEED_UI_PROGRAM UiProgram ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+./
+
+TopLevel: T_FEED_JS_STATEMENT Statement ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+./
+
+TopLevel: T_FEED_JS_EXPRESSION Expression ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+./
+
+TopLevel: T_FEED_JS_SOURCE_ELEMENT SourceElement ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+./
+
+TopLevel: T_FEED_UI_OBJECT_MEMBER UiObjectMember ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+./
+
+TopLevel: T_FEED_JS_PROGRAM Program ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+./
+
+UiProgram: UiImportListOpt UiRootMember ;
+/.
+case $rule_number: {
+ sym(1).UiProgram = makeAstNode<AST::UiProgram> (driver->nodePool(), sym(1).UiImportList,
+ sym(2).UiObjectMemberList->finish());
+} break;
+./
+
+UiImportListOpt: Empty ;
+UiImportListOpt: UiImportList ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(1).UiImportList->finish();
+} break;
+./
+
+UiImportList: UiImport ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::UiImportList> (driver->nodePool(), sym(1).UiImport);
+} break;
+./
+
+UiImportList: UiImportList UiImport ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::UiImportList> (driver->nodePool(),
+ sym(1).UiImportList, sym(2).UiImport);
+} break;
+./
+
+ImportId: MemberExpression ;
+
+UiImport: UiImportHead T_AUTOMATIC_SEMICOLON ;
+UiImport: UiImportHead T_SEMICOLON ;
+/.
+case $rule_number: {
+ sym(1).UiImport->semicolonToken = loc(2);
+} break;
+./
+
+UiImport: UiImportHead T_NUMERIC_LITERAL T_AUTOMATIC_SEMICOLON ;
+UiImport: UiImportHead T_NUMERIC_LITERAL T_SEMICOLON ;
+/.
+case $rule_number: {
+ sym(1).UiImport->versionToken = loc(2);
+ sym(1).UiImport->semicolonToken = loc(3);
+} break;
+./
+
+UiImport: UiImportHead T_NUMERIC_LITERAL T_AS JsIdentifier T_AUTOMATIC_SEMICOLON ;
+UiImport: UiImportHead T_NUMERIC_LITERAL T_AS JsIdentifier T_SEMICOLON ;
+/.
+case $rule_number: {
+ sym(1).UiImport->versionToken = loc(2);
+ sym(1).UiImport->asToken = loc(3);
+ sym(1).UiImport->importIdToken = loc(4);
+ sym(1).UiImport->importId = sym(4).sval;
+ sym(1).UiImport->semicolonToken = loc(5);
+} break;
+./
+
+UiImport: UiImportHead T_AS JsIdentifier T_AUTOMATIC_SEMICOLON ;
+UiImport: UiImportHead T_AS JsIdentifier T_SEMICOLON ;
+/.
+case $rule_number: {
+ sym(1).UiImport->asToken = loc(2);
+ sym(1).UiImport->importIdToken = loc(3);
+ sym(1).UiImport->importId = sym(3).sval;
+ sym(1).UiImport->semicolonToken = loc(4);
+} break;
+./
+
+
+UiImportHead: T_IMPORT ImportId ;
+/.
+case $rule_number: {
+ AST::UiImport *node = 0;
+
+ if (AST::StringLiteral *importIdLiteral = AST::cast<AST::StringLiteral *>(sym(2).Expression)) {
+ node = makeAstNode<AST::UiImport>(driver->nodePool(), importIdLiteral->value);
+ node->fileNameToken = loc(2);
+ } else if (AST::UiQualifiedId *qualifiedId = reparseAsQualifiedId(sym(2).Expression)) {
+ QString text;
+ for (AST::UiQualifiedId *q = qualifiedId; q; q = q->next) {
+ text += q->name->asString();
+ if (q->next) text += QLatin1String(".");
+ }
+ node = makeAstNode<AST::UiImport>(driver->nodePool(), qualifiedId);
+ node->fileNameToken = loc(2);
+ }
+
+ sym(1).Node = node;
+
+ if (! node) {
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc(1),
+ QLatin1String("Expected a qualified name id or a string literal")));
+
+ return false; // ### remove me
+ }
+} break;
+./
+
+Empty: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+UiRootMember: UiObjectDefinition ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::UiObjectMemberList> (driver->nodePool(), sym(1).UiObjectMember);
+} break;
+./
+
+UiObjectMemberList: UiObjectMember ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::UiObjectMemberList> (driver->nodePool(), sym(1).UiObjectMember);
+} break;
+./
+
+UiObjectMemberList: UiObjectMemberList UiObjectMember ;
+/.
+case $rule_number: {
+ AST::UiObjectMemberList *node = makeAstNode<AST:: UiObjectMemberList> (driver->nodePool(),
+ sym(1).UiObjectMemberList, sym(2).UiObjectMember);
+ sym(1).Node = node;
+} break;
+./
+
+UiArrayMemberList: UiObjectDefinition ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::UiArrayMemberList> (driver->nodePool(), sym(1).UiObjectMember);
+} break;
+./
+
+UiArrayMemberList: UiArrayMemberList T_COMMA UiObjectDefinition ;
+/.
+case $rule_number: {
+ AST::UiArrayMemberList *node = makeAstNode<AST::UiArrayMemberList> (driver->nodePool(),
+ sym(1).UiArrayMemberList, sym(3).UiObjectMember);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectInitializer: T_LBRACE T_RBRACE ;
+/.
+case $rule_number: {
+ AST::UiObjectInitializer *node = makeAstNode<AST::UiObjectInitializer> (driver->nodePool(), (AST::UiObjectMemberList*)0);
+ node->lbraceToken = loc(1);
+ node->rbraceToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectInitializer: T_LBRACE UiObjectMemberList T_RBRACE ;
+/.
+case $rule_number: {
+ AST::UiObjectInitializer *node = makeAstNode<AST::UiObjectInitializer> (driver->nodePool(), sym(2).UiObjectMemberList->finish());
+ node->lbraceToken = loc(1);
+ node->rbraceToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectDefinition: UiQualifiedId UiObjectInitializer ;
+/.
+case $rule_number: {
+ AST::UiObjectDefinition *node = makeAstNode<AST::UiObjectDefinition> (driver->nodePool(), sym(1).UiQualifiedId,
+ sym(2).UiObjectInitializer);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: UiObjectDefinition ;
+
+UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ;
+/.
+case $rule_number: {
+ AST::UiArrayBinding *node = makeAstNode<AST::UiArrayBinding> (driver->nodePool(),
+ sym(1).UiQualifiedId, sym(4).UiArrayMemberList->finish());
+ node->colonToken = loc(2);
+ node->lbracketToken = loc(3);
+ node->rbracketToken = loc(5);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: UiQualifiedId T_COLON UiQualifiedId UiObjectInitializer ;
+/.
+case $rule_number: {
+ AST::UiObjectBinding *node = makeAstNode<AST::UiObjectBinding> (driver->nodePool(),
+ sym(1).UiQualifiedId, sym(3).UiQualifiedId, sym(4).UiObjectInitializer);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: UiQualifiedId T_COLON Block ;
+/.case $rule_number:./
+
+UiObjectMember: UiQualifiedId T_COLON EmptyStatement ;
+/.case $rule_number:./
+
+UiObjectMember: UiQualifiedId T_COLON ExpressionStatement ;
+/.case $rule_number:./
+
+UiObjectMember: UiQualifiedId T_COLON IfStatement ; --- ### do we really want if statement in a binding?
+/.case $rule_number:./
+
+/.
+{
+ AST::UiScriptBinding *node = makeAstNode<AST::UiScriptBinding> (driver->nodePool(),
+ sym(1).UiQualifiedId, sym(3).Statement);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+UiPropertyType: T_VAR ;
+/.
+case $rule_number:
+./
+UiPropertyType: T_RESERVED_WORD ;
+/.
+case $rule_number: {
+ sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount());
+ break;
+}
+./
+
+UiPropertyType: T_IDENTIFIER ;
+
+UiParameterListOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+UiParameterListOpt: UiParameterList ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(1).UiParameterList->finish ();
+} break;
+./
+
+UiParameterList: UiPropertyType JsIdentifier ;
+/.
+case $rule_number: {
+ AST::UiParameterList *node = makeAstNode<AST::UiParameterList> (driver->nodePool(), sym(1).sval, sym(2).sval);
+ node->identifierToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+UiParameterList: UiParameterList T_COMMA UiPropertyType JsIdentifier ;
+/.
+case $rule_number: {
+ AST::UiParameterList *node = makeAstNode<AST::UiParameterList> (driver->nodePool(), sym(1).UiParameterList, sym(3).sval, sym(4).sval);
+ node->commaToken = loc(2);
+ node->identifierToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: T_SIGNAL T_IDENTIFIER T_LPAREN UiParameterListOpt T_RPAREN T_AUTOMATIC_SEMICOLON ;
+UiObjectMember: T_SIGNAL T_IDENTIFIER T_LPAREN UiParameterListOpt T_RPAREN T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), (NameId *)0, sym(2).sval);
+ node->type = AST::UiPublicMember::Signal;
+ node->propertyToken = loc(1);
+ node->typeToken = loc(2);
+ node->identifierToken = loc(2);
+ node->parameters = sym(4).UiParameterList;
+ node->semicolonToken = loc(6);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: T_SIGNAL T_IDENTIFIER T_AUTOMATIC_SEMICOLON ;
+UiObjectMember: T_SIGNAL T_IDENTIFIER T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), (NameId *)0, sym(2).sval);
+ node->type = AST::UiPublicMember::Signal;
+ node->propertyToken = loc(1);
+ node->typeToken = loc(2);
+ node->identifierToken = loc(2);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: T_PROPERTY T_IDENTIFIER T_LT UiPropertyType T_GT T_IDENTIFIER T_AUTOMATIC_SEMICOLON ;
+UiObjectMember: T_PROPERTY T_IDENTIFIER T_LT UiPropertyType T_GT T_IDENTIFIER T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(4).sval, sym(6).sval);
+ node->typeModifier = sym(2).sval;
+ node->propertyToken = loc(1);
+ node->typeModifierToken = loc(2);
+ node->typeToken = loc(4);
+ node->identifierToken = loc(6);
+ node->semicolonToken = loc(7);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_AUTOMATIC_SEMICOLON ;
+UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(2).sval, sym(3).sval);
+ node->propertyToken = loc(1);
+ node->typeToken = loc(2);
+ node->identifierToken = loc(3);
+ node->semicolonToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_AUTOMATIC_SEMICOLON ;
+UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(3).sval, sym(4).sval);
+ node->isDefaultMember = true;
+ node->defaultToken = loc(1);
+ node->propertyToken = loc(2);
+ node->typeToken = loc(3);
+ node->identifierToken = loc(4);
+ node->semicolonToken = loc(5);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_AUTOMATIC_SEMICOLON ;
+UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(2).sval, sym(3).sval,
+ sym(5).Expression);
+ node->propertyToken = loc(1);
+ node->typeToken = loc(2);
+ node->identifierToken = loc(3);
+ node->colonToken = loc(4);
+ node->semicolonToken = loc(6);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: T_READONLY T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_AUTOMATIC_SEMICOLON ;
+UiObjectMember: T_READONLY T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(3).sval, sym(4).sval,
+ sym(6).Expression);
+ node->isReadonlyMember = true;
+ node->readonlyToken = loc(1);
+ node->propertyToken = loc(2);
+ node->typeToken = loc(3);
+ node->identifierToken = loc(4);
+ node->colonToken = loc(5);
+ node->semicolonToken = loc(7);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_AUTOMATIC_SEMICOLON ;
+UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(3).sval, sym(4).sval,
+ sym(6).Expression);
+ node->isDefaultMember = true;
+ node->defaultToken = loc(1);
+ node->propertyToken = loc(2);
+ node->typeToken = loc(3);
+ node->identifierToken = loc(4);
+ node->colonToken = loc(5);
+ node->semicolonToken = loc(7);
+ sym(1).Node = node;
+} break;
+./
+
+UiObjectMember: FunctionDeclaration ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::UiSourceElement>(driver->nodePool(), sym(1).Node);
+} break;
+./
+
+UiObjectMember: VariableStatement ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::UiSourceElement>(driver->nodePool(), sym(1).Node);
+} break;
+./
+
+JsIdentifier: T_IDENTIFIER;
+
+JsIdentifier: T_PROPERTY ;
+/.
+case $rule_number: {
+ QString s = QLatin1String(QmlJSGrammar::spell[T_PROPERTY]);
+ sym(1).sval = driver->intern(s.constData(), s.length());
+ break;
+}
+./
+
+JsIdentifier: T_SIGNAL ;
+/.
+case $rule_number: {
+ QString s = QLatin1String(QmlJSGrammar::spell[T_SIGNAL]);
+ sym(1).sval = driver->intern(s.constData(), s.length());
+ break;
+}
+./
+
+JsIdentifier: T_READONLY ;
+/.
+case $rule_number: {
+ QString s = QLatin1String(QmlJSGrammar::spell[T_READONLY]);
+ sym(1).sval = driver->intern(s.constData(), s.length());
+ break;
+}
+./
+
+--------------------------------------------------------------------------------------------------------
+-- Expressions
+--------------------------------------------------------------------------------------------------------
+
+PrimaryExpression: T_THIS ;
+/.
+case $rule_number: {
+ AST::ThisExpression *node = makeAstNode<AST::ThisExpression> (driver->nodePool());
+ node->thisToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: JsIdentifier ;
+/.
+case $rule_number: {
+ AST::IdentifierExpression *node = makeAstNode<AST::IdentifierExpression> (driver->nodePool(), sym(1).sval);
+ node->identifierToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_NULL ;
+/.
+case $rule_number: {
+ AST::NullExpression *node = makeAstNode<AST::NullExpression> (driver->nodePool());
+ node->nullToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_TRUE ;
+/.
+case $rule_number: {
+ AST::TrueLiteral *node = makeAstNode<AST::TrueLiteral> (driver->nodePool());
+ node->trueToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_FALSE ;
+/.
+case $rule_number: {
+ AST::FalseLiteral *node = makeAstNode<AST::FalseLiteral> (driver->nodePool());
+ node->falseToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_NUMERIC_LITERAL ;
+/.
+case $rule_number: {
+ AST::NumericLiteral *node = makeAstNode<AST::NumericLiteral> (driver->nodePool(), sym(1).dval);
+ node->literalToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_MULTILINE_STRING_LITERAL ;
+/.case $rule_number:./
+
+PrimaryExpression: T_STRING_LITERAL ;
+/.
+case $rule_number: {
+ AST::StringLiteral *node = makeAstNode<AST::StringLiteral> (driver->nodePool(), sym(1).sval);
+ node->literalToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_DIVIDE_ ;
+/:
+#define J_SCRIPT_REGEXPLITERAL_RULE1 $rule_number
+:/
+/.
+case $rule_number: {
+ bool rx = lexer->scanRegExp(Lexer::NoPrefix);
+ if (!rx) {
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage()));
+ return false; // ### remove me
+ }
+ AST::RegExpLiteral *node = makeAstNode<AST::RegExpLiteral> (driver->nodePool(), lexer->pattern, lexer->flags);
+ node->literalToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_DIVIDE_EQ ;
+/:
+#define J_SCRIPT_REGEXPLITERAL_RULE2 $rule_number
+:/
+/.
+case $rule_number: {
+ bool rx = lexer->scanRegExp(Lexer::EqualPrefix);
+ if (!rx) {
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage()));
+ return false;
+ }
+ AST::RegExpLiteral *node = makeAstNode<AST::RegExpLiteral> (driver->nodePool(), lexer->pattern, lexer->flags);
+ node->literalToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_LBRACKET T_RBRACKET ;
+/.
+case $rule_number: {
+ AST::ArrayLiteral *node = makeAstNode<AST::ArrayLiteral> (driver->nodePool(), (AST::Elision *) 0);
+ node->lbracketToken = loc(1);
+ node->rbracketToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_LBRACKET Elision T_RBRACKET ;
+/.
+case $rule_number: {
+ AST::ArrayLiteral *node = makeAstNode<AST::ArrayLiteral> (driver->nodePool(), sym(2).Elision->finish());
+ node->lbracketToken = loc(1);
+ node->rbracketToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_LBRACKET ElementList T_RBRACKET ;
+/.
+case $rule_number: {
+ AST::ArrayLiteral *node = makeAstNode<AST::ArrayLiteral> (driver->nodePool(), sym(2).ElementList->finish ());
+ node->lbracketToken = loc(1);
+ node->rbracketToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_LBRACKET ElementList T_COMMA T_RBRACKET ;
+/.
+case $rule_number: {
+ AST::ArrayLiteral *node = makeAstNode<AST::ArrayLiteral> (driver->nodePool(), sym(2).ElementList->finish (),
+ (AST::Elision *) 0);
+ node->lbracketToken = loc(1);
+ node->commaToken = loc(3);
+ node->rbracketToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_LBRACKET ElementList T_COMMA Elision T_RBRACKET ;
+/.
+case $rule_number: {
+ AST::ArrayLiteral *node = makeAstNode<AST::ArrayLiteral> (driver->nodePool(), sym(2).ElementList->finish (),
+ sym(4).Elision->finish());
+ node->lbracketToken = loc(1);
+ node->commaToken = loc(3);
+ node->rbracketToken = loc(5);
+ sym(1).Node = node;
+} break;
+./
+
+-- PrimaryExpression: T_LBRACE T_RBRACE ;
+-- /.
+-- case $rule_number: {
+-- sym(1).Node = makeAstNode<AST::ObjectLiteral> (driver->nodePool());
+-- } break;
+-- ./
+
+PrimaryExpression: T_LBRACE PropertyNameAndValueListOpt T_RBRACE ;
+/.
+case $rule_number: {
+ AST::ObjectLiteral *node = 0;
+ if (sym(2).Node)
+ node = makeAstNode<AST::ObjectLiteral> (driver->nodePool(),
+ sym(2).PropertyNameAndValueList->finish ());
+ else
+ node = makeAstNode<AST::ObjectLiteral> (driver->nodePool());
+ node->lbraceToken = loc(1);
+ node->lbraceToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_LBRACE PropertyNameAndValueList T_COMMA T_RBRACE ;
+/.
+case $rule_number: {
+ AST::ObjectLiteral *node = makeAstNode<AST::ObjectLiteral> (driver->nodePool(),
+ sym(2).PropertyNameAndValueList->finish ());
+ node->lbraceToken = loc(1);
+ node->lbraceToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+PrimaryExpression: T_LPAREN Expression T_RPAREN ;
+/.
+case $rule_number: {
+ AST::NestedExpression *node = makeAstNode<AST::NestedExpression>(driver->nodePool(), sym(2).Expression);
+ node->lparenToken = loc(1);
+ node->rparenToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+UiQualifiedId: MemberExpression ;
+/.
+case $rule_number: {
+ if (AST::ArrayMemberExpression *mem = AST::cast<AST::ArrayMemberExpression *>(sym(1).Expression)) {
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, mem->lbracketToken,
+ QLatin1String("Ignored annotation")));
+
+ sym(1).Expression = mem->base;
+ }
+
+ if (AST::UiQualifiedId *qualifiedId = reparseAsQualifiedId(sym(1).Expression)) {
+ sym(1).UiQualifiedId = qualifiedId;
+ } else {
+ sym(1).UiQualifiedId = 0;
+
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc(1),
+ QLatin1String("Expected a qualified name id")));
+
+ return false; // ### recover
+ }
+} break;
+./
+
+ElementList: AssignmentExpression ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::ElementList> (driver->nodePool(), (AST::Elision *) 0, sym(1).Expression);
+} break;
+./
+
+ElementList: Elision AssignmentExpression ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::ElementList> (driver->nodePool(), sym(1).Elision->finish(), sym(2).Expression);
+} break;
+./
+
+ElementList: ElementList T_COMMA AssignmentExpression ;
+/.
+case $rule_number: {
+ AST::ElementList *node = makeAstNode<AST::ElementList> (driver->nodePool(), sym(1).ElementList,
+ (AST::Elision *) 0, sym(3).Expression);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+ElementList: ElementList T_COMMA Elision AssignmentExpression ;
+/.
+case $rule_number: {
+ AST::ElementList *node = makeAstNode<AST::ElementList> (driver->nodePool(), sym(1).ElementList, sym(3).Elision->finish(),
+ sym(4).Expression);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+Elision: T_COMMA ;
+/.
+case $rule_number: {
+ AST::Elision *node = makeAstNode<AST::Elision> (driver->nodePool());
+ node->commaToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+Elision: Elision T_COMMA ;
+/.
+case $rule_number: {
+ AST::Elision *node = makeAstNode<AST::Elision> (driver->nodePool(), sym(1).Elision);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+PropertyNameAndValueList: PropertyName T_COLON AssignmentExpression ;
+/.
+case $rule_number: {
+ AST::PropertyNameAndValueList *node = makeAstNode<AST::PropertyNameAndValueList> (driver->nodePool(),
+ sym(1).PropertyName, sym(3).Expression);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+PropertyNameAndValueList: PropertyNameAndValueList T_COMMA PropertyName T_COLON AssignmentExpression ;
+/.
+case $rule_number: {
+ AST::PropertyNameAndValueList *node = makeAstNode<AST::PropertyNameAndValueList> (driver->nodePool(),
+ sym(1).PropertyNameAndValueList, sym(3).PropertyName, sym(5).Expression);
+ node->commaToken = loc(2);
+ node->colonToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+PropertyName: T_IDENTIFIER %prec REDUCE_HERE ;
+/.
+case $rule_number: {
+ AST::IdentifierPropertyName *node = makeAstNode<AST::IdentifierPropertyName> (driver->nodePool(), sym(1).sval);
+ node->propertyNameToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PropertyName: T_SIGNAL ;
+/.case $rule_number:./
+
+PropertyName: T_PROPERTY ;
+/.
+case $rule_number: {
+ AST::IdentifierPropertyName *node = makeAstNode<AST::IdentifierPropertyName> (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount()));
+ node->propertyNameToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PropertyName: T_STRING_LITERAL ;
+/.
+case $rule_number: {
+ AST::StringLiteralPropertyName *node = makeAstNode<AST::StringLiteralPropertyName> (driver->nodePool(), sym(1).sval);
+ node->propertyNameToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PropertyName: T_NUMERIC_LITERAL ;
+/.
+case $rule_number: {
+ AST::NumericLiteralPropertyName *node = makeAstNode<AST::NumericLiteralPropertyName> (driver->nodePool(), sym(1).dval);
+ node->propertyNameToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+PropertyName: ReservedIdentifier ;
+/.
+case $rule_number: {
+ AST::IdentifierPropertyName *node = makeAstNode<AST::IdentifierPropertyName> (driver->nodePool(), sym(1).sval);
+ node->propertyNameToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+ReservedIdentifier: T_BREAK ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_CASE ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_CATCH ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_CONTINUE ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_DEFAULT ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_DELETE ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_DO ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_ELSE ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_FALSE ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_FINALLY ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_FOR ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_FUNCTION ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_IF ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_IN ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_INSTANCEOF ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_NEW ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_NULL ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_RETURN ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_SWITCH ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_THIS ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_THROW ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_TRUE ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_TRY ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_TYPEOF ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_VAR ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_VOID ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_WHILE ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_CONST ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_DEBUGGER ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_RESERVED_WORD ;
+/.
+case $rule_number:
+./
+ReservedIdentifier: T_WITH ;
+/.
+case $rule_number:
+{
+ sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount());
+} break;
+./
+
+PropertyIdentifier: JsIdentifier ;
+PropertyIdentifier: ReservedIdentifier ;
+
+MemberExpression: PrimaryExpression ;
+MemberExpression: FunctionExpression ;
+
+MemberExpression: MemberExpression T_LBRACKET Expression T_RBRACKET ;
+/.
+case $rule_number: {
+ AST::ArrayMemberExpression *node = makeAstNode<AST::ArrayMemberExpression> (driver->nodePool(), sym(1).Expression, sym(3).Expression);
+ node->lbracketToken = loc(2);
+ node->rbracketToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+MemberExpression: MemberExpression T_DOT PropertyIdentifier ;
+/.
+case $rule_number: {
+ AST::FieldMemberExpression *node = makeAstNode<AST::FieldMemberExpression> (driver->nodePool(), sym(1).Expression, sym(3).sval);
+ node->dotToken = loc(2);
+ node->identifierToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+MemberExpression: T_NEW MemberExpression T_LPAREN ArgumentListOpt T_RPAREN ;
+/.
+case $rule_number: {
+ AST::NewMemberExpression *node = makeAstNode<AST::NewMemberExpression> (driver->nodePool(), sym(2).Expression, sym(4).ArgumentList);
+ node->newToken = loc(1);
+ node->lparenToken = loc(3);
+ node->rparenToken = loc(5);
+ sym(1).Node = node;
+} break;
+./
+
+NewExpression: MemberExpression ;
+
+NewExpression: T_NEW NewExpression ;
+/.
+case $rule_number: {
+ AST::NewExpression *node = makeAstNode<AST::NewExpression> (driver->nodePool(), sym(2).Expression);
+ node->newToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+CallExpression: MemberExpression T_LPAREN ArgumentListOpt T_RPAREN ;
+/.
+case $rule_number: {
+ AST::CallExpression *node = makeAstNode<AST::CallExpression> (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+CallExpression: CallExpression T_LPAREN ArgumentListOpt T_RPAREN ;
+/.
+case $rule_number: {
+ AST::CallExpression *node = makeAstNode<AST::CallExpression> (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+CallExpression: CallExpression T_LBRACKET Expression T_RBRACKET ;
+/.
+case $rule_number: {
+ AST::ArrayMemberExpression *node = makeAstNode<AST::ArrayMemberExpression> (driver->nodePool(), sym(1).Expression, sym(3).Expression);
+ node->lbracketToken = loc(2);
+ node->rbracketToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+CallExpression: CallExpression T_DOT PropertyIdentifier ;
+/.
+case $rule_number: {
+ AST::FieldMemberExpression *node = makeAstNode<AST::FieldMemberExpression> (driver->nodePool(), sym(1).Expression, sym(3).sval);
+ node->dotToken = loc(2);
+ node->identifierToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+ArgumentListOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+ArgumentListOpt: ArgumentList ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(1).ArgumentList->finish();
+} break;
+./
+
+ArgumentList: AssignmentExpression ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::ArgumentList> (driver->nodePool(), sym(1).Expression);
+} break;
+./
+
+ArgumentList: ArgumentList T_COMMA AssignmentExpression ;
+/.
+case $rule_number: {
+ AST::ArgumentList *node = makeAstNode<AST::ArgumentList> (driver->nodePool(), sym(1).ArgumentList, sym(3).Expression);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+LeftHandSideExpression: NewExpression ;
+LeftHandSideExpression: CallExpression ;
+PostfixExpression: LeftHandSideExpression ;
+
+PostfixExpression: LeftHandSideExpression T_PLUS_PLUS ;
+/.
+case $rule_number: {
+ AST::PostIncrementExpression *node = makeAstNode<AST::PostIncrementExpression> (driver->nodePool(), sym(1).Expression);
+ node->incrementToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+PostfixExpression: LeftHandSideExpression T_MINUS_MINUS ;
+/.
+case $rule_number: {
+ AST::PostDecrementExpression *node = makeAstNode<AST::PostDecrementExpression> (driver->nodePool(), sym(1).Expression);
+ node->decrementToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+UnaryExpression: PostfixExpression ;
+
+UnaryExpression: T_DELETE UnaryExpression ;
+/.
+case $rule_number: {
+ AST::DeleteExpression *node = makeAstNode<AST::DeleteExpression> (driver->nodePool(), sym(2).Expression);
+ node->deleteToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+UnaryExpression: T_VOID UnaryExpression ;
+/.
+case $rule_number: {
+ AST::VoidExpression *node = makeAstNode<AST::VoidExpression> (driver->nodePool(), sym(2).Expression);
+ node->voidToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+UnaryExpression: T_TYPEOF UnaryExpression ;
+/.
+case $rule_number: {
+ AST::TypeOfExpression *node = makeAstNode<AST::TypeOfExpression> (driver->nodePool(), sym(2).Expression);
+ node->typeofToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+UnaryExpression: T_PLUS_PLUS UnaryExpression ;
+/.
+case $rule_number: {
+ AST::PreIncrementExpression *node = makeAstNode<AST::PreIncrementExpression> (driver->nodePool(), sym(2).Expression);
+ node->incrementToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+UnaryExpression: T_MINUS_MINUS UnaryExpression ;
+/.
+case $rule_number: {
+ AST::PreDecrementExpression *node = makeAstNode<AST::PreDecrementExpression> (driver->nodePool(), sym(2).Expression);
+ node->decrementToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+UnaryExpression: T_PLUS UnaryExpression ;
+/.
+case $rule_number: {
+ AST::UnaryPlusExpression *node = makeAstNode<AST::UnaryPlusExpression> (driver->nodePool(), sym(2).Expression);
+ node->plusToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+UnaryExpression: T_MINUS UnaryExpression ;
+/.
+case $rule_number: {
+ AST::UnaryMinusExpression *node = makeAstNode<AST::UnaryMinusExpression> (driver->nodePool(), sym(2).Expression);
+ node->minusToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+UnaryExpression: T_TILDE UnaryExpression ;
+/.
+case $rule_number: {
+ AST::TildeExpression *node = makeAstNode<AST::TildeExpression> (driver->nodePool(), sym(2).Expression);
+ node->tildeToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+UnaryExpression: T_NOT UnaryExpression ;
+/.
+case $rule_number: {
+ AST::NotExpression *node = makeAstNode<AST::NotExpression> (driver->nodePool(), sym(2).Expression);
+ node->notToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+MultiplicativeExpression: UnaryExpression ;
+
+MultiplicativeExpression: MultiplicativeExpression T_STAR UnaryExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Mul, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+MultiplicativeExpression: MultiplicativeExpression T_DIVIDE_ UnaryExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Div, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+MultiplicativeExpression: MultiplicativeExpression T_REMAINDER UnaryExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Mod, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+AdditiveExpression: MultiplicativeExpression ;
+
+AdditiveExpression: AdditiveExpression T_PLUS MultiplicativeExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Add, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+AdditiveExpression: AdditiveExpression T_MINUS MultiplicativeExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Sub, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+ShiftExpression: AdditiveExpression ;
+
+ShiftExpression: ShiftExpression T_LT_LT AdditiveExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::LShift, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+ShiftExpression: ShiftExpression T_GT_GT AdditiveExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::RShift, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+ShiftExpression: ShiftExpression T_GT_GT_GT AdditiveExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::URShift, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpression: ShiftExpression ;
+
+RelationalExpression: RelationalExpression T_LT ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Lt, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpression: RelationalExpression T_GT ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Gt, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpression: RelationalExpression T_LE ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Le, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpression: RelationalExpression T_GE ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Ge, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpression: RelationalExpression T_INSTANCEOF ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::InstanceOf, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpression: RelationalExpression T_IN ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::In, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpressionNotIn: ShiftExpression ;
+
+RelationalExpressionNotIn: RelationalExpressionNotIn T_LT ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Lt, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpressionNotIn: RelationalExpressionNotIn T_GT ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Gt, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpressionNotIn: RelationalExpressionNotIn T_LE ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Le, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpressionNotIn: RelationalExpressionNotIn T_GE ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Ge, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+RelationalExpressionNotIn: RelationalExpressionNotIn T_INSTANCEOF ShiftExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::InstanceOf, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+EqualityExpression: RelationalExpression ;
+
+EqualityExpression: EqualityExpression T_EQ_EQ RelationalExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Equal, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+EqualityExpression: EqualityExpression T_NOT_EQ RelationalExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::NotEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+EqualityExpression: EqualityExpression T_EQ_EQ_EQ RelationalExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::StrictEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+EqualityExpression: EqualityExpression T_NOT_EQ_EQ RelationalExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::StrictNotEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+EqualityExpressionNotIn: RelationalExpressionNotIn ;
+
+EqualityExpressionNotIn: EqualityExpressionNotIn T_EQ_EQ RelationalExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Equal, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+EqualityExpressionNotIn: EqualityExpressionNotIn T_NOT_EQ RelationalExpressionNotIn;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::NotEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+EqualityExpressionNotIn: EqualityExpressionNotIn T_EQ_EQ_EQ RelationalExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::StrictEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+EqualityExpressionNotIn: EqualityExpressionNotIn T_NOT_EQ_EQ RelationalExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::StrictNotEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+BitwiseANDExpression: EqualityExpression ;
+
+BitwiseANDExpression: BitwiseANDExpression T_AND EqualityExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitAnd, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+BitwiseANDExpressionNotIn: EqualityExpressionNotIn ;
+
+BitwiseANDExpressionNotIn: BitwiseANDExpressionNotIn T_AND EqualityExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitAnd, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+BitwiseXORExpression: BitwiseANDExpression ;
+
+BitwiseXORExpression: BitwiseXORExpression T_XOR BitwiseANDExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitXor, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+BitwiseXORExpressionNotIn: BitwiseANDExpressionNotIn ;
+
+BitwiseXORExpressionNotIn: BitwiseXORExpressionNotIn T_XOR BitwiseANDExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitXor, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+BitwiseORExpression: BitwiseXORExpression ;
+
+BitwiseORExpression: BitwiseORExpression T_OR BitwiseXORExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitOr, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+BitwiseORExpressionNotIn: BitwiseXORExpressionNotIn ;
+
+BitwiseORExpressionNotIn: BitwiseORExpressionNotIn T_OR BitwiseXORExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitOr, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+LogicalANDExpression: BitwiseORExpression ;
+
+LogicalANDExpression: LogicalANDExpression T_AND_AND BitwiseORExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::And, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+LogicalANDExpressionNotIn: BitwiseORExpressionNotIn ;
+
+LogicalANDExpressionNotIn: LogicalANDExpressionNotIn T_AND_AND BitwiseORExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::And, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+LogicalORExpression: LogicalANDExpression ;
+
+LogicalORExpression: LogicalORExpression T_OR_OR LogicalANDExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Or, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+LogicalORExpressionNotIn: LogicalANDExpressionNotIn ;
+
+LogicalORExpressionNotIn: LogicalORExpressionNotIn T_OR_OR LogicalANDExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Or, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+ConditionalExpression: LogicalORExpression ;
+
+ConditionalExpression: LogicalORExpression T_QUESTION AssignmentExpression T_COLON AssignmentExpression ;
+/.
+case $rule_number: {
+ AST::ConditionalExpression *node = makeAstNode<AST::ConditionalExpression> (driver->nodePool(), sym(1).Expression,
+ sym(3).Expression, sym(5).Expression);
+ node->questionToken = loc(2);
+ node->colonToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+ConditionalExpressionNotIn: LogicalORExpressionNotIn ;
+
+ConditionalExpressionNotIn: LogicalORExpressionNotIn T_QUESTION AssignmentExpressionNotIn T_COLON AssignmentExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::ConditionalExpression *node = makeAstNode<AST::ConditionalExpression> (driver->nodePool(), sym(1).Expression,
+ sym(3).Expression, sym(5).Expression);
+ node->questionToken = loc(2);
+ node->colonToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+AssignmentExpression: ConditionalExpression ;
+
+AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ sym(2).ival, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+AssignmentExpressionNotIn: ConditionalExpressionNotIn ;
+
+AssignmentExpressionNotIn: LeftHandSideExpression AssignmentOperator AssignmentExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ sym(2).ival, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+AssignmentOperator: T_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::Assign;
+} break;
+./
+
+AssignmentOperator: T_STAR_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceMul;
+} break;
+./
+
+AssignmentOperator: T_DIVIDE_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceDiv;
+} break;
+./
+
+AssignmentOperator: T_REMAINDER_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceMod;
+} break;
+./
+
+AssignmentOperator: T_PLUS_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceAdd;
+} break;
+./
+
+AssignmentOperator: T_MINUS_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceSub;
+} break;
+./
+
+AssignmentOperator: T_LT_LT_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceLeftShift;
+} break;
+./
+
+AssignmentOperator: T_GT_GT_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceRightShift;
+} break;
+./
+
+AssignmentOperator: T_GT_GT_GT_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceURightShift;
+} break;
+./
+
+AssignmentOperator: T_AND_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceAnd;
+} break;
+./
+
+AssignmentOperator: T_XOR_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceXor;
+} break;
+./
+
+AssignmentOperator: T_OR_EQ ;
+/.
+case $rule_number: {
+ sym(1).ival = QSOperator::InplaceOr;
+} break;
+./
+
+Expression: AssignmentExpression ;
+
+Expression: Expression T_COMMA AssignmentExpression ;
+/.
+case $rule_number: {
+ AST::Expression *node = makeAstNode<AST::Expression> (driver->nodePool(), sym(1).Expression, sym(3).Expression);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+ExpressionOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+ExpressionOpt: Expression ;
+
+ExpressionNotIn: AssignmentExpressionNotIn ;
+
+ExpressionNotIn: ExpressionNotIn T_COMMA AssignmentExpressionNotIn ;
+/.
+case $rule_number: {
+ AST::Expression *node = makeAstNode<AST::Expression> (driver->nodePool(), sym(1).Expression, sym(3).Expression);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+ExpressionNotInOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+ExpressionNotInOpt: ExpressionNotIn ;
+
+Statement: Block ;
+Statement: VariableStatement ;
+Statement: EmptyStatement ;
+Statement: ExpressionStatement ;
+Statement: IfStatement ;
+Statement: IterationStatement ;
+Statement: ContinueStatement ;
+Statement: BreakStatement ;
+Statement: ReturnStatement ;
+Statement: WithStatement ;
+Statement: LabelledStatement ;
+Statement: SwitchStatement ;
+Statement: ThrowStatement ;
+Statement: TryStatement ;
+Statement: DebuggerStatement ;
+
+
+Block: T_LBRACE StatementListOpt T_RBRACE ;
+/.
+case $rule_number: {
+ AST::Block *node = makeAstNode<AST::Block> (driver->nodePool(), sym(2).StatementList);
+ node->lbraceToken = loc(1);
+ node->rbraceToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+StatementList: Statement ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::StatementList> (driver->nodePool(), sym(1).Statement);
+} break;
+./
+
+StatementList: StatementList Statement ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::StatementList> (driver->nodePool(), sym(1).StatementList, sym(2).Statement);
+} break;
+./
+
+StatementListOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+StatementListOpt: StatementList ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(1).StatementList->finish ();
+} break;
+./
+
+VariableStatement: VariableDeclarationKind VariableDeclarationList T_AUTOMATIC_SEMICOLON ; -- automatic semicolon
+VariableStatement: VariableDeclarationKind VariableDeclarationList T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::VariableStatement *node = makeAstNode<AST::VariableStatement> (driver->nodePool(),
+ sym(2).VariableDeclarationList->finish (/*readOnly=*/sym(1).ival == T_CONST));
+ node->declarationKindToken = loc(1);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+VariableDeclarationKind: T_CONST ;
+/.
+case $rule_number: {
+ sym(1).ival = T_CONST;
+} break;
+./
+
+VariableDeclarationKind: T_VAR ;
+/.
+case $rule_number: {
+ sym(1).ival = T_VAR;
+} break;
+./
+
+VariableDeclarationList: VariableDeclaration ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::VariableDeclarationList> (driver->nodePool(), sym(1).VariableDeclaration);
+} break;
+./
+
+VariableDeclarationList: VariableDeclarationList T_COMMA VariableDeclaration ;
+/.
+case $rule_number: {
+ AST::VariableDeclarationList *node = makeAstNode<AST::VariableDeclarationList> (driver->nodePool(),
+ sym(1).VariableDeclarationList, sym(3).VariableDeclaration);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+VariableDeclarationListNotIn: VariableDeclarationNotIn ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::VariableDeclarationList> (driver->nodePool(), sym(1).VariableDeclaration);
+} break;
+./
+
+VariableDeclarationListNotIn: VariableDeclarationListNotIn T_COMMA VariableDeclarationNotIn ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::VariableDeclarationList> (driver->nodePool(), sym(1).VariableDeclarationList, sym(3).VariableDeclaration);
+} break;
+./
+
+VariableDeclaration: JsIdentifier InitialiserOpt ;
+/.
+case $rule_number: {
+ AST::VariableDeclaration *node = makeAstNode<AST::VariableDeclaration> (driver->nodePool(), sym(1).sval, sym(2).Expression);
+ node->identifierToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+VariableDeclarationNotIn: JsIdentifier InitialiserNotInOpt ;
+/.
+case $rule_number: {
+ AST::VariableDeclaration *node = makeAstNode<AST::VariableDeclaration> (driver->nodePool(), sym(1).sval, sym(2).Expression);
+ node->identifierToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+Initialiser: T_EQ AssignmentExpression ;
+/.
+case $rule_number: {
+ // ### TODO: AST for initializer
+ sym(1) = sym(2);
+} break;
+./
+
+InitialiserOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+InitialiserOpt: Initialiser ;
+
+InitialiserNotIn: T_EQ AssignmentExpressionNotIn ;
+/.
+case $rule_number: {
+ // ### TODO: AST for initializer
+ sym(1) = sym(2);
+} break;
+./
+
+InitialiserNotInOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+InitialiserNotInOpt: InitialiserNotIn ;
+
+EmptyStatement: T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::EmptyStatement *node = makeAstNode<AST::EmptyStatement> (driver->nodePool());
+ node->semicolonToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+ExpressionStatement: Expression T_AUTOMATIC_SEMICOLON ; -- automatic semicolon
+ExpressionStatement: Expression T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::ExpressionStatement *node = makeAstNode<AST::ExpressionStatement> (driver->nodePool(), sym(1).Expression);
+ node->semicolonToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+IfStatement: T_IF T_LPAREN Expression T_RPAREN Statement T_ELSE Statement ;
+/.
+case $rule_number: {
+ AST::IfStatement *node = makeAstNode<AST::IfStatement> (driver->nodePool(), sym(3).Expression, sym(5).Statement, sym(7).Statement);
+ node->ifToken = loc(1);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ node->elseToken = loc(5);
+ sym(1).Node = node;
+} break;
+./
+
+IfStatement: T_IF T_LPAREN Expression T_RPAREN Statement ;
+/.
+case $rule_number: {
+ AST::IfStatement *node = makeAstNode<AST::IfStatement> (driver->nodePool(), sym(3).Expression, sym(5).Statement);
+ node->ifToken = loc(1);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+
+IterationStatement: T_DO Statement T_WHILE T_LPAREN Expression T_RPAREN T_AUTOMATIC_SEMICOLON ; -- automatic semicolon
+IterationStatement: T_DO Statement T_WHILE T_LPAREN Expression T_RPAREN T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::DoWhileStatement *node = makeAstNode<AST::DoWhileStatement> (driver->nodePool(), sym(2).Statement, sym(5).Expression);
+ node->doToken = loc(1);
+ node->whileToken = loc(3);
+ node->lparenToken = loc(4);
+ node->rparenToken = loc(6);
+ node->semicolonToken = loc(7);
+ sym(1).Node = node;
+} break;
+./
+
+IterationStatement: T_WHILE T_LPAREN Expression T_RPAREN Statement ;
+/.
+case $rule_number: {
+ AST::WhileStatement *node = makeAstNode<AST::WhileStatement> (driver->nodePool(), sym(3).Expression, sym(5).Statement);
+ node->whileToken = loc(1);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+IterationStatement: T_FOR T_LPAREN ExpressionNotInOpt T_SEMICOLON ExpressionOpt T_SEMICOLON ExpressionOpt T_RPAREN Statement ;
+/.
+case $rule_number: {
+ AST::ForStatement *node = makeAstNode<AST::ForStatement> (driver->nodePool(), sym(3).Expression,
+ sym(5).Expression, sym(7).Expression, sym(9).Statement);
+ node->forToken = loc(1);
+ node->lparenToken = loc(2);
+ node->firstSemicolonToken = loc(4);
+ node->secondSemicolonToken = loc(6);
+ node->rparenToken = loc(8);
+ sym(1).Node = node;
+} break;
+./
+
+IterationStatement: T_FOR T_LPAREN T_VAR VariableDeclarationListNotIn T_SEMICOLON ExpressionOpt T_SEMICOLON ExpressionOpt T_RPAREN Statement ;
+/.
+case $rule_number: {
+ AST::LocalForStatement *node = makeAstNode<AST::LocalForStatement> (driver->nodePool(),
+ sym(4).VariableDeclarationList->finish (/*readOnly=*/false), sym(6).Expression,
+ sym(8).Expression, sym(10).Statement);
+ node->forToken = loc(1);
+ node->lparenToken = loc(2);
+ node->varToken = loc(3);
+ node->firstSemicolonToken = loc(5);
+ node->secondSemicolonToken = loc(7);
+ node->rparenToken = loc(9);
+ sym(1).Node = node;
+} break;
+./
+
+IterationStatement: T_FOR T_LPAREN LeftHandSideExpression T_IN Expression T_RPAREN Statement ;
+/.
+case $rule_number: {
+ AST:: ForEachStatement *node = makeAstNode<AST::ForEachStatement> (driver->nodePool(), sym(3).Expression,
+ sym(5).Expression, sym(7).Statement);
+ node->forToken = loc(1);
+ node->lparenToken = loc(2);
+ node->inToken = loc(4);
+ node->rparenToken = loc(6);
+ sym(1).Node = node;
+} break;
+./
+
+IterationStatement: T_FOR T_LPAREN T_VAR VariableDeclarationNotIn T_IN Expression T_RPAREN Statement ;
+/.
+case $rule_number: {
+ AST::LocalForEachStatement *node = makeAstNode<AST::LocalForEachStatement> (driver->nodePool(),
+ sym(4).VariableDeclaration, sym(6).Expression, sym(8).Statement);
+ node->forToken = loc(1);
+ node->lparenToken = loc(2);
+ node->varToken = loc(3);
+ node->inToken = loc(5);
+ node->rparenToken = loc(7);
+ sym(1).Node = node;
+} break;
+./
+
+ContinueStatement: T_CONTINUE T_AUTOMATIC_SEMICOLON ; -- automatic semicolon
+ContinueStatement: T_CONTINUE T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::ContinueStatement *node = makeAstNode<AST::ContinueStatement> (driver->nodePool());
+ node->continueToken = loc(1);
+ node->semicolonToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+ContinueStatement: T_CONTINUE JsIdentifier T_AUTOMATIC_SEMICOLON ; -- automatic semicolon
+ContinueStatement: T_CONTINUE JsIdentifier T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::ContinueStatement *node = makeAstNode<AST::ContinueStatement> (driver->nodePool(), sym(2).sval);
+ node->continueToken = loc(1);
+ node->identifierToken = loc(2);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+BreakStatement: T_BREAK T_AUTOMATIC_SEMICOLON ; -- automatic semicolon
+BreakStatement: T_BREAK T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::BreakStatement *node = makeAstNode<AST::BreakStatement> (driver->nodePool());
+ node->breakToken = loc(1);
+ node->semicolonToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+BreakStatement: T_BREAK JsIdentifier T_AUTOMATIC_SEMICOLON ; -- automatic semicolon
+BreakStatement: T_BREAK JsIdentifier T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::BreakStatement *node = makeAstNode<AST::BreakStatement> (driver->nodePool(), sym(2).sval);
+ node->breakToken = loc(1);
+ node->identifierToken = loc(2);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+ReturnStatement: T_RETURN ExpressionOpt T_AUTOMATIC_SEMICOLON ; -- automatic semicolon
+ReturnStatement: T_RETURN ExpressionOpt T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::ReturnStatement *node = makeAstNode<AST::ReturnStatement> (driver->nodePool(), sym(2).Expression);
+ node->returnToken = loc(1);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+WithStatement: T_WITH T_LPAREN Expression T_RPAREN Statement ;
+/.
+case $rule_number: {
+ AST::WithStatement *node = makeAstNode<AST::WithStatement> (driver->nodePool(), sym(3).Expression, sym(5).Statement);
+ node->withToken = loc(1);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+SwitchStatement: T_SWITCH T_LPAREN Expression T_RPAREN CaseBlock ;
+/.
+case $rule_number: {
+ AST::SwitchStatement *node = makeAstNode<AST::SwitchStatement> (driver->nodePool(), sym(3).Expression, sym(5).CaseBlock);
+ node->switchToken = loc(1);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+CaseBlock: T_LBRACE CaseClausesOpt T_RBRACE ;
+/.
+case $rule_number: {
+ AST::CaseBlock *node = makeAstNode<AST::CaseBlock> (driver->nodePool(), sym(2).CaseClauses);
+ node->lbraceToken = loc(1);
+ node->rbraceToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+CaseBlock: T_LBRACE CaseClausesOpt DefaultClause CaseClausesOpt T_RBRACE ;
+/.
+case $rule_number: {
+ AST::CaseBlock *node = makeAstNode<AST::CaseBlock> (driver->nodePool(), sym(2).CaseClauses, sym(3).DefaultClause, sym(4).CaseClauses);
+ node->lbraceToken = loc(1);
+ node->rbraceToken = loc(5);
+ sym(1).Node = node;
+} break;
+./
+
+CaseClauses: CaseClause ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::CaseClauses> (driver->nodePool(), sym(1).CaseClause);
+} break;
+./
+
+CaseClauses: CaseClauses CaseClause ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::CaseClauses> (driver->nodePool(), sym(1).CaseClauses, sym(2).CaseClause);
+} break;
+./
+
+CaseClausesOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+CaseClausesOpt: CaseClauses ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(1).CaseClauses->finish ();
+} break;
+./
+
+CaseClause: T_CASE Expression T_COLON StatementListOpt ;
+/.
+case $rule_number: {
+ AST::CaseClause *node = makeAstNode<AST::CaseClause> (driver->nodePool(), sym(2).Expression, sym(4).StatementList);
+ node->caseToken = loc(1);
+ node->colonToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+DefaultClause: T_DEFAULT T_COLON StatementListOpt ;
+/.
+case $rule_number: {
+ AST::DefaultClause *node = makeAstNode<AST::DefaultClause> (driver->nodePool(), sym(3).StatementList);
+ node->defaultToken = loc(1);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+LabelledStatement: T_SIGNAL T_COLON Statement ;
+/.case $rule_number:./
+
+LabelledStatement: T_PROPERTY T_COLON Statement ;
+/.
+case $rule_number: {
+ AST::LabelledStatement *node = makeAstNode<AST::LabelledStatement> (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount()), sym(3).Statement);
+ node->identifierToken = loc(1);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+LabelledStatement: T_IDENTIFIER T_COLON Statement ;
+/.
+case $rule_number: {
+ AST::LabelledStatement *node = makeAstNode<AST::LabelledStatement> (driver->nodePool(), sym(1).sval, sym(3).Statement);
+ node->identifierToken = loc(1);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+ThrowStatement: T_THROW Expression T_AUTOMATIC_SEMICOLON ; -- automatic semicolon
+ThrowStatement: T_THROW Expression T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::ThrowStatement *node = makeAstNode<AST::ThrowStatement> (driver->nodePool(), sym(2).Expression);
+ node->throwToken = loc(1);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+TryStatement: T_TRY Block Catch ;
+/.
+case $rule_number: {
+ AST::TryStatement *node = makeAstNode<AST::TryStatement> (driver->nodePool(), sym(2).Statement, sym(3).Catch);
+ node->tryToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+TryStatement: T_TRY Block Finally ;
+/.
+case $rule_number: {
+ AST::TryStatement *node = makeAstNode<AST::TryStatement> (driver->nodePool(), sym(2).Statement, sym(3).Finally);
+ node->tryToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+TryStatement: T_TRY Block Catch Finally ;
+/.
+case $rule_number: {
+ AST::TryStatement *node = makeAstNode<AST::TryStatement> (driver->nodePool(), sym(2).Statement, sym(3).Catch, sym(4).Finally);
+ node->tryToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+Catch: T_CATCH T_LPAREN JsIdentifier T_RPAREN Block ;
+/.
+case $rule_number: {
+ AST::Catch *node = makeAstNode<AST::Catch> (driver->nodePool(), sym(3).sval, sym(5).Block);
+ node->catchToken = loc(1);
+ node->lparenToken = loc(2);
+ node->identifierToken = loc(3);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+./
+
+Finally: T_FINALLY Block ;
+/.
+case $rule_number: {
+ AST::Finally *node = makeAstNode<AST::Finally> (driver->nodePool(), sym(2).Block);
+ node->finallyToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+DebuggerStatement: T_DEBUGGER T_AUTOMATIC_SEMICOLON ; -- automatic semicolon
+DebuggerStatement: T_DEBUGGER T_SEMICOLON ;
+/.
+case $rule_number: {
+ AST::DebuggerStatement *node = makeAstNode<AST::DebuggerStatement> (driver->nodePool());
+ node->debuggerToken = loc(1);
+ node->semicolonToken = loc(2);
+ sym(1).Node = node;
+} break;
+./
+
+FunctionDeclaration: T_FUNCTION JsIdentifier T_LPAREN FormalParameterListOpt T_RPAREN T_LBRACE FunctionBodyOpt T_RBRACE ;
+/.
+case $rule_number: {
+ AST::FunctionDeclaration *node = makeAstNode<AST::FunctionDeclaration> (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody);
+ node->functionToken = loc(1);
+ node->identifierToken = loc(2);
+ node->lparenToken = loc(3);
+ node->rparenToken = loc(5);
+ node->lbraceToken = loc(6);
+ node->rbraceToken = loc(8);
+ sym(1).Node = node;
+} break;
+./
+
+FunctionExpression: T_FUNCTION IdentifierOpt T_LPAREN FormalParameterListOpt T_RPAREN T_LBRACE FunctionBodyOpt T_RBRACE ;
+/.
+case $rule_number: {
+ AST::FunctionExpression *node = makeAstNode<AST::FunctionExpression> (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody);
+ node->functionToken = loc(1);
+ if (sym(2).sval)
+ node->identifierToken = loc(2);
+ node->lparenToken = loc(3);
+ node->rparenToken = loc(5);
+ node->lbraceToken = loc(6);
+ node->rbraceToken = loc(8);
+ sym(1).Node = node;
+} break;
+./
+
+FormalParameterList: JsIdentifier ;
+/.
+case $rule_number: {
+ AST::FormalParameterList *node = makeAstNode<AST::FormalParameterList> (driver->nodePool(), sym(1).sval);
+ node->identifierToken = loc(1);
+ sym(1).Node = node;
+} break;
+./
+
+FormalParameterList: FormalParameterList T_COMMA JsIdentifier ;
+/.
+case $rule_number: {
+ AST::FormalParameterList *node = makeAstNode<AST::FormalParameterList> (driver->nodePool(), sym(1).FormalParameterList, sym(3).sval);
+ node->commaToken = loc(2);
+ node->identifierToken = loc(3);
+ sym(1).Node = node;
+} break;
+./
+
+FormalParameterListOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+FormalParameterListOpt: FormalParameterList ;
+/.
+case $rule_number: {
+ sym(1).Node = sym(1).FormalParameterList->finish ();
+} break;
+./
+
+FunctionBodyOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+FunctionBodyOpt: FunctionBody ;
+
+FunctionBody: SourceElements ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::FunctionBody> (driver->nodePool(), sym(1).SourceElements->finish ());
+} break;
+./
+
+Program: SourceElements ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::Program> (driver->nodePool(), sym(1).SourceElements->finish ());
+} break;
+./
+
+SourceElements: SourceElement ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::SourceElements> (driver->nodePool(), sym(1).SourceElement);
+} break;
+./
+
+SourceElements: SourceElements SourceElement ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::SourceElements> (driver->nodePool(), sym(1).SourceElements, sym(2).SourceElement);
+} break;
+./
+
+SourceElement: Statement ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::StatementSourceElement> (driver->nodePool(), sym(1).Statement);
+} break;
+./
+
+SourceElement: FunctionDeclaration ;
+/.
+case $rule_number: {
+ sym(1).Node = makeAstNode<AST::FunctionSourceElement> (driver->nodePool(), sym(1).FunctionDeclaration);
+} break;
+./
+
+IdentifierOpt: ;
+/.
+case $rule_number: {
+ sym(1).sval = 0;
+} break;
+./
+
+IdentifierOpt: JsIdentifier ;
+
+PropertyNameAndValueListOpt: ;
+/.
+case $rule_number: {
+ sym(1).Node = 0;
+} break;
+./
+
+PropertyNameAndValueListOpt: PropertyNameAndValueList ;
+
+/.
+ } // switch
+ action = nt_action(state_stack[tos], lhs[r] - TERMINAL_COUNT);
+ } // if
+ } while (action != 0);
+
+ if (first_token == last_token) {
+ const int errorState = state_stack[tos];
+
+ // automatic insertion of `;'
+ if (yytoken != -1 && t_action(errorState, T_AUTOMATIC_SEMICOLON) && automatic(driver, yytoken)) {
+ SavedToken &tk = token_buffer[0];
+ tk.token = yytoken;
+ tk.dval = yylval;
+ tk.loc = yylloc;
+
+ yylloc = yyprevlloc;
+ yylloc.offset += yylloc.length;
+ yylloc.startColumn += yylloc.length;
+ yylloc.length = 0;
+
+ //const QString msg = qApp->translate("QmlParser", "Missing `;'");
+ //diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, yylloc, msg));
+
+ first_token = &token_buffer[0];
+ last_token = &token_buffer[1];
+
+ yytoken = T_SEMICOLON;
+ yylval = 0;
+
+ action = errorState;
+
+ goto _Lcheck_token;
+ }
+
+ hadErrors = true;
+
+ token_buffer[0].token = yytoken;
+ token_buffer[0].dval = yylval;
+ token_buffer[0].loc = yylloc;
+
+ token_buffer[1].token = yytoken = lexer->lex();
+ token_buffer[1].dval = yylval = lexer->dval();
+ token_buffer[1].loc = yylloc = location(lexer);
+
+ if (t_action(errorState, yytoken)) {
+ QString msg;
+ int token = token_buffer[0].token;
+ if (token < 0 || token >= TERMINAL_COUNT)
+ msg = qApp->translate("QmlParser", "Syntax error");
+ else
+ msg = qApp->translate("QmlParser", "Unexpected token `%1'").arg(QLatin1String(spell[token]));
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg));
+
+ action = errorState;
+ goto _Lcheck_token;
+ }
+
+ static int tokens[] = {
+ T_PLUS,
+ T_EQ,
+
+ T_COMMA,
+ T_COLON,
+ T_SEMICOLON,
+
+ T_RPAREN, T_RBRACKET, T_RBRACE,
+
+ T_NUMERIC_LITERAL,
+ T_IDENTIFIER,
+
+ T_LPAREN, T_LBRACKET, T_LBRACE,
+
+ EOF_SYMBOL
+ };
+
+ for (int *tk = tokens; *tk != EOF_SYMBOL; ++tk) {
+ int a = t_action(errorState, *tk);
+ if (a > 0 && t_action(a, yytoken)) {
+ const QString msg = qApp->translate("QmlParser", "Expected token `%1'").arg(QLatin1String(spell[*tk]));
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg));
+
+ yytoken = *tk;
+ yylval = 0;
+ yylloc = token_buffer[0].loc;
+ yylloc.length = 0;
+
+ first_token = &token_buffer[0];
+ last_token = &token_buffer[2];
+
+ action = errorState;
+ goto _Lcheck_token;
+ }
+ }
+
+ for (int tk = 1; tk < TERMINAL_COUNT; ++tk) {
+ if (tk == T_AUTOMATIC_SEMICOLON || tk == T_FEED_UI_PROGRAM ||
+ tk == T_FEED_JS_STATEMENT || tk == T_FEED_JS_EXPRESSION ||
+ tk == T_FEED_JS_SOURCE_ELEMENT)
+ continue;
+
+ int a = t_action(errorState, tk);
+ if (a > 0 && t_action(a, yytoken)) {
+ const QString msg = qApp->translate("QmlParser", "Expected token `%1'").arg(QLatin1String(spell[tk]));
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg));
+
+ yytoken = tk;
+ yylval = 0;
+ yylloc = token_buffer[0].loc;
+ yylloc.length = 0;
+
+ action = errorState;
+ goto _Lcheck_token;
+ }
+ }
+
+ const QString msg = qApp->translate("QmlParser", "Syntax error");
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg));
+ }
+
+ return false;
+}
+
+QT_QML_END_NAMESPACE
+
+
+./
+/:
+QT_QML_END_NAMESPACE
+
+
+
+#endif // QMLJSPARSER_P_H
+:/
diff --git a/src/declarative/qml/parser/qmljsast.cpp b/src/declarative/qml/parser/qmljsast.cpp
new file mode 100644
index 0000000..e80b05e
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsast.cpp
@@ -0,0 +1,955 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmljsast_p.h"
+
+#include "qmljsastvisitor_p.h"
+
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS { namespace AST {
+
+void Node::accept(Visitor *visitor)
+{
+ if (visitor->preVisit(this)) {
+ accept0(visitor);
+ }
+ visitor->postVisit(this);
+}
+
+void Node::accept(Node *node, Visitor *visitor)
+{
+ if (node)
+ node->accept(visitor);
+}
+
+ExpressionNode *Node::expressionCast()
+{
+ return 0;
+}
+
+BinaryExpression *Node::binaryExpressionCast()
+{
+ return 0;
+}
+
+Statement *Node::statementCast()
+{
+ return 0;
+}
+
+UiObjectMember *Node::uiObjectMemberCast()
+{
+ return 0;
+}
+
+ExpressionNode *ExpressionNode::expressionCast()
+{
+ return this;
+}
+
+BinaryExpression *BinaryExpression::binaryExpressionCast()
+{
+ return this;
+}
+
+Statement *Statement::statementCast()
+{
+ return this;
+}
+
+UiObjectMember *UiObjectMember::uiObjectMemberCast()
+{
+ return this;
+}
+
+void NestedExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+ visitor->endVisit(this);
+}
+
+void ThisExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void IdentifierExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void NullExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void TrueLiteral::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void FalseLiteral::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void StringLiteral::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void NumericLiteral::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void RegExpLiteral::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void ArrayLiteral::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(elements, visitor);
+ accept(elision, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void ObjectLiteral::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(properties, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void ElementList::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ for (ElementList *it = this; it; it = it->next) {
+ accept(it->elision, visitor);
+ accept(it->expression, visitor);
+ }
+ }
+
+ visitor->endVisit(this);
+}
+
+void Elision::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ // ###
+ }
+
+ visitor->endVisit(this);
+}
+
+void PropertyNameAndValueList::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ for (PropertyNameAndValueList *it = this; it; it = it->next) {
+ accept(it->name, visitor);
+ accept(it->value, visitor);
+ }
+ }
+
+ visitor->endVisit(this);
+}
+
+void IdentifierPropertyName::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void StringLiteralPropertyName::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void NumericLiteralPropertyName::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void ArrayMemberExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(base, visitor);
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void FieldMemberExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(base, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void NewMemberExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(base, visitor);
+ accept(arguments, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void NewExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void CallExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(base, visitor);
+ accept(arguments, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void ArgumentList::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ for (ArgumentList *it = this; it; it = it->next) {
+ accept(it->expression, visitor);
+ }
+ }
+
+ visitor->endVisit(this);
+}
+
+void PostIncrementExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(base, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void PostDecrementExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(base, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void DeleteExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void VoidExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void TypeOfExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void PreIncrementExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void PreDecrementExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UnaryPlusExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UnaryMinusExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void TildeExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void NotExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void BinaryExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(left, visitor);
+ accept(right, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void ConditionalExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ accept(ok, visitor);
+ accept(ko, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void Expression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(left, visitor);
+ accept(right, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void Block::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(statements, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void StatementList::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ for (StatementList *it = this; it; it = it->next) {
+ accept(it->statement, visitor);
+ }
+ }
+
+ visitor->endVisit(this);
+}
+
+void VariableStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(declarations, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void VariableDeclarationList::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ for (VariableDeclarationList *it = this; it; it = it->next) {
+ accept(it->declaration, visitor);
+ }
+ }
+
+ visitor->endVisit(this);
+}
+
+void VariableDeclaration::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void EmptyStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void ExpressionStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void IfStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ accept(ok, visitor);
+ accept(ko, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void DoWhileStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(statement, visitor);
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void WhileStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void ForStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(initialiser, visitor);
+ accept(condition, visitor);
+ accept(expression, visitor);
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void LocalForStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(declarations, visitor);
+ accept(condition, visitor);
+ accept(expression, visitor);
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void ForEachStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(initialiser, visitor);
+ accept(expression, visitor);
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void LocalForEachStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(declaration, visitor);
+ accept(expression, visitor);
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void ContinueStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void BreakStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void ReturnStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void WithStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void SwitchStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ accept(block, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void CaseBlock::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(clauses, visitor);
+ accept(defaultClause, visitor);
+ accept(moreClauses, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void CaseClauses::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ for (CaseClauses *it = this; it; it = it->next) {
+ accept(it->clause, visitor);
+ }
+ }
+
+ visitor->endVisit(this);
+}
+
+void CaseClause::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ accept(statements, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void DefaultClause::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(statements, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void LabelledStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void ThrowStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void TryStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(statement, visitor);
+ accept(catchExpression, visitor);
+ accept(finallyExpression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void Catch::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void Finally::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void FunctionDeclaration::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(formals, visitor);
+ accept(body, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void FunctionExpression::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(formals, visitor);
+ accept(body, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void FormalParameterList::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ // ###
+ }
+
+ visitor->endVisit(this);
+}
+
+void FunctionBody::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(elements, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void Program::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(elements, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void SourceElements::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ for (SourceElements *it = this; it; it = it->next) {
+ accept(it->element, visitor);
+ }
+ }
+
+ visitor->endVisit(this);
+}
+
+void FunctionSourceElement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(declaration, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void StatementSourceElement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void DebuggerStatement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiProgram::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(imports, visitor);
+ accept(members, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiSignature::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(formals, visitor);
+ }
+ visitor->endVisit(this);
+}
+
+void UiFormalList::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ for (UiFormalList *it = this; it; it = it->next) {
+ accept(it->formal, visitor);
+ }
+ }
+ visitor->endVisit(this);
+}
+
+void UiFormal::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+ visitor->endVisit(this);
+}
+
+void UiPublicMember::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(expression, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiObjectDefinition::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(qualifiedTypeNameId, visitor);
+ accept(initializer, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiObjectInitializer::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(members, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiObjectBinding::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(qualifiedId, visitor);
+ accept(qualifiedTypeNameId, visitor);
+ accept(initializer, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiScriptBinding::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(qualifiedId, visitor);
+ accept(statement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiArrayBinding::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(qualifiedId, visitor);
+ accept(members, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiObjectMemberList::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ for (UiObjectMemberList *it = this; it; it = it->next)
+ accept(it->member, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiArrayMemberList::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ for (UiArrayMemberList *it = this; it; it = it->next)
+ accept(it->member, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiQualifiedId::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiImport::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(importUri, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiImportList::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(import, visitor);
+ accept(next, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+void UiSourceElement::accept0(Visitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(sourceElement, visitor);
+ }
+
+ visitor->endVisit(this);
+}
+
+} } // namespace QmlJS::AST
+
+QT_QML_END_NAMESPACE
+
+
diff --git a/src/declarative/qml/parser/qmljsast_p.h b/src/declarative/qml/parser/qmljsast_p.h
new file mode 100644
index 0000000..032fbb1
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsast_p.h
@@ -0,0 +1,2678 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLJSAST_P_H
+#define QMLJSAST_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qmljsastvisitor_p.h"
+#include "qmljsglobal_p.h"
+
+#include <QtCore/QString>
+
+QT_QML_BEGIN_NAMESPACE
+
+#define QMLJS_DECLARE_AST_NODE(name) \
+ enum { K = Kind_##name };
+
+namespace QSOperator // ### rename
+{
+
+enum Op {
+ Add,
+ And,
+ InplaceAnd,
+ Assign,
+ BitAnd,
+ BitOr,
+ BitXor,
+ InplaceSub,
+ Div,
+ InplaceDiv,
+ Equal,
+ Ge,
+ Gt,
+ In,
+ InplaceAdd,
+ InstanceOf,
+ Le,
+ LShift,
+ InplaceLeftShift,
+ Lt,
+ Mod,
+ InplaceMod,
+ Mul,
+ InplaceMul,
+ NotEqual,
+ Or,
+ InplaceOr,
+ RShift,
+ InplaceRightShift,
+ StrictEqual,
+ StrictNotEqual,
+ Sub,
+ URShift,
+ InplaceURightShift,
+ InplaceXor
+};
+
+} // namespace QSOperator
+
+namespace QmlJS {
+class NameId;
+namespace AST {
+
+template <typename _T1, typename _T2>
+_T1 cast(_T2 *ast)
+{
+ if (ast && ast->kind == static_cast<_T1>(0)->K)
+ return static_cast<_T1>(ast);
+
+ return 0;
+}
+
+class QML_PARSER_EXPORT Node
+{
+public:
+ enum Kind {
+ Kind_Undefined,
+
+ Kind_ArgumentList,
+ Kind_ArrayLiteral,
+ Kind_ArrayMemberExpression,
+ Kind_BinaryExpression,
+ Kind_Block,
+ Kind_BreakStatement,
+ Kind_CallExpression,
+ Kind_CaseBlock,
+ Kind_CaseClause,
+ Kind_CaseClauses,
+ Kind_Catch,
+ Kind_ConditionalExpression,
+ Kind_ContinueStatement,
+ Kind_DebuggerStatement,
+ Kind_DefaultClause,
+ Kind_DeleteExpression,
+ Kind_DoWhileStatement,
+ Kind_ElementList,
+ Kind_Elision,
+ Kind_EmptyStatement,
+ Kind_Expression,
+ Kind_ExpressionStatement,
+ Kind_FalseLiteral,
+ Kind_FieldMemberExpression,
+ Kind_Finally,
+ Kind_ForEachStatement,
+ Kind_ForStatement,
+ Kind_FormalParameterList,
+ Kind_FunctionBody,
+ Kind_FunctionDeclaration,
+ Kind_FunctionExpression,
+ Kind_FunctionSourceElement,
+ Kind_IdentifierExpression,
+ Kind_IdentifierPropertyName,
+ Kind_IfStatement,
+ Kind_LabelledStatement,
+ Kind_LocalForEachStatement,
+ Kind_LocalForStatement,
+ Kind_NewExpression,
+ Kind_NewMemberExpression,
+ Kind_NotExpression,
+ Kind_NullExpression,
+ Kind_NumericLiteral,
+ Kind_NumericLiteralPropertyName,
+ Kind_ObjectLiteral,
+ Kind_PostDecrementExpression,
+ Kind_PostIncrementExpression,
+ Kind_PreDecrementExpression,
+ Kind_PreIncrementExpression,
+ Kind_Program,
+ Kind_PropertyName,
+ Kind_PropertyNameAndValueList,
+ Kind_RegExpLiteral,
+ Kind_ReturnStatement,
+ Kind_SourceElement,
+ Kind_SourceElements,
+ Kind_StatementList,
+ Kind_StatementSourceElement,
+ Kind_StringLiteral,
+ Kind_StringLiteralPropertyName,
+ Kind_SwitchStatement,
+ Kind_ThisExpression,
+ Kind_ThrowStatement,
+ Kind_TildeExpression,
+ Kind_TrueLiteral,
+ Kind_TryStatement,
+ Kind_TypeOfExpression,
+ Kind_UnaryMinusExpression,
+ Kind_UnaryPlusExpression,
+ Kind_VariableDeclaration,
+ Kind_VariableDeclarationList,
+ Kind_VariableStatement,
+ Kind_VoidExpression,
+ Kind_WhileStatement,
+ Kind_WithStatement,
+ Kind_NestedExpression,
+
+ Kind_UiArrayBinding,
+ Kind_UiImport,
+ Kind_UiImportList,
+ Kind_UiObjectBinding,
+ Kind_UiObjectDefinition,
+ Kind_UiObjectInitializer,
+ Kind_UiObjectMemberList,
+ Kind_UiArrayMemberList,
+ Kind_UiProgram,
+ Kind_UiParameterList,
+ Kind_UiPublicMember,
+ Kind_UiQualifiedId,
+ Kind_UiScriptBinding,
+ Kind_UiSourceElement,
+ Kind_UiFormal,
+ Kind_UiFormalList,
+ Kind_UiSignature
+ };
+
+ inline Node()
+ : kind(Kind_Undefined) {}
+
+ virtual ~Node() {}
+
+ virtual ExpressionNode *expressionCast();
+ virtual BinaryExpression *binaryExpressionCast();
+ virtual Statement *statementCast();
+ virtual UiObjectMember *uiObjectMemberCast();
+
+ void accept(Visitor *visitor);
+ static void accept(Node *node, Visitor *visitor);
+
+ inline static void acceptChild(Node *node, Visitor *visitor)
+ { return accept(node, visitor); } // ### remove
+
+ virtual void accept0(Visitor *visitor) = 0;
+
+// attributes
+ int kind;
+};
+
+class QML_PARSER_EXPORT ExpressionNode: public Node
+{
+public:
+ ExpressionNode() {}
+ virtual ~ExpressionNode() {}
+
+ virtual ExpressionNode *expressionCast();
+
+ virtual SourceLocation firstSourceLocation() const = 0;
+ virtual SourceLocation lastSourceLocation() const = 0;
+};
+
+class QML_PARSER_EXPORT Statement: public Node
+{
+public:
+ Statement() {}
+ virtual ~Statement() {}
+
+ virtual Statement *statementCast();
+
+ virtual SourceLocation firstSourceLocation() const = 0;
+ virtual SourceLocation lastSourceLocation() const = 0;
+};
+
+class QML_PARSER_EXPORT UiFormal: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiFormal)
+
+ UiFormal(NameId *name, NameId *alias = 0)
+ : name(name), alias(alias)
+ { }
+
+ virtual SourceLocation firstSourceLocation() const
+ { return SourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return SourceLocation(); }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ NameId *name;
+ NameId *alias;
+ SourceLocation identifierToken;
+ SourceLocation asToken;
+ SourceLocation aliasToken;
+};
+
+class QML_PARSER_EXPORT UiFormalList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiFormalList)
+
+ UiFormalList(UiFormal *formal)
+ : formal(formal), next(this) {}
+
+ UiFormalList(UiFormalList *previous, UiFormal *formal)
+ : formal(formal)
+ {
+ next = previous->next;
+ previous->next = this;
+ }
+
+ UiFormalList *finish()
+ {
+ UiFormalList *head = next;
+ next = 0;
+ return head;
+ }
+
+ virtual SourceLocation firstSourceLocation() const
+ { return SourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return SourceLocation(); }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ UiFormal *formal;
+ UiFormalList *next;
+};
+
+class QML_PARSER_EXPORT UiSignature: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiSignature)
+
+ UiSignature(UiFormalList *formals = 0)
+ : formals(formals)
+ { }
+
+ virtual SourceLocation firstSourceLocation() const
+ { return SourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return SourceLocation(); }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ SourceLocation lparenToken;
+ UiFormalList *formals;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT NestedExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(NestedExpression)
+
+ NestedExpression(ExpressionNode *expression)
+ : expression(expression)
+ { kind = K; }
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return lparenToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return rparenToken; }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation lparenToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT ThisExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ThisExpression)
+
+ ThisExpression() { kind = K; }
+ virtual ~ThisExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return thisToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return thisToken; }
+
+// attributes
+ SourceLocation thisToken;
+};
+
+class QML_PARSER_EXPORT IdentifierExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(IdentifierExpression)
+
+ IdentifierExpression(NameId *n):
+ name (n) { kind = K; }
+
+ virtual ~IdentifierExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return identifierToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return identifierToken; }
+
+// attributes
+ NameId *name;
+ SourceLocation identifierToken;
+};
+
+class QML_PARSER_EXPORT NullExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(NullExpression)
+
+ NullExpression() { kind = K; }
+ virtual ~NullExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return nullToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return nullToken; }
+
+// attributes
+ SourceLocation nullToken;
+};
+
+class QML_PARSER_EXPORT TrueLiteral: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(TrueLiteral)
+
+ TrueLiteral() { kind = K; }
+ virtual ~TrueLiteral() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return trueToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return trueToken; }
+
+// attributes
+ SourceLocation trueToken;
+};
+
+class QML_PARSER_EXPORT FalseLiteral: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(FalseLiteral)
+
+ FalseLiteral() { kind = K; }
+ virtual ~FalseLiteral() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return falseToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return falseToken; }
+
+// attributes
+ SourceLocation falseToken;
+};
+
+class QML_PARSER_EXPORT NumericLiteral: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(NumericLiteral)
+
+ NumericLiteral(double v):
+ value(v) { kind = K; }
+ virtual ~NumericLiteral() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return literalToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return literalToken; }
+
+// attributes:
+ double value;
+ SourceLocation literalToken;
+};
+
+class QML_PARSER_EXPORT StringLiteral: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(StringLiteral)
+
+ StringLiteral(NameId *v):
+ value (v) { kind = K; }
+
+ virtual ~StringLiteral() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return literalToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return literalToken; }
+
+// attributes:
+ NameId *value;
+ SourceLocation literalToken;
+};
+
+class QML_PARSER_EXPORT RegExpLiteral: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(RegExpLiteral)
+
+ RegExpLiteral(NameId *p, int f):
+ pattern (p), flags (f) { kind = K; }
+
+ virtual ~RegExpLiteral() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return literalToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return literalToken; }
+
+// attributes:
+ NameId *pattern;
+ int flags;
+ SourceLocation literalToken;
+};
+
+class QML_PARSER_EXPORT ArrayLiteral: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ArrayLiteral)
+
+ ArrayLiteral(Elision *e):
+ elements (0), elision (e)
+ { kind = K; }
+
+ ArrayLiteral(ElementList *elts):
+ elements (elts), elision (0)
+ { kind = K; }
+
+ ArrayLiteral(ElementList *elts, Elision *e):
+ elements (elts), elision (e)
+ { kind = K; }
+
+ virtual ~ArrayLiteral() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return lbracketToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return rbracketToken; }
+
+// attributes
+ ElementList *elements;
+ Elision *elision;
+ SourceLocation lbracketToken;
+ SourceLocation commaToken;
+ SourceLocation rbracketToken;
+};
+
+class QML_PARSER_EXPORT ObjectLiteral: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ObjectLiteral)
+
+ ObjectLiteral():
+ properties (0) { kind = K; }
+
+ ObjectLiteral(PropertyNameAndValueList *plist):
+ properties (plist) { kind = K; }
+
+ virtual ~ObjectLiteral() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return lbraceToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return rbraceToken; }
+
+// attributes
+ PropertyNameAndValueList *properties;
+ SourceLocation lbraceToken;
+ SourceLocation rbraceToken;
+};
+
+class QML_PARSER_EXPORT ElementList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ElementList)
+
+ ElementList(Elision *e, ExpressionNode *expr):
+ elision (e), expression (expr), next (this)
+ { kind = K; }
+
+ ElementList(ElementList *previous, Elision *e, ExpressionNode *expr):
+ elision (e), expression (expr)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~ElementList() {}
+
+ inline ElementList *finish ()
+ {
+ ElementList *front = next;
+ next = 0;
+ return front;
+ }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ Elision *elision;
+ ExpressionNode *expression;
+ ElementList *next;
+ SourceLocation commaToken;
+};
+
+class QML_PARSER_EXPORT Elision: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(Elision)
+
+ Elision():
+ next (this) { kind = K; }
+
+ Elision(Elision *previous)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~Elision() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ inline Elision *finish ()
+ {
+ Elision *front = next;
+ next = 0;
+ return front;
+ }
+
+// attributes
+ Elision *next;
+ SourceLocation commaToken;
+};
+
+class QML_PARSER_EXPORT PropertyNameAndValueList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(PropertyNameAndValueList)
+
+ PropertyNameAndValueList(PropertyName *n, ExpressionNode *v):
+ name (n), value (v), next (this)
+ { kind = K; }
+
+ PropertyNameAndValueList(PropertyNameAndValueList *previous, PropertyName *n, ExpressionNode *v):
+ name (n), value (v)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~PropertyNameAndValueList() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ inline PropertyNameAndValueList *finish ()
+ {
+ PropertyNameAndValueList *front = next;
+ next = 0;
+ return front;
+ }
+
+// attributes
+ PropertyName *name;
+ ExpressionNode *value;
+ PropertyNameAndValueList *next;
+ SourceLocation colonToken;
+ SourceLocation commaToken;
+};
+
+class QML_PARSER_EXPORT PropertyName: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(PropertyName)
+
+ PropertyName() { kind = K; }
+ virtual ~PropertyName() {}
+
+// attributes
+ SourceLocation propertyNameToken;
+};
+
+class QML_PARSER_EXPORT IdentifierPropertyName: public PropertyName
+{
+public:
+ QMLJS_DECLARE_AST_NODE(IdentifierPropertyName)
+
+ IdentifierPropertyName(NameId *n):
+ id (n) { kind = K; }
+
+ virtual ~IdentifierPropertyName() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ NameId *id;
+};
+
+class QML_PARSER_EXPORT StringLiteralPropertyName: public PropertyName
+{
+public:
+ QMLJS_DECLARE_AST_NODE(StringLiteralPropertyName)
+
+ StringLiteralPropertyName(NameId *n):
+ id (n) { kind = K; }
+ virtual ~StringLiteralPropertyName() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ NameId *id;
+};
+
+class QML_PARSER_EXPORT NumericLiteralPropertyName: public PropertyName
+{
+public:
+ QMLJS_DECLARE_AST_NODE(NumericLiteralPropertyName)
+
+ NumericLiteralPropertyName(double n):
+ id (n) { kind = K; }
+ virtual ~NumericLiteralPropertyName() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ double id;
+};
+
+class QML_PARSER_EXPORT ArrayMemberExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ArrayMemberExpression)
+
+ ArrayMemberExpression(ExpressionNode *b, ExpressionNode *e):
+ base (b), expression (e)
+ { kind = K; }
+
+ virtual ~ArrayMemberExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return base->firstSourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return rbracketToken; }
+
+// attributes
+ ExpressionNode *base;
+ ExpressionNode *expression;
+ SourceLocation lbracketToken;
+ SourceLocation rbracketToken;
+};
+
+class QML_PARSER_EXPORT FieldMemberExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(FieldMemberExpression)
+
+ FieldMemberExpression(ExpressionNode *b, NameId *n):
+ base (b), name (n)
+ { kind = K; }
+
+ virtual ~FieldMemberExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return base->firstSourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return identifierToken; }
+
+ // attributes
+ ExpressionNode *base;
+ NameId *name;
+ SourceLocation dotToken;
+ SourceLocation identifierToken;
+};
+
+class QML_PARSER_EXPORT NewMemberExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(NewMemberExpression)
+
+ NewMemberExpression(ExpressionNode *b, ArgumentList *a):
+ base (b), arguments (a)
+ { kind = K; }
+
+ virtual ~NewMemberExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return newToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return rparenToken; }
+
+ // attributes
+ ExpressionNode *base;
+ ArgumentList *arguments;
+ SourceLocation newToken;
+ SourceLocation lparenToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT NewExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(NewExpression)
+
+ NewExpression(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~NewExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return newToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return expression->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation newToken;
+};
+
+class QML_PARSER_EXPORT CallExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(CallExpression)
+
+ CallExpression(ExpressionNode *b, ArgumentList *a):
+ base (b), arguments (a)
+ { kind = K; }
+
+ virtual ~CallExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return base->firstSourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return rparenToken; }
+
+// attributes
+ ExpressionNode *base;
+ ArgumentList *arguments;
+ SourceLocation lparenToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT ArgumentList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ArgumentList)
+
+ ArgumentList(ExpressionNode *e):
+ expression (e), next (this)
+ { kind = K; }
+
+ ArgumentList(ArgumentList *previous, ExpressionNode *e):
+ expression (e)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~ArgumentList() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ inline ArgumentList *finish ()
+ {
+ ArgumentList *front = next;
+ next = 0;
+ return front;
+ }
+
+// attributes
+ ExpressionNode *expression;
+ ArgumentList *next;
+ SourceLocation commaToken;
+};
+
+class QML_PARSER_EXPORT PostIncrementExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(PostIncrementExpression)
+
+ PostIncrementExpression(ExpressionNode *b):
+ base (b) { kind = K; }
+
+ virtual ~PostIncrementExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return base->firstSourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return incrementToken; }
+
+// attributes
+ ExpressionNode *base;
+ SourceLocation incrementToken;
+};
+
+class QML_PARSER_EXPORT PostDecrementExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(PostDecrementExpression)
+
+ PostDecrementExpression(ExpressionNode *b):
+ base (b) { kind = K; }
+
+ virtual ~PostDecrementExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return base->firstSourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return decrementToken; }
+
+// attributes
+ ExpressionNode *base;
+ SourceLocation decrementToken;
+};
+
+class QML_PARSER_EXPORT DeleteExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(DeleteExpression)
+
+ DeleteExpression(ExpressionNode *e):
+ expression (e) { kind = K; }
+ virtual ~DeleteExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return deleteToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return expression->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation deleteToken;
+};
+
+class QML_PARSER_EXPORT VoidExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(VoidExpression)
+
+ VoidExpression(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~VoidExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return voidToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return expression->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation voidToken;
+};
+
+class QML_PARSER_EXPORT TypeOfExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(TypeOfExpression)
+
+ TypeOfExpression(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~TypeOfExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return typeofToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return expression->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation typeofToken;
+};
+
+class QML_PARSER_EXPORT PreIncrementExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(PreIncrementExpression)
+
+ PreIncrementExpression(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~PreIncrementExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return incrementToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return expression->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation incrementToken;
+};
+
+class QML_PARSER_EXPORT PreDecrementExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(PreDecrementExpression)
+
+ PreDecrementExpression(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~PreDecrementExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return decrementToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return expression->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation decrementToken;
+};
+
+class QML_PARSER_EXPORT UnaryPlusExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UnaryPlusExpression)
+
+ UnaryPlusExpression(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~UnaryPlusExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return plusToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return expression->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation plusToken;
+};
+
+class QML_PARSER_EXPORT UnaryMinusExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UnaryMinusExpression)
+
+ UnaryMinusExpression(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~UnaryMinusExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return minusToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return expression->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation minusToken;
+};
+
+class QML_PARSER_EXPORT TildeExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(TildeExpression)
+
+ TildeExpression(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~TildeExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return tildeToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return expression->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation tildeToken;
+};
+
+class QML_PARSER_EXPORT NotExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(NotExpression)
+
+ NotExpression(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~NotExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return notToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return expression->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation notToken;
+};
+
+class QML_PARSER_EXPORT BinaryExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(BinaryExpression)
+
+ BinaryExpression(ExpressionNode *l, int o, ExpressionNode *r):
+ left (l), op (o), right (r)
+ { kind = K; }
+
+ virtual ~BinaryExpression() {}
+
+ virtual BinaryExpression *binaryExpressionCast();
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return left->firstSourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return right->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *left;
+ int op;
+ ExpressionNode *right;
+ SourceLocation operatorToken;
+};
+
+class QML_PARSER_EXPORT ConditionalExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ConditionalExpression)
+
+ ConditionalExpression(ExpressionNode *e, ExpressionNode *t, ExpressionNode *f):
+ expression (e), ok (t), ko (f)
+ { kind = K; }
+
+ virtual ~ConditionalExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return expression->firstSourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return ko->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ ExpressionNode *ok;
+ ExpressionNode *ko;
+ SourceLocation questionToken;
+ SourceLocation colonToken;
+};
+
+class QML_PARSER_EXPORT Expression: public ExpressionNode // ### rename
+{
+public:
+ QMLJS_DECLARE_AST_NODE(Expression)
+
+ Expression(ExpressionNode *l, ExpressionNode *r):
+ left (l), right (r) { kind = K; }
+
+ virtual ~Expression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return left->firstSourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return right->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *left;
+ ExpressionNode *right;
+ SourceLocation commaToken;
+};
+
+class QML_PARSER_EXPORT Block: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(Block)
+
+ Block(StatementList *slist):
+ statements (slist) { kind = K; }
+
+ virtual ~Block() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return lbraceToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return rbraceToken; }
+
+ // attributes
+ StatementList *statements;
+ SourceLocation lbraceToken;
+ SourceLocation rbraceToken;
+};
+
+class QML_PARSER_EXPORT StatementList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(StatementList)
+
+ StatementList(Statement *stmt):
+ statement (stmt), next (this)
+ { kind = K; }
+
+ StatementList(StatementList *previous, Statement *stmt):
+ statement (stmt)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~StatementList() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ inline StatementList *finish ()
+ {
+ StatementList *front = next;
+ next = 0;
+ return front;
+ }
+
+// attributes
+ Statement *statement;
+ StatementList *next;
+};
+
+class QML_PARSER_EXPORT VariableStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(VariableStatement)
+
+ VariableStatement(VariableDeclarationList *vlist):
+ declarations (vlist)
+ { kind = K; }
+
+ virtual ~VariableStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return declarationKindToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return semicolonToken; }
+
+// attributes
+ VariableDeclarationList *declarations;
+ SourceLocation declarationKindToken;
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT VariableDeclaration: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(VariableDeclaration)
+
+ VariableDeclaration(NameId *n, ExpressionNode *e):
+ name (n), expression (e), readOnly(false)
+ { kind = K; }
+
+ virtual ~VariableDeclaration() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ NameId *name;
+ ExpressionNode *expression;
+ bool readOnly;
+ SourceLocation identifierToken;
+};
+
+class QML_PARSER_EXPORT VariableDeclarationList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(VariableDeclarationList)
+
+ VariableDeclarationList(VariableDeclaration *decl):
+ declaration (decl), next (this)
+ { kind = K; }
+
+ VariableDeclarationList(VariableDeclarationList *previous, VariableDeclaration *decl):
+ declaration (decl)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~VariableDeclarationList() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ inline VariableDeclarationList *finish (bool readOnly)
+ {
+ VariableDeclarationList *front = next;
+ next = 0;
+ if (readOnly) {
+ VariableDeclarationList *vdl;
+ for (vdl = front; vdl != 0; vdl = vdl->next)
+ vdl->declaration->readOnly = true;
+ }
+ return front;
+ }
+
+// attributes
+ VariableDeclaration *declaration;
+ VariableDeclarationList *next;
+ SourceLocation commaToken;
+};
+
+class QML_PARSER_EXPORT EmptyStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(EmptyStatement)
+
+ EmptyStatement() { kind = K; }
+ virtual ~EmptyStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return semicolonToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return semicolonToken; }
+
+// attributes
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT ExpressionStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ExpressionStatement)
+
+ ExpressionStatement(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~ExpressionStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return expression->firstSourceLocation(); }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return semicolonToken; }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT IfStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(IfStatement)
+
+ IfStatement(ExpressionNode *e, Statement *t, Statement *f = 0):
+ expression (e), ok (t), ko (f)
+ { kind = K; }
+
+ virtual ~IfStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return ifToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ {
+ if (ko)
+ return ko->lastSourceLocation();
+
+ return ok->lastSourceLocation();
+ }
+
+// attributes
+ ExpressionNode *expression;
+ Statement *ok;
+ Statement *ko;
+ SourceLocation ifToken;
+ SourceLocation lparenToken;
+ SourceLocation rparenToken;
+ SourceLocation elseToken;
+};
+
+class QML_PARSER_EXPORT DoWhileStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(DoWhileStatement)
+
+ DoWhileStatement(Statement *stmt, ExpressionNode *e):
+ statement (stmt), expression (e)
+ { kind = K; }
+
+ virtual ~DoWhileStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return doToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return semicolonToken; }
+
+// attributes
+ Statement *statement;
+ ExpressionNode *expression;
+ SourceLocation doToken;
+ SourceLocation whileToken;
+ SourceLocation lparenToken;
+ SourceLocation rparenToken;
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT WhileStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(WhileStatement)
+
+ WhileStatement(ExpressionNode *e, Statement *stmt):
+ expression (e), statement (stmt)
+ { kind = K; }
+
+ virtual ~WhileStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return whileToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return statement->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ Statement *statement;
+ SourceLocation whileToken;
+ SourceLocation lparenToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT ForStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ForStatement)
+
+ ForStatement(ExpressionNode *i, ExpressionNode *c, ExpressionNode *e, Statement *stmt):
+ initialiser (i), condition (c), expression (e), statement (stmt)
+ { kind = K; }
+
+ virtual ~ForStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return forToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return statement->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *initialiser;
+ ExpressionNode *condition;
+ ExpressionNode *expression;
+ Statement *statement;
+ SourceLocation forToken;
+ SourceLocation lparenToken;
+ SourceLocation firstSemicolonToken;
+ SourceLocation secondSemicolonToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT LocalForStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(LocalForStatement)
+
+ LocalForStatement(VariableDeclarationList *vlist, ExpressionNode *c, ExpressionNode *e, Statement *stmt):
+ declarations (vlist), condition (c), expression (e), statement (stmt)
+ { kind = K; }
+
+ virtual ~LocalForStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return forToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return statement->lastSourceLocation(); }
+
+// attributes
+ VariableDeclarationList *declarations;
+ ExpressionNode *condition;
+ ExpressionNode *expression;
+ Statement *statement;
+ SourceLocation forToken;
+ SourceLocation lparenToken;
+ SourceLocation varToken;
+ SourceLocation firstSemicolonToken;
+ SourceLocation secondSemicolonToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT ForEachStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ForEachStatement)
+
+ ForEachStatement(ExpressionNode *i, ExpressionNode *e, Statement *stmt):
+ initialiser (i), expression (e), statement (stmt)
+ { kind = K; }
+
+ virtual ~ForEachStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return forToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return statement->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *initialiser;
+ ExpressionNode *expression;
+ Statement *statement;
+ SourceLocation forToken;
+ SourceLocation lparenToken;
+ SourceLocation inToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT LocalForEachStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(LocalForEachStatement)
+
+ LocalForEachStatement(VariableDeclaration *v, ExpressionNode *e, Statement *stmt):
+ declaration (v), expression (e), statement (stmt)
+ { kind = K; }
+
+ virtual ~LocalForEachStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return forToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return statement->lastSourceLocation(); }
+
+// attributes
+ VariableDeclaration *declaration;
+ ExpressionNode *expression;
+ Statement *statement;
+ SourceLocation forToken;
+ SourceLocation lparenToken;
+ SourceLocation varToken;
+ SourceLocation inToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT ContinueStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ContinueStatement)
+
+ ContinueStatement(NameId *l = 0):
+ label (l) { kind = K; }
+
+ virtual ~ContinueStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return continueToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return semicolonToken; }
+
+// attributes
+ NameId *label;
+ SourceLocation continueToken;
+ SourceLocation identifierToken;
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT BreakStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(BreakStatement)
+
+ BreakStatement(NameId *l = 0):
+ label (l) { kind = K; }
+
+ virtual ~BreakStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return breakToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return semicolonToken; }
+
+ // attributes
+ NameId *label;
+ SourceLocation breakToken;
+ SourceLocation identifierToken;
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT ReturnStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ReturnStatement)
+
+ ReturnStatement(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~ReturnStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return returnToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return semicolonToken; }
+
+// attributes
+ ExpressionNode *expression;
+ SourceLocation returnToken;
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT WithStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(WithStatement)
+
+ WithStatement(ExpressionNode *e, Statement *stmt):
+ expression (e), statement (stmt)
+ { kind = K; }
+
+ virtual ~WithStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return withToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return statement->lastSourceLocation(); }
+
+// attributes
+ ExpressionNode *expression;
+ Statement *statement;
+ SourceLocation withToken;
+ SourceLocation lparenToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT CaseBlock: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(CaseBlock)
+
+ CaseBlock(CaseClauses *c, DefaultClause *d = 0, CaseClauses *r = 0):
+ clauses (c), defaultClause (d), moreClauses (r)
+ { kind = K; }
+
+ virtual ~CaseBlock() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ CaseClauses *clauses;
+ DefaultClause *defaultClause;
+ CaseClauses *moreClauses;
+ SourceLocation lbraceToken;
+ SourceLocation rbraceToken;
+};
+
+class QML_PARSER_EXPORT SwitchStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(SwitchStatement)
+
+ SwitchStatement(ExpressionNode *e, CaseBlock *b):
+ expression (e), block (b)
+ { kind = K; }
+
+ virtual ~SwitchStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return switchToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return block->rbraceToken; }
+
+// attributes
+ ExpressionNode *expression;
+ CaseBlock *block;
+ SourceLocation switchToken;
+ SourceLocation lparenToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT CaseClauses: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(CaseClauses)
+
+ CaseClauses(CaseClause *c):
+ clause (c), next (this)
+ { kind = K; }
+
+ CaseClauses(CaseClauses *previous, CaseClause *c):
+ clause (c)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~CaseClauses() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ inline CaseClauses *finish ()
+ {
+ CaseClauses *front = next;
+ next = 0;
+ return front;
+ }
+
+//attributes
+ CaseClause *clause;
+ CaseClauses *next;
+};
+
+class QML_PARSER_EXPORT CaseClause: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(CaseClause)
+
+ CaseClause(ExpressionNode *e, StatementList *slist):
+ expression (e), statements (slist)
+ { kind = K; }
+
+ virtual ~CaseClause() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ ExpressionNode *expression;
+ StatementList *statements;
+ SourceLocation caseToken;
+ SourceLocation colonToken;
+};
+
+class QML_PARSER_EXPORT DefaultClause: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(DefaultClause)
+
+ DefaultClause(StatementList *slist):
+ statements (slist)
+ { kind = K; }
+
+ virtual ~DefaultClause() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ StatementList *statements;
+ SourceLocation defaultToken;
+ SourceLocation colonToken;
+};
+
+class QML_PARSER_EXPORT LabelledStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(LabelledStatement)
+
+ LabelledStatement(NameId *l, Statement *stmt):
+ label (l), statement (stmt)
+ { kind = K; }
+
+ virtual ~LabelledStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return identifierToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return statement->lastSourceLocation(); }
+
+// attributes
+ NameId *label;
+ Statement *statement;
+ SourceLocation identifierToken;
+ SourceLocation colonToken;
+};
+
+class QML_PARSER_EXPORT ThrowStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(ThrowStatement)
+
+ ThrowStatement(ExpressionNode *e):
+ expression (e) { kind = K; }
+
+ virtual ~ThrowStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return throwToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return semicolonToken; }
+
+ // attributes
+ ExpressionNode *expression;
+ SourceLocation throwToken;
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT Catch: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(Catch)
+
+ Catch(NameId *n, Block *stmt):
+ name (n), statement (stmt)
+ { kind = K; }
+
+ virtual ~Catch() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ NameId *name;
+ Block *statement;
+ SourceLocation catchToken;
+ SourceLocation lparenToken;
+ SourceLocation identifierToken;
+ SourceLocation rparenToken;
+};
+
+class QML_PARSER_EXPORT Finally: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(Finally)
+
+ Finally(Block *stmt):
+ statement (stmt)
+ { kind = K; }
+
+ virtual ~Finally() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ Block *statement;
+ SourceLocation finallyToken;
+};
+
+class QML_PARSER_EXPORT TryStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(TryStatement)
+
+ TryStatement(Statement *stmt, Catch *c, Finally *f):
+ statement (stmt), catchExpression (c), finallyExpression (f)
+ { kind = K; }
+
+ TryStatement(Statement *stmt, Finally *f):
+ statement (stmt), catchExpression (0), finallyExpression (f)
+ { kind = K; }
+
+ TryStatement(Statement *stmt, Catch *c):
+ statement (stmt), catchExpression (c), finallyExpression (0)
+ { kind = K; }
+
+ virtual ~TryStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return tryToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ {
+ if (finallyExpression)
+ return finallyExpression->statement->rbraceToken;
+ else if (catchExpression)
+ return catchExpression->statement->rbraceToken;
+
+ return statement->lastSourceLocation();
+ }
+
+// attributes
+ Statement *statement;
+ Catch *catchExpression;
+ Finally *finallyExpression;
+ SourceLocation tryToken;
+};
+
+class QML_PARSER_EXPORT FunctionExpression: public ExpressionNode
+{
+public:
+ QMLJS_DECLARE_AST_NODE(FunctionExpression)
+
+ FunctionExpression(NameId *n, FormalParameterList *f, FunctionBody *b):
+ name (n), formals (f), body (b)
+ { kind = K; }
+
+ virtual ~FunctionExpression() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return functionToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return rbraceToken; }
+
+// attributes
+ NameId *name;
+ FormalParameterList *formals;
+ FunctionBody *body;
+ SourceLocation functionToken;
+ SourceLocation identifierToken;
+ SourceLocation lparenToken;
+ SourceLocation rparenToken;
+ SourceLocation lbraceToken;
+ SourceLocation rbraceToken;
+};
+
+class QML_PARSER_EXPORT FunctionDeclaration: public FunctionExpression
+{
+public:
+ QMLJS_DECLARE_AST_NODE(FunctionDeclaration)
+
+ FunctionDeclaration(NameId *n, FormalParameterList *f, FunctionBody *b):
+ FunctionExpression(n, f, b)
+ { kind = K; }
+
+ virtual ~FunctionDeclaration() {}
+
+ virtual void accept0(Visitor *visitor);
+};
+
+class QML_PARSER_EXPORT FormalParameterList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(FormalParameterList)
+
+ FormalParameterList(NameId *n):
+ name (n), next (this)
+ { kind = K; }
+
+ FormalParameterList(FormalParameterList *previous, NameId *n):
+ name (n)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~FormalParameterList() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ inline FormalParameterList *finish ()
+ {
+ FormalParameterList *front = next;
+ next = 0;
+ return front;
+ }
+
+// attributes
+ NameId *name;
+ FormalParameterList *next;
+ SourceLocation commaToken;
+ SourceLocation identifierToken;
+};
+
+class QML_PARSER_EXPORT FunctionBody: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(FunctionBody)
+
+ FunctionBody(SourceElements *elts):
+ elements (elts)
+ { kind = K; }
+
+ virtual ~FunctionBody() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ SourceElements *elements;
+};
+
+class QML_PARSER_EXPORT Program: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(Program)
+
+ Program(SourceElements *elts):
+ elements (elts)
+ { kind = K; }
+
+ virtual ~Program() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ SourceElements *elements;
+};
+
+class QML_PARSER_EXPORT SourceElements: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(SourceElements)
+
+ SourceElements(SourceElement *elt):
+ element (elt), next (this)
+ { kind = K; }
+
+ SourceElements(SourceElements *previous, SourceElement *elt):
+ element (elt)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~SourceElements() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ inline SourceElements *finish ()
+ {
+ SourceElements *front = next;
+ next = 0;
+ return front;
+ }
+
+// attributes
+ SourceElement *element;
+ SourceElements *next;
+};
+
+class QML_PARSER_EXPORT SourceElement: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(SourceElement)
+
+ inline SourceElement()
+ { kind = K; }
+
+ virtual ~SourceElement() {}
+};
+
+class QML_PARSER_EXPORT FunctionSourceElement: public SourceElement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(FunctionSourceElement)
+
+ FunctionSourceElement(FunctionDeclaration *f):
+ declaration (f)
+ { kind = K; }
+
+ virtual ~FunctionSourceElement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ FunctionDeclaration *declaration;
+};
+
+class QML_PARSER_EXPORT StatementSourceElement: public SourceElement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(StatementSourceElement)
+
+ StatementSourceElement(Statement *stmt):
+ statement (stmt)
+ { kind = K; }
+
+ virtual ~StatementSourceElement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ Statement *statement;
+};
+
+class QML_PARSER_EXPORT DebuggerStatement: public Statement
+{
+public:
+ QMLJS_DECLARE_AST_NODE(DebuggerStatement)
+
+ DebuggerStatement()
+ { kind = K; }
+
+ virtual ~DebuggerStatement() {}
+
+ virtual void accept0(Visitor *visitor);
+
+ virtual SourceLocation firstSourceLocation() const
+ { return debuggerToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return semicolonToken; }
+
+// attributes
+ SourceLocation debuggerToken;
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT UiProgram: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiProgram)
+
+ UiProgram(UiImportList *imports, UiObjectMemberList *members)
+ : imports(imports), members(members)
+ { kind = K; }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ UiImportList *imports;
+ UiObjectMemberList *members;
+};
+
+class QML_PARSER_EXPORT UiQualifiedId: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiQualifiedId)
+
+ UiQualifiedId(NameId *name)
+ : next(this), name(name)
+ { kind = K; }
+
+ UiQualifiedId(UiQualifiedId *previous, NameId *name)
+ : name(name)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~UiQualifiedId() {}
+
+ UiQualifiedId *finish()
+ {
+ UiQualifiedId *head = next;
+ next = 0;
+ return head;
+ }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ UiQualifiedId *next;
+ NameId *name;
+ SourceLocation identifierToken;
+};
+
+class QML_PARSER_EXPORT UiImport: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiImport)
+
+ UiImport(NameId *fileName)
+ : fileName(fileName), importUri(0), importId(0)
+ { kind = K; }
+
+ UiImport(UiQualifiedId *uri)
+ : fileName(0), importUri(uri), importId(0)
+ { kind = K; }
+
+ virtual SourceLocation firstSourceLocation() const
+ { return importToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return semicolonToken; }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ NameId *fileName;
+ UiQualifiedId *importUri;
+ NameId *importId;
+ SourceLocation importToken;
+ SourceLocation fileNameToken;
+ SourceLocation versionToken;
+ SourceLocation asToken;
+ SourceLocation importIdToken;
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT UiImportList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiImportList)
+
+ UiImportList(UiImport *import)
+ : import(import),
+ next(this)
+ { kind = K; }
+
+ UiImportList(UiImportList *previous, UiImport *import)
+ : import(import)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual SourceLocation firstSourceLocation() const
+ {
+ if (import) return import->firstSourceLocation();
+ else return SourceLocation();
+ }
+
+ virtual SourceLocation lastSourceLocation() const
+ {
+ for (const UiImportList *it = this; it; it = it->next)
+ if (!it->next && it->import)
+ return it->import->lastSourceLocation();
+
+ return SourceLocation();
+ }
+
+ UiImportList *finish()
+ {
+ UiImportList *head = next;
+ next = 0;
+ return head;
+ }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ UiImport *import;
+ UiImportList *next;
+};
+
+class QML_PARSER_EXPORT UiObjectMember: public Node
+{
+public:
+ virtual SourceLocation firstSourceLocation() const = 0;
+ virtual SourceLocation lastSourceLocation() const = 0;
+
+ virtual UiObjectMember *uiObjectMemberCast();
+};
+
+class QML_PARSER_EXPORT UiObjectMemberList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiObjectMemberList)
+
+ UiObjectMemberList(UiObjectMember *member)
+ : next(this), member(member)
+ { kind = K; }
+
+ UiObjectMemberList(UiObjectMemberList *previous, UiObjectMember *member)
+ : member(member)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual void accept0(Visitor *visitor);
+
+ UiObjectMemberList *finish()
+ {
+ UiObjectMemberList *head = next;
+ next = 0;
+ return head;
+ }
+
+// attributes
+ UiObjectMemberList *next;
+ UiObjectMember *member;
+};
+
+class QML_PARSER_EXPORT UiArrayMemberList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiArrayMemberList)
+
+ UiArrayMemberList(UiObjectMember *member)
+ : next(this), member(member)
+ { kind = K; }
+
+ UiArrayMemberList(UiArrayMemberList *previous, UiObjectMember *member)
+ : member(member)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual void accept0(Visitor *visitor);
+
+ UiArrayMemberList *finish()
+ {
+ UiArrayMemberList *head = next;
+ next = 0;
+ return head;
+ }
+
+// attributes
+ UiArrayMemberList *next;
+ UiObjectMember *member;
+ SourceLocation commaToken;
+};
+
+class QML_PARSER_EXPORT UiObjectInitializer: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiObjectInitializer)
+
+ UiObjectInitializer(UiObjectMemberList *members)
+ : members(members)
+ { kind = K; }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ SourceLocation lbraceToken;
+ UiObjectMemberList *members;
+ SourceLocation rbraceToken;
+};
+
+class QML_PARSER_EXPORT UiParameterList: public Node
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiParameterList)
+
+ UiParameterList(NameId *t, NameId *n):
+ type (t), name (n), next (this)
+ { kind = K; }
+
+ UiParameterList(UiParameterList *previous, NameId *t, NameId *n):
+ type (t), name (n)
+ {
+ kind = K;
+ next = previous->next;
+ previous->next = this;
+ }
+
+ virtual ~UiParameterList() {}
+
+ virtual void accept0(Visitor *) {}
+
+ inline UiParameterList *finish ()
+ {
+ UiParameterList *front = next;
+ next = 0;
+ return front;
+ }
+
+// attributes
+ NameId *type;
+ NameId *name;
+ UiParameterList *next;
+ SourceLocation commaToken;
+ SourceLocation identifierToken;
+};
+
+class QML_PARSER_EXPORT UiPublicMember: public UiObjectMember
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiPublicMember)
+
+ UiPublicMember(NameId *memberType,
+ NameId *name)
+ : type(Property), typeModifier(0), memberType(memberType), name(name), expression(0), isDefaultMember(false), isReadonlyMember(false), parameters(0)
+ { kind = K; }
+
+ UiPublicMember(NameId *memberType,
+ NameId *name,
+ ExpressionNode *expression)
+ : type(Property), typeModifier(0), memberType(memberType), name(name), expression(expression), isDefaultMember(false), isReadonlyMember(false), parameters(0)
+ { kind = K; }
+
+ virtual SourceLocation firstSourceLocation() const
+ {
+ if (defaultToken.isValid())
+ return defaultToken;
+ else if (readonlyToken.isValid())
+ return readonlyToken;
+
+ return propertyToken;
+ }
+
+ virtual SourceLocation lastSourceLocation() const
+ {
+ return semicolonToken;
+ }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ enum { Signal, Property } type;
+ NameId *typeModifier;
+ NameId *memberType;
+ NameId *name;
+ ExpressionNode *expression;
+ bool isDefaultMember;
+ bool isReadonlyMember;
+ UiParameterList *parameters;
+ SourceLocation defaultToken;
+ SourceLocation readonlyToken;
+ SourceLocation propertyToken;
+ SourceLocation typeModifierToken;
+ SourceLocation typeToken;
+ SourceLocation identifierToken;
+ SourceLocation colonToken;
+ SourceLocation semicolonToken;
+};
+
+class QML_PARSER_EXPORT UiObjectDefinition: public UiObjectMember
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiObjectDefinition)
+
+ UiObjectDefinition(UiQualifiedId *qualifiedTypeNameId,
+ UiObjectInitializer *initializer)
+ : qualifiedTypeNameId(qualifiedTypeNameId), initializer(initializer)
+ { kind = K; }
+
+ virtual SourceLocation firstSourceLocation() const
+ { return qualifiedTypeNameId->identifierToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return initializer->rbraceToken; }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ UiQualifiedId *qualifiedTypeNameId;
+ UiObjectInitializer *initializer;
+};
+
+class QML_PARSER_EXPORT UiSourceElement: public UiObjectMember
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiSourceElement)
+
+ UiSourceElement(Node *sourceElement)
+ : sourceElement(sourceElement)
+ { kind = K; }
+
+ virtual SourceLocation firstSourceLocation() const
+ {
+ if (FunctionDeclaration *funDecl = cast<FunctionDeclaration *>(sourceElement))
+ return funDecl->firstSourceLocation();
+ else if (VariableStatement *varStmt = cast<VariableStatement *>(sourceElement))
+ return varStmt->firstSourceLocation();
+
+ return SourceLocation();
+ }
+
+ virtual SourceLocation lastSourceLocation() const
+ {
+ if (FunctionDeclaration *funDecl = cast<FunctionDeclaration *>(sourceElement))
+ return funDecl->lastSourceLocation();
+ else if (VariableStatement *varStmt = cast<VariableStatement *>(sourceElement))
+ return varStmt->lastSourceLocation();
+
+ return SourceLocation();
+ }
+
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ Node *sourceElement;
+};
+
+class QML_PARSER_EXPORT UiObjectBinding: public UiObjectMember
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiObjectBinding)
+
+ UiObjectBinding(UiQualifiedId *qualifiedId,
+ UiQualifiedId *qualifiedTypeNameId,
+ UiObjectInitializer *initializer)
+ : qualifiedId(qualifiedId),
+ qualifiedTypeNameId(qualifiedTypeNameId),
+ initializer(initializer)
+ { kind = K; }
+
+ virtual SourceLocation firstSourceLocation() const
+ { return qualifiedId->identifierToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return initializer->rbraceToken; }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ UiQualifiedId *qualifiedId;
+ UiQualifiedId *qualifiedTypeNameId;
+ UiObjectInitializer *initializer;
+ SourceLocation colonToken;
+};
+
+class QML_PARSER_EXPORT UiScriptBinding: public UiObjectMember
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiScriptBinding)
+
+ UiScriptBinding(UiQualifiedId *qualifiedId,
+ Statement *statement)
+ : qualifiedId(qualifiedId),
+ statement(statement)
+ { kind = K; }
+
+ virtual SourceLocation firstSourceLocation() const
+ { return qualifiedId->identifierToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return statement->lastSourceLocation(); }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ UiQualifiedId *qualifiedId;
+ Statement *statement;
+ SourceLocation colonToken;
+};
+
+class QML_PARSER_EXPORT UiArrayBinding: public UiObjectMember
+{
+public:
+ QMLJS_DECLARE_AST_NODE(UiArrayBinding)
+
+ UiArrayBinding(UiQualifiedId *qualifiedId,
+ UiArrayMemberList *members)
+ : qualifiedId(qualifiedId),
+ members(members)
+ { kind = K; }
+
+ virtual SourceLocation firstSourceLocation() const
+ { return qualifiedId->identifierToken; }
+
+ virtual SourceLocation lastSourceLocation() const
+ { return rbracketToken; }
+
+ virtual void accept0(Visitor *visitor);
+
+// attributes
+ UiQualifiedId *qualifiedId;
+ UiArrayMemberList *members;
+ SourceLocation colonToken;
+ SourceLocation lbracketToken;
+ SourceLocation rbracketToken;
+};
+
+} } // namespace AST
+
+
+
+QT_QML_END_NAMESPACE
+
+#endif
diff --git a/src/declarative/qml/parser/qmljsastfwd_p.h b/src/declarative/qml/parser/qmljsastfwd_p.h
new file mode 100644
index 0000000..f571a2e
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsastfwd_p.h
@@ -0,0 +1,189 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLJSAST_FWD_P_H
+#define QMLJSAST_FWD_P_H
+
+#include "qmljsglobal_p.h"
+
+#include <QtCore/qglobal.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_QML_BEGIN_NAMESPACE
+
+namespace QmlJS { namespace AST {
+
+class SourceLocation
+{
+public:
+ SourceLocation(quint32 offset = 0, quint32 length = 0, quint32 line = 0, quint32 column = 0)
+ : offset(offset), length(length),
+ startLine(line), startColumn(column)
+ { }
+
+ bool isValid() const { return length != 0; }
+
+ quint32 begin() const { return offset; }
+ quint32 end() const { return offset + length; }
+
+// attributes
+ // ### encode
+ quint32 offset;
+ quint32 length;
+ quint32 startLine;
+ quint32 startColumn;
+};
+
+class Visitor;
+class Node;
+class ExpressionNode;
+class Statement;
+class ThisExpression;
+class IdentifierExpression;
+class NullExpression;
+class TrueLiteral;
+class FalseLiteral;
+class NumericLiteral;
+class StringLiteral;
+class RegExpLiteral;
+class ArrayLiteral;
+class ObjectLiteral;
+class ElementList;
+class Elision;
+class PropertyNameAndValueList;
+class PropertyName;
+class IdentifierPropertyName;
+class StringLiteralPropertyName;
+class NumericLiteralPropertyName;
+class ArrayMemberExpression;
+class FieldMemberExpression;
+class NewMemberExpression;
+class NewExpression;
+class CallExpression;
+class ArgumentList;
+class PostIncrementExpression;
+class PostDecrementExpression;
+class DeleteExpression;
+class VoidExpression;
+class TypeOfExpression;
+class PreIncrementExpression;
+class PreDecrementExpression;
+class UnaryPlusExpression;
+class UnaryMinusExpression;
+class TildeExpression;
+class NotExpression;
+class BinaryExpression;
+class ConditionalExpression;
+class Expression; // ### rename
+class Block;
+class StatementList;
+class VariableStatement;
+class VariableDeclarationList;
+class VariableDeclaration;
+class EmptyStatement;
+class ExpressionStatement;
+class IfStatement;
+class DoWhileStatement;
+class WhileStatement;
+class ForStatement;
+class LocalForStatement;
+class ForEachStatement;
+class LocalForEachStatement;
+class ContinueStatement;
+class BreakStatement;
+class ReturnStatement;
+class WithStatement;
+class SwitchStatement;
+class CaseBlock;
+class CaseClauses;
+class CaseClause;
+class DefaultClause;
+class LabelledStatement;
+class ThrowStatement;
+class TryStatement;
+class Catch;
+class Finally;
+class FunctionDeclaration;
+class FunctionExpression;
+class FormalParameterList;
+class FunctionBody;
+class Program;
+class SourceElements;
+class SourceElement;
+class FunctionSourceElement;
+class StatementSourceElement;
+class DebuggerStatement;
+class NestedExpression;
+
+// ui elements
+class UiProgram;
+class UiImportList;
+class UiImport;
+class UiPublicMember;
+class UiObjectDefinition;
+class UiObjectInitializer;
+class UiObjectBinding;
+class UiScriptBinding;
+class UiSourceElement;
+class UiArrayBinding;
+class UiObjectMember;
+class UiObjectMemberList;
+class UiArrayMemberList;
+class UiQualifiedId;
+class UiFormalList;
+class UiFormal;
+class UiSignature;
+
+} } // namespace AST
+
+QT_QML_END_NAMESPACE
+
+#endif
diff --git a/src/declarative/qml/parser/qmljsastvisitor.cpp b/src/declarative/qml/parser/qmljsastvisitor.cpp
new file mode 100644
index 0000000..1290c89
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsastvisitor.cpp
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmljsastvisitor_p.h"
+
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS { namespace AST {
+
+Visitor::Visitor()
+{
+}
+
+Visitor::~Visitor()
+{
+}
+
+} } // namespace QmlJS::AST
+
+QT_QML_END_NAMESPACE
diff --git a/src/declarative/qml/parser/qmljsastvisitor_p.h b/src/declarative/qml/parser/qmljsastvisitor_p.h
new file mode 100644
index 0000000..1b50bcc
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsastvisitor_p.h
@@ -0,0 +1,335 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLJSASTVISITOR_P_H
+#define QMLJSASTVISITOR_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qmljsastfwd_p.h"
+#include "qmljsglobal_p.h"
+
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS { namespace AST {
+
+class QML_PARSER_EXPORT Visitor
+{
+public:
+ Visitor();
+ virtual ~Visitor();
+
+ virtual bool preVisit(Node *) { return true; }
+ virtual void postVisit(Node *) {}
+
+ // Ui
+ virtual bool visit(UiProgram *) { return true; }
+ virtual bool visit(UiImportList *) { return true; }
+ virtual bool visit(UiImport *) { return true; }
+ virtual bool visit(UiPublicMember *) { return true; }
+ virtual bool visit(UiSourceElement *) { return true; }
+ virtual bool visit(UiObjectDefinition *) { return true; }
+ virtual bool visit(UiObjectInitializer *) { return true; }
+ virtual bool visit(UiObjectBinding *) { return true; }
+ virtual bool visit(UiScriptBinding *) { return true; }
+ virtual bool visit(UiArrayBinding *) { return true; }
+ virtual bool visit(UiObjectMemberList *) { return true; }
+ virtual bool visit(UiArrayMemberList *) { return true; }
+ virtual bool visit(UiQualifiedId *) { return true; }
+ virtual bool visit(UiSignature *) { return true; }
+ virtual bool visit(UiFormalList *) { return true; }
+ virtual bool visit(UiFormal *) { return true; }
+
+ virtual void endVisit(UiProgram *) {}
+ virtual void endVisit(UiImportList *) {}
+ virtual void endVisit(UiImport *) {}
+ virtual void endVisit(UiPublicMember *) {}
+ virtual void endVisit(UiSourceElement *) {}
+ virtual void endVisit(UiObjectDefinition *) {}
+ virtual void endVisit(UiObjectInitializer *) {}
+ virtual void endVisit(UiObjectBinding *) {}
+ virtual void endVisit(UiScriptBinding *) {}
+ virtual void endVisit(UiArrayBinding *) {}
+ virtual void endVisit(UiObjectMemberList *) {}
+ virtual void endVisit(UiArrayMemberList *) {}
+ virtual void endVisit(UiQualifiedId *) {}
+ virtual void endVisit(UiSignature *) {}
+ virtual void endVisit(UiFormalList *) {}
+ virtual void endVisit(UiFormal *) {}
+
+ // QmlJS
+ virtual bool visit(ThisExpression *) { return true; }
+ virtual void endVisit(ThisExpression *) {}
+
+ virtual bool visit(IdentifierExpression *) { return true; }
+ virtual void endVisit(IdentifierExpression *) {}
+
+ virtual bool visit(NullExpression *) { return true; }
+ virtual void endVisit(NullExpression *) {}
+
+ virtual bool visit(TrueLiteral *) { return true; }
+ virtual void endVisit(TrueLiteral *) {}
+
+ virtual bool visit(FalseLiteral *) { return true; }
+ virtual void endVisit(FalseLiteral *) {}
+
+ virtual bool visit(StringLiteral *) { return true; }
+ virtual void endVisit(StringLiteral *) {}
+
+ virtual bool visit(NumericLiteral *) { return true; }
+ virtual void endVisit(NumericLiteral *) {}
+
+ virtual bool visit(RegExpLiteral *) { return true; }
+ virtual void endVisit(RegExpLiteral *) {}
+
+ virtual bool visit(ArrayLiteral *) { return true; }
+ virtual void endVisit(ArrayLiteral *) {}
+
+ virtual bool visit(ObjectLiteral *) { return true; }
+ virtual void endVisit(ObjectLiteral *) {}
+
+ virtual bool visit(ElementList *) { return true; }
+ virtual void endVisit(ElementList *) {}
+
+ virtual bool visit(Elision *) { return true; }
+ virtual void endVisit(Elision *) {}
+
+ virtual bool visit(PropertyNameAndValueList *) { return true; }
+ virtual void endVisit(PropertyNameAndValueList *) {}
+
+ virtual bool visit(NestedExpression *) { return true; }
+ virtual void endVisit(NestedExpression *) {}
+
+ virtual bool visit(IdentifierPropertyName *) { return true; }
+ virtual void endVisit(IdentifierPropertyName *) {}
+
+ virtual bool visit(StringLiteralPropertyName *) { return true; }
+ virtual void endVisit(StringLiteralPropertyName *) {}
+
+ virtual bool visit(NumericLiteralPropertyName *) { return true; }
+ virtual void endVisit(NumericLiteralPropertyName *) {}
+
+ virtual bool visit(ArrayMemberExpression *) { return true; }
+ virtual void endVisit(ArrayMemberExpression *) {}
+
+ virtual bool visit(FieldMemberExpression *) { return true; }
+ virtual void endVisit(FieldMemberExpression *) {}
+
+ virtual bool visit(NewMemberExpression *) { return true; }
+ virtual void endVisit(NewMemberExpression *) {}
+
+ virtual bool visit(NewExpression *) { return true; }
+ virtual void endVisit(NewExpression *) {}
+
+ virtual bool visit(CallExpression *) { return true; }
+ virtual void endVisit(CallExpression *) {}
+
+ virtual bool visit(ArgumentList *) { return true; }
+ virtual void endVisit(ArgumentList *) {}
+
+ virtual bool visit(PostIncrementExpression *) { return true; }
+ virtual void endVisit(PostIncrementExpression *) {}
+
+ virtual bool visit(PostDecrementExpression *) { return true; }
+ virtual void endVisit(PostDecrementExpression *) {}
+
+ virtual bool visit(DeleteExpression *) { return true; }
+ virtual void endVisit(DeleteExpression *) {}
+
+ virtual bool visit(VoidExpression *) { return true; }
+ virtual void endVisit(VoidExpression *) {}
+
+ virtual bool visit(TypeOfExpression *) { return true; }
+ virtual void endVisit(TypeOfExpression *) {}
+
+ virtual bool visit(PreIncrementExpression *) { return true; }
+ virtual void endVisit(PreIncrementExpression *) {}
+
+ virtual bool visit(PreDecrementExpression *) { return true; }
+ virtual void endVisit(PreDecrementExpression *) {}
+
+ virtual bool visit(UnaryPlusExpression *) { return true; }
+ virtual void endVisit(UnaryPlusExpression *) {}
+
+ virtual bool visit(UnaryMinusExpression *) { return true; }
+ virtual void endVisit(UnaryMinusExpression *) {}
+
+ virtual bool visit(TildeExpression *) { return true; }
+ virtual void endVisit(TildeExpression *) {}
+
+ virtual bool visit(NotExpression *) { return true; }
+ virtual void endVisit(NotExpression *) {}
+
+ virtual bool visit(BinaryExpression *) { return true; }
+ virtual void endVisit(BinaryExpression *) {}
+
+ virtual bool visit(ConditionalExpression *) { return true; }
+ virtual void endVisit(ConditionalExpression *) {}
+
+ virtual bool visit(Expression *) { return true; }
+ virtual void endVisit(Expression *) {}
+
+ virtual bool visit(Block *) { return true; }
+ virtual void endVisit(Block *) {}
+
+ virtual bool visit(StatementList *) { return true; }
+ virtual void endVisit(StatementList *) {}
+
+ virtual bool visit(VariableStatement *) { return true; }
+ virtual void endVisit(VariableStatement *) {}
+
+ virtual bool visit(VariableDeclarationList *) { return true; }
+ virtual void endVisit(VariableDeclarationList *) {}
+
+ virtual bool visit(VariableDeclaration *) { return true; }
+ virtual void endVisit(VariableDeclaration *) {}
+
+ virtual bool visit(EmptyStatement *) { return true; }
+ virtual void endVisit(EmptyStatement *) {}
+
+ virtual bool visit(ExpressionStatement *) { return true; }
+ virtual void endVisit(ExpressionStatement *) {}
+
+ virtual bool visit(IfStatement *) { return true; }
+ virtual void endVisit(IfStatement *) {}
+
+ virtual bool visit(DoWhileStatement *) { return true; }
+ virtual void endVisit(DoWhileStatement *) {}
+
+ virtual bool visit(WhileStatement *) { return true; }
+ virtual void endVisit(WhileStatement *) {}
+
+ virtual bool visit(ForStatement *) { return true; }
+ virtual void endVisit(ForStatement *) {}
+
+ virtual bool visit(LocalForStatement *) { return true; }
+ virtual void endVisit(LocalForStatement *) {}
+
+ virtual bool visit(ForEachStatement *) { return true; }
+ virtual void endVisit(ForEachStatement *) {}
+
+ virtual bool visit(LocalForEachStatement *) { return true; }
+ virtual void endVisit(LocalForEachStatement *) {}
+
+ virtual bool visit(ContinueStatement *) { return true; }
+ virtual void endVisit(ContinueStatement *) {}
+
+ virtual bool visit(BreakStatement *) { return true; }
+ virtual void endVisit(BreakStatement *) {}
+
+ virtual bool visit(ReturnStatement *) { return true; }
+ virtual void endVisit(ReturnStatement *) {}
+
+ virtual bool visit(WithStatement *) { return true; }
+ virtual void endVisit(WithStatement *) {}
+
+ virtual bool visit(SwitchStatement *) { return true; }
+ virtual void endVisit(SwitchStatement *) {}
+
+ virtual bool visit(CaseBlock *) { return true; }
+ virtual void endVisit(CaseBlock *) {}
+
+ virtual bool visit(CaseClauses *) { return true; }
+ virtual void endVisit(CaseClauses *) {}
+
+ virtual bool visit(CaseClause *) { return true; }
+ virtual void endVisit(CaseClause *) {}
+
+ virtual bool visit(DefaultClause *) { return true; }
+ virtual void endVisit(DefaultClause *) {}
+
+ virtual bool visit(LabelledStatement *) { return true; }
+ virtual void endVisit(LabelledStatement *) {}
+
+ virtual bool visit(ThrowStatement *) { return true; }
+ virtual void endVisit(ThrowStatement *) {}
+
+ virtual bool visit(TryStatement *) { return true; }
+ virtual void endVisit(TryStatement *) {}
+
+ virtual bool visit(Catch *) { return true; }
+ virtual void endVisit(Catch *) {}
+
+ virtual bool visit(Finally *) { return true; }
+ virtual void endVisit(Finally *) {}
+
+ virtual bool visit(FunctionDeclaration *) { return true; }
+ virtual void endVisit(FunctionDeclaration *) {}
+
+ virtual bool visit(FunctionExpression *) { return true; }
+ virtual void endVisit(FunctionExpression *) {}
+
+ virtual bool visit(FormalParameterList *) { return true; }
+ virtual void endVisit(FormalParameterList *) {}
+
+ virtual bool visit(FunctionBody *) { return true; }
+ virtual void endVisit(FunctionBody *) {}
+
+ virtual bool visit(Program *) { return true; }
+ virtual void endVisit(Program *) {}
+
+ virtual bool visit(SourceElements *) { return true; }
+ virtual void endVisit(SourceElements *) {}
+
+ virtual bool visit(FunctionSourceElement *) { return true; }
+ virtual void endVisit(FunctionSourceElement *) {}
+
+ virtual bool visit(StatementSourceElement *) { return true; }
+ virtual void endVisit(StatementSourceElement *) {}
+
+ virtual bool visit(DebuggerStatement *) { return true; }
+ virtual void endVisit(DebuggerStatement *) {}
+};
+
+} } // namespace AST
+
+QT_QML_END_NAMESPACE
+
+#endif // QMLJSASTVISITOR_P_H
diff --git a/src/declarative/qml/parser/qmljsengine_p.cpp b/src/declarative/qml/parser/qmljsengine_p.cpp
new file mode 100644
index 0000000..b8ecd18
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsengine_p.cpp
@@ -0,0 +1,212 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmljsengine_p.h"
+
+#include "qmljsglobal_p.h"
+#include "qmljsnodepool_p.h"
+
+#include <qnumeric.h>
+#include <QHash>
+
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS {
+
+uint qHash(const QmlJS::NameId &id)
+{ return qHash(id.asString()); }
+
+QString numberToString(double value)
+{ return QString::number(value); }
+
+int Ecma::RegExp::flagFromChar(const QChar &ch)
+{
+ static QHash<QChar, int> flagsHash;
+ if (flagsHash.isEmpty()) {
+ flagsHash[QLatin1Char('g')] = Global;
+ flagsHash[QLatin1Char('i')] = IgnoreCase;
+ flagsHash[QLatin1Char('m')] = Multiline;
+ }
+ QHash<QChar, int>::const_iterator it;
+ it = flagsHash.constFind(ch);
+ if (it == flagsHash.constEnd())
+ return 0;
+ return it.value();
+}
+
+QString Ecma::RegExp::flagsToString(int flags)
+{
+ QString result;
+ if (flags & Global)
+ result += QLatin1Char('g');
+ if (flags & IgnoreCase)
+ result += QLatin1Char('i');
+ if (flags & Multiline)
+ result += QLatin1Char('m');
+ return result;
+}
+
+NodePool::NodePool(const QString &fileName, Engine *engine)
+ : m_fileName(fileName), m_engine(engine)
+{
+ m_engine->setNodePool(this);
+}
+
+NodePool::~NodePool()
+{
+}
+
+Code *NodePool::createCompiledCode(AST::Node *, CompilationUnit &)
+{
+ Q_ASSERT(0);
+ return 0;
+}
+
+static int toDigit(char c)
+{
+ if ((c >= '0') && (c <= '9'))
+ return c - '0';
+ else if ((c >= 'a') && (c <= 'z'))
+ return 10 + c - 'a';
+ else if ((c >= 'A') && (c <= 'Z'))
+ return 10 + c - 'A';
+ return -1;
+}
+
+double integerFromString(const char *buf, int size, int radix)
+{
+ if (size == 0)
+ return qSNaN();
+
+ double sign = 1.0;
+ int i = 0;
+ if (buf[0] == '+') {
+ ++i;
+ } else if (buf[0] == '-') {
+ sign = -1.0;
+ ++i;
+ }
+
+ if (((size-i) >= 2) && (buf[i] == '0')) {
+ if (((buf[i+1] == 'x') || (buf[i+1] == 'X'))
+ && (radix < 34)) {
+ if ((radix != 0) && (radix != 16))
+ return 0;
+ radix = 16;
+ i += 2;
+ } else {
+ if (radix == 0) {
+ radix = 8;
+ ++i;
+ }
+ }
+ } else if (radix == 0) {
+ radix = 10;
+ }
+
+ int j = i;
+ for ( ; i < size; ++i) {
+ int d = toDigit(buf[i]);
+ if ((d == -1) || (d >= radix))
+ break;
+ }
+ double result;
+ if (j == i) {
+ if (!qstrcmp(buf, "Infinity"))
+ result = qInf();
+ else
+ result = qSNaN();
+ } else {
+ result = 0;
+ double multiplier = 1;
+ for (--i ; i >= j; --i, multiplier *= radix)
+ result += toDigit(buf[i]) * multiplier;
+ }
+ result *= sign;
+ return result;
+}
+
+double integerFromString(const QString &str, int radix)
+{
+ QByteArray ba = str.trimmed().toLatin1();
+ return integerFromString(ba.constData(), ba.size(), radix);
+}
+
+
+Engine::Engine()
+ : _lexer(0), _nodePool(0)
+{ }
+
+Engine::~Engine()
+{ }
+
+QSet<NameId> Engine::literals() const
+{ return _literals; }
+
+void Engine::addComment(int pos, int len, int line, int col)
+{ if (len > 0) _comments.append(QmlJS::AST::SourceLocation(pos, len, line, col)); }
+
+QList<QmlJS::AST::SourceLocation> Engine::comments() const
+{ return _comments; }
+
+NameId *Engine::intern(const QChar *u, int s)
+{ return const_cast<NameId *>(&*_literals.insert(NameId(u, s))); }
+
+QString Engine::toString(NameId *id)
+{ return id->asString(); }
+
+Lexer *Engine::lexer() const
+{ return _lexer; }
+
+void Engine::setLexer(Lexer *lexer)
+{ _lexer = lexer; }
+
+NodePool *Engine::nodePool() const
+{ return _nodePool; }
+
+void Engine::setNodePool(NodePool *nodePool)
+{ _nodePool = nodePool; }
+
+
+
+} // end of namespace QmlJS
+
+QT_QML_END_NAMESPACE
diff --git a/src/declarative/qml/parser/qmljsengine_p.h b/src/declarative/qml/parser/qmljsengine_p.h
new file mode 100644
index 0000000..2c15af3
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsengine_p.h
@@ -0,0 +1,173 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLJSENGINE_P_H
+#define QMLJSENGINE_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 "qmljsglobal_p.h"
+#include "qmljsastfwd_p.h"
+
+#include <QString>
+#include <QSet>
+
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS {
+class QML_PARSER_EXPORT NameId
+{
+ QString _text;
+
+public:
+ NameId(const QChar *u, int s)
+ : _text(u, s)
+ { }
+
+ const QString asString() const
+ { return _text; }
+
+ bool operator == (const NameId &other) const
+ { return _text == other._text; }
+
+ bool operator != (const NameId &other) const
+ { return _text != other._text; }
+
+ bool operator < (const NameId &other) const
+ { return _text < other._text; }
+};
+
+uint qHash(const QmlJS::NameId &id);
+
+} // end of namespace QmlJS
+
+#if defined(Q_CC_MSVC) && _MSC_VER <= 1300
+//this ensures that code outside QmlJS can use the hash function
+//it also a workaround for some compilers
+inline uint qHash(const QmlJS::NameId &nameId) { return QmlJS::qHash(nameId); }
+#endif
+
+namespace QmlJS {
+
+class Lexer;
+class NodePool;
+
+namespace Ecma {
+
+class QML_PARSER_EXPORT RegExp
+{
+public:
+ enum RegExpFlag {
+ Global = 0x01,
+ IgnoreCase = 0x02,
+ Multiline = 0x04
+ };
+
+public:
+ static int flagFromChar(const QChar &);
+ static QString flagsToString(int flags);
+};
+
+} // end of namespace Ecma
+
+class QML_PARSER_EXPORT DiagnosticMessage
+{
+public:
+ enum Kind { Warning, Error };
+
+ DiagnosticMessage()
+ : kind(Error) {}
+
+ DiagnosticMessage(Kind kind, const AST::SourceLocation &loc, const QString &message)
+ : kind(kind), loc(loc), message(message) {}
+
+ bool isWarning() const
+ { return kind == Warning; }
+
+ bool isError() const
+ { return kind == Error; }
+
+ Kind kind;
+ AST::SourceLocation loc;
+ QString message;
+};
+
+class QML_PARSER_EXPORT Engine
+{
+ Lexer *_lexer;
+ NodePool *_nodePool;
+ QSet<NameId> _literals;
+ QList<QmlJS::AST::SourceLocation> _comments;
+
+public:
+ Engine();
+ ~Engine();
+
+ QSet<NameId> literals() const;
+
+ void addComment(int pos, int len, int line, int col);
+ QList<QmlJS::AST::SourceLocation> comments() const;
+
+ NameId *intern(const QChar *u, int s);
+
+ static QString toString(NameId *id);
+
+ Lexer *lexer() const;
+ void setLexer(Lexer *lexer);
+
+ NodePool *nodePool() const;
+ void setNodePool(NodePool *nodePool);
+};
+
+} // end of namespace QmlJS
+
+QT_QML_END_NAMESPACE
+
+#endif // QMLJSENGINE_P_H
diff --git a/src/declarative/qml/parser/qmljsglobal_p.h b/src/declarative/qml/parser/qmljsglobal_p.h
new file mode 100644
index 0000000..49e50cf
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsglobal_p.h
@@ -0,0 +1,64 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+#ifndef QMLJSGLOBAL_P_H
+#define QMLJSGLOBAL_P_H
+
+#include <QtCore/qglobal.h>
+
+#ifdef QT_CREATOR
+# define QT_QML_BEGIN_NAMESPACE
+# define QT_QML_END_NAMESPACE
+
+# ifdef QMLJS_BUILD_DIR
+# define QML_PARSER_EXPORT Q_DECL_EXPORT
+# elif QML_BUILD_STATIC_LIB
+# define QML_PARSER_EXPORT
+# else
+# define QML_PARSER_EXPORT Q_DECL_IMPORT
+# endif // QMLJS_BUILD_DIR
+
+#else // !QT_CREATOR
+# define QT_QML_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
+# define QT_QML_END_NAMESPACE QT_END_NAMESPACE
+# define QML_PARSER_EXPORT
+#endif // QT_CREATOR
+
+#endif // QMLJSGLOBAL_P_H
diff --git a/src/declarative/qml/parser/qmljsgrammar.cpp b/src/declarative/qml/parser/qmljsgrammar.cpp
new file mode 100644
index 0000000..b416959
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsgrammar.cpp
@@ -0,0 +1,939 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+// This file was generated by qlalr - DO NOT EDIT!
+#include "qmljsgrammar_p.h"
+
+QT_BEGIN_NAMESPACE
+
+const char *const QmlJSGrammar::spell [] = {
+ "end of file", "&", "&&", "&=", "break", "case", "catch", ":", ";", "continue",
+ "default", "delete", "/", "/=", "do", ".", "else", "=", "==", "===",
+ "finally", "for", "function", ">=", ">", ">>", ">>=", ">>>", ">>>=", "identifier",
+ "if", "in", "instanceof", "{", "[", "<=", "(", "<", "<<", "<<=",
+ "-", "-=", "--", "new", "!", "!=", "!==", "numeric literal", "|", "|=",
+ "||", "+", "+=", "++", "?", "}", "]", "%", "%=", "return",
+ ")", ";", 0, "*", "*=", "string literal", "property", "signal", "readonly", "switch",
+ "this", "throw", "~", "try", "typeof", "var", "void", "while", "with", "^",
+ "^=", "null", "true", "false", "const", "debugger", "reserved word", "multiline string literal", "comment", "public",
+ "import", "as", 0, 0, 0, 0, 0, 0, 0, 0};
+
+const short QmlJSGrammar::lhs [] = {
+ 100, 100, 100, 100, 100, 100, 101, 107, 107, 110,
+ 110, 112, 111, 111, 111, 111, 111, 111, 111, 111,
+ 114, 109, 108, 117, 117, 118, 118, 119, 119, 116,
+ 105, 105, 105, 105, 105, 105, 105, 125, 125, 125,
+ 126, 126, 127, 127, 105, 105, 105, 105, 105, 105,
+ 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
+ 105, 105, 115, 115, 115, 115, 130, 130, 130, 130,
+ 130, 130, 130, 130, 130, 130, 130, 130, 130, 130,
+ 130, 130, 130, 130, 120, 132, 132, 132, 132, 131,
+ 131, 134, 134, 136, 136, 136, 136, 136, 136, 137,
+ 137, 137, 137, 137, 137, 137, 137, 137, 137, 137,
+ 137, 137, 137, 137, 137, 137, 137, 137, 137, 137,
+ 137, 137, 137, 137, 137, 137, 137, 137, 137, 137,
+ 138, 138, 113, 113, 113, 113, 113, 141, 141, 142,
+ 142, 142, 142, 140, 140, 143, 143, 144, 144, 145,
+ 145, 145, 146, 146, 146, 146, 146, 146, 146, 146,
+ 146, 146, 147, 147, 147, 147, 148, 148, 148, 149,
+ 149, 149, 149, 150, 150, 150, 150, 150, 150, 150,
+ 151, 151, 151, 151, 151, 151, 152, 152, 152, 152,
+ 152, 153, 153, 153, 153, 153, 154, 154, 155, 155,
+ 156, 156, 157, 157, 158, 158, 159, 159, 160, 160,
+ 161, 161, 162, 162, 163, 163, 164, 164, 165, 165,
+ 135, 135, 166, 166, 167, 167, 167, 167, 167, 167,
+ 167, 167, 167, 167, 167, 167, 103, 103, 168, 168,
+ 169, 169, 170, 170, 102, 102, 102, 102, 102, 102,
+ 102, 102, 102, 102, 102, 102, 102, 102, 102, 121,
+ 182, 182, 181, 181, 129, 129, 183, 183, 184, 184,
+ 186, 186, 185, 187, 190, 188, 188, 191, 189, 189,
+ 122, 123, 123, 124, 124, 171, 171, 171, 171, 171,
+ 171, 171, 172, 172, 172, 172, 173, 173, 173, 173,
+ 174, 174, 175, 177, 192, 192, 195, 195, 193, 193,
+ 196, 194, 176, 176, 176, 178, 178, 179, 179, 179,
+ 197, 198, 180, 180, 128, 139, 202, 202, 199, 199,
+ 200, 200, 203, 106, 204, 204, 104, 104, 201, 201,
+ 133, 133, 205};
+
+const short QmlJSGrammar::rhs [] = {
+ 2, 2, 2, 2, 2, 2, 2, 1, 1, 1,
+ 2, 1, 2, 2, 3, 3, 5, 5, 4, 4,
+ 2, 0, 1, 1, 2, 1, 3, 2, 3, 2,
+ 1, 5, 4, 3, 3, 3, 3, 1, 1, 1,
+ 0, 1, 2, 4, 6, 6, 3, 3, 7, 7,
+ 4, 4, 5, 5, 6, 6, 7, 7, 7, 7,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 2, 3, 3, 4,
+ 5, 3, 4, 3, 1, 1, 2, 3, 4, 1,
+ 2, 3, 5, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 4, 3, 5, 1, 2, 4,
+ 4, 4, 3, 0, 1, 1, 3, 1, 1, 1,
+ 2, 2, 1, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 1, 3, 3, 3, 1, 3, 3, 1,
+ 3, 3, 3, 1, 3, 3, 3, 3, 3, 3,
+ 1, 3, 3, 3, 3, 3, 1, 3, 3, 3,
+ 3, 1, 3, 3, 3, 3, 1, 3, 1, 3,
+ 1, 3, 1, 3, 1, 3, 1, 3, 1, 3,
+ 1, 3, 1, 3, 1, 3, 1, 5, 1, 5,
+ 1, 3, 1, 3, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 3, 0, 1,
+ 1, 3, 0, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 3,
+ 1, 2, 0, 1, 3, 3, 1, 1, 1, 3,
+ 1, 3, 2, 2, 2, 0, 1, 2, 0, 1,
+ 1, 2, 2, 7, 5, 7, 7, 5, 9, 10,
+ 7, 8, 2, 2, 3, 3, 2, 2, 3, 3,
+ 3, 3, 5, 5, 3, 5, 1, 2, 0, 1,
+ 4, 3, 3, 3, 3, 3, 3, 3, 3, 4,
+ 5, 2, 2, 2, 8, 8, 1, 3, 0, 1,
+ 0, 1, 1, 1, 1, 2, 1, 1, 0, 1,
+ 0, 1, 2};
+
+const short QmlJSGrammar::action_default [] = {
+ 0, 0, 0, 0, 0, 0, 22, 0, 170, 237,
+ 201, 209, 205, 149, 221, 197, 3, 134, 68, 150,
+ 213, 217, 138, 167, 148, 153, 133, 187, 174, 0,
+ 75, 76, 71, 339, 63, 341, 0, 0, 0, 0,
+ 73, 0, 0, 69, 72, 0, 0, 64, 66, 65,
+ 74, 67, 0, 70, 0, 0, 163, 0, 0, 150,
+ 169, 152, 151, 0, 0, 0, 165, 166, 164, 168,
+ 0, 198, 0, 0, 0, 0, 188, 0, 0, 0,
+ 0, 0, 0, 178, 0, 0, 0, 172, 173, 171,
+ 176, 180, 179, 177, 175, 190, 189, 191, 0, 206,
+ 0, 202, 0, 0, 144, 131, 143, 132, 100, 101,
+ 102, 127, 103, 128, 104, 105, 106, 107, 108, 109,
+ 110, 111, 112, 113, 114, 115, 116, 129, 117, 118,
+ 119, 120, 121, 122, 123, 124, 125, 126, 130, 0,
+ 0, 142, 238, 145, 0, 146, 0, 147, 141, 0,
+ 234, 227, 225, 232, 233, 231, 230, 236, 229, 228,
+ 226, 235, 222, 0, 210, 0, 0, 214, 0, 0,
+ 218, 0, 0, 144, 136, 0, 135, 0, 140, 154,
+ 0, 340, 329, 330, 0, 327, 0, 328, 0, 331,
+ 245, 252, 251, 259, 247, 0, 248, 332, 0, 338,
+ 249, 250, 255, 253, 335, 333, 337, 256, 0, 267,
+ 0, 0, 0, 0, 339, 63, 0, 341, 64, 239,
+ 281, 65, 0, 0, 0, 268, 0, 0, 257, 258,
+ 0, 246, 254, 282, 283, 326, 336, 0, 297, 298,
+ 299, 300, 0, 293, 294, 295, 296, 323, 324, 0,
+ 0, 0, 0, 0, 286, 287, 243, 241, 203, 211,
+ 207, 223, 199, 244, 0, 150, 215, 219, 192, 181,
+ 0, 0, 200, 0, 0, 0, 0, 193, 0, 0,
+ 0, 0, 0, 185, 183, 186, 184, 182, 195, 194,
+ 196, 0, 208, 0, 204, 0, 242, 150, 0, 224,
+ 239, 240, 0, 239, 0, 0, 289, 0, 0, 0,
+ 291, 0, 212, 0, 0, 216, 0, 0, 220, 279,
+ 0, 271, 280, 274, 0, 278, 0, 239, 272, 0,
+ 239, 0, 0, 290, 0, 0, 0, 292, 340, 329,
+ 0, 0, 331, 0, 325, 0, 315, 0, 0, 0,
+ 285, 0, 284, 0, 342, 0, 99, 261, 264, 0,
+ 100, 267, 103, 128, 105, 106, 71, 110, 111, 63,
+ 112, 115, 69, 72, 64, 239, 65, 74, 118, 67,
+ 120, 70, 122, 123, 268, 125, 126, 130, 0, 92,
+ 0, 0, 94, 98, 96, 83, 95, 97, 0, 93,
+ 82, 262, 260, 138, 139, 144, 0, 137, 0, 314,
+ 0, 301, 302, 0, 313, 0, 0, 0, 304, 309,
+ 307, 310, 0, 0, 308, 309, 0, 305, 0, 306,
+ 263, 312, 0, 263, 311, 0, 316, 317, 0, 263,
+ 318, 319, 0, 0, 320, 0, 0, 0, 321, 322,
+ 156, 155, 0, 0, 0, 288, 0, 0, 0, 303,
+ 276, 269, 0, 277, 273, 0, 275, 265, 0, 266,
+ 270, 86, 0, 0, 90, 77, 0, 79, 88, 0,
+ 80, 89, 91, 81, 87, 78, 0, 84, 160, 158,
+ 162, 159, 157, 161, 6, 334, 4, 2, 61, 85,
+ 0, 0, 64, 66, 65, 31, 5, 0, 62, 0,
+ 40, 39, 38, 0, 0, 53, 0, 54, 0, 59,
+ 60, 0, 40, 0, 0, 0, 0, 0, 49, 50,
+ 0, 51, 0, 52, 0, 55, 56, 0, 0, 0,
+ 0, 0, 57, 58, 0, 47, 41, 48, 42, 0,
+ 0, 0, 0, 44, 0, 45, 46, 43, 0, 0,
+ 30, 34, 35, 36, 37, 138, 263, 0, 0, 100,
+ 267, 103, 128, 105, 106, 71, 110, 111, 63, 112,
+ 115, 69, 72, 64, 239, 65, 74, 118, 67, 120,
+ 70, 122, 123, 268, 125, 126, 130, 138, 0, 26,
+ 0, 0, 32, 27, 33, 28, 24, 0, 29, 25,
+ 8, 0, 10, 0, 9, 0, 1, 21, 12, 0,
+ 13, 0, 14, 0, 19, 20, 0, 15, 16, 0,
+ 17, 18, 11, 23, 7, 343};
+
+const short QmlJSGrammar::goto_default [] = {
+ 7, 616, 206, 195, 204, 506, 494, 615, 634, 610,
+ 614, 612, 617, 22, 613, 18, 505, 607, 598, 560,
+ 507, 190, 194, 196, 200, 523, 549, 548, 199, 231,
+ 26, 473, 472, 355, 354, 9, 353, 356, 106, 17,
+ 144, 24, 13, 143, 19, 25, 56, 23, 8, 28,
+ 27, 268, 15, 262, 10, 258, 12, 260, 11, 259,
+ 20, 266, 21, 267, 14, 261, 257, 298, 410, 263,
+ 264, 201, 192, 191, 203, 232, 202, 207, 228, 229,
+ 193, 359, 358, 230, 462, 461, 320, 321, 464, 323,
+ 463, 322, 418, 422, 425, 421, 420, 440, 441, 184,
+ 198, 180, 183, 197, 205, 0};
+
+const short QmlJSGrammar::action_index [] = {
+ 439, 1109, 2228, 2228, 2132, 814, -74, 18, 147, -100,
+ 31, -17, -49, 232, -100, 318, 85, -100, -100, 554,
+ 33, 94, 331, 215, -100, -100, -100, 448, 231, 1109,
+ -100, -100, -100, 320, -100, 1940, 1472, 1109, 1109, 1109,
+ -100, 724, 1109, -100, -100, 1109, 1109, -100, -100, -100,
+ -100, -100, 1109, -100, 1109, 1109, -100, 1109, 1109, 129,
+ 157, -100, -100, 1109, 1109, 1109, -100, -100, -100, 200,
+ 1109, 293, 1109, 1109, 1109, 1109, 466, 1109, 1109, 1109,
+ 1109, 1109, 1109, 179, 1109, 1109, 1109, 119, 125, 95,
+ 188, 198, 184, 203, 178, 567, 567, 484, 1109, -5,
+ 1109, 67, 1844, 1109, 1109, -100, -100, -100, -100, -100,
+ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100,
+ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100,
+ -100, -100, -100, -100, -100, -100, -100, -100, -100, 110,
+ 1109, -100, -100, 70, 61, -100, 1109, -100, -100, 1109,
+ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100,
+ -100, -100, -100, 1109, 55, 1109, 1109, 73, 63, 1109,
+ -100, 1844, 1109, 1109, -100, 141, -100, 41, -100, -100,
+ 87, -100, 255, 80, 78, -100, 287, -100, 83, 2228,
+ -100, -100, -100, -100, -100, 225, -100, -100, 52, -100,
+ -100, -100, -100, -100, -100, 2228, -100, -100, 420, -100,
+ 408, 113, 2132, 50, 330, 65, 46, 2420, 72, 1109,
+ -100, 74, 75, 1109, 77, -100, 53, 56, -100, -100,
+ 323, -100, -100, -100, -100, -100, -100, 96, -100, -100,
+ -100, -100, 99, -100, -100, -100, -100, -100, -100, 60,
+ 47, 1109, 118, 93, -100, -100, 1291, -100, 79, 66,
+ 64, -100, 413, 76, 51, 664, 89, 97, 393, 183,
+ 337, 1109, 413, 1109, 1109, 1109, 1109, 411, 1109, 1109,
+ 1109, 1109, 1109, 252, 272, 212, 217, 221, 490, 490,
+ 383, 1109, 64, 1109, 84, 1109, -100, 536, 1109, -100,
+ 1109, 69, 68, 1109, 44, 2132, -100, 1109, 124, 2132,
+ -100, 1109, 54, 1109, 1109, 71, 88, 1109, -100, 82,
+ 122, 154, -100, -100, 1109, -100, 343, 1109, -100, 81,
+ 1109, 90, 2132, -100, 1109, 112, 2132, -100, 86, 333,
+ -39, -10, 2228, -33, -100, 2132, -100, 1109, 246, 2132,
+ 4, 2132, -100, 10, 16, -21, -100, -100, 2132, -26,
+ 480, 19, 462, 128, 1109, 2132, 6, -9, 400, 8,
+ -22, 840, -3, -6, -100, 1202, -100, -7, -28, 5,
+ 1109, 2, -23, 1109, 0, 1109, -34, -30, 1109, -100,
+ 2036, 21, -100, -100, -100, -100, -100, -100, 1109, -100,
+ -100, -100, -100, 209, -100, 1109, 40, -100, 2132, -100,
+ 101, -100, -100, 2132, -100, 1109, 120, 43, -100, 62,
+ -100, 59, 109, 1109, -100, 57, 58, -100, 39, -100,
+ 2132, -100, 117, 2132, -100, 199, -100, -100, 107, 2132,
+ 34, -100, 24, 11, -100, 346, -19, 14, -100, -100,
+ -100, -100, 1109, 133, 2132, -100, 1109, 126, 2132, -100,
+ 20, -100, 173, -100, -100, 1109, -100, -100, 303, -100,
+ -100, -100, 100, 1656, -100, -100, 1564, -100, -100, 1748,
+ -100, -100, -100, -100, -100, -100, 131, -100, -100, -100,
+ -100, -100, -100, -100, -100, 2228, -100, -100, -100, 158,
+ -20, 752, 165, -16, 22, -100, -100, 98, -100, 189,
+ -100, -100, -100, 28, 170, -100, 1109, -100, 230, -100,
+ -100, 247, 1, 13, 238, 37, -24, 106, -100, -100,
+ 273, -100, 1109, -100, 265, -100, -100, 242, -4, 12,
+ 1109, 241, -100, -100, 234, -100, 245, -100, 3, 9,
+ 311, 190, 316, -100, 134, -100, -100, -100, 1380, 1020,
+ -100, -100, -100, -100, -100, 359, 2324, 1472, 15, 444,
+ 38, 394, 138, 1109, 2132, 36, 17, 397, 42, 23,
+ 840, 32, 29, -100, 1202, -100, 26, 35, 48, 1109,
+ 45, 25, 1109, 49, 1109, 27, 30, 314, 132, -100,
+ 7, 752, -100, -100, -100, -100, -100, 930, -100, -100,
+ -100, 752, -100, 253, -87, 617, -100, -100, 102, 290,
+ -100, 191, -100, 140, -100, -100, 275, -100, -100, 91,
+ -100, -100, -100, -100, -100, -100,
+
+ -106, 12, -87, 18, 17, 212, -106, -106, -106, -106,
+ -106, -106, -106, -106, -106, -106, -106, -106, -106, -53,
+ -106, -106, -106, -106, -106, -106, -106, -106, -106, 162,
+ -106, -106, -106, -4, -106, -106, -11, 24, 75, 76,
+ -106, 83, 55, -106, -106, 157, 158, -106, -106, -106,
+ -106, -106, 150, -106, 172, 176, -106, 168, 167, -106,
+ -106, -106, -106, 173, 154, 115, -106, -106, -106, -106,
+ 147, -106, 121, 113, 112, 125, -106, 128, 143, 146,
+ 140, 139, 136, -106, 122, 138, 130, -106, -106, -106,
+ -106, -106, -106, -106, -106, -106, -106, -106, 149, -106,
+ 153, -106, 110, 82, 46, -106, -106, -106, -106, -106,
+ -106, -106, -106, -106, -106, -106, -106, -106, -106, -106,
+ -106, -106, -106, -106, -106, -106, -106, -106, -106, -106,
+ -106, -106, -106, -106, -106, -106, -106, -106, -106, -106,
+ 35, -106, -106, -106, -106, -106, 37, -106, -106, 45,
+ -106, -106, -106, -106, -106, -106, -106, -106, -106, -106,
+ -106, -106, -106, 92, -106, 88, 58, -106, -106, 51,
+ -106, 209, 72, 78, -106, -106, -106, -106, -106, -106,
+ -106, -106, 27, -106, -106, -106, 63, -106, -106, -106,
+ -106, -106, -106, -106, -106, -106, -106, -106, -106, -106,
+ -106, -106, -106, -106, -106, 50, -106, -106, 28, -106,
+ 29, -106, 47, -106, 33, -106, -106, 66, -106, 73,
+ -106, -106, -106, 81, 53, -106, -106, -106, -106, -106,
+ -13, -106, -106, -106, -106, -106, -106, -106, -106, -106,
+ -106, -106, -106, -106, -106, -106, -106, -106, -106, -106,
+ -106, 9, -106, -106, -106, -106, 111, -106, -106, -106,
+ -106, -106, -106, -106, -106, -106, -106, -106, -106, -106,
+ 3, 186, -106, 220, 228, 234, 204, -106, 90, 91,
+ 94, 97, 93, -106, -106, -106, -106, -106, -106, -106,
+ -106, 210, -106, 187, -106, 214, -106, -106, 208, -106,
+ 207, -106, -106, 155, -106, 8, -106, 4, -106, -1,
+ -106, 217, -106, 177, 185, -106, -106, 184, -106, -106,
+ -106, -106, -106, -106, 183, -106, 194, 105, -106, -106,
+ 99, -106, 71, -106, 74, -106, 65, -106, -106, 114,
+ -106, -106, -55, -106, -106, 64, -106, 44, -106, 30,
+ -106, 31, -106, -106, -106, -106, -106, -106, 57, -106,
+ 36, -106, 40, -106, 70, 59, -106, -106, 42, -106,
+ -106, 104, -106, -106, -106, 38, -106, -106, -106, -106,
+ 79, -106, 69, 108, -106, 84, -106, -106, 56, -106,
+ 68, -106, -106, -106, -106, -106, -106, -106, 52, -106,
+ -106, -106, -106, -106, -106, 109, -106, -106, 77, -106,
+ -106, -106, -106, 86, -106, 80, -106, -106, -106, -106,
+ -106, -59, -106, 43, -106, -63, -106, -106, -106, -106,
+ 98, -106, -106, 95, -106, -106, -106, -106, -106, 60,
+ -34, -106, -106, 32, -106, 41, -106, 39, -106, -106,
+ -106, -106, 49, -106, 61, -106, 62, -106, 48, -106,
+ -106, -106, -106, -106, -106, 23, -106, -106, 96, -106,
+ -106, -106, -106, 34, -106, -106, 133, -106, -106, 54,
+ -106, -106, -106, -106, -106, -106, -106, -106, -106, -106,
+ -106, -106, -106, -106, -106, 67, -106, -106, -106, -106,
+ -106, 22, -106, -106, -106, -106, -106, -106, -106, -22,
+ -106, -106, -106, -106, -106, -106, 2, -106, -106, -106,
+ -106, -106, -106, -106, -19, -106, -106, -106, -106, -106,
+ -106, -106, 100, -106, -106, -106, -106, -21, -106, -106,
+ -3, -106, -106, -106, -106, -106, 13, -106, -106, -106,
+ 11, 14, 10, -106, -106, -106, -106, -106, 279, 283,
+ -106, -106, -106, -106, -106, -106, 19, 273, 15, 16,
+ -106, 21, -106, 224, 6, -106, -106, 25, -106, -106,
+ 85, -106, -106, -106, 26, -106, -106, -106, -106, 20,
+ -106, 7, 87, -106, 107, -106, -106, -106, -106, -106,
+ -106, 317, -106, -106, -106, -106, -106, 277, -106, -106,
+ -106, 0, -106, -106, -2, 271, -106, -106, -106, 1,
+ -106, -106, -106, -106, -106, -106, 5, -106, -106, -106,
+ -106, -106, -106, -106, -106, -106};
+
+const short QmlJSGrammar::action_info [] = {
+ -97, -98, 452, 611, -116, 527, 456, -124, 415, -121,
+ 439, 551, -119, -108, 347, -94, 611, 388, 635, 540,
+ 351, 341, 344, 342, 390, 539, -127, 256, 398, 402,
+ 100, 98, 70, -97, 400, 163, -98, 465, 524, -116,
+ 559, 447, 530, -108, 439, -127, 509, 439, 559, -94,
+ 537, 544, -121, 256, 443, -119, -124, 514, 439, 347,
+ 445, 526, 423, 452, 423, 430, 456, 423, 70, 554,
+ 169, 415, 345, 311, 100, 163, 419, 140, 146, 408,
+ 271, 413, 347, 251, 295, 271, 256, 0, 186, 452,
+ 0, 311, 456, 140, 429, 317, 0, 0, 0, 324,
+ 407, 178, 291, 98, 305, 558, 0, 235, 476, 0,
+ 439, 415, 300, 442, 291, 0, 189, 171, 140, 426,
+ 140, 148, 339, 182, 433, 140, 140, 443, 140, 303,
+ 326, 559, 140, 0, 140, 57, 172, 250, 188, 140,
+ 601, 140, 330, 293, 165, 0, 58, 313, 166, 140,
+ 332, 314, 631, 630, 255, 254, 477, 241, 240, 57,
+ 246, 245, 412, 411, 427, 57, 141, 529, 528, 63,
+ 58, 61, 336, 171, 248, 247, 58, 516, 253, 0,
+ 417, 468, 62, 327, 309, 334, 458, 57, 602, 248,
+ 247, 487, 172, 454, 522, 556, 555, 176, 58, 248,
+ 247, 625, 624, 84, 84, 85, 85, 140, 84, 84,
+ 85, 85, 63, 84, 64, 85, 86, 86, 510, 510,
+ 65, 86, 86, 84, 171, 85, 86, 63, 84, 0,
+ 85, 517, 515, 140, 469, 467, 86, 84, 140, 85,
+ 512, 86, 84, 172, 85, 405, 84, 102, 85, 140,
+ 86, 511, 628, 627, 140, 86, 84, 64, 85, 86,
+ 437, 436, 171, 65, 512, 512, 103, 510, 104, 86,
+ 546, 510, 64, 140, 510, 511, 511, 84, 65, 85,
+ 532, 172, 626, 405, 34, 0, 234, 233, 0, 0,
+ 86, 520, 519, 0, 0, 547, 545, 84, 0, 85,
+ 621, 0, 543, 542, 34, 0, 349, 0, 0, 0,
+ 86, 72, 73, 512, 622, 620, 34, 512, 0, 34,
+ 512, 47, 49, 48, 511, 0, 536, 535, 511, 171,
+ 0, 511, 34, 0, 533, 531, 72, 73, 74, 75,
+ 34, 47, 49, 48, 619, 34, 171, -85, 172, 34,
+ 173, 0, 34, 47, 49, 48, 47, 49, 48, 34,
+ 0, 0, 34, 74, 75, 172, 34, 173, 0, 47,
+ 49, 48, 34, 0, 171, 34, 0, 47, 49, 48,
+ 0, 0, 47, 49, 48, 0, 47, 49, 48, 47,
+ 49, 48, -85, 172, 0, 173, 47, 49, 48, 47,
+ 49, 48, 0, 47, 49, 48, 278, 279, 0, 47,
+ 49, 48, 47, 49, 48, 280, 278, 279, 281, 0,
+ 282, 0, 0, 34, 0, 280, 34, 0, 281, 34,
+ 282, 273, 274, -339, 278, 279, -339, 34, 0, 0,
+ 0, 0, 0, 280, 0, 0, 281, 0, 282, 34,
+ 0, 0, 0, 0, 0, 244, 243, 0, 275, 276,
+ 47, 49, 48, 47, 49, 48, 47, 49, 48, 244,
+ 243, 77, 78, 34, 47, 49, 48, 0, 0, 79,
+ 80, 239, 238, 81, 0, 82, 47, 49, 48, 77,
+ 78, 34, 0, 0, 0, 0, 0, 79, 80, 0,
+ 0, 81, 0, 82, 0, 239, 238, 77, 78, 34,
+ 47, 49, 48, 278, 279, 79, 80, 0, 0, 81,
+ 0, 82, 280, 244, 243, 281, 0, 282, 47, 49,
+ 48, 6, 5, 4, 1, 3, 2, 0, 0, 150,
+ 0, 239, 238, 0, 0, 0, 47, 49, 48, 151,
+ 0, 0, 0, 152, 0, 0, 0, 150, 0, 0,
+ 0, 0, 153, 0, 154, 0, 0, 151, 0, 0,
+ 0, 152, 0, 0, 0, 155, 0, 156, 61, 0,
+ 153, 0, 154, 0, 0, 157, 0, 0, 158, 62,
+ 77, 78, 0, 155, 159, 156, 61, 0, 79, 80,
+ 160, 0, 81, 157, 82, 0, 158, 62, 0, 0,
+ 0, 0, 159, 0, 0, 0, 161, 0, 160, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 30,
+ 31, 0, 0, 0, 161, 0, 0, 0, 0, 33,
+ 0, 0, 0, 0, 0, 0, 34, 0, 0, 0,
+ 35, 36, 0, 37, 0, 0, 0, 0, 0, 0,
+ 501, 0, 0, 0, 44, 0, 0, 150, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 151, 0, 0,
+ 0, 152, 50, 47, 49, 48, 0, 51, 0, 0,
+ 153, 0, 154, 0, 0, 307, 0, 0, 43, 53,
+ 32, 0, 0, 155, 40, 156, 61, 0, 0, 0,
+ 0, 0, 0, 157, 0, 0, 158, 62, 0, 0,
+ 0, 0, 159, 0, 0, 0, 0, 0, 160, 0,
+ 0, 0, 0, 0, 0, 0, 30, 31, 0, 0,
+ 0, 0, 0, 0, 161, 0, 33, 0, 0, 0,
+ 0, 0, 0, 34, 0, 0, 0, 35, 36, 0,
+ 37, 0, 0, 0, 30, 31, 0, 41, 0, 0,
+ 0, 44, 0, 0, 33, 0, 0, 0, 0, 0,
+ 0, 34, 0, 0, 0, 35, 36, 0, 37, 50,
+ 47, 49, 48, 0, 51, 501, 0, 0, 0, 44,
+ 0, 0, 0, 0, 0, 43, 53, 32, 0, 0,
+ 0, 40, 0, 0, 0, 0, 0, 50, 47, 49,
+ 48, 0, 51, 0, 500, 0, 30, 31, 0, 0,
+ 0, 0, 0, 43, 53, 32, 214, 0, 0, 40,
+ 0, 0, 0, 34, 0, 0, 0, 35, 36, 0,
+ 37, 0, 30, 31, 0, 0, 0, 501, 0, 0,
+ 0, 44, 33, 0, 0, 0, 0, 0, 0, 34,
+ 0, 0, 0, 35, 36, 0, 37, 0, 0, 50,
+ 502, 504, 503, 41, 51, 0, 0, 44, 0, 225,
+ 0, 0, 0, 0, 0, 43, 53, 32, 209, 0,
+ 0, 40, 0, 0, 0, 50, 47, 49, 48, 0,
+ 51, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 43, 53, 32, 0, 0, 0, 40, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 500, 0, 30, 31, 0, 0, 0, 0, 0, 0,
+ 0, 0, 214, 0, 0, 0, 0, 0, 0, 34,
+ 0, 0, 0, 35, 36, 0, 37, 0, 0, 0,
+ 0, 0, 0, 501, 0, 0, 0, 44, 0, 0,
+ 0, 0, 0, 0, 0, 608, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 50, 502, 504, 503, 0,
+ 51, 0, 0, 0, 0, 225, 0, 0, 0, 0,
+ 0, 43, 53, 32, 209, 0, 0, 40, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 500, 0, 30, 31, 0, 0, 0, 0, 0, 0,
+ 0, 0, 214, 0, 0, 0, 0, 0, 0, 34,
+ 0, 0, 0, 35, 36, 0, 37, 0, 0, 0,
+ 0, 0, 0, 501, 0, 0, 0, 44, 0, 0,
+ 0, 0, 0, 0, 0, 605, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 50, 502, 504, 503, 0,
+ 51, 0, 0, 0, 0, 225, 0, 0, 0, 0,
+ 0, 43, 53, 32, 209, 0, 0, 40, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 29, 30, 31, 0, 0, 0, 0, 0, 0, 0,
+ 0, 33, 0, 0, 0, 0, 0, 0, 34, 0,
+ 0, 0, 35, 36, 0, 37, 0, 0, 0, 38,
+ 0, 39, 41, 42, 0, 0, 44, 0, 0, 0,
+ 45, 0, 46, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 50, 47, 49, 48, 0, 51,
+ 0, 52, 0, 54, 0, 55, 0, 0, 0, 0,
+ 43, 53, 32, 0, 0, 0, 40, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, -117,
+ 0, 0, 0, 29, 30, 31, 0, 0, 0, 0,
+ 0, 0, 0, 0, 33, 0, 0, 0, 0, 0,
+ 0, 34, 0, 0, 0, 35, 36, 0, 37, 0,
+ 0, 0, 38, 0, 39, 41, 42, 0, 0, 44,
+ 0, 0, 0, 45, 0, 46, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 50, 47, 49,
+ 48, 0, 51, 0, 52, 0, 54, 0, 55, 0,
+ 0, 0, 0, 43, 53, 32, 0, 0, 0, 40,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 29, 30, 31, 0, 0, 0, 0, 0,
+ 0, 0, 0, 33, 0, 0, 0, 0, 0, 0,
+ 34, 0, 0, 0, 35, 36, 0, 37, 0, 0,
+ 0, 38, 0, 39, 41, 42, 0, 0, 44, 0,
+ 0, 0, 45, 0, 46, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 50, 47, 49, 48,
+ 0, 51, 0, 52, 0, 54, 270, 55, 0, 0,
+ 0, 0, 43, 53, 32, 0, 0, 0, 40, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 29, 30, 31, 0, 0, 0, 0, 0, 0,
+ 0, 0, 33, 0, 0, 0, 0, 0, 0, 34,
+ 216, 0, 0, 566, 567, 0, 37, 0, 0, 0,
+ 38, 0, 39, 41, 42, 0, 0, 44, 0, 0,
+ 0, 45, 0, 46, 0, 0, 0, 0, 0, 0,
+ 0, 220, 0, 0, 0, 50, 47, 49, 48, 0,
+ 51, 0, 52, 0, 54, 0, 55, 0, 0, 0,
+ 0, 43, 53, 32, 0, 0, 0, 40, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 474, 0, 0, 29, 30, 31, 0, 0, 0, 0,
+ 0, 0, 0, 0, 33, 0, 0, 0, 0, 0,
+ 0, 34, 0, 0, 0, 35, 36, 0, 37, 0,
+ 0, 0, 38, 0, 39, 41, 42, 0, 0, 44,
+ 0, 0, 0, 45, 0, 46, 0, 0, 475, 0,
+ 0, 0, 0, 0, 0, 0, 0, 50, 47, 49,
+ 48, 0, 51, 0, 52, 0, 54, 0, 55, 0,
+ 0, 0, 0, 43, 53, 32, 0, 0, 0, 40,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 474, 0, 0, 29, 30, 31, 0, 0,
+ 0, 0, 0, 0, 0, 0, 33, 0, 0, 0,
+ 0, 0, 0, 34, 0, 0, 0, 35, 36, 0,
+ 37, 0, 0, 0, 38, 0, 39, 41, 42, 0,
+ 0, 44, 0, 0, 0, 45, 0, 46, 0, 0,
+ 480, 0, 0, 0, 0, 0, 0, 0, 0, 50,
+ 47, 49, 48, 0, 51, 0, 52, 0, 54, 0,
+ 55, 0, 0, 0, 0, 43, 53, 32, 0, 0,
+ 0, 40, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 482, 0, 0, 29, 30, 31,
+ 0, 0, 0, 0, 0, 0, 0, 0, 33, 0,
+ 0, 0, 0, 0, 0, 34, 0, 0, 0, 35,
+ 36, 0, 37, 0, 0, 0, 38, 0, 39, 41,
+ 42, 0, 0, 44, 0, 0, 0, 45, 0, 46,
+ 0, 0, 485, 0, 0, 0, 0, 0, 0, 0,
+ 0, 50, 47, 49, 48, 0, 51, 0, 52, 0,
+ 54, 0, 55, 0, 0, 0, 0, 43, 53, 32,
+ 0, 0, 0, 40, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 482, 0, 0, 29,
+ 30, 31, 0, 0, 0, 0, 0, 0, 0, 0,
+ 33, 0, 0, 0, 0, 0, 0, 34, 0, 0,
+ 0, 35, 36, 0, 37, 0, 0, 0, 38, 0,
+ 39, 41, 42, 0, 0, 44, 0, 0, 0, 45,
+ 0, 46, 0, 0, 483, 0, 0, 0, 0, 0,
+ 0, 0, 0, 50, 47, 49, 48, 0, 51, 0,
+ 52, 0, 54, 0, 55, 0, 0, 0, 0, 43,
+ 53, 32, 0, 0, 0, 40, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 108, 109,
+ 110, 0, 0, 112, 114, 115, 0, 0, 116, 0,
+ 117, 0, 0, 0, 119, 120, 121, 0, 0, 0,
+ 0, 0, 0, 34, 122, 123, 124, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 125, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 128, 0, 0, 0, 0, 0, 0,
+ 47, 49, 48, 129, 130, 131, 0, 133, 134, 135,
+ 136, 137, 138, 0, 0, 126, 132, 118, 111, 113,
+ 127, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 108, 109, 110, 0, 0, 112,
+ 114, 115, 0, 0, 116, 0, 117, 0, 0, 0,
+ 119, 120, 121, 0, 0, 0, 0, 0, 0, 392,
+ 122, 123, 124, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 125, 0, 0, 0, 393, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 128,
+ 0, 0, 0, 0, 0, 397, 394, 396, 0, 129,
+ 130, 131, 0, 133, 134, 135, 136, 137, 138, 0,
+ 0, 126, 132, 118, 111, 113, 127, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 108, 109, 110, 0, 0, 112, 114, 115, 0, 0,
+ 116, 0, 117, 0, 0, 0, 119, 120, 121, 0,
+ 0, 0, 0, 0, 0, 392, 122, 123, 124, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 125,
+ 0, 0, 0, 393, 0, 0, 0, 0, 0, 0,
+ 0, 395, 0, 0, 0, 128, 0, 0, 0, 0,
+ 0, 397, 394, 396, 0, 129, 130, 131, 0, 133,
+ 134, 135, 136, 137, 138, 0, 0, 126, 132, 118,
+ 111, 113, 127, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 208, 0, 0, 0,
+ 0, 210, 0, 29, 30, 31, 212, 0, 0, 0,
+ 0, 0, 0, 213, 33, 0, 0, 0, 0, 0,
+ 0, 215, 216, 0, 0, 217, 36, 0, 37, 0,
+ 0, 0, 38, 0, 39, 41, 42, 0, 0, 44,
+ 0, 0, 0, 45, 0, 46, 0, 0, 0, 0,
+ 0, 219, 0, 220, 0, 0, 0, 50, 218, 221,
+ 48, 222, 51, 223, 52, 224, 54, 225, 55, 226,
+ 227, 0, 0, 43, 53, 32, 209, 211, 0, 40,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 208, 0, 0, 0, 0, 210, 0, 29,
+ 30, 31, 212, 0, 0, 0, 0, 0, 0, 213,
+ 214, 0, 0, 0, 0, 0, 0, 215, 216, 0,
+ 0, 217, 36, 0, 37, 0, 0, 0, 38, 0,
+ 39, 41, 42, 0, 0, 44, 0, 0, 0, 45,
+ 0, 46, 0, 0, 0, 0, 0, 219, 0, 220,
+ 0, 0, 0, 50, 218, 221, 48, 222, 51, 223,
+ 52, 224, 54, 225, 55, 226, 227, 0, 0, 43,
+ 53, 32, 209, 211, 0, 40, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 569, 109,
+ 110, 0, 0, 571, 114, 573, 30, 31, 574, 0,
+ 117, 0, 0, 0, 119, 576, 577, 0, 0, 0,
+ 0, 0, 0, 578, 579, 123, 124, 217, 36, 0,
+ 37, 0, 0, 0, 38, 0, 39, 580, 42, 0,
+ 0, 582, 0, 0, 0, 45, 0, 46, 0, 0,
+ 0, 0, 0, 584, 0, 220, 0, 0, 0, 586,
+ 583, 585, 48, 587, 588, 589, 52, 591, 592, 593,
+ 594, 595, 596, 0, 0, 581, 590, 575, 570, 572,
+ 127, 40, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 360, 109, 110, 0, 0, 362,
+ 114, 364, 30, 31, 365, 0, 117, 0, 0, 0,
+ 119, 367, 368, 0, 0, 0, 0, 0, 0, 369,
+ 370, 123, 124, 217, 36, 0, 37, 0, 0, 0,
+ 38, 0, 39, 371, 42, 0, 0, 373, 0, 0,
+ 0, 45, 0, 46, 0, -263, 0, 0, 0, 375,
+ 0, 220, 0, 0, 0, 377, 374, 376, 48, 378,
+ 379, 380, 52, 382, 383, 384, 385, 386, 387, 0,
+ 0, 372, 381, 366, 361, 363, 127, 40, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+
+ 541, 310, 460, 513, 538, 518, 525, 308, 249, 632,
+ 306, 181, 252, 618, 149, 16, 623, 495, 319, 497,
+ 629, 357, 496, 435, 471, 553, 557, 486, 438, 301,
+ 428, 237, 350, 352, 604, 521, 242, 424, 550, 552,
+ 181, 301, 185, 237, 242, 343, 432, 348, 338, 249,
+ 459, 237, 453, 449, 236, 242, 446, 181, 466, 401,
+ 448, 249, 357, 455, 444, 457, 346, 337, 357, 484,
+ 142, 236, 147, 333, 438, 175, 301, 335, 187, 409,
+ 162, 145, 435, 416, 435, 139, 170, 399, 414, 481,
+ 438, 389, 0, 168, 0, 0, 403, 357, 403, 59,
+ 357, 490, 301, 534, 391, 0, 0, 0, 301, 0,
+ 0, 460, 0, 145, 59, 0, 179, 403, 177, 59,
+ 59, 488, 489, 0, 404, 105, 404, 0, 59, 185,
+ 451, 59, 59, 450, 59, 59, 59, 59, 59, 283,
+ 284, 59, 287, 285, 145, 404, 286, 107, 167, 406,
+ 164, 59, 59, 451, 450, 265, 59, 59, 301, 59,
+ 269, 68, 96, 95, 479, 59, 59, 331, 478, 59,
+ 87, 76, 59, 329, 59, 97, 434, 83, 89, 431,
+ 59, 470, 59, 59, 59, 94, 88, 59, 93, 92,
+ 59, 59, 90, 59, 59, 91, 493, 59, 59, 71,
+ 67, 59, 59, 491, 492, 99, 59, 101, 179, 319,
+ 301, 59, 59, 340, 69, 60, 59, 59, 450, 66,
+ 59, 59, 451, 304, 105, 499, 269, 297, 297, 297,
+ 59, 59, 269, 269, 269, 269, 269, 0, 315, 272,
+ 498, 508, 294, 0, 0, 0, 107, 174, 59, 325,
+ 318, 316, 297, 269, 59, 290, 0, 269, 297, 269,
+ 0, 59, 0, 269, 59, 0, 269, 292, 59, 269,
+ 179, 277, 59, 0, 299, 302, 312, 269, 59, 288,
+ 296, 328, 609, 269, 499, 289, 597, 633, 606, 599,
+ 499, 600, 565, 600, 0, 0, 499, 0, 0, 568,
+ 561, 562, 563, 564, 0, 498, 508, 0, 471, 0,
+ 0, 498, 508, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 499, 0, 0, 603, 0, 0, 0, 600, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0};
+
+const short QmlJSGrammar::action_check [] = {
+ 7, 7, 36, 90, 7, 29, 36, 7, 36, 7,
+ 33, 8, 7, 7, 36, 7, 90, 7, 0, 7,
+ 16, 60, 55, 33, 8, 29, 7, 36, 7, 55,
+ 79, 48, 1, 7, 55, 2, 7, 17, 37, 7,
+ 33, 60, 29, 7, 33, 7, 66, 33, 33, 7,
+ 66, 29, 7, 36, 20, 7, 7, 29, 33, 36,
+ 36, 24, 5, 36, 5, 7, 36, 5, 1, 60,
+ 7, 36, 7, 2, 79, 2, 33, 8, 8, 7,
+ 1, 7, 36, 36, 8, 1, 36, -1, 8, 36,
+ -1, 2, 36, 8, 55, 7, -1, -1, -1, 17,
+ 60, 60, 48, 48, 60, 7, -1, 55, 8, -1,
+ 33, 36, 61, 6, 48, -1, 33, 15, 8, 10,
+ 8, 60, 36, 36, 7, 8, 8, 20, 8, 61,
+ 8, 33, 8, -1, 8, 40, 34, 77, 60, 8,
+ 8, 8, 61, 79, 50, -1, 51, 50, 54, 8,
+ 60, 54, 61, 62, 61, 62, 56, 61, 62, 40,
+ 61, 62, 61, 62, 55, 40, 56, 61, 62, 12,
+ 51, 42, 60, 15, 61, 62, 51, 7, 60, -1,
+ 60, 8, 53, 61, 60, 31, 60, 40, 56, 61,
+ 62, 60, 34, 60, 29, 61, 62, 56, 51, 61,
+ 62, 61, 62, 25, 25, 27, 27, 8, 25, 25,
+ 27, 27, 12, 25, 57, 27, 38, 38, 29, 29,
+ 63, 38, 38, 25, 15, 27, 38, 12, 25, -1,
+ 27, 61, 62, 8, 61, 62, 38, 25, 8, 27,
+ 75, 38, 25, 34, 27, 36, 25, 15, 27, 8,
+ 38, 86, 61, 62, 8, 38, 25, 57, 27, 38,
+ 61, 62, 15, 63, 75, 75, 34, 29, 36, 38,
+ 36, 29, 57, 8, 29, 86, 86, 25, 63, 27,
+ 7, 34, 91, 36, 29, -1, 61, 62, -1, -1,
+ 38, 61, 62, -1, -1, 61, 62, 25, -1, 27,
+ 47, -1, 61, 62, 29, -1, 60, -1, -1, -1,
+ 38, 18, 19, 75, 61, 62, 29, 75, -1, 29,
+ 75, 66, 67, 68, 86, -1, 61, 62, 86, 15,
+ -1, 86, 29, -1, 61, 62, 18, 19, 45, 46,
+ 29, 66, 67, 68, 91, 29, 15, 33, 34, 29,
+ 36, -1, 29, 66, 67, 68, 66, 67, 68, 29,
+ -1, -1, 29, 45, 46, 34, 29, 36, -1, 66,
+ 67, 68, 29, -1, 15, 29, -1, 66, 67, 68,
+ -1, -1, 66, 67, 68, -1, 66, 67, 68, 66,
+ 67, 68, 33, 34, -1, 36, 66, 67, 68, 66,
+ 67, 68, -1, 66, 67, 68, 23, 24, -1, 66,
+ 67, 68, 66, 67, 68, 32, 23, 24, 35, -1,
+ 37, -1, -1, 29, -1, 32, 29, -1, 35, 29,
+ 37, 18, 19, 36, 23, 24, 36, 29, -1, -1,
+ -1, -1, -1, 32, -1, -1, 35, -1, 37, 29,
+ -1, -1, -1, -1, -1, 61, 62, -1, 45, 46,
+ 66, 67, 68, 66, 67, 68, 66, 67, 68, 61,
+ 62, 23, 24, 29, 66, 67, 68, -1, -1, 31,
+ 32, 61, 62, 35, -1, 37, 66, 67, 68, 23,
+ 24, 29, -1, -1, -1, -1, -1, 31, 32, -1,
+ -1, 35, -1, 37, -1, 61, 62, 23, 24, 29,
+ 66, 67, 68, 23, 24, 31, 32, -1, -1, 35,
+ -1, 37, 32, 61, 62, 35, -1, 37, 66, 67,
+ 68, 92, 93, 94, 95, 96, 97, -1, -1, 3,
+ -1, 61, 62, -1, -1, -1, 66, 67, 68, 13,
+ -1, -1, -1, 17, -1, -1, -1, 3, -1, -1,
+ -1, -1, 26, -1, 28, -1, -1, 13, -1, -1,
+ -1, 17, -1, -1, -1, 39, -1, 41, 42, -1,
+ 26, -1, 28, -1, -1, 49, -1, -1, 52, 53,
+ 23, 24, -1, 39, 58, 41, 42, -1, 31, 32,
+ 64, -1, 35, 49, 37, -1, 52, 53, -1, -1,
+ -1, -1, 58, -1, -1, -1, 80, -1, 64, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, 12,
+ 13, -1, -1, -1, 80, -1, -1, -1, -1, 22,
+ -1, -1, -1, -1, -1, -1, 29, -1, -1, -1,
+ 33, 34, -1, 36, -1, -1, -1, -1, -1, -1,
+ 43, -1, -1, -1, 47, -1, -1, 3, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, 13, -1, -1,
+ -1, 17, 65, 66, 67, 68, -1, 70, -1, -1,
+ 26, -1, 28, -1, -1, 31, -1, -1, 81, 82,
+ 83, -1, -1, 39, 87, 41, 42, -1, -1, -1,
+ -1, -1, -1, 49, -1, -1, 52, 53, -1, -1,
+ -1, -1, 58, -1, -1, -1, -1, -1, 64, -1,
+ -1, -1, -1, -1, -1, -1, 12, 13, -1, -1,
+ -1, -1, -1, -1, 80, -1, 22, -1, -1, -1,
+ -1, -1, -1, 29, -1, -1, -1, 33, 34, -1,
+ 36, -1, -1, -1, 12, 13, -1, 43, -1, -1,
+ -1, 47, -1, -1, 22, -1, -1, -1, -1, -1,
+ -1, 29, -1, -1, -1, 33, 34, -1, 36, 65,
+ 66, 67, 68, -1, 70, 43, -1, -1, -1, 47,
+ -1, -1, -1, -1, -1, 81, 82, 83, -1, -1,
+ -1, 87, -1, -1, -1, -1, -1, 65, 66, 67,
+ 68, -1, 70, -1, 10, -1, 12, 13, -1, -1,
+ -1, -1, -1, 81, 82, 83, 22, -1, -1, 87,
+ -1, -1, -1, 29, -1, -1, -1, 33, 34, -1,
+ 36, -1, 12, 13, -1, -1, -1, 43, -1, -1,
+ -1, 47, 22, -1, -1, -1, -1, -1, -1, 29,
+ -1, -1, -1, 33, 34, -1, 36, -1, -1, 65,
+ 66, 67, 68, 43, 70, -1, -1, 47, -1, 75,
+ -1, -1, -1, -1, -1, 81, 82, 83, 84, -1,
+ -1, 87, -1, -1, -1, 65, 66, 67, 68, -1,
+ 70, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, 81, 82, 83, -1, -1, -1, 87, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ 10, -1, 12, 13, -1, -1, -1, -1, -1, -1,
+ -1, -1, 22, -1, -1, -1, -1, -1, -1, 29,
+ -1, -1, -1, 33, 34, -1, 36, -1, -1, -1,
+ -1, -1, -1, 43, -1, -1, -1, 47, -1, -1,
+ -1, -1, -1, -1, -1, 55, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, 65, 66, 67, 68, -1,
+ 70, -1, -1, -1, -1, 75, -1, -1, -1, -1,
+ -1, 81, 82, 83, 84, -1, -1, 87, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ 10, -1, 12, 13, -1, -1, -1, -1, -1, -1,
+ -1, -1, 22, -1, -1, -1, -1, -1, -1, 29,
+ -1, -1, -1, 33, 34, -1, 36, -1, -1, -1,
+ -1, -1, -1, 43, -1, -1, -1, 47, -1, -1,
+ -1, -1, -1, -1, -1, 55, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, 65, 66, 67, 68, -1,
+ 70, -1, -1, -1, -1, 75, -1, -1, -1, -1,
+ -1, 81, 82, 83, 84, -1, -1, 87, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ 11, 12, 13, -1, -1, -1, -1, -1, -1, -1,
+ -1, 22, -1, -1, -1, -1, -1, -1, 29, -1,
+ -1, -1, 33, 34, -1, 36, -1, -1, -1, 40,
+ -1, 42, 43, 44, -1, -1, 47, -1, -1, -1,
+ 51, -1, 53, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, 65, 66, 67, 68, -1, 70,
+ -1, 72, -1, 74, -1, 76, -1, -1, -1, -1,
+ 81, 82, 83, -1, -1, -1, 87, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, 7,
+ -1, -1, -1, 11, 12, 13, -1, -1, -1, -1,
+ -1, -1, -1, -1, 22, -1, -1, -1, -1, -1,
+ -1, 29, -1, -1, -1, 33, 34, -1, 36, -1,
+ -1, -1, 40, -1, 42, 43, 44, -1, -1, 47,
+ -1, -1, -1, 51, -1, 53, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, 65, 66, 67,
+ 68, -1, 70, -1, 72, -1, 74, -1, 76, -1,
+ -1, -1, -1, 81, 82, 83, -1, -1, -1, 87,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, 11, 12, 13, -1, -1, -1, -1, -1,
+ -1, -1, -1, 22, -1, -1, -1, -1, -1, -1,
+ 29, -1, -1, -1, 33, 34, -1, 36, -1, -1,
+ -1, 40, -1, 42, 43, 44, -1, -1, 47, -1,
+ -1, -1, 51, -1, 53, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, 65, 66, 67, 68,
+ -1, 70, -1, 72, -1, 74, 75, 76, -1, -1,
+ -1, -1, 81, 82, 83, -1, -1, -1, 87, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, 11, 12, 13, -1, -1, -1, -1, -1, -1,
+ -1, -1, 22, -1, -1, -1, -1, -1, -1, 29,
+ 30, -1, -1, 33, 34, -1, 36, -1, -1, -1,
+ 40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
+ -1, 51, -1, 53, -1, -1, -1, -1, -1, -1,
+ -1, 61, -1, -1, -1, 65, 66, 67, 68, -1,
+ 70, -1, 72, -1, 74, -1, 76, -1, -1, -1,
+ -1, 81, 82, 83, -1, -1, -1, 87, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ 8, -1, -1, 11, 12, 13, -1, -1, -1, -1,
+ -1, -1, -1, -1, 22, -1, -1, -1, -1, -1,
+ -1, 29, -1, -1, -1, 33, 34, -1, 36, -1,
+ -1, -1, 40, -1, 42, 43, 44, -1, -1, 47,
+ -1, -1, -1, 51, -1, 53, -1, -1, 56, -1,
+ -1, -1, -1, -1, -1, -1, -1, 65, 66, 67,
+ 68, -1, 70, -1, 72, -1, 74, -1, 76, -1,
+ -1, -1, -1, 81, 82, 83, -1, -1, -1, 87,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, 8, -1, -1, 11, 12, 13, -1, -1,
+ -1, -1, -1, -1, -1, -1, 22, -1, -1, -1,
+ -1, -1, -1, 29, -1, -1, -1, 33, 34, -1,
+ 36, -1, -1, -1, 40, -1, 42, 43, 44, -1,
+ -1, 47, -1, -1, -1, 51, -1, 53, -1, -1,
+ 56, -1, -1, -1, -1, -1, -1, -1, -1, 65,
+ 66, 67, 68, -1, 70, -1, 72, -1, 74, -1,
+ 76, -1, -1, -1, -1, 81, 82, 83, -1, -1,
+ -1, 87, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, 8, -1, -1, 11, 12, 13,
+ -1, -1, -1, -1, -1, -1, -1, -1, 22, -1,
+ -1, -1, -1, -1, -1, 29, -1, -1, -1, 33,
+ 34, -1, 36, -1, -1, -1, 40, -1, 42, 43,
+ 44, -1, -1, 47, -1, -1, -1, 51, -1, 53,
+ -1, -1, 56, -1, -1, -1, -1, -1, -1, -1,
+ -1, 65, 66, 67, 68, -1, 70, -1, 72, -1,
+ 74, -1, 76, -1, -1, -1, -1, 81, 82, 83,
+ -1, -1, -1, 87, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, 8, -1, -1, 11,
+ 12, 13, -1, -1, -1, -1, -1, -1, -1, -1,
+ 22, -1, -1, -1, -1, -1, -1, 29, -1, -1,
+ -1, 33, 34, -1, 36, -1, -1, -1, 40, -1,
+ 42, 43, 44, -1, -1, 47, -1, -1, -1, 51,
+ -1, 53, -1, -1, 56, -1, -1, -1, -1, -1,
+ -1, -1, -1, 65, 66, 67, 68, -1, 70, -1,
+ 72, -1, 74, -1, 76, -1, -1, -1, -1, 81,
+ 82, 83, -1, -1, -1, 87, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, 4, 5,
+ 6, -1, -1, 9, 10, 11, -1, -1, 14, -1,
+ 16, -1, -1, -1, 20, 21, 22, -1, -1, -1,
+ -1, -1, -1, 29, 30, 31, 32, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, 43, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, 59, -1, -1, -1, -1, -1, -1,
+ 66, 67, 68, 69, 70, 71, -1, 73, 74, 75,
+ 76, 77, 78, -1, -1, 81, 82, 83, 84, 85,
+ 86, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, 4, 5, 6, -1, -1, 9,
+ 10, 11, -1, -1, 14, -1, 16, -1, -1, -1,
+ 20, 21, 22, -1, -1, -1, -1, -1, -1, 29,
+ 30, 31, 32, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, 43, -1, -1, -1, 47, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, 59,
+ -1, -1, -1, -1, -1, 65, 66, 67, -1, 69,
+ 70, 71, -1, 73, 74, 75, 76, 77, 78, -1,
+ -1, 81, 82, 83, 84, 85, 86, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ 4, 5, 6, -1, -1, 9, 10, 11, -1, -1,
+ 14, -1, 16, -1, -1, -1, 20, 21, 22, -1,
+ -1, -1, -1, -1, -1, 29, 30, 31, 32, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, 43,
+ -1, -1, -1, 47, -1, -1, -1, -1, -1, -1,
+ -1, 55, -1, -1, -1, 59, -1, -1, -1, -1,
+ -1, 65, 66, 67, -1, 69, 70, 71, -1, 73,
+ 74, 75, 76, 77, 78, -1, -1, 81, 82, 83,
+ 84, 85, 86, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, 4, -1, -1, -1,
+ -1, 9, -1, 11, 12, 13, 14, -1, -1, -1,
+ -1, -1, -1, 21, 22, -1, -1, -1, -1, -1,
+ -1, 29, 30, -1, -1, 33, 34, -1, 36, -1,
+ -1, -1, 40, -1, 42, 43, 44, -1, -1, 47,
+ -1, -1, -1, 51, -1, 53, -1, -1, -1, -1,
+ -1, 59, -1, 61, -1, -1, -1, 65, 66, 67,
+ 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
+ 78, -1, -1, 81, 82, 83, 84, 85, -1, 87,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, 4, -1, -1, -1, -1, 9, -1, 11,
+ 12, 13, 14, -1, -1, -1, -1, -1, -1, 21,
+ 22, -1, -1, -1, -1, -1, -1, 29, 30, -1,
+ -1, 33, 34, -1, 36, -1, -1, -1, 40, -1,
+ 42, 43, 44, -1, -1, 47, -1, -1, -1, 51,
+ -1, 53, -1, -1, -1, -1, -1, 59, -1, 61,
+ -1, -1, -1, 65, 66, 67, 68, 69, 70, 71,
+ 72, 73, 74, 75, 76, 77, 78, -1, -1, 81,
+ 82, 83, 84, 85, -1, 87, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, 4, 5,
+ 6, -1, -1, 9, 10, 11, 12, 13, 14, -1,
+ 16, -1, -1, -1, 20, 21, 22, -1, -1, -1,
+ -1, -1, -1, 29, 30, 31, 32, 33, 34, -1,
+ 36, -1, -1, -1, 40, -1, 42, 43, 44, -1,
+ -1, 47, -1, -1, -1, 51, -1, 53, -1, -1,
+ -1, -1, -1, 59, -1, 61, -1, -1, -1, 65,
+ 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
+ 76, 77, 78, -1, -1, 81, 82, 83, 84, 85,
+ 86, 87, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, 4, 5, 6, -1, -1, 9,
+ 10, 11, 12, 13, 14, -1, 16, -1, -1, -1,
+ 20, 21, 22, -1, -1, -1, -1, -1, -1, 29,
+ 30, 31, 32, 33, 34, -1, 36, -1, -1, -1,
+ 40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
+ -1, 51, -1, 53, -1, 55, -1, -1, -1, 59,
+ -1, 61, -1, -1, -1, 65, 66, 67, 68, 69,
+ 70, 71, 72, 73, 74, 75, 76, 77, 78, -1,
+ -1, 81, 82, 83, 84, 85, 86, 87, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+
+ 3, 2, 15, 25, 25, 3, 25, 3, 2, 11,
+ 2, 15, 3, 13, 67, 3, 15, 104, 15, 2,
+ 15, 2, 4, 3, 35, 15, 15, 3, 21, 3,
+ 93, 15, 2, 2, 19, 13, 15, 96, 25, 25,
+ 15, 3, 15, 15, 15, 100, 3, 3, 15, 2,
+ 2, 15, 3, 21, 4, 15, 15, 15, 35, 2,
+ 21, 2, 2, 2, 98, 3, 2, 2, 2, 35,
+ 35, 4, 35, 2, 21, 3, 3, 3, 15, 2,
+ 35, 35, 3, 3, 3, 3, 35, 35, 2, 35,
+ 21, 35, -1, 35, -1, -1, 13, 2, 13, 44,
+ 2, 46, 3, 3, 36, -1, -1, -1, 3, -1,
+ -1, 15, -1, 35, 44, -1, 46, 13, 40, 44,
+ 44, 46, 46, -1, 41, 15, 41, -1, 44, 15,
+ 46, 44, 44, 46, 44, 44, 44, 44, 44, 49,
+ 49, 44, 49, 49, 35, 41, 49, 37, 60, 40,
+ 58, 44, 44, 46, 46, 44, 44, 44, 3, 44,
+ 49, 46, 50, 50, 31, 44, 44, 68, 35, 44,
+ 48, 50, 44, 68, 44, 50, 81, 49, 48, 81,
+ 44, 85, 44, 44, 44, 49, 48, 44, 49, 49,
+ 44, 44, 49, 44, 44, 49, 46, 44, 44, 52,
+ 46, 44, 44, 46, 46, 56, 44, 54, 46, 15,
+ 3, 44, 44, 99, 47, 47, 44, 44, 46, 46,
+ 44, 44, 46, 68, 15, 13, 49, 44, 44, 44,
+ 44, 44, 49, 49, 49, 49, 49, -1, 61, 53,
+ 28, 29, 55, -1, -1, -1, 37, 38, 44, 66,
+ 66, 66, 44, 49, 44, 51, -1, 49, 44, 49,
+ -1, 44, -1, 49, 44, -1, 49, 57, 44, 49,
+ 46, 51, 44, -1, 66, 68, 59, 49, 44, 51,
+ 66, 87, 5, 49, 13, 51, 13, 16, 5, 16,
+ 13, 20, 13, 20, -1, -1, 13, -1, -1, 20,
+ 21, 22, 23, 24, -1, 28, 29, -1, 35, -1,
+ -1, 28, 29, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ 13, -1, -1, 16, -1, -1, -1, 20, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1};
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/parser/qmljsgrammar_p.h b/src/declarative/qml/parser/qmljsgrammar_p.h
new file mode 100644
index 0000000..c2e2693
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsgrammar_p.h
@@ -0,0 +1,209 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of other Qt classes. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+// This file was generated by qlalr - DO NOT EDIT!
+#ifndef QMLJSGRAMMAR_P_H
+#define QMLJSGRAMMAR_P_H
+
+#include <QtCore/qglobal.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlJSGrammar
+{
+public:
+ enum VariousConstants {
+ EOF_SYMBOL = 0,
+ REDUCE_HERE = 99,
+ SHIFT_THERE = 98,
+ T_AND = 1,
+ T_AND_AND = 2,
+ T_AND_EQ = 3,
+ T_AS = 91,
+ T_AUTOMATIC_SEMICOLON = 62,
+ T_BREAK = 4,
+ T_CASE = 5,
+ T_CATCH = 6,
+ T_COLON = 7,
+ T_COMMA = 8,
+ T_COMMENT = 88,
+ T_CONST = 84,
+ T_CONTINUE = 9,
+ T_DEBUGGER = 85,
+ T_DEFAULT = 10,
+ T_DELETE = 11,
+ T_DIVIDE_ = 12,
+ T_DIVIDE_EQ = 13,
+ T_DO = 14,
+ T_DOT = 15,
+ T_ELSE = 16,
+ T_EQ = 17,
+ T_EQ_EQ = 18,
+ T_EQ_EQ_EQ = 19,
+ T_FALSE = 83,
+ T_FEED_JS_EXPRESSION = 95,
+ T_FEED_JS_PROGRAM = 97,
+ T_FEED_JS_SOURCE_ELEMENT = 96,
+ T_FEED_JS_STATEMENT = 94,
+ T_FEED_UI_OBJECT_MEMBER = 93,
+ T_FEED_UI_PROGRAM = 92,
+ T_FINALLY = 20,
+ T_FOR = 21,
+ T_FUNCTION = 22,
+ T_GE = 23,
+ T_GT = 24,
+ T_GT_GT = 25,
+ T_GT_GT_EQ = 26,
+ T_GT_GT_GT = 27,
+ T_GT_GT_GT_EQ = 28,
+ T_IDENTIFIER = 29,
+ T_IF = 30,
+ T_IMPORT = 90,
+ T_IN = 31,
+ T_INSTANCEOF = 32,
+ T_LBRACE = 33,
+ T_LBRACKET = 34,
+ T_LE = 35,
+ T_LPAREN = 36,
+ T_LT = 37,
+ T_LT_LT = 38,
+ T_LT_LT_EQ = 39,
+ T_MINUS = 40,
+ T_MINUS_EQ = 41,
+ T_MINUS_MINUS = 42,
+ T_MULTILINE_STRING_LITERAL = 87,
+ T_NEW = 43,
+ T_NOT = 44,
+ T_NOT_EQ = 45,
+ T_NOT_EQ_EQ = 46,
+ T_NULL = 81,
+ T_NUMERIC_LITERAL = 47,
+ T_OR = 48,
+ T_OR_EQ = 49,
+ T_OR_OR = 50,
+ T_PLUS = 51,
+ T_PLUS_EQ = 52,
+ T_PLUS_PLUS = 53,
+ T_PROPERTY = 66,
+ T_PUBLIC = 89,
+ T_QUESTION = 54,
+ T_RBRACE = 55,
+ T_RBRACKET = 56,
+ T_READONLY = 68,
+ T_REMAINDER = 57,
+ T_REMAINDER_EQ = 58,
+ T_RESERVED_WORD = 86,
+ T_RETURN = 59,
+ T_RPAREN = 60,
+ T_SEMICOLON = 61,
+ T_SIGNAL = 67,
+ T_STAR = 63,
+ T_STAR_EQ = 64,
+ T_STRING_LITERAL = 65,
+ T_SWITCH = 69,
+ T_THIS = 70,
+ T_THROW = 71,
+ T_TILDE = 72,
+ T_TRUE = 82,
+ T_TRY = 73,
+ T_TYPEOF = 74,
+ T_VAR = 75,
+ T_VOID = 76,
+ T_WHILE = 77,
+ T_WITH = 78,
+ T_XOR = 79,
+ T_XOR_EQ = 80,
+
+ ACCEPT_STATE = 635,
+ RULE_COUNT = 343,
+ STATE_COUNT = 636,
+ TERMINAL_COUNT = 100,
+ NON_TERMINAL_COUNT = 106,
+
+ GOTO_INDEX_OFFSET = 636,
+ GOTO_INFO_OFFSET = 2520,
+ GOTO_CHECK_OFFSET = 2520
+ };
+
+ static const char *const spell [];
+ static const short lhs [];
+ static const short rhs [];
+ static const short goto_default [];
+ static const short action_default [];
+ static const short action_index [];
+ static const short action_info [];
+ static const short action_check [];
+
+ static inline int nt_action (int state, int nt)
+ {
+ const int yyn = action_index [GOTO_INDEX_OFFSET + state] + nt;
+ if (yyn < 0 || action_check [GOTO_CHECK_OFFSET + yyn] != nt)
+ return goto_default [nt];
+
+ return action_info [GOTO_INFO_OFFSET + yyn];
+ }
+
+ static inline int t_action (int state, int token)
+ {
+ const int yyn = action_index [state] + token;
+
+ if (yyn < 0 || action_check [yyn] != token)
+ return - action_default [state];
+
+ return action_info [yyn];
+ }
+};
+
+
+QT_END_NAMESPACE
+#endif // QMLJSGRAMMAR_P_H
+
diff --git a/src/declarative/qml/parser/qmljslexer.cpp b/src/declarative/qml/parser/qmljslexer.cpp
new file mode 100644
index 0000000..cf3ed34
--- /dev/null
+++ b/src/declarative/qml/parser/qmljslexer.cpp
@@ -0,0 +1,1161 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "qmljslexer_p.h"
+
+#include "qmljsglobal_p.h"
+#include "qmljsengine_p.h"
+#include "qmljsgrammar_p.h"
+
+#include <QtCore/qcoreapplication.h>
+
+#include <ctype.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+QT_QML_BEGIN_NAMESPACE
+
+extern double qstrtod(const char *s00, char const **se, bool *ok);
+
+#define shiftWindowsLineBreak() \
+ do { \
+ if (((current == '\r') && (next1 == '\n')) \
+ || ((current == '\n') && (next1 == '\r'))) { \
+ shift(1); \
+ } \
+ } \
+ while (0)
+
+namespace QmlJS {
+extern double integerFromString(const char *buf, int size, int radix);
+}
+
+using namespace QmlJS;
+
+Lexer::Lexer(Engine *eng, bool tokenizeComments)
+ : driver(eng),
+ yylineno(0),
+ done(false),
+ size8(128), size16(128),
+ pos8(0), pos16(0),
+ terminator(false),
+ restrKeyword(false),
+ delimited(false),
+ stackToken(-1),
+ state(Start),
+ pos(0),
+ code(0), length(0),
+ yycolumn(0),
+ startpos(0),
+ startlineno(0), startcolumn(0),
+ bol(true),
+ current(0), next1(0), next2(0), next3(0),
+ err(NoError),
+ wantRx(false),
+ check_reserved(true),
+ parenthesesState(IgnoreParentheses),
+ parenthesesCount(0),
+ prohibitAutomaticSemicolon(false),
+ tokenizeComments(tokenizeComments)
+{
+ driver->setLexer(this);
+ // allocate space for read buffers
+ buffer8 = new char[size8];
+ buffer16 = new QChar[size16];
+ pattern = 0;
+ flags = 0;
+
+}
+
+Lexer::~Lexer()
+{
+ delete [] buffer8;
+ delete [] buffer16;
+}
+
+void Lexer::setCode(const QString &c, int lineno)
+{
+ errmsg = QString();
+ yylineno = lineno;
+ yycolumn = 1;
+ restrKeyword = false;
+ delimited = false;
+ stackToken = -1;
+ pos = 0;
+ code = c.unicode();
+ length = c.length();
+ bol = true;
+
+ // read first characters
+ current = (length > 0) ? code[0].unicode() : 0;
+ next1 = (length > 1) ? code[1].unicode() : 0;
+ next2 = (length > 2) ? code[2].unicode() : 0;
+ next3 = (length > 3) ? code[3].unicode() : 0;
+}
+
+void Lexer::shift(uint p)
+{
+ while (p--) {
+ ++pos;
+ ++yycolumn;
+ current = next1;
+ next1 = next2;
+ next2 = next3;
+ next3 = (pos + 3 < length) ? code[pos+3].unicode() : 0;
+ }
+}
+
+void Lexer::setDone(State s)
+{
+ state = s;
+ done = true;
+}
+
+int Lexer::findReservedWord(const QChar *c, int size) const
+{
+ switch (size) {
+ case 2: {
+ if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('o'))
+ return QmlJSGrammar::T_DO;
+ else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('f'))
+ return QmlJSGrammar::T_IF;
+ else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n'))
+ return QmlJSGrammar::T_IN;
+ else if (c[0] == QLatin1Char('a') && c[1] == QLatin1Char('s'))
+ return QmlJSGrammar::T_AS;
+ } break;
+
+ case 3: {
+ if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('o') && c[2] == QLatin1Char('r'))
+ return QmlJSGrammar::T_FOR;
+ else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('e') && c[2] == QLatin1Char('w'))
+ return QmlJSGrammar::T_NEW;
+ else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r') && c[2] == QLatin1Char('y'))
+ return QmlJSGrammar::T_TRY;
+ else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('a') && c[2] == QLatin1Char('r'))
+ return QmlJSGrammar::T_VAR;
+ else if (check_reserved) {
+ if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n') && c[2] == QLatin1Char('t'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ }
+ } break;
+
+ case 4: {
+ if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('a')
+ && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('e'))
+ return QmlJSGrammar::T_CASE;
+ else if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('l')
+ && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('e'))
+ return QmlJSGrammar::T_ELSE;
+ else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h')
+ && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('s'))
+ return QmlJSGrammar::T_THIS;
+ else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('o')
+ && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('d'))
+ return QmlJSGrammar::T_VOID;
+ else if (c[0] == QLatin1Char('w') && c[1] == QLatin1Char('i')
+ && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('h'))
+ return QmlJSGrammar::T_WITH;
+ else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r')
+ && c[2] == QLatin1Char('u') && c[3] == QLatin1Char('e'))
+ return QmlJSGrammar::T_TRUE;
+ else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('u')
+ && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('l'))
+ return QmlJSGrammar::T_NULL;
+ else if (check_reserved) {
+ if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('n')
+ && c[2] == QLatin1Char('u') && c[3] == QLatin1Char('m'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('y')
+ && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('l') && c[1] == QLatin1Char('o')
+ && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('g'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('h')
+ && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('r'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('g') && c[1] == QLatin1Char('o')
+ && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('o'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ }
+ } break;
+
+ case 5: {
+ if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('r')
+ && c[2] == QLatin1Char('e') && c[3] == QLatin1Char('a')
+ && c[4] == QLatin1Char('k'))
+ return QmlJSGrammar::T_BREAK;
+ else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('a')
+ && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('c')
+ && c[4] == QLatin1Char('h'))
+ return QmlJSGrammar::T_CATCH;
+ else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h')
+ && c[2] == QLatin1Char('r') && c[3] == QLatin1Char('o')
+ && c[4] == QLatin1Char('w'))
+ return QmlJSGrammar::T_THROW;
+ else if (c[0] == QLatin1Char('w') && c[1] == QLatin1Char('h')
+ && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('l')
+ && c[4] == QLatin1Char('e'))
+ return QmlJSGrammar::T_WHILE;
+ else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('o')
+ && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('s')
+ && c[4] == QLatin1Char('t'))
+ return QmlJSGrammar::T_CONST;
+ else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('a')
+ && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('s')
+ && c[4] == QLatin1Char('e'))
+ return QmlJSGrammar::T_FALSE;
+ else if (check_reserved) {
+ if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('h')
+ && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('r')
+ && c[4] == QLatin1Char('t'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('u')
+ && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('e')
+ && c[4] == QLatin1Char('r'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('i')
+ && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('a')
+ && c[4] == QLatin1Char('l'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('l')
+ && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('s')
+ && c[4] == QLatin1Char('s'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('l')
+ && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('a')
+ && c[4] == QLatin1Char('t'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ }
+ } break;
+
+ case 6: {
+ if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e')
+ && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('e')
+ && c[4] == QLatin1Char('t') && c[5] == QLatin1Char('e'))
+ return QmlJSGrammar::T_DELETE;
+ else if (c[0] == QLatin1Char('r') && c[1] == QLatin1Char('e')
+ && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('u')
+ && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('n'))
+ return QmlJSGrammar::T_RETURN;
+ else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('w')
+ && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('t')
+ && c[4] == QLatin1Char('c') && c[5] == QLatin1Char('h'))
+ return QmlJSGrammar::T_SWITCH;
+ else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('y')
+ && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('e')
+ && c[4] == QLatin1Char('o') && c[5] == QLatin1Char('f'))
+ return QmlJSGrammar::T_TYPEOF;
+ else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m')
+ && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o')
+ && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t'))
+ return QmlJSGrammar::T_IMPORT;
+ else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('i')
+ && c[2] == QLatin1Char('g') && c[3] == QLatin1Char('n')
+ && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('l'))
+ return QmlJSGrammar::T_SIGNAL;
+ else if (check_reserved) {
+ if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('x')
+ && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o')
+ && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('t')
+ && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('t')
+ && c[4] == QLatin1Char('i') && c[5] == QLatin1Char('c'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('o')
+ && c[2] == QLatin1Char('u') && c[3] == QLatin1Char('b')
+ && c[4] == QLatin1Char('l') && c[5] == QLatin1Char('e'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m')
+ && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o')
+ && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('u')
+ && c[2] == QLatin1Char('b') && c[3] == QLatin1Char('l')
+ && c[4] == QLatin1Char('i') && c[5] == QLatin1Char('c'))
+ return QmlJSGrammar::T_PUBLIC;
+ else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('a')
+ && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('i')
+ && c[4] == QLatin1Char('v') && c[5] == QLatin1Char('e'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h')
+ && c[2] == QLatin1Char('r') && c[3] == QLatin1Char('o')
+ && c[4] == QLatin1Char('w') && c[5] == QLatin1Char('s'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ }
+ } break;
+
+ case 7: {
+ if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e')
+ && c[2] == QLatin1Char('f') && c[3] == QLatin1Char('a')
+ && c[4] == QLatin1Char('u') && c[5] == QLatin1Char('l')
+ && c[6] == QLatin1Char('t'))
+ return QmlJSGrammar::T_DEFAULT;
+ else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('i')
+ && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('a')
+ && c[4] == QLatin1Char('l') && c[5] == QLatin1Char('l')
+ && c[6] == QLatin1Char('y'))
+ return QmlJSGrammar::T_FINALLY;
+ else if (check_reserved) {
+ if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('o')
+ && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('l')
+ && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('a')
+ && c[6] == QLatin1Char('n'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('x')
+ && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e')
+ && c[4] == QLatin1Char('n') && c[5] == QLatin1Char('d')
+ && c[6] == QLatin1Char('s'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('a')
+ && c[2] == QLatin1Char('c') && c[3] == QLatin1Char('k')
+ && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('g')
+ && c[6] == QLatin1Char('e'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r')
+ && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('v')
+ && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('t')
+ && c[6] == QLatin1Char('e'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ }
+ } break;
+
+ case 8: {
+ if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('o')
+ && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('t')
+ && c[4] == QLatin1Char('i') && c[5] == QLatin1Char('n')
+ && c[6] == QLatin1Char('u') && c[7] == QLatin1Char('e'))
+ return QmlJSGrammar::T_CONTINUE;
+ else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('u')
+ && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('c')
+ && c[4] == QLatin1Char('t') && c[5] == QLatin1Char('i')
+ && c[6] == QLatin1Char('o') && c[7] == QLatin1Char('n'))
+ return QmlJSGrammar::T_FUNCTION;
+ else if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e')
+ && c[2] == QLatin1Char('b') && c[3] == QLatin1Char('u')
+ && c[4] == QLatin1Char('g') && c[5] == QLatin1Char('g')
+ && c[6] == QLatin1Char('e') && c[7] == QLatin1Char('r'))
+ return QmlJSGrammar::T_DEBUGGER;
+ else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r')
+ && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('p')
+ && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('r')
+ && c[6] == QLatin1Char('t') && c[7] == QLatin1Char('y'))
+ return QmlJSGrammar::T_PROPERTY;
+ else if (c[0] == QLatin1Char('r') && c[1] == QLatin1Char('e')
+ && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('d')
+ && c[4] == QLatin1Char('o') && c[5] == QLatin1Char('n')
+ && c[6] == QLatin1Char('l') && c[7] == QLatin1Char('y'))
+ return QmlJSGrammar::T_READONLY;
+ else if (check_reserved) {
+ if (c[0] == QLatin1Char('a') && c[1] == QLatin1Char('b')
+ && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('t')
+ && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('a')
+ && c[6] == QLatin1Char('c') && c[7] == QLatin1Char('t'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('o')
+ && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('a')
+ && c[4] == QLatin1Char('t') && c[5] == QLatin1Char('i')
+ && c[6] == QLatin1Char('l') && c[7] == QLatin1Char('e'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ }
+ } break;
+
+ case 9: {
+ if (check_reserved) {
+ if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n')
+ && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e')
+ && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('f')
+ && c[6] == QLatin1Char('a') && c[7] == QLatin1Char('c')
+ && c[8] == QLatin1Char('e'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r')
+ && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('n')
+ && c[4] == QLatin1Char('s') && c[5] == QLatin1Char('i')
+ && c[6] == QLatin1Char('e') && c[7] == QLatin1Char('n')
+ && c[8] == QLatin1Char('t'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r')
+ && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('t')
+ && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('c')
+ && c[6] == QLatin1Char('t') && c[7] == QLatin1Char('e')
+ && c[8] == QLatin1Char('d'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ }
+ } break;
+
+ case 10: {
+ if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n')
+ && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('t')
+ && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('n')
+ && c[6] == QLatin1Char('c') && c[7] == QLatin1Char('e')
+ && c[8] == QLatin1Char('o') && c[9] == QLatin1Char('f'))
+ return QmlJSGrammar::T_INSTANCEOF;
+ else if (check_reserved) {
+ if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m')
+ && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('l')
+ && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('m')
+ && c[6] == QLatin1Char('e') && c[7] == QLatin1Char('n')
+ && c[8] == QLatin1Char('t') && c[9] == QLatin1Char('s'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ }
+ } break;
+
+ case 12: {
+ if (check_reserved) {
+ if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('y')
+ && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('c')
+ && c[4] == QLatin1Char('h') && c[5] == QLatin1Char('r')
+ && c[6] == QLatin1Char('o') && c[7] == QLatin1Char('n')
+ && c[8] == QLatin1Char('i') && c[9] == QLatin1Char('z')
+ && c[10] == QLatin1Char('e') && c[11] == QLatin1Char('d'))
+ return QmlJSGrammar::T_RESERVED_WORD;
+ }
+ } break;
+
+ } // switch
+
+ return -1;
+}
+
+int Lexer::lex()
+{
+ int token = 0;
+ state = Start;
+ ushort stringType = 0; // either single or double quotes
+ bool multiLineString = false;
+ pos8 = pos16 = 0;
+ done = false;
+ terminator = false;
+
+ // did we push a token on the stack previously ?
+ // (after an automatic semicolon insertion)
+ if (stackToken >= 0) {
+ setDone(Other);
+ token = stackToken;
+ stackToken = -1;
+ }
+
+ while (!done) {
+ switch (state) {
+ case Start:
+ if (isWhiteSpace()) {
+ // do nothing
+ } else if (current == '/' && next1 == '/') {
+ recordStartPos();
+ shift(1);
+ state = InSingleLineComment;
+ } else if (current == '/' && next1 == '*') {
+ recordStartPos();
+ shift(1);
+ state = InMultiLineComment;
+ } else if (current == 0) {
+ syncProhibitAutomaticSemicolon();
+ if (!terminator && !delimited && !prohibitAutomaticSemicolon) {
+ // automatic semicolon insertion if program incomplete
+ token = QmlJSGrammar::T_SEMICOLON;
+ stackToken = 0;
+ setDone(Other);
+ } else {
+ setDone(Eof);
+ }
+ } else if (isLineTerminator()) {
+ shiftWindowsLineBreak();
+ yylineno++;
+ yycolumn = 0;
+ bol = true;
+ terminator = true;
+ syncProhibitAutomaticSemicolon();
+ if (restrKeyword) {
+ token = QmlJSGrammar::T_SEMICOLON;
+ setDone(Other);
+ }
+ } else if (current == '"' || current == '\'') {
+ recordStartPos();
+ state = InString;
+ multiLineString = false;
+ stringType = current;
+ } else if (isIdentLetter(current)) {
+ recordStartPos();
+ record16(current);
+ state = InIdentifier;
+ } else if (current == '0') {
+ recordStartPos();
+ record8(current);
+ state = InNum0;
+ } else if (isDecimalDigit(current)) {
+ recordStartPos();
+ record8(current);
+ state = InNum;
+ } else if (current == '.' && isDecimalDigit(next1)) {
+ recordStartPos();
+ record8(current);
+ state = InDecimal;
+ } else {
+ recordStartPos();
+ token = matchPunctuator(current, next1, next2, next3);
+ if (token != -1) {
+ if (terminator && !delimited && !prohibitAutomaticSemicolon
+ && (token == QmlJSGrammar::T_PLUS_PLUS
+ || token == QmlJSGrammar::T_MINUS_MINUS)) {
+ // automatic semicolon insertion
+ stackToken = token;
+ token = QmlJSGrammar::T_SEMICOLON;
+ }
+ setDone(Other);
+ }
+ else {
+ setDone(Bad);
+ err = IllegalCharacter;
+ errmsg = QCoreApplication::translate("QmlParser", "Illegal character");
+ }
+ }
+ break;
+ case InString:
+ if (current == stringType) {
+ shift(1);
+ setDone(String);
+ } else if (isLineTerminator()) {
+ multiLineString = true;
+ record16(current);
+ } else if (current == 0 || isLineTerminator()) {
+ setDone(Bad);
+ err = UnclosedStringLiteral;
+ errmsg = QCoreApplication::translate("QmlParser", "Unclosed string at end of line");
+ } else if (current == '\\') {
+ state = InEscapeSequence;
+ } else {
+ record16(current);
+ }
+ break;
+ // Escape Sequences inside of strings
+ case InEscapeSequence:
+ if (isOctalDigit(current)) {
+ if (current >= '0' && current <= '3' &&
+ isOctalDigit(next1) && isOctalDigit(next2)) {
+ record16(convertOctal(current, next1, next2));
+ shift(2);
+ state = InString;
+ } else if (isOctalDigit(current) &&
+ isOctalDigit(next1)) {
+ record16(convertOctal('0', current, next1));
+ shift(1);
+ state = InString;
+ } else if (isOctalDigit(current)) {
+ record16(convertOctal('0', '0', current));
+ state = InString;
+ } else {
+ setDone(Bad);
+ err = IllegalEscapeSequence;
+ errmsg = QCoreApplication::translate("QmlParser", "Illegal escape squence");
+ }
+ } else if (current == 'x')
+ state = InHexEscape;
+ else if (current == 'u')
+ state = InUnicodeEscape;
+ else {
+ if (isLineTerminator()) {
+ shiftWindowsLineBreak();
+ yylineno++;
+ yycolumn = 0;
+ bol = true;
+ } else {
+ record16(singleEscape(current));
+ }
+ state = InString;
+ }
+ break;
+ case InHexEscape:
+ if (isHexDigit(current) && isHexDigit(next1)) {
+ state = InString;
+ record16(QLatin1Char(convertHex(current, next1)));
+ shift(1);
+ } else if (current == stringType) {
+ record16(QLatin1Char('x'));
+ shift(1);
+ setDone(String);
+ } else {
+ record16(QLatin1Char('x'));
+ record16(current);
+ state = InString;
+ }
+ break;
+ case InUnicodeEscape:
+ if (isHexDigit(current) && isHexDigit(next1) &&
+ isHexDigit(next2) && isHexDigit(next3)) {
+ record16(convertUnicode(current, next1, next2, next3));
+ shift(3);
+ state = InString;
+ } else if (current == stringType) {
+ record16(QLatin1Char('u'));
+ shift(1);
+ setDone(String);
+ } else {
+ setDone(Bad);
+ err = IllegalUnicodeEscapeSequence;
+ errmsg = QCoreApplication::translate("QmlParser", "Illegal unicode escape sequence");
+ }
+ break;
+ case InSingleLineComment:
+ if (isLineTerminator()) {
+ shiftWindowsLineBreak();
+ yylineno++;
+ yycolumn = 0;
+ terminator = true;
+ bol = true;
+ if (restrKeyword) {
+ token = QmlJSGrammar::T_SEMICOLON;
+ setDone(Other);
+ } else
+ state = Start;
+ driver->addComment(startpos, tokenLength(), startlineno, startcolumn);
+ } else if (current == 0) {
+ driver->addComment(startpos, tokenLength(), startlineno, startcolumn);
+ setDone(Eof);
+ }
+
+ break;
+ case InMultiLineComment:
+ if (current == 0) {
+ setDone(Bad);
+ err = UnclosedComment;
+ errmsg = QCoreApplication::translate("QmlParser", "Unclosed comment at end of file");
+ driver->addComment(startpos, tokenLength(), startlineno, startcolumn);
+ } else if (isLineTerminator()) {
+ shiftWindowsLineBreak();
+ yylineno++;
+ } else if (current == '*' && next1 == '/') {
+ state = Start;
+ shift(1);
+ driver->addComment(startpos, tokenLength(), startlineno, startcolumn);
+ }
+
+ break;
+ case InIdentifier:
+ if (isIdentLetter(current) || isDecimalDigit(current)) {
+ record16(current);
+ break;
+ }
+ setDone(Identifier);
+ break;
+ case InNum0:
+ if (current == 'x' || current == 'X') {
+ record8(current);
+ state = InHex;
+ } else if (current == '.') {
+ record8(current);
+ state = InDecimal;
+ } else if (current == 'e' || current == 'E') {
+ record8(current);
+ state = InExponentIndicator;
+ } else if (isOctalDigit(current)) {
+ record8(current);
+ state = InOctal;
+ } else if (isDecimalDigit(current)) {
+ record8(current);
+ state = InDecimal;
+ } else {
+ setDone(Number);
+ }
+ break;
+ case InHex:
+ if (isHexDigit(current))
+ record8(current);
+ else
+ setDone(Hex);
+ break;
+ case InOctal:
+ if (isOctalDigit(current)) {
+ record8(current);
+ } else if (isDecimalDigit(current)) {
+ record8(current);
+ state = InDecimal;
+ } else {
+ setDone(Octal);
+ }
+ break;
+ case InNum:
+ if (isDecimalDigit(current)) {
+ record8(current);
+ } else if (current == '.') {
+ record8(current);
+ state = InDecimal;
+ } else if (current == 'e' || current == 'E') {
+ record8(current);
+ state = InExponentIndicator;
+ } else {
+ setDone(Number);
+ }
+ break;
+ case InDecimal:
+ if (isDecimalDigit(current)) {
+ record8(current);
+ } else if (current == 'e' || current == 'E') {
+ record8(current);
+ state = InExponentIndicator;
+ } else {
+ setDone(Number);
+ }
+ break;
+ case InExponentIndicator:
+ if (current == '+' || current == '-') {
+ record8(current);
+ } else if (isDecimalDigit(current)) {
+ record8(current);
+ state = InExponent;
+ } else {
+ setDone(Bad);
+ err = IllegalExponentIndicator;
+ errmsg = QCoreApplication::translate("QmlParser", "Illegal syntax for exponential number");
+ }
+ break;
+ case InExponent:
+ if (isDecimalDigit(current)) {
+ record8(current);
+ } else {
+ setDone(Number);
+ }
+ break;
+ default:
+ Q_ASSERT_X(0, "Lexer::lex", "Unhandled state in switch statement");
+ }
+
+ // move on to the next character
+ if (!done)
+ shift(1);
+ if (state != Start && state != InSingleLineComment)
+ bol = false;
+ }
+
+ // no identifiers allowed directly after numeric literal, e.g. "3in" is bad
+ if ((state == Number || state == Octal || state == Hex)
+ && isIdentLetter(current)) {
+ state = Bad;
+ err = IllegalIdentifier;
+ errmsg = QCoreApplication::translate("QmlParser", "Identifier cannot start with numeric literal");
+ }
+
+ // terminate string
+ buffer8[pos8] = '\0';
+
+ double dval = 0;
+ if (state == Number) {
+ dval = qstrtod(buffer8, 0, 0);
+ } else if (state == Hex) { // scan hex numbers
+ dval = integerFromString(buffer8, pos8, 16);
+ state = Number;
+ } else if (state == Octal) { // scan octal number
+ dval = integerFromString(buffer8, pos8, 8);
+ state = Number;
+ }
+
+ restrKeyword = false;
+ delimited = false;
+
+ switch (parenthesesState) {
+ case IgnoreParentheses:
+ break;
+ case CountParentheses:
+ if (token == QmlJSGrammar::T_RPAREN) {
+ --parenthesesCount;
+ if (parenthesesCount == 0)
+ parenthesesState = BalancedParentheses;
+ } else if (token == QmlJSGrammar::T_LPAREN) {
+ ++parenthesesCount;
+ }
+ break;
+ case BalancedParentheses:
+ parenthesesState = IgnoreParentheses;
+ break;
+ }
+
+ switch (state) {
+ case Eof:
+ return 0;
+ case Other:
+ if (token == QmlJSGrammar::T_RBRACE || token == QmlJSGrammar::T_SEMICOLON)
+ delimited = true;
+ return token;
+ case Identifier:
+ if ((token = findReservedWord(buffer16, pos16)) < 0) {
+ /* TODO: close leak on parse error. same holds true for String */
+ if (driver)
+ qsyylval.ustr = driver->intern(buffer16, pos16);
+ else
+ qsyylval.ustr = 0;
+ return QmlJSGrammar::T_IDENTIFIER;
+ }
+ if (token == QmlJSGrammar::T_CONTINUE || token == QmlJSGrammar::T_BREAK
+ || token == QmlJSGrammar::T_RETURN || token == QmlJSGrammar::T_THROW) {
+ restrKeyword = true;
+ } else if (token == QmlJSGrammar::T_IF || token == QmlJSGrammar::T_FOR
+ || token == QmlJSGrammar::T_WHILE || token == QmlJSGrammar::T_WITH) {
+ parenthesesState = CountParentheses;
+ parenthesesCount = 0;
+ } else if (token == QmlJSGrammar::T_DO) {
+ parenthesesState = BalancedParentheses;
+ }
+ return token;
+ case String:
+ if (driver)
+ qsyylval.ustr = driver->intern(buffer16, pos16);
+ else
+ qsyylval.ustr = 0;
+ return multiLineString?QmlJSGrammar::T_MULTILINE_STRING_LITERAL:QmlJSGrammar::T_STRING_LITERAL;
+ case Number:
+ qsyylval.dval = dval;
+ return QmlJSGrammar::T_NUMERIC_LITERAL;
+ case Bad:
+ return -1;
+ default:
+ Q_ASSERT(!"unhandled numeration value in switch");
+ return -1;
+ }
+}
+
+bool Lexer::isWhiteSpace() const
+{
+ return (current == ' ' || current == '\t' ||
+ current == 0x0b || current == 0x0c);
+}
+
+bool Lexer::isLineTerminator() const
+{
+ return (current == '\n' || current == '\r');
+}
+
+bool Lexer::isIdentLetter(ushort c)
+{
+ // ASCII-biased, since all reserved words are ASCII, aand hence the
+ // bulk of content to be parsed.
+ if ((c >= 'a' && c <= 'z')
+ || (c >= 'A' && c <= 'Z')
+ || c == '$'
+ || c == '_')
+ return true;
+ if (c < 128)
+ return false;
+ return QChar(c).isLetterOrNumber();
+}
+
+bool Lexer::isDecimalDigit(ushort c)
+{
+ return (c >= '0' && c <= '9');
+}
+
+bool Lexer::isHexDigit(ushort c) const
+{
+ return ((c >= '0' && c <= '9')
+ || (c >= 'a' && c <= 'f')
+ || (c >= 'A' && c <= 'F'));
+}
+
+bool Lexer::isOctalDigit(ushort c) const
+{
+ return (c >= '0' && c <= '7');
+}
+
+int Lexer::matchPunctuator(ushort c1, ushort c2,
+ ushort c3, ushort c4)
+{
+ if (c1 == '>' && c2 == '>' && c3 == '>' && c4 == '=') {
+ shift(4);
+ return QmlJSGrammar::T_GT_GT_GT_EQ;
+ } else if (c1 == '=' && c2 == '=' && c3 == '=') {
+ shift(3);
+ return QmlJSGrammar::T_EQ_EQ_EQ;
+ } else if (c1 == '!' && c2 == '=' && c3 == '=') {
+ shift(3);
+ return QmlJSGrammar::T_NOT_EQ_EQ;
+ } else if (c1 == '>' && c2 == '>' && c3 == '>') {
+ shift(3);
+ return QmlJSGrammar::T_GT_GT_GT;
+ } else if (c1 == '<' && c2 == '<' && c3 == '=') {
+ shift(3);
+ return QmlJSGrammar::T_LT_LT_EQ;
+ } else if (c1 == '>' && c2 == '>' && c3 == '=') {
+ shift(3);
+ return QmlJSGrammar::T_GT_GT_EQ;
+ } else if (c1 == '<' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_LE;
+ } else if (c1 == '>' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_GE;
+ } else if (c1 == '!' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_NOT_EQ;
+ } else if (c1 == '+' && c2 == '+') {
+ shift(2);
+ return QmlJSGrammar::T_PLUS_PLUS;
+ } else if (c1 == '-' && c2 == '-') {
+ shift(2);
+ return QmlJSGrammar::T_MINUS_MINUS;
+ } else if (c1 == '=' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_EQ_EQ;
+ } else if (c1 == '+' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_PLUS_EQ;
+ } else if (c1 == '-' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_MINUS_EQ;
+ } else if (c1 == '*' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_STAR_EQ;
+ } else if (c1 == '/' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_DIVIDE_EQ;
+ } else if (c1 == '&' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_AND_EQ;
+ } else if (c1 == '^' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_XOR_EQ;
+ } else if (c1 == '%' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_REMAINDER_EQ;
+ } else if (c1 == '|' && c2 == '=') {
+ shift(2);
+ return QmlJSGrammar::T_OR_EQ;
+ } else if (c1 == '<' && c2 == '<') {
+ shift(2);
+ return QmlJSGrammar::T_LT_LT;
+ } else if (c1 == '>' && c2 == '>') {
+ shift(2);
+ return QmlJSGrammar::T_GT_GT;
+ } else if (c1 == '&' && c2 == '&') {
+ shift(2);
+ return QmlJSGrammar::T_AND_AND;
+ } else if (c1 == '|' && c2 == '|') {
+ shift(2);
+ return QmlJSGrammar::T_OR_OR;
+ }
+
+ switch(c1) {
+ case '=': shift(1); return QmlJSGrammar::T_EQ;
+ case '>': shift(1); return QmlJSGrammar::T_GT;
+ case '<': shift(1); return QmlJSGrammar::T_LT;
+ case ',': shift(1); return QmlJSGrammar::T_COMMA;
+ case '!': shift(1); return QmlJSGrammar::T_NOT;
+ case '~': shift(1); return QmlJSGrammar::T_TILDE;
+ case '?': shift(1); return QmlJSGrammar::T_QUESTION;
+ case ':': shift(1); return QmlJSGrammar::T_COLON;
+ case '.': shift(1); return QmlJSGrammar::T_DOT;
+ case '+': shift(1); return QmlJSGrammar::T_PLUS;
+ case '-': shift(1); return QmlJSGrammar::T_MINUS;
+ case '*': shift(1); return QmlJSGrammar::T_STAR;
+ case '/': shift(1); return QmlJSGrammar::T_DIVIDE_;
+ case '&': shift(1); return QmlJSGrammar::T_AND;
+ case '|': shift(1); return QmlJSGrammar::T_OR;
+ case '^': shift(1); return QmlJSGrammar::T_XOR;
+ case '%': shift(1); return QmlJSGrammar::T_REMAINDER;
+ case '(': shift(1); return QmlJSGrammar::T_LPAREN;
+ case ')': shift(1); return QmlJSGrammar::T_RPAREN;
+ case '{': shift(1); return QmlJSGrammar::T_LBRACE;
+ case '}': shift(1); return QmlJSGrammar::T_RBRACE;
+ case '[': shift(1); return QmlJSGrammar::T_LBRACKET;
+ case ']': shift(1); return QmlJSGrammar::T_RBRACKET;
+ case ';': shift(1); return QmlJSGrammar::T_SEMICOLON;
+
+ default: return -1;
+ }
+}
+
+ushort Lexer::singleEscape(ushort c) const
+{
+ switch(c) {
+ case 'b':
+ return 0x08;
+ case 't':
+ return 0x09;
+ case 'n':
+ return 0x0A;
+ case 'v':
+ return 0x0B;
+ case 'f':
+ return 0x0C;
+ case 'r':
+ return 0x0D;
+ case '"':
+ return 0x22;
+ case '\'':
+ return 0x27;
+ case '\\':
+ return 0x5C;
+ default:
+ return c;
+ }
+}
+
+ushort Lexer::convertOctal(ushort c1, ushort c2,
+ ushort c3) const
+{
+ return ((c1 - '0') * 64 + (c2 - '0') * 8 + c3 - '0');
+}
+
+unsigned char Lexer::convertHex(ushort c)
+{
+ if (c >= '0' && c <= '9')
+ return (c - '0');
+ else if (c >= 'a' && c <= 'f')
+ return (c - 'a' + 10);
+ else
+ return (c - 'A' + 10);
+}
+
+unsigned char Lexer::convertHex(ushort c1, ushort c2)
+{
+ return ((convertHex(c1) << 4) + convertHex(c2));
+}
+
+QChar Lexer::convertUnicode(ushort c1, ushort c2,
+ ushort c3, ushort c4)
+{
+ return QChar((convertHex(c3) << 4) + convertHex(c4),
+ (convertHex(c1) << 4) + convertHex(c2));
+}
+
+void Lexer::record8(ushort c)
+{
+ Q_ASSERT(c <= 0xff);
+
+ // enlarge buffer if full
+ if (pos8 >= size8 - 1) {
+ char *tmp = new char[2 * size8];
+ memcpy(tmp, buffer8, size8 * sizeof(char));
+ delete [] buffer8;
+ buffer8 = tmp;
+ size8 *= 2;
+ }
+
+ buffer8[pos8++] = (char) c;
+}
+
+void Lexer::record16(QChar c)
+{
+ // enlarge buffer if full
+ if (pos16 >= size16 - 1) {
+ QChar *tmp = new QChar[2 * size16];
+ memcpy(tmp, buffer16, size16 * sizeof(QChar));
+ delete [] buffer16;
+ buffer16 = tmp;
+ size16 *= 2;
+ }
+
+ buffer16[pos16++] = c;
+}
+
+void Lexer::recordStartPos()
+{
+ startpos = pos;
+ startlineno = yylineno;
+ startcolumn = yycolumn;
+}
+
+bool Lexer::scanRegExp(RegExpBodyPrefix prefix)
+{
+ pos16 = 0;
+ bool lastWasEscape = false;
+
+ if (prefix == EqualPrefix)
+ record16(QLatin1Char('='));
+
+ while (1) {
+ if (isLineTerminator() || current == 0) {
+ errmsg = QCoreApplication::translate("QmlParser", "Unterminated regular expression literal");
+ return false;
+ }
+ else if (current != '/' || lastWasEscape == true)
+ {
+ record16(current);
+ lastWasEscape = !lastWasEscape && (current == '\\');
+ }
+ else {
+ if (driver)
+ pattern = driver->intern(buffer16, pos16);
+ else
+ pattern = 0;
+ pos16 = 0;
+ shift(1);
+ break;
+ }
+ shift(1);
+ }
+
+ flags = 0;
+ while (isIdentLetter(current)) {
+ int flag = Ecma::RegExp::flagFromChar(current);
+ if (flag == 0) {
+ errmsg = QCoreApplication::translate("QmlParser", "Invalid regular expression flag '%0'")
+ .arg(QChar(current));
+ return false;
+ }
+ flags |= flag;
+ record16(current);
+ shift(1);
+ }
+
+ return true;
+}
+
+void Lexer::syncProhibitAutomaticSemicolon()
+{
+ if (parenthesesState == BalancedParentheses) {
+ // we have seen something like "if (foo)", which means we should
+ // never insert an automatic semicolon at this point, since it would
+ // then be expanded into an empty statement (ECMA-262 7.9.1)
+ prohibitAutomaticSemicolon = true;
+ parenthesesState = IgnoreParentheses;
+ } else {
+ prohibitAutomaticSemicolon = false;
+ }
+}
+
+QT_QML_END_NAMESPACE
+
+
diff --git a/src/declarative/qml/parser/qmljslexer_p.h b/src/declarative/qml/parser/qmljslexer_p.h
new file mode 100644
index 0000000..b830071
--- /dev/null
+++ b/src/declarative/qml/parser/qmljslexer_p.h
@@ -0,0 +1,249 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLJSLEXER_P_H
+#define QMLJSLEXER_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qmljsglobal_p.h"
+
+#include <QtCore/QString>
+
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS {
+
+class Engine;
+class NameId;
+
+class QML_PARSER_EXPORT Lexer
+{
+public:
+ Lexer(Engine *eng, bool tokenizeComments = false);
+ ~Lexer();
+
+ void setCode(const QString &c, int lineno);
+ int lex();
+
+ int currentLineNo() const { return yylineno; }
+ int currentColumnNo() const { return yycolumn; }
+
+ int tokenOffset() const { return startpos; }
+ int tokenLength() const { return pos - startpos; }
+
+ int startLineNo() const { return startlineno; }
+ int startColumnNo() const { return startcolumn; }
+
+ int endLineNo() const { return currentLineNo(); }
+ int endColumnNo() const
+ { int col = currentColumnNo(); return (col > 0) ? col - 1 : col; }
+
+ bool prevTerminator() const { return terminator; }
+
+ enum State { Start,
+ Identifier,
+ InIdentifier,
+ InSingleLineComment,
+ InMultiLineComment,
+ InNum,
+ InNum0,
+ InHex,
+ InOctal,
+ InDecimal,
+ InExponentIndicator,
+ InExponent,
+ Hex,
+ Octal,
+ Number,
+ String,
+ Eof,
+ InString,
+ InEscapeSequence,
+ InHexEscape,
+ InUnicodeEscape,
+ Other,
+ Bad };
+
+ enum Error {
+ NoError,
+ IllegalCharacter,
+ UnclosedStringLiteral,
+ IllegalEscapeSequence,
+ IllegalUnicodeEscapeSequence,
+ UnclosedComment,
+ IllegalExponentIndicator,
+ IllegalIdentifier
+ };
+
+ enum ParenthesesState {
+ IgnoreParentheses,
+ CountParentheses,
+ BalancedParentheses
+ };
+
+ enum RegExpBodyPrefix {
+ NoPrefix,
+ EqualPrefix
+ };
+
+ bool scanRegExp(RegExpBodyPrefix prefix = NoPrefix);
+
+ NameId *pattern;
+ int flags;
+
+ State lexerState() const
+ { return state; }
+
+ QString errorMessage() const
+ { return errmsg; }
+ void setErrorMessage(const QString &err)
+ { errmsg = err; }
+ void setErrorMessage(const char *err)
+ { setErrorMessage(QString::fromLatin1(err)); }
+
+ Error error() const
+ { return err; }
+ void clearError()
+ { err = NoError; }
+
+private:
+ Engine *driver;
+ int yylineno;
+ bool done;
+ char *buffer8;
+ QChar *buffer16;
+ uint size8, size16;
+ uint pos8, pos16;
+ bool terminator;
+ bool restrKeyword;
+ // encountered delimiter like "'" and "}" on last run
+ bool delimited;
+ int stackToken;
+
+ State state;
+ void setDone(State s);
+ uint pos;
+ void shift(uint p);
+ int lookupKeyword(const char *);
+
+ bool isWhiteSpace() const;
+ bool isLineTerminator() const;
+ bool isHexDigit(ushort c) const;
+ bool isOctalDigit(ushort c) const;
+
+ int matchPunctuator(ushort c1, ushort c2,
+ ushort c3, ushort c4);
+ ushort singleEscape(ushort c) const;
+ ushort convertOctal(ushort c1, ushort c2,
+ ushort c3) const;
+public:
+ static unsigned char convertHex(ushort c1);
+ static unsigned char convertHex(ushort c1, ushort c2);
+ static QChar convertUnicode(ushort c1, ushort c2,
+ ushort c3, ushort c4);
+ static bool isIdentLetter(ushort c);
+ static bool isDecimalDigit(ushort c);
+
+ inline int ival() const { return qsyylval.ival; }
+ inline double dval() const { return qsyylval.dval; }
+ inline NameId *ustr() const { return qsyylval.ustr; }
+
+ const QChar *characterBuffer() const { return buffer16; }
+ int characterCount() const { return pos16; }
+
+private:
+ void record8(ushort c);
+ void record16(QChar c);
+ void recordStartPos();
+
+ int findReservedWord(const QChar *buffer, int size) const;
+
+ void syncProhibitAutomaticSemicolon();
+
+ const QChar *code;
+ uint length;
+ int yycolumn;
+ int startpos;
+ int startlineno;
+ int startcolumn;
+ int bol; // begin of line
+
+ union {
+ int ival;
+ double dval;
+ NameId *ustr;
+ } qsyylval;
+
+ // current and following unicode characters
+ ushort current, next1, next2, next3;
+
+ struct keyword {
+ const char *name;
+ int token;
+ };
+
+ QString errmsg;
+ Error err;
+
+ bool wantRx;
+ bool check_reserved;
+
+ ParenthesesState parenthesesState;
+ int parenthesesCount;
+ bool prohibitAutomaticSemicolon;
+ bool tokenizeComments;
+};
+
+} // namespace QmlJS
+
+QT_QML_END_NAMESPACE
+
+#endif
diff --git a/src/declarative/qml/parser/qmljsmemorypool_p.h b/src/declarative/qml/parser/qmljsmemorypool_p.h
new file mode 100644
index 0000000..3da2678
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsmemorypool_p.h
@@ -0,0 +1,133 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLJSMEMORYPOOL_P_H
+#define QMLJSMEMORYPOOL_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qmljsglobal_p.h"
+
+#include <QtCore/qglobal.h>
+#include <QtCore/qshareddata.h>
+
+#include <string.h>
+
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS {
+
+class QML_PARSER_EXPORT MemoryPool : public QSharedData
+{
+public:
+ enum { maxBlockCount = -1 };
+ enum { defaultBlockSize = 1 << 12 };
+
+ MemoryPool() {
+ m_blockIndex = maxBlockCount;
+ m_currentIndex = 0;
+ m_storage = 0;
+ m_currentBlock = 0;
+ m_currentBlockSize = 0;
+ }
+
+ virtual ~MemoryPool() {
+ for (int index = 0; index < m_blockIndex + 1; ++index)
+ qFree(m_storage[index]);
+
+ qFree(m_storage);
+ }
+
+ char *allocate(int bytes) {
+ bytes += (8 - bytes) & 7; // ensure multiple of 8 bytes (maintain alignment)
+ if (m_currentBlock == 0 || m_currentBlockSize < m_currentIndex + bytes) {
+ ++m_blockIndex;
+ m_currentBlockSize = defaultBlockSize << m_blockIndex;
+
+ m_storage = reinterpret_cast<char**>(qRealloc(m_storage, sizeof(char*) * (1 + m_blockIndex)));
+ m_currentBlock = m_storage[m_blockIndex] = reinterpret_cast<char*>(qMalloc(m_currentBlockSize));
+ ::memset(m_currentBlock, 0, m_currentBlockSize);
+
+ m_currentIndex = (8 - quintptr(m_currentBlock)) & 7; // ensure first chunk is 64-bit aligned
+ Q_ASSERT(m_currentIndex + bytes <= m_currentBlockSize);
+ }
+
+ char *p = reinterpret_cast<char *>
+ (m_currentBlock + m_currentIndex);
+
+ m_currentIndex += bytes;
+
+ return p;
+ }
+
+ int bytesAllocated() const {
+ int bytes = 0;
+ for (int index = 0; index < m_blockIndex; ++index)
+ bytes += (defaultBlockSize << index);
+ bytes += m_currentIndex;
+ return bytes;
+ }
+
+private:
+ int m_blockIndex;
+ int m_currentIndex;
+ char *m_currentBlock;
+ int m_currentBlockSize;
+ char **m_storage;
+
+private:
+ Q_DISABLE_COPY(MemoryPool)
+};
+
+} // namespace QmlJS
+
+QT_QML_END_NAMESPACE
+
+#endif
diff --git a/src/declarative/qml/parser/qmljsnodepool_p.h b/src/declarative/qml/parser/qmljsnodepool_p.h
new file mode 100644
index 0000000..abe4cc8
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsnodepool_p.h
@@ -0,0 +1,139 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLJSNODEPOOL_P_H
+#define QMLJSNODEPOOL_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qmljsglobal_p.h"
+#include "qmljsmemorypool_p.h"
+
+#include <QtCore/QHash>
+#include <QtCore/QString>
+
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS {
+
+namespace AST {
+class Node;
+} // namespace AST
+
+class Code;
+class CompilationUnit;
+class Engine;
+
+template <typename NodeType>
+inline NodeType *makeAstNode(MemoryPool *storage)
+{
+ NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType();
+ return node;
+}
+
+template <typename NodeType, typename Arg1>
+inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1)
+{
+ NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1);
+ return node;
+}
+
+template <typename NodeType, typename Arg1, typename Arg2>
+inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1, Arg2 arg2)
+{
+ NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1, arg2);
+ return node;
+}
+
+template <typename NodeType, typename Arg1, typename Arg2, typename Arg3>
+inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1, Arg2 arg2, Arg3 arg3)
+{
+ NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1, arg2, arg3);
+ return node;
+}
+
+template <typename NodeType, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
+inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4)
+{
+ NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1, arg2, arg3, arg4);
+ return node;
+}
+
+class QML_PARSER_EXPORT NodePool : public MemoryPool
+{
+public:
+ NodePool(const QString &fileName, Engine *engine);
+ virtual ~NodePool();
+
+ Code *createCompiledCode(AST::Node *node, CompilationUnit &compilation);
+
+ inline QString fileName() const { return m_fileName; }
+ inline Engine *engine() const { return m_engine; }
+#ifndef J_SCRIPT_NO_EVENT_NOTIFY
+ inline qint64 id() const { return m_id; }
+#endif
+
+private:
+ QHash<AST::Node*, Code*> m_codeCache;
+ QString m_fileName;
+ Engine *m_engine;
+#ifndef J_SCRIPT_NO_EVENT_NOTIFY
+ qint64 m_id;
+#endif
+
+private:
+ Q_DISABLE_COPY(NodePool)
+};
+
+} // namespace QmlJS
+
+QT_QML_END_NAMESPACE
+
+#endif
diff --git a/src/declarative/qml/parser/qmljsparser.cpp b/src/declarative/qml/parser/qmljsparser.cpp
new file mode 100644
index 0000000..856d06d
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsparser.cpp
@@ -0,0 +1,1843 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtCore/QtDebug>
+#include <QtGui/QApplication>
+
+#include <string.h>
+
+#include "qmljsengine_p.h"
+#include "qmljslexer_p.h"
+#include "qmljsast_p.h"
+#include "qmljsnodepool_p.h"
+
+
+
+#include "qmljsparser_p.h"
+#include <QVarLengthArray>
+
+//
+// This file is automatically generated from qmljs.g.
+// Changes will be lost.
+//
+
+using namespace QmlJS;
+
+QT_QML_BEGIN_NAMESPACE
+
+void Parser::reallocateStack()
+{
+ if (! stack_size)
+ stack_size = 128;
+ else
+ stack_size <<= 1;
+
+ sym_stack = reinterpret_cast<Value*> (qRealloc(sym_stack, stack_size * sizeof(Value)));
+ state_stack = reinterpret_cast<int*> (qRealloc(state_stack, stack_size * sizeof(int)));
+ location_stack = reinterpret_cast<AST::SourceLocation*> (qRealloc(location_stack, stack_size * sizeof(AST::SourceLocation)));
+}
+
+inline static bool automatic(Engine *driver, int token)
+{
+ return token == QmlJSGrammar::T_RBRACE
+ || token == 0
+ || driver->lexer()->prevTerminator();
+}
+
+
+Parser::Parser(Engine *engine):
+ driver(engine),
+ tos(0),
+ stack_size(0),
+ sym_stack(0),
+ state_stack(0),
+ location_stack(0),
+ first_token(0),
+ last_token(0)
+{
+}
+
+Parser::~Parser()
+{
+ if (stack_size) {
+ qFree(sym_stack);
+ qFree(state_stack);
+ qFree(location_stack);
+ }
+}
+
+static inline AST::SourceLocation location(Lexer *lexer)
+{
+ AST::SourceLocation loc;
+ loc.offset = lexer->tokenOffset();
+ loc.length = lexer->tokenLength();
+ loc.startLine = lexer->startLineNo();
+ loc.startColumn = lexer->startColumnNo();
+ return loc;
+}
+
+AST::UiQualifiedId *Parser::reparseAsQualifiedId(AST::ExpressionNode *expr)
+{
+ QVarLengthArray<NameId *, 4> nameIds;
+ QVarLengthArray<AST::SourceLocation, 4> locations;
+
+ AST::ExpressionNode *it = expr;
+ while (AST::FieldMemberExpression *m = AST::cast<AST::FieldMemberExpression *>(it)) {
+ nameIds.append(m->name);
+ locations.append(m->identifierToken);
+ it = m->base;
+ }
+
+ if (AST::IdentifierExpression *idExpr = AST::cast<AST::IdentifierExpression *>(it)) {
+ AST::UiQualifiedId *q = makeAstNode<AST::UiQualifiedId>(driver->nodePool(), idExpr->name);
+ q->identifierToken = idExpr->identifierToken;
+
+ AST::UiQualifiedId *currentId = q;
+ for (int i = nameIds.size() - 1; i != -1; --i) {
+ currentId = makeAstNode<AST::UiQualifiedId>(driver->nodePool(), currentId, nameIds[i]);
+ currentId->identifierToken = locations[i];
+ }
+
+ return currentId->finish();
+ }
+
+ return 0;
+}
+
+bool Parser::parse(int startToken)
+{
+ Lexer *lexer = driver->lexer();
+ bool hadErrors = false;
+ int yytoken = -1;
+ int action = 0;
+
+ token_buffer[0].token = startToken;
+ first_token = &token_buffer[0];
+ last_token = &token_buffer[1];
+
+ tos = -1;
+ program = 0;
+
+ do {
+ if (++tos == stack_size)
+ reallocateStack();
+
+ state_stack[tos] = action;
+
+ _Lcheck_token:
+ if (yytoken == -1 && -TERMINAL_COUNT != action_index[action]) {
+ yyprevlloc = yylloc;
+
+ if (first_token == last_token) {
+ yytoken = lexer->lex();
+ yylval = lexer->dval();
+ yylloc = location(lexer);
+ } else {
+ yytoken = first_token->token;
+ yylval = first_token->dval;
+ yylloc = first_token->loc;
+ ++first_token;
+ }
+ }
+
+ action = t_action(action, yytoken);
+ if (action > 0) {
+ if (action != ACCEPT_STATE) {
+ yytoken = -1;
+ sym(1).dval = yylval;
+ loc(1) = yylloc;
+ } else {
+ --tos;
+ return ! hadErrors;
+ }
+ } else if (action < 0) {
+ const int r = -action - 1;
+ tos -= rhs[r];
+
+ switch (r) {
+
+case 0: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+
+case 1: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+
+case 2: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+
+case 3: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+
+case 4: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+
+case 5: {
+ sym(1).Node = sym(2).Node;
+ program = sym(1).Node;
+} break;
+
+case 6: {
+ sym(1).UiProgram = makeAstNode<AST::UiProgram> (driver->nodePool(), sym(1).UiImportList,
+ sym(2).UiObjectMemberList->finish());
+} break;
+
+case 8: {
+ sym(1).Node = sym(1).UiImportList->finish();
+} break;
+
+case 9: {
+ sym(1).Node = makeAstNode<AST::UiImportList> (driver->nodePool(), sym(1).UiImport);
+} break;
+
+case 10: {
+ sym(1).Node = makeAstNode<AST::UiImportList> (driver->nodePool(),
+ sym(1).UiImportList, sym(2).UiImport);
+} break;
+
+case 13: {
+ sym(1).UiImport->semicolonToken = loc(2);
+} break;
+
+case 15: {
+ sym(1).UiImport->versionToken = loc(2);
+ sym(1).UiImport->semicolonToken = loc(3);
+} break;
+
+case 17: {
+ sym(1).UiImport->versionToken = loc(2);
+ sym(1).UiImport->asToken = loc(3);
+ sym(1).UiImport->importIdToken = loc(4);
+ sym(1).UiImport->importId = sym(4).sval;
+ sym(1).UiImport->semicolonToken = loc(5);
+} break;
+
+case 19: {
+ sym(1).UiImport->asToken = loc(2);
+ sym(1).UiImport->importIdToken = loc(3);
+ sym(1).UiImport->importId = sym(3).sval;
+ sym(1).UiImport->semicolonToken = loc(4);
+} break;
+
+case 20: {
+ AST::UiImport *node = 0;
+
+ if (AST::StringLiteral *importIdLiteral = AST::cast<AST::StringLiteral *>(sym(2).Expression)) {
+ node = makeAstNode<AST::UiImport>(driver->nodePool(), importIdLiteral->value);
+ node->fileNameToken = loc(2);
+ } else if (AST::UiQualifiedId *qualifiedId = reparseAsQualifiedId(sym(2).Expression)) {
+ QString text;
+ for (AST::UiQualifiedId *q = qualifiedId; q; q = q->next) {
+ text += q->name->asString();
+ if (q->next) text += QLatin1String(".");
+ }
+ node = makeAstNode<AST::UiImport>(driver->nodePool(), qualifiedId);
+ node->fileNameToken = loc(2);
+ }
+
+ sym(1).Node = node;
+
+ if (! node) {
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc(1),
+ QLatin1String("Expected a qualified name id or a string literal")));
+
+ return false; // ### remove me
+ }
+} break;
+
+case 21: {
+ sym(1).Node = 0;
+} break;
+
+case 22: {
+ sym(1).Node = makeAstNode<AST::UiObjectMemberList> (driver->nodePool(), sym(1).UiObjectMember);
+} break;
+
+case 23: {
+ sym(1).Node = makeAstNode<AST::UiObjectMemberList> (driver->nodePool(), sym(1).UiObjectMember);
+} break;
+
+case 24: {
+ AST::UiObjectMemberList *node = makeAstNode<AST:: UiObjectMemberList> (driver->nodePool(),
+ sym(1).UiObjectMemberList, sym(2).UiObjectMember);
+ sym(1).Node = node;
+} break;
+
+case 25: {
+ sym(1).Node = makeAstNode<AST::UiArrayMemberList> (driver->nodePool(), sym(1).UiObjectMember);
+} break;
+
+case 26: {
+ AST::UiArrayMemberList *node = makeAstNode<AST::UiArrayMemberList> (driver->nodePool(),
+ sym(1).UiArrayMemberList, sym(3).UiObjectMember);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 27: {
+ AST::UiObjectInitializer *node = makeAstNode<AST::UiObjectInitializer> (driver->nodePool(), (AST::UiObjectMemberList*)0);
+ node->lbraceToken = loc(1);
+ node->rbraceToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 28: {
+ AST::UiObjectInitializer *node = makeAstNode<AST::UiObjectInitializer> (driver->nodePool(), sym(2).UiObjectMemberList->finish());
+ node->lbraceToken = loc(1);
+ node->rbraceToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 29: {
+ AST::UiObjectDefinition *node = makeAstNode<AST::UiObjectDefinition> (driver->nodePool(), sym(1).UiQualifiedId,
+ sym(2).UiObjectInitializer);
+ sym(1).Node = node;
+} break;
+
+case 31: {
+ AST::UiArrayBinding *node = makeAstNode<AST::UiArrayBinding> (driver->nodePool(),
+ sym(1).UiQualifiedId, sym(4).UiArrayMemberList->finish());
+ node->colonToken = loc(2);
+ node->lbracketToken = loc(3);
+ node->rbracketToken = loc(5);
+ sym(1).Node = node;
+} break;
+
+case 32: {
+ AST::UiObjectBinding *node = makeAstNode<AST::UiObjectBinding> (driver->nodePool(),
+ sym(1).UiQualifiedId, sym(3).UiQualifiedId, sym(4).UiObjectInitializer);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+case 33:case 34:case 35:case 36:
+{
+ AST::UiScriptBinding *node = makeAstNode<AST::UiScriptBinding> (driver->nodePool(),
+ sym(1).UiQualifiedId, sym(3).Statement);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 37:
+
+case 38: {
+ sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount());
+ break;
+}
+
+case 40: {
+ sym(1).Node = 0;
+} break;
+
+case 41: {
+ sym(1).Node = sym(1).UiParameterList->finish ();
+} break;
+
+case 42: {
+ AST::UiParameterList *node = makeAstNode<AST::UiParameterList> (driver->nodePool(), sym(1).sval, sym(2).sval);
+ node->identifierToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 43: {
+ AST::UiParameterList *node = makeAstNode<AST::UiParameterList> (driver->nodePool(), sym(1).UiParameterList, sym(3).sval, sym(4).sval);
+ node->commaToken = loc(2);
+ node->identifierToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 45: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), (NameId *)0, sym(2).sval);
+ node->type = AST::UiPublicMember::Signal;
+ node->propertyToken = loc(1);
+ node->typeToken = loc(2);
+ node->identifierToken = loc(2);
+ node->parameters = sym(4).UiParameterList;
+ node->semicolonToken = loc(6);
+ sym(1).Node = node;
+} break;
+
+case 47: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), (NameId *)0, sym(2).sval);
+ node->type = AST::UiPublicMember::Signal;
+ node->propertyToken = loc(1);
+ node->typeToken = loc(2);
+ node->identifierToken = loc(2);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 49: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(4).sval, sym(6).sval);
+ node->typeModifier = sym(2).sval;
+ node->propertyToken = loc(1);
+ node->typeModifierToken = loc(2);
+ node->typeToken = loc(4);
+ node->identifierToken = loc(6);
+ node->semicolonToken = loc(7);
+ sym(1).Node = node;
+} break;
+
+case 51: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(2).sval, sym(3).sval);
+ node->propertyToken = loc(1);
+ node->typeToken = loc(2);
+ node->identifierToken = loc(3);
+ node->semicolonToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 53: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(3).sval, sym(4).sval);
+ node->isDefaultMember = true;
+ node->defaultToken = loc(1);
+ node->propertyToken = loc(2);
+ node->typeToken = loc(3);
+ node->identifierToken = loc(4);
+ node->semicolonToken = loc(5);
+ sym(1).Node = node;
+} break;
+
+case 55: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(2).sval, sym(3).sval,
+ sym(5).Expression);
+ node->propertyToken = loc(1);
+ node->typeToken = loc(2);
+ node->identifierToken = loc(3);
+ node->colonToken = loc(4);
+ node->semicolonToken = loc(6);
+ sym(1).Node = node;
+} break;
+
+case 57: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(3).sval, sym(4).sval,
+ sym(6).Expression);
+ node->isReadonlyMember = true;
+ node->readonlyToken = loc(1);
+ node->propertyToken = loc(2);
+ node->typeToken = loc(3);
+ node->identifierToken = loc(4);
+ node->colonToken = loc(5);
+ node->semicolonToken = loc(7);
+ sym(1).Node = node;
+} break;
+
+case 59: {
+ AST::UiPublicMember *node = makeAstNode<AST::UiPublicMember> (driver->nodePool(), sym(3).sval, sym(4).sval,
+ sym(6).Expression);
+ node->isDefaultMember = true;
+ node->defaultToken = loc(1);
+ node->propertyToken = loc(2);
+ node->typeToken = loc(3);
+ node->identifierToken = loc(4);
+ node->colonToken = loc(5);
+ node->semicolonToken = loc(7);
+ sym(1).Node = node;
+} break;
+
+case 60: {
+ sym(1).Node = makeAstNode<AST::UiSourceElement>(driver->nodePool(), sym(1).Node);
+} break;
+
+case 61: {
+ sym(1).Node = makeAstNode<AST::UiSourceElement>(driver->nodePool(), sym(1).Node);
+} break;
+
+case 63: {
+ QString s = QLatin1String(QmlJSGrammar::spell[T_PROPERTY]);
+ sym(1).sval = driver->intern(s.constData(), s.length());
+ break;
+}
+
+case 64: {
+ QString s = QLatin1String(QmlJSGrammar::spell[T_SIGNAL]);
+ sym(1).sval = driver->intern(s.constData(), s.length());
+ break;
+}
+
+case 65: {
+ QString s = QLatin1String(QmlJSGrammar::spell[T_READONLY]);
+ sym(1).sval = driver->intern(s.constData(), s.length());
+ break;
+}
+
+case 66: {
+ AST::ThisExpression *node = makeAstNode<AST::ThisExpression> (driver->nodePool());
+ node->thisToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 67: {
+ AST::IdentifierExpression *node = makeAstNode<AST::IdentifierExpression> (driver->nodePool(), sym(1).sval);
+ node->identifierToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 68: {
+ AST::NullExpression *node = makeAstNode<AST::NullExpression> (driver->nodePool());
+ node->nullToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 69: {
+ AST::TrueLiteral *node = makeAstNode<AST::TrueLiteral> (driver->nodePool());
+ node->trueToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 70: {
+ AST::FalseLiteral *node = makeAstNode<AST::FalseLiteral> (driver->nodePool());
+ node->falseToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 71: {
+ AST::NumericLiteral *node = makeAstNode<AST::NumericLiteral> (driver->nodePool(), sym(1).dval);
+ node->literalToken = loc(1);
+ sym(1).Node = node;
+} break;
+case 72:
+case 73: {
+ AST::StringLiteral *node = makeAstNode<AST::StringLiteral> (driver->nodePool(), sym(1).sval);
+ node->literalToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 74: {
+ bool rx = lexer->scanRegExp(Lexer::NoPrefix);
+ if (!rx) {
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage()));
+ return false; // ### remove me
+ }
+ AST::RegExpLiteral *node = makeAstNode<AST::RegExpLiteral> (driver->nodePool(), lexer->pattern, lexer->flags);
+ node->literalToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 75: {
+ bool rx = lexer->scanRegExp(Lexer::EqualPrefix);
+ if (!rx) {
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage()));
+ return false;
+ }
+ AST::RegExpLiteral *node = makeAstNode<AST::RegExpLiteral> (driver->nodePool(), lexer->pattern, lexer->flags);
+ node->literalToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 76: {
+ AST::ArrayLiteral *node = makeAstNode<AST::ArrayLiteral> (driver->nodePool(), (AST::Elision *) 0);
+ node->lbracketToken = loc(1);
+ node->rbracketToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 77: {
+ AST::ArrayLiteral *node = makeAstNode<AST::ArrayLiteral> (driver->nodePool(), sym(2).Elision->finish());
+ node->lbracketToken = loc(1);
+ node->rbracketToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 78: {
+ AST::ArrayLiteral *node = makeAstNode<AST::ArrayLiteral> (driver->nodePool(), sym(2).ElementList->finish ());
+ node->lbracketToken = loc(1);
+ node->rbracketToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 79: {
+ AST::ArrayLiteral *node = makeAstNode<AST::ArrayLiteral> (driver->nodePool(), sym(2).ElementList->finish (),
+ (AST::Elision *) 0);
+ node->lbracketToken = loc(1);
+ node->commaToken = loc(3);
+ node->rbracketToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 80: {
+ AST::ArrayLiteral *node = makeAstNode<AST::ArrayLiteral> (driver->nodePool(), sym(2).ElementList->finish (),
+ sym(4).Elision->finish());
+ node->lbracketToken = loc(1);
+ node->commaToken = loc(3);
+ node->rbracketToken = loc(5);
+ sym(1).Node = node;
+} break;
+
+case 81: {
+ AST::ObjectLiteral *node = 0;
+ if (sym(2).Node)
+ node = makeAstNode<AST::ObjectLiteral> (driver->nodePool(),
+ sym(2).PropertyNameAndValueList->finish ());
+ else
+ node = makeAstNode<AST::ObjectLiteral> (driver->nodePool());
+ node->lbraceToken = loc(1);
+ node->lbraceToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 82: {
+ AST::ObjectLiteral *node = makeAstNode<AST::ObjectLiteral> (driver->nodePool(),
+ sym(2).PropertyNameAndValueList->finish ());
+ node->lbraceToken = loc(1);
+ node->lbraceToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 83: {
+ AST::NestedExpression *node = makeAstNode<AST::NestedExpression>(driver->nodePool(), sym(2).Expression);
+ node->lparenToken = loc(1);
+ node->rparenToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 84: {
+ if (AST::ArrayMemberExpression *mem = AST::cast<AST::ArrayMemberExpression *>(sym(1).Expression)) {
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, mem->lbracketToken,
+ QLatin1String("Ignored annotation")));
+
+ sym(1).Expression = mem->base;
+ }
+
+ if (AST::UiQualifiedId *qualifiedId = reparseAsQualifiedId(sym(1).Expression)) {
+ sym(1).UiQualifiedId = qualifiedId;
+ } else {
+ sym(1).UiQualifiedId = 0;
+
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc(1),
+ QLatin1String("Expected a qualified name id")));
+
+ return false; // ### recover
+ }
+} break;
+
+case 85: {
+ sym(1).Node = makeAstNode<AST::ElementList> (driver->nodePool(), (AST::Elision *) 0, sym(1).Expression);
+} break;
+
+case 86: {
+ sym(1).Node = makeAstNode<AST::ElementList> (driver->nodePool(), sym(1).Elision->finish(), sym(2).Expression);
+} break;
+
+case 87: {
+ AST::ElementList *node = makeAstNode<AST::ElementList> (driver->nodePool(), sym(1).ElementList,
+ (AST::Elision *) 0, sym(3).Expression);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 88: {
+ AST::ElementList *node = makeAstNode<AST::ElementList> (driver->nodePool(), sym(1).ElementList, sym(3).Elision->finish(),
+ sym(4).Expression);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 89: {
+ AST::Elision *node = makeAstNode<AST::Elision> (driver->nodePool());
+ node->commaToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 90: {
+ AST::Elision *node = makeAstNode<AST::Elision> (driver->nodePool(), sym(1).Elision);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 91: {
+ AST::PropertyNameAndValueList *node = makeAstNode<AST::PropertyNameAndValueList> (driver->nodePool(),
+ sym(1).PropertyName, sym(3).Expression);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 92: {
+ AST::PropertyNameAndValueList *node = makeAstNode<AST::PropertyNameAndValueList> (driver->nodePool(),
+ sym(1).PropertyNameAndValueList, sym(3).PropertyName, sym(5).Expression);
+ node->commaToken = loc(2);
+ node->colonToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 93: {
+ AST::IdentifierPropertyName *node = makeAstNode<AST::IdentifierPropertyName> (driver->nodePool(), sym(1).sval);
+ node->propertyNameToken = loc(1);
+ sym(1).Node = node;
+} break;
+case 94:
+case 95: {
+ AST::IdentifierPropertyName *node = makeAstNode<AST::IdentifierPropertyName> (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount()));
+ node->propertyNameToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 96: {
+ AST::StringLiteralPropertyName *node = makeAstNode<AST::StringLiteralPropertyName> (driver->nodePool(), sym(1).sval);
+ node->propertyNameToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 97: {
+ AST::NumericLiteralPropertyName *node = makeAstNode<AST::NumericLiteralPropertyName> (driver->nodePool(), sym(1).dval);
+ node->propertyNameToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 98: {
+ AST::IdentifierPropertyName *node = makeAstNode<AST::IdentifierPropertyName> (driver->nodePool(), sym(1).sval);
+ node->propertyNameToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 99:
+
+case 100:
+
+case 101:
+
+case 102:
+
+case 103:
+
+case 104:
+
+case 105:
+
+case 106:
+
+case 107:
+
+case 108:
+
+case 109:
+
+case 110:
+
+case 111:
+
+case 112:
+
+case 113:
+
+case 114:
+
+case 115:
+
+case 116:
+
+case 117:
+
+case 118:
+
+case 119:
+
+case 120:
+
+case 121:
+
+case 122:
+
+case 123:
+
+case 124:
+
+case 125:
+
+case 126:
+
+case 127:
+
+case 128:
+
+case 129:
+{
+ sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount());
+} break;
+
+case 134: {
+ AST::ArrayMemberExpression *node = makeAstNode<AST::ArrayMemberExpression> (driver->nodePool(), sym(1).Expression, sym(3).Expression);
+ node->lbracketToken = loc(2);
+ node->rbracketToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 135: {
+ AST::FieldMemberExpression *node = makeAstNode<AST::FieldMemberExpression> (driver->nodePool(), sym(1).Expression, sym(3).sval);
+ node->dotToken = loc(2);
+ node->identifierToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 136: {
+ AST::NewMemberExpression *node = makeAstNode<AST::NewMemberExpression> (driver->nodePool(), sym(2).Expression, sym(4).ArgumentList);
+ node->newToken = loc(1);
+ node->lparenToken = loc(3);
+ node->rparenToken = loc(5);
+ sym(1).Node = node;
+} break;
+
+case 138: {
+ AST::NewExpression *node = makeAstNode<AST::NewExpression> (driver->nodePool(), sym(2).Expression);
+ node->newToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 139: {
+ AST::CallExpression *node = makeAstNode<AST::CallExpression> (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 140: {
+ AST::CallExpression *node = makeAstNode<AST::CallExpression> (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 141: {
+ AST::ArrayMemberExpression *node = makeAstNode<AST::ArrayMemberExpression> (driver->nodePool(), sym(1).Expression, sym(3).Expression);
+ node->lbracketToken = loc(2);
+ node->rbracketToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 142: {
+ AST::FieldMemberExpression *node = makeAstNode<AST::FieldMemberExpression> (driver->nodePool(), sym(1).Expression, sym(3).sval);
+ node->dotToken = loc(2);
+ node->identifierToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 143: {
+ sym(1).Node = 0;
+} break;
+
+case 144: {
+ sym(1).Node = sym(1).ArgumentList->finish();
+} break;
+
+case 145: {
+ sym(1).Node = makeAstNode<AST::ArgumentList> (driver->nodePool(), sym(1).Expression);
+} break;
+
+case 146: {
+ AST::ArgumentList *node = makeAstNode<AST::ArgumentList> (driver->nodePool(), sym(1).ArgumentList, sym(3).Expression);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 150: {
+ AST::PostIncrementExpression *node = makeAstNode<AST::PostIncrementExpression> (driver->nodePool(), sym(1).Expression);
+ node->incrementToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 151: {
+ AST::PostDecrementExpression *node = makeAstNode<AST::PostDecrementExpression> (driver->nodePool(), sym(1).Expression);
+ node->decrementToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 153: {
+ AST::DeleteExpression *node = makeAstNode<AST::DeleteExpression> (driver->nodePool(), sym(2).Expression);
+ node->deleteToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 154: {
+ AST::VoidExpression *node = makeAstNode<AST::VoidExpression> (driver->nodePool(), sym(2).Expression);
+ node->voidToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 155: {
+ AST::TypeOfExpression *node = makeAstNode<AST::TypeOfExpression> (driver->nodePool(), sym(2).Expression);
+ node->typeofToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 156: {
+ AST::PreIncrementExpression *node = makeAstNode<AST::PreIncrementExpression> (driver->nodePool(), sym(2).Expression);
+ node->incrementToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 157: {
+ AST::PreDecrementExpression *node = makeAstNode<AST::PreDecrementExpression> (driver->nodePool(), sym(2).Expression);
+ node->decrementToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 158: {
+ AST::UnaryPlusExpression *node = makeAstNode<AST::UnaryPlusExpression> (driver->nodePool(), sym(2).Expression);
+ node->plusToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 159: {
+ AST::UnaryMinusExpression *node = makeAstNode<AST::UnaryMinusExpression> (driver->nodePool(), sym(2).Expression);
+ node->minusToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 160: {
+ AST::TildeExpression *node = makeAstNode<AST::TildeExpression> (driver->nodePool(), sym(2).Expression);
+ node->tildeToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 161: {
+ AST::NotExpression *node = makeAstNode<AST::NotExpression> (driver->nodePool(), sym(2).Expression);
+ node->notToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 163: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Mul, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 164: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Div, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 165: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Mod, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 167: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Add, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 168: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Sub, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 170: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::LShift, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 171: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::RShift, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 172: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::URShift, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 174: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Lt, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 175: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Gt, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 176: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Le, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 177: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Ge, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 178: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::InstanceOf, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 179: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::In, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 181: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Lt, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 182: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Gt, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 183: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Le, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 184: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Ge, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 185: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::InstanceOf, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 187: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Equal, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 188: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::NotEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 189: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::StrictEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 190: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::StrictNotEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 192: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Equal, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 193: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::NotEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 194: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::StrictEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 195: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::StrictNotEqual, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 197: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitAnd, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 199: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitAnd, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 201: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitXor, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 203: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitXor, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 205: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitOr, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 207: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::BitOr, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 209: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::And, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 211: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::And, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 213: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Or, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 215: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ QSOperator::Or, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 217: {
+ AST::ConditionalExpression *node = makeAstNode<AST::ConditionalExpression> (driver->nodePool(), sym(1).Expression,
+ sym(3).Expression, sym(5).Expression);
+ node->questionToken = loc(2);
+ node->colonToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 219: {
+ AST::ConditionalExpression *node = makeAstNode<AST::ConditionalExpression> (driver->nodePool(), sym(1).Expression,
+ sym(3).Expression, sym(5).Expression);
+ node->questionToken = loc(2);
+ node->colonToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 221: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ sym(2).ival, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 223: {
+ AST::BinaryExpression *node = makeAstNode<AST::BinaryExpression> (driver->nodePool(), sym(1).Expression,
+ sym(2).ival, sym(3).Expression);
+ node->operatorToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 224: {
+ sym(1).ival = QSOperator::Assign;
+} break;
+
+case 225: {
+ sym(1).ival = QSOperator::InplaceMul;
+} break;
+
+case 226: {
+ sym(1).ival = QSOperator::InplaceDiv;
+} break;
+
+case 227: {
+ sym(1).ival = QSOperator::InplaceMod;
+} break;
+
+case 228: {
+ sym(1).ival = QSOperator::InplaceAdd;
+} break;
+
+case 229: {
+ sym(1).ival = QSOperator::InplaceSub;
+} break;
+
+case 230: {
+ sym(1).ival = QSOperator::InplaceLeftShift;
+} break;
+
+case 231: {
+ sym(1).ival = QSOperator::InplaceRightShift;
+} break;
+
+case 232: {
+ sym(1).ival = QSOperator::InplaceURightShift;
+} break;
+
+case 233: {
+ sym(1).ival = QSOperator::InplaceAnd;
+} break;
+
+case 234: {
+ sym(1).ival = QSOperator::InplaceXor;
+} break;
+
+case 235: {
+ sym(1).ival = QSOperator::InplaceOr;
+} break;
+
+case 237: {
+ AST::Expression *node = makeAstNode<AST::Expression> (driver->nodePool(), sym(1).Expression, sym(3).Expression);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 238: {
+ sym(1).Node = 0;
+} break;
+
+case 241: {
+ AST::Expression *node = makeAstNode<AST::Expression> (driver->nodePool(), sym(1).Expression, sym(3).Expression);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 242: {
+ sym(1).Node = 0;
+} break;
+
+case 259: {
+ AST::Block *node = makeAstNode<AST::Block> (driver->nodePool(), sym(2).StatementList);
+ node->lbraceToken = loc(1);
+ node->rbraceToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 260: {
+ sym(1).Node = makeAstNode<AST::StatementList> (driver->nodePool(), sym(1).Statement);
+} break;
+
+case 261: {
+ sym(1).Node = makeAstNode<AST::StatementList> (driver->nodePool(), sym(1).StatementList, sym(2).Statement);
+} break;
+
+case 262: {
+ sym(1).Node = 0;
+} break;
+
+case 263: {
+ sym(1).Node = sym(1).StatementList->finish ();
+} break;
+
+case 265: {
+ AST::VariableStatement *node = makeAstNode<AST::VariableStatement> (driver->nodePool(),
+ sym(2).VariableDeclarationList->finish (/*readOnly=*/sym(1).ival == T_CONST));
+ node->declarationKindToken = loc(1);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 266: {
+ sym(1).ival = T_CONST;
+} break;
+
+case 267: {
+ sym(1).ival = T_VAR;
+} break;
+
+case 268: {
+ sym(1).Node = makeAstNode<AST::VariableDeclarationList> (driver->nodePool(), sym(1).VariableDeclaration);
+} break;
+
+case 269: {
+ AST::VariableDeclarationList *node = makeAstNode<AST::VariableDeclarationList> (driver->nodePool(),
+ sym(1).VariableDeclarationList, sym(3).VariableDeclaration);
+ node->commaToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 270: {
+ sym(1).Node = makeAstNode<AST::VariableDeclarationList> (driver->nodePool(), sym(1).VariableDeclaration);
+} break;
+
+case 271: {
+ sym(1).Node = makeAstNode<AST::VariableDeclarationList> (driver->nodePool(), sym(1).VariableDeclarationList, sym(3).VariableDeclaration);
+} break;
+
+case 272: {
+ AST::VariableDeclaration *node = makeAstNode<AST::VariableDeclaration> (driver->nodePool(), sym(1).sval, sym(2).Expression);
+ node->identifierToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 273: {
+ AST::VariableDeclaration *node = makeAstNode<AST::VariableDeclaration> (driver->nodePool(), sym(1).sval, sym(2).Expression);
+ node->identifierToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 274: {
+ // ### TODO: AST for initializer
+ sym(1) = sym(2);
+} break;
+
+case 275: {
+ sym(1).Node = 0;
+} break;
+
+case 277: {
+ // ### TODO: AST for initializer
+ sym(1) = sym(2);
+} break;
+
+case 278: {
+ sym(1).Node = 0;
+} break;
+
+case 280: {
+ AST::EmptyStatement *node = makeAstNode<AST::EmptyStatement> (driver->nodePool());
+ node->semicolonToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 282: {
+ AST::ExpressionStatement *node = makeAstNode<AST::ExpressionStatement> (driver->nodePool(), sym(1).Expression);
+ node->semicolonToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 283: {
+ AST::IfStatement *node = makeAstNode<AST::IfStatement> (driver->nodePool(), sym(3).Expression, sym(5).Statement, sym(7).Statement);
+ node->ifToken = loc(1);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ node->elseToken = loc(5);
+ sym(1).Node = node;
+} break;
+
+case 284: {
+ AST::IfStatement *node = makeAstNode<AST::IfStatement> (driver->nodePool(), sym(3).Expression, sym(5).Statement);
+ node->ifToken = loc(1);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 286: {
+ AST::DoWhileStatement *node = makeAstNode<AST::DoWhileStatement> (driver->nodePool(), sym(2).Statement, sym(5).Expression);
+ node->doToken = loc(1);
+ node->whileToken = loc(3);
+ node->lparenToken = loc(4);
+ node->rparenToken = loc(6);
+ node->semicolonToken = loc(7);
+ sym(1).Node = node;
+} break;
+
+case 287: {
+ AST::WhileStatement *node = makeAstNode<AST::WhileStatement> (driver->nodePool(), sym(3).Expression, sym(5).Statement);
+ node->whileToken = loc(1);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 288: {
+ AST::ForStatement *node = makeAstNode<AST::ForStatement> (driver->nodePool(), sym(3).Expression,
+ sym(5).Expression, sym(7).Expression, sym(9).Statement);
+ node->forToken = loc(1);
+ node->lparenToken = loc(2);
+ node->firstSemicolonToken = loc(4);
+ node->secondSemicolonToken = loc(6);
+ node->rparenToken = loc(8);
+ sym(1).Node = node;
+} break;
+
+case 289: {
+ AST::LocalForStatement *node = makeAstNode<AST::LocalForStatement> (driver->nodePool(),
+ sym(4).VariableDeclarationList->finish (/*readOnly=*/false), sym(6).Expression,
+ sym(8).Expression, sym(10).Statement);
+ node->forToken = loc(1);
+ node->lparenToken = loc(2);
+ node->varToken = loc(3);
+ node->firstSemicolonToken = loc(5);
+ node->secondSemicolonToken = loc(7);
+ node->rparenToken = loc(9);
+ sym(1).Node = node;
+} break;
+
+case 290: {
+ AST:: ForEachStatement *node = makeAstNode<AST::ForEachStatement> (driver->nodePool(), sym(3).Expression,
+ sym(5).Expression, sym(7).Statement);
+ node->forToken = loc(1);
+ node->lparenToken = loc(2);
+ node->inToken = loc(4);
+ node->rparenToken = loc(6);
+ sym(1).Node = node;
+} break;
+
+case 291: {
+ AST::LocalForEachStatement *node = makeAstNode<AST::LocalForEachStatement> (driver->nodePool(),
+ sym(4).VariableDeclaration, sym(6).Expression, sym(8).Statement);
+ node->forToken = loc(1);
+ node->lparenToken = loc(2);
+ node->varToken = loc(3);
+ node->inToken = loc(5);
+ node->rparenToken = loc(7);
+ sym(1).Node = node;
+} break;
+
+case 293: {
+ AST::ContinueStatement *node = makeAstNode<AST::ContinueStatement> (driver->nodePool());
+ node->continueToken = loc(1);
+ node->semicolonToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 295: {
+ AST::ContinueStatement *node = makeAstNode<AST::ContinueStatement> (driver->nodePool(), sym(2).sval);
+ node->continueToken = loc(1);
+ node->identifierToken = loc(2);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 297: {
+ AST::BreakStatement *node = makeAstNode<AST::BreakStatement> (driver->nodePool());
+ node->breakToken = loc(1);
+ node->semicolonToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 299: {
+ AST::BreakStatement *node = makeAstNode<AST::BreakStatement> (driver->nodePool(), sym(2).sval);
+ node->breakToken = loc(1);
+ node->identifierToken = loc(2);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 301: {
+ AST::ReturnStatement *node = makeAstNode<AST::ReturnStatement> (driver->nodePool(), sym(2).Expression);
+ node->returnToken = loc(1);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 302: {
+ AST::WithStatement *node = makeAstNode<AST::WithStatement> (driver->nodePool(), sym(3).Expression, sym(5).Statement);
+ node->withToken = loc(1);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 303: {
+ AST::SwitchStatement *node = makeAstNode<AST::SwitchStatement> (driver->nodePool(), sym(3).Expression, sym(5).CaseBlock);
+ node->switchToken = loc(1);
+ node->lparenToken = loc(2);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 304: {
+ AST::CaseBlock *node = makeAstNode<AST::CaseBlock> (driver->nodePool(), sym(2).CaseClauses);
+ node->lbraceToken = loc(1);
+ node->rbraceToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 305: {
+ AST::CaseBlock *node = makeAstNode<AST::CaseBlock> (driver->nodePool(), sym(2).CaseClauses, sym(3).DefaultClause, sym(4).CaseClauses);
+ node->lbraceToken = loc(1);
+ node->rbraceToken = loc(5);
+ sym(1).Node = node;
+} break;
+
+case 306: {
+ sym(1).Node = makeAstNode<AST::CaseClauses> (driver->nodePool(), sym(1).CaseClause);
+} break;
+
+case 307: {
+ sym(1).Node = makeAstNode<AST::CaseClauses> (driver->nodePool(), sym(1).CaseClauses, sym(2).CaseClause);
+} break;
+
+case 308: {
+ sym(1).Node = 0;
+} break;
+
+case 309: {
+ sym(1).Node = sym(1).CaseClauses->finish ();
+} break;
+
+case 310: {
+ AST::CaseClause *node = makeAstNode<AST::CaseClause> (driver->nodePool(), sym(2).Expression, sym(4).StatementList);
+ node->caseToken = loc(1);
+ node->colonToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 311: {
+ AST::DefaultClause *node = makeAstNode<AST::DefaultClause> (driver->nodePool(), sym(3).StatementList);
+ node->defaultToken = loc(1);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+case 312:
+case 313: {
+ AST::LabelledStatement *node = makeAstNode<AST::LabelledStatement> (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount()), sym(3).Statement);
+ node->identifierToken = loc(1);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 314: {
+ AST::LabelledStatement *node = makeAstNode<AST::LabelledStatement> (driver->nodePool(), sym(1).sval, sym(3).Statement);
+ node->identifierToken = loc(1);
+ node->colonToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 316: {
+ AST::ThrowStatement *node = makeAstNode<AST::ThrowStatement> (driver->nodePool(), sym(2).Expression);
+ node->throwToken = loc(1);
+ node->semicolonToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 317: {
+ AST::TryStatement *node = makeAstNode<AST::TryStatement> (driver->nodePool(), sym(2).Statement, sym(3).Catch);
+ node->tryToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 318: {
+ AST::TryStatement *node = makeAstNode<AST::TryStatement> (driver->nodePool(), sym(2).Statement, sym(3).Finally);
+ node->tryToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 319: {
+ AST::TryStatement *node = makeAstNode<AST::TryStatement> (driver->nodePool(), sym(2).Statement, sym(3).Catch, sym(4).Finally);
+ node->tryToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 320: {
+ AST::Catch *node = makeAstNode<AST::Catch> (driver->nodePool(), sym(3).sval, sym(5).Block);
+ node->catchToken = loc(1);
+ node->lparenToken = loc(2);
+ node->identifierToken = loc(3);
+ node->rparenToken = loc(4);
+ sym(1).Node = node;
+} break;
+
+case 321: {
+ AST::Finally *node = makeAstNode<AST::Finally> (driver->nodePool(), sym(2).Block);
+ node->finallyToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 323: {
+ AST::DebuggerStatement *node = makeAstNode<AST::DebuggerStatement> (driver->nodePool());
+ node->debuggerToken = loc(1);
+ node->semicolonToken = loc(2);
+ sym(1).Node = node;
+} break;
+
+case 324: {
+ AST::FunctionDeclaration *node = makeAstNode<AST::FunctionDeclaration> (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody);
+ node->functionToken = loc(1);
+ node->identifierToken = loc(2);
+ node->lparenToken = loc(3);
+ node->rparenToken = loc(5);
+ node->lbraceToken = loc(6);
+ node->rbraceToken = loc(8);
+ sym(1).Node = node;
+} break;
+
+case 325: {
+ AST::FunctionExpression *node = makeAstNode<AST::FunctionExpression> (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody);
+ node->functionToken = loc(1);
+ if (sym(2).sval)
+ node->identifierToken = loc(2);
+ node->lparenToken = loc(3);
+ node->rparenToken = loc(5);
+ node->lbraceToken = loc(6);
+ node->rbraceToken = loc(8);
+ sym(1).Node = node;
+} break;
+
+case 326: {
+ AST::FormalParameterList *node = makeAstNode<AST::FormalParameterList> (driver->nodePool(), sym(1).sval);
+ node->identifierToken = loc(1);
+ sym(1).Node = node;
+} break;
+
+case 327: {
+ AST::FormalParameterList *node = makeAstNode<AST::FormalParameterList> (driver->nodePool(), sym(1).FormalParameterList, sym(3).sval);
+ node->commaToken = loc(2);
+ node->identifierToken = loc(3);
+ sym(1).Node = node;
+} break;
+
+case 328: {
+ sym(1).Node = 0;
+} break;
+
+case 329: {
+ sym(1).Node = sym(1).FormalParameterList->finish ();
+} break;
+
+case 330: {
+ sym(1).Node = 0;
+} break;
+
+case 332: {
+ sym(1).Node = makeAstNode<AST::FunctionBody> (driver->nodePool(), sym(1).SourceElements->finish ());
+} break;
+
+case 333: {
+ sym(1).Node = makeAstNode<AST::Program> (driver->nodePool(), sym(1).SourceElements->finish ());
+} break;
+
+case 334: {
+ sym(1).Node = makeAstNode<AST::SourceElements> (driver->nodePool(), sym(1).SourceElement);
+} break;
+
+case 335: {
+ sym(1).Node = makeAstNode<AST::SourceElements> (driver->nodePool(), sym(1).SourceElements, sym(2).SourceElement);
+} break;
+
+case 336: {
+ sym(1).Node = makeAstNode<AST::StatementSourceElement> (driver->nodePool(), sym(1).Statement);
+} break;
+
+case 337: {
+ sym(1).Node = makeAstNode<AST::FunctionSourceElement> (driver->nodePool(), sym(1).FunctionDeclaration);
+} break;
+
+case 338: {
+ sym(1).sval = 0;
+} break;
+
+case 340: {
+ sym(1).Node = 0;
+} break;
+
+ } // switch
+ action = nt_action(state_stack[tos], lhs[r] - TERMINAL_COUNT);
+ } // if
+ } while (action != 0);
+
+ if (first_token == last_token) {
+ const int errorState = state_stack[tos];
+
+ // automatic insertion of `;'
+ if (yytoken != -1 && t_action(errorState, T_AUTOMATIC_SEMICOLON) && automatic(driver, yytoken)) {
+ SavedToken &tk = token_buffer[0];
+ tk.token = yytoken;
+ tk.dval = yylval;
+ tk.loc = yylloc;
+
+ yylloc = yyprevlloc;
+ yylloc.offset += yylloc.length;
+ yylloc.startColumn += yylloc.length;
+ yylloc.length = 0;
+
+ //const QString msg = qApp->translate("QmlParser", "Missing `;'");
+ //diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, yylloc, msg));
+
+ first_token = &token_buffer[0];
+ last_token = &token_buffer[1];
+
+ yytoken = T_SEMICOLON;
+ yylval = 0;
+
+ action = errorState;
+
+ goto _Lcheck_token;
+ }
+
+ hadErrors = true;
+
+ token_buffer[0].token = yytoken;
+ token_buffer[0].dval = yylval;
+ token_buffer[0].loc = yylloc;
+
+ token_buffer[1].token = yytoken = lexer->lex();
+ token_buffer[1].dval = yylval = lexer->dval();
+ token_buffer[1].loc = yylloc = location(lexer);
+
+ if (t_action(errorState, yytoken)) {
+ QString msg;
+ int token = token_buffer[0].token;
+ if (token < 0 || token >= TERMINAL_COUNT)
+ msg = qApp->translate("QmlParser", "Syntax error");
+ else
+ msg = qApp->translate("QmlParser", "Unexpected token `%1'").arg(QLatin1String(spell[token]));
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg));
+
+ action = errorState;
+ goto _Lcheck_token;
+ }
+
+ static int tokens[] = {
+ T_PLUS,
+ T_EQ,
+
+ T_COMMA,
+ T_COLON,
+ T_SEMICOLON,
+
+ T_RPAREN, T_RBRACKET, T_RBRACE,
+
+ T_NUMERIC_LITERAL,
+ T_IDENTIFIER,
+
+ T_LPAREN, T_LBRACKET, T_LBRACE,
+
+ EOF_SYMBOL
+ };
+
+ for (int *tk = tokens; *tk != EOF_SYMBOL; ++tk) {
+ int a = t_action(errorState, *tk);
+ if (a > 0 && t_action(a, yytoken)) {
+ const QString msg = qApp->translate("QmlParser", "Expected token `%1'").arg(QLatin1String(spell[*tk]));
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg));
+
+ yytoken = *tk;
+ yylval = 0;
+ yylloc = token_buffer[0].loc;
+ yylloc.length = 0;
+
+ first_token = &token_buffer[0];
+ last_token = &token_buffer[2];
+
+ action = errorState;
+ goto _Lcheck_token;
+ }
+ }
+
+ for (int tk = 1; tk < TERMINAL_COUNT; ++tk) {
+ if (tk == T_AUTOMATIC_SEMICOLON || tk == T_FEED_UI_PROGRAM ||
+ tk == T_FEED_JS_STATEMENT || tk == T_FEED_JS_EXPRESSION ||
+ tk == T_FEED_JS_SOURCE_ELEMENT)
+ continue;
+
+ int a = t_action(errorState, tk);
+ if (a > 0 && t_action(a, yytoken)) {
+ const QString msg = qApp->translate("QmlParser", "Expected token `%1'").arg(QLatin1String(spell[tk]));
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg));
+
+ yytoken = tk;
+ yylval = 0;
+ yylloc = token_buffer[0].loc;
+ yylloc.length = 0;
+
+ action = errorState;
+ goto _Lcheck_token;
+ }
+ }
+
+ const QString msg = qApp->translate("QmlParser", "Syntax error");
+ diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg));
+ }
+
+ return false;
+}
+
+QT_QML_END_NAMESPACE
+
+
diff --git a/src/declarative/qml/parser/qmljsparser_p.h b/src/declarative/qml/parser/qmljsparser_p.h
new file mode 100644
index 0000000..42fb422
--- /dev/null
+++ b/src/declarative/qml/parser/qmljsparser_p.h
@@ -0,0 +1,246 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+//
+// This file is automatically generated from qmljs.g.
+// Changes will be lost.
+//
+
+#ifndef QMLJSPARSER_P_H
+#define QMLJSPARSER_P_H
+
+#include "qmljsglobal_p.h"
+#include "qmljsgrammar_p.h"
+#include "qmljsast_p.h"
+#include "qmljsengine_p.h"
+
+#include <QtCore/QList>
+#include <QtCore/QString>
+
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS {
+
+class Engine;
+class NameId;
+
+class QML_PARSER_EXPORT Parser: protected QmlJSGrammar
+{
+public:
+ union Value {
+ int ival;
+ double dval;
+ NameId *sval;
+ AST::ArgumentList *ArgumentList;
+ AST::CaseBlock *CaseBlock;
+ AST::CaseClause *CaseClause;
+ AST::CaseClauses *CaseClauses;
+ AST::Catch *Catch;
+ AST::DefaultClause *DefaultClause;
+ AST::ElementList *ElementList;
+ AST::Elision *Elision;
+ AST::ExpressionNode *Expression;
+ AST::Finally *Finally;
+ AST::FormalParameterList *FormalParameterList;
+ AST::FunctionBody *FunctionBody;
+ AST::FunctionDeclaration *FunctionDeclaration;
+ AST::Node *Node;
+ AST::PropertyName *PropertyName;
+ AST::PropertyNameAndValueList *PropertyNameAndValueList;
+ AST::SourceElement *SourceElement;
+ AST::SourceElements *SourceElements;
+ AST::Statement *Statement;
+ AST::StatementList *StatementList;
+ AST::Block *Block;
+ AST::VariableDeclaration *VariableDeclaration;
+ AST::VariableDeclarationList *VariableDeclarationList;
+
+ AST::UiProgram *UiProgram;
+ AST::UiImportList *UiImportList;
+ AST::UiImport *UiImport;
+ AST::UiParameterList *UiParameterList;
+ AST::UiPublicMember *UiPublicMember;
+ AST::UiObjectDefinition *UiObjectDefinition;
+ AST::UiObjectInitializer *UiObjectInitializer;
+ AST::UiObjectBinding *UiObjectBinding;
+ AST::UiScriptBinding *UiScriptBinding;
+ AST::UiArrayBinding *UiArrayBinding;
+ AST::UiObjectMember *UiObjectMember;
+ AST::UiObjectMemberList *UiObjectMemberList;
+ AST::UiArrayMemberList *UiArrayMemberList;
+ AST::UiQualifiedId *UiQualifiedId;
+ AST::UiSignature *UiSignature;
+ AST::UiFormalList *UiFormalList;
+ AST::UiFormal *UiFormal;
+ };
+
+public:
+ Parser(Engine *engine);
+ ~Parser();
+
+ // parse a UI program
+ bool parse() { return parse(T_FEED_UI_PROGRAM); }
+ bool parseStatement() { return parse(T_FEED_JS_STATEMENT); }
+ bool parseExpression() { return parse(T_FEED_JS_EXPRESSION); }
+ bool parseSourceElement() { return parse(T_FEED_JS_SOURCE_ELEMENT); }
+ bool parseUiObjectMember() { return parse(T_FEED_UI_OBJECT_MEMBER); }
+ bool parseProgram() { return parse(T_FEED_JS_PROGRAM); }
+
+ AST::UiProgram *ast() const
+ { return AST::cast<AST::UiProgram *>(program); }
+
+ AST::Statement *statement() const
+ {
+ if (! program)
+ return 0;
+
+ return program->statementCast();
+ }
+
+ AST::ExpressionNode *expression() const
+ {
+ if (! program)
+ return 0;
+
+ return program->expressionCast();
+ }
+
+ AST::UiObjectMember *uiObjectMember() const
+ {
+ if (! program)
+ return 0;
+
+ return program->uiObjectMemberCast();
+ }
+
+ AST::Node *rootNode() const
+ { return program; }
+
+ QList<DiagnosticMessage> diagnosticMessages() const
+ { return diagnostic_messages; }
+
+ inline DiagnosticMessage diagnosticMessage() const
+ {
+ foreach (const DiagnosticMessage &d, diagnostic_messages) {
+ if (! d.kind == DiagnosticMessage::Warning)
+ return d;
+ }
+
+ return DiagnosticMessage();
+ }
+
+ inline QString errorMessage() const
+ { return diagnosticMessage().message; }
+
+ inline int errorLineNumber() const
+ { return diagnosticMessage().loc.startLine; }
+
+ inline int errorColumnNumber() const
+ { return diagnosticMessage().loc.startColumn; }
+
+protected:
+ bool parse(int startToken);
+
+ void reallocateStack();
+
+ inline Value &sym(int index)
+ { return sym_stack [tos + index - 1]; }
+
+ inline AST::SourceLocation &loc(int index)
+ { return location_stack [tos + index - 1]; }
+
+ AST::UiQualifiedId *reparseAsQualifiedId(AST::ExpressionNode *expr);
+
+protected:
+ Engine *driver;
+ int tos;
+ int stack_size;
+ Value *sym_stack;
+ int *state_stack;
+ AST::SourceLocation *location_stack;
+
+ AST::Node *program;
+
+ // error recovery
+ enum { TOKEN_BUFFER_SIZE = 3 };
+
+ struct SavedToken {
+ int token;
+ double dval;
+ AST::SourceLocation loc;
+ };
+
+ double yylval;
+ AST::SourceLocation yylloc;
+ AST::SourceLocation yyprevlloc;
+
+ SavedToken token_buffer[TOKEN_BUFFER_SIZE];
+ SavedToken *first_token;
+ SavedToken *last_token;
+
+ QList<DiagnosticMessage> diagnostic_messages;
+};
+
+} // end of namespace QmlJS
+
+
+
+#define J_SCRIPT_REGEXPLITERAL_RULE1 74
+
+#define J_SCRIPT_REGEXPLITERAL_RULE2 75
+
+QT_QML_END_NAMESPACE
+
+
+
+#endif // QMLJSPARSER_P_H
diff --git a/src/declarative/qml/qbitfield_p.h b/src/declarative/qml/qbitfield_p.h
new file mode 100644
index 0000000..8b3afdb
--- /dev/null
+++ b/src/declarative/qml/qbitfield_p.h
@@ -0,0 +1,165 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QBITFIELD_P_H
+#define QBITFIELD_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 QBitField
+{
+public:
+ inline QBitField();
+ inline QBitField(const quint32 *, int bits);
+ inline QBitField(const QBitField &);
+ inline ~QBitField();
+
+ inline QBitField &operator=(const QBitField &);
+
+ inline quint32 size() const;
+ inline QBitField united(const QBitField &);
+ inline bool testBit(int) const;
+
+private:
+ quint32 bits:31;
+ quint32 *ownData;
+ const quint32 *data;
+};
+
+QBitField::QBitField()
+: bits(0), ownData(0), data(0)
+{
+}
+
+QBitField::QBitField(const quint32 *bitData, int bitCount)
+: bits((quint32)bitCount), ownData(0), data(bitData)
+{
+}
+
+QBitField::QBitField(const QBitField &other)
+: bits(other.bits), ownData(other.ownData), data(other.data)
+{
+ if (ownData)
+ ++(*ownData);
+}
+
+QBitField::~QBitField()
+{
+ if (ownData)
+ if(0 == --(*ownData)) delete [] ownData;
+}
+
+QBitField &QBitField::operator=(const QBitField &other)
+{
+ if (other.data == data)
+ return *this;
+
+ if (ownData)
+ if(0 == --(*ownData)) delete [] ownData;
+
+ bits = other.bits;
+ ownData = other.ownData;
+ data = other.data;
+
+ if (ownData)
+ ++(*ownData);
+
+ return *this;
+}
+
+inline quint32 QBitField::size() const
+{
+ return bits;
+}
+
+QBitField QBitField::united(const QBitField &o)
+{
+ if (o.bits == 0) {
+ return *this;
+ } else if (bits == 0) {
+ return o;
+ } else {
+ int max = (bits > o.bits)?bits:o.bits;
+ int length = (max + 31) / 32;
+ QBitField rv;
+ rv.bits = max;
+ rv.ownData = new quint32[length + 1];
+ *(rv.ownData) = 1;
+ rv.data = rv.ownData + 1;
+ if (bits > o.bits) {
+ ::memcpy((quint32 *)rv.data, data, length * sizeof(quint32));
+ for (quint32 ii = 0; ii < (o.bits + quint32(31)) / 32; ++ii)
+ ((quint32 *)rv.data)[ii] |= o.data[ii];
+ } else {
+ ::memcpy((quint32 *)rv.data, o.data, length * sizeof(quint32));
+ for (quint32 ii = 0; ii < (bits + quint32(31)) / 32; ++ii)
+ ((quint32 *)rv.data)[ii] |= data[ii];
+ }
+ return rv;
+ }
+}
+
+bool QBitField::testBit(int b) const
+{
+ Q_ASSERT(b >= 0);
+ if ((quint32)b < bits) {
+ return data[b / 32] & (1 << (b % 32));
+ } else {
+ return false;
+ }
+}
+
+QT_END_NAMESPACE
+
+#endif // QBITFIELD_P_H
diff --git a/src/declarative/qml/qmetaobjectbuilder.cpp b/src/declarative/qml/qmetaobjectbuilder.cpp
new file mode 100644
index 0000000..11b9f80
--- /dev/null
+++ b/src/declarative/qml/qmetaobjectbuilder.cpp
@@ -0,0 +1,2575 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmetaobjectbuilder_p.h"
+
+#ifndef Q_OS_WIN
+#include <stdint.h>
+#endif
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QMetaObjectBuilder
+ \internal
+ \brief The QMetaObjectBuilder class supports building QMetaObject objects at runtime.
+
+*/
+
+/*!
+ \enum QMetaObjectBuilder::AddMember
+ This enum defines which members of QMetaObject should be copied by QMetaObjectBuilder::addMetaObject()
+
+ \value ClassName Add the class name.
+ \value SuperClass Add the super class.
+ \value Methods Add methods that aren't signals or slots.
+ \value Signals Add signals.
+ \value Slots Add slots.
+ \value Constructors Add constructors.
+ \value Properties Add properties.
+ \value Enumerators Add enumerators.
+ \value ClassInfos Add items of class information.
+ \value RelatedMetaObjects Add related meta objects.
+ \value StaticMetacall Add the static metacall function.
+ \value PublicMethods Add public methods (ignored for signals).
+ \value ProtectedMethods Add protected methods (ignored for signals).
+ \value PrivateMethods All private methods (ignored for signals).
+ \value AllMembers Add all members.
+ \value AllPrimaryMembers Add everything except the class name, super class, and static metacall function.
+*/
+
+// copied from moc's generator.cpp
+uint qvariant_nameToType(const char* name)
+{
+ if (!name)
+ return 0;
+
+ if (strcmp(name, "QVariant") == 0)
+ return 0xffffffff;
+ if (strcmp(name, "QCString") == 0)
+ return QMetaType::QByteArray;
+ if (strcmp(name, "Q_LLONG") == 0)
+ return QMetaType::LongLong;
+ if (strcmp(name, "Q_ULLONG") == 0)
+ return QMetaType::ULongLong;
+ if (strcmp(name, "QIconSet") == 0)
+ return QMetaType::QIcon;
+
+ uint tp = QMetaType::type(name);
+ return tp < QMetaType::User ? tp : 0;
+}
+
+/*
+ Returns true if the type is a QVariant types.
+*/
+bool isVariantType(const char* type)
+{
+ return qvariant_nameToType(type) != 0;
+}
+
+// copied from qmetaobject.cpp
+// do not touch without touching the moc as well
+enum PropertyFlags {
+ Invalid = 0x00000000,
+ Readable = 0x00000001,
+ Writable = 0x00000002,
+ Resettable = 0x00000004,
+ EnumOrFlag = 0x00000008,
+ StdCppSet = 0x00000100,
+// Override = 0x00000200,
+ Designable = 0x00001000,
+ ResolveDesignable = 0x00002000,
+ Scriptable = 0x00004000,
+ ResolveScriptable = 0x00008000,
+ Stored = 0x00010000,
+ ResolveStored = 0x00020000,
+ Editable = 0x00040000,
+ ResolveEditable = 0x00080000,
+ User = 0x00100000,
+ ResolveUser = 0x00200000,
+ Notify = 0x00400000,
+ Dynamic = 0x00800000
+};
+
+enum MethodFlags {
+ AccessPrivate = 0x00,
+ AccessProtected = 0x01,
+ AccessPublic = 0x02,
+ AccessMask = 0x03, //mask
+
+ MethodMethod = 0x00,
+ MethodSignal = 0x04,
+ MethodSlot = 0x08,
+ MethodConstructor = 0x0c,
+ MethodTypeMask = 0x0c,
+
+ MethodCompatibility = 0x10,
+ MethodCloned = 0x20,
+ MethodScriptable = 0x40
+};
+
+struct QMetaObjectPrivate
+{
+ int revision;
+ int className;
+ int classInfoCount, classInfoData;
+ int methodCount, methodData;
+ int propertyCount, propertyData;
+ int enumeratorCount, enumeratorData;
+ int constructorCount, constructorData;
+ int flags;
+};
+
+static inline const QMetaObjectPrivate *priv(const uint* data)
+{ return reinterpret_cast<const QMetaObjectPrivate*>(data); }
+// end of copied lines from qmetaobject.cpp
+
+class QMetaMethodBuilderPrivate
+{
+public:
+ QMetaMethodBuilderPrivate
+ (QMetaMethod::MethodType _methodType,
+ const QByteArray& _signature,
+ const QByteArray& _returnType = QByteArray(),
+ QMetaMethod::Access _access = QMetaMethod::Public)
+ : signature(QMetaObject::normalizedSignature(_signature.constData())),
+ returnType(QMetaObject::normalizedType(_returnType)),
+ attributes(((int)_access) | (((int)_methodType) << 2))
+ {
+ }
+
+ QByteArray signature;
+ QByteArray returnType;
+ QList<QByteArray> parameterNames;
+ QByteArray tag;
+ int attributes;
+
+ QMetaMethod::MethodType methodType() const
+ {
+ return (QMetaMethod::MethodType)((attributes & MethodTypeMask) >> 2);
+ }
+
+ QMetaMethod::Access access() const
+ {
+ return (QMetaMethod::Access)(attributes & AccessMask);
+ }
+
+ void setAccess(QMetaMethod::Access value)
+ {
+ attributes = ((attributes & ~AccessMask) | (int)value);
+ }
+};
+
+class QMetaPropertyBuilderPrivate
+{
+public:
+ QMetaPropertyBuilderPrivate
+ (const QByteArray& _name, const QByteArray& _type, int notifierIdx=-1)
+ : name(_name),
+ type(QMetaObject::normalizedType(_type.constData())),
+ flags(Readable | Writable), notifySignal(-1)
+ {
+ if (notifierIdx >= 0) {
+ flags |= Notify;
+ notifySignal = notifierIdx;
+ }
+ }
+
+ QByteArray name;
+ QByteArray type;
+ int flags;
+ int notifySignal;
+
+ bool flag(int f) const
+ {
+ return ((flags & f) != 0);
+ }
+
+ void setFlag(int f, bool value)
+ {
+ if (value)
+ flags |= f;
+ else
+ flags &= ~f;
+ }
+};
+
+class QMetaEnumBuilderPrivate
+{
+public:
+ QMetaEnumBuilderPrivate(const QByteArray& _name)
+ : name(_name), isFlag(false)
+ {
+ }
+
+ QByteArray name;
+ bool isFlag;
+ QList<QByteArray> keys;
+ QList<int> values;
+};
+
+class QMetaObjectBuilderPrivate
+{
+public:
+ QMetaObjectBuilderPrivate()
+ : flags(0)
+ {
+ superClass = &QObject::staticMetaObject;
+ staticMetacallFunction = 0;
+ }
+
+ QByteArray className;
+ const QMetaObject *superClass;
+ QMetaObjectBuilder::StaticMetacallFunction staticMetacallFunction;
+ QList<QMetaMethodBuilderPrivate> methods;
+ QList<QMetaMethodBuilderPrivate> constructors;
+ QList<QMetaPropertyBuilderPrivate> properties;
+ QList<QByteArray> classInfoNames;
+ QList<QByteArray> classInfoValues;
+ QList<QMetaEnumBuilderPrivate> enumerators;
+#ifdef Q_NO_DATA_RELOCATION
+ QList<QMetaObjectAccessor> relatedMetaObjects;
+#else
+ QList<const QMetaObject *> relatedMetaObjects;
+#endif
+ int flags;
+};
+
+/*!
+ Constructs a new QMetaObjectBuilder.
+*/
+QMetaObjectBuilder::QMetaObjectBuilder()
+{
+ d = new QMetaObjectBuilderPrivate();
+}
+
+/*!
+ Constructs a new QMetaObjectBuilder which is a copy of the
+ meta object information in \a prototype. Note: the super class
+ contents for \a prototype are not copied, only the immediate
+ class that is defined by \a prototype.
+
+ The \a members parameter indicates which members of \a prototype
+ should be added. The default is AllMembers.
+
+ \sa addMetaObject()
+*/
+QMetaObjectBuilder::QMetaObjectBuilder
+ (const QMetaObject *prototype, QMetaObjectBuilder::AddMembers members)
+{
+ d = new QMetaObjectBuilderPrivate();
+ addMetaObject(prototype, members);
+}
+
+/*!
+ Destroys this meta object builder.
+*/
+QMetaObjectBuilder::~QMetaObjectBuilder()
+{
+ delete d;
+}
+
+/*!
+ Returns the name of the class being constructed by this
+ meta object builder. The default value is an empty QByteArray.
+
+ \sa setClassName(), superClass()
+*/
+QByteArray QMetaObjectBuilder::className() const
+{
+ return d->className;
+}
+
+/*!
+ Sets the \a name of the class being constructed by this
+ meta object builder.
+
+ \sa className(), setSuperClass()
+*/
+void QMetaObjectBuilder::setClassName(const QByteArray& name)
+{
+ d->className = name;
+}
+
+/*!
+ Returns the superclass meta object of the class being constructed
+ by this meta object builder. The default value is the meta object
+ for QObject.
+
+ \sa setSuperClass(), className()
+*/
+const QMetaObject *QMetaObjectBuilder::superClass() const
+{
+ return d->superClass;
+}
+
+/*!
+ Sets the superclass meta object of the class being constructed
+ by this meta object builder to \a meta. The \a meta parameter
+ must not be null.
+
+ \sa superClass(), setClassName()
+*/
+void QMetaObjectBuilder::setSuperClass(const QMetaObject *meta)
+{
+ Q_ASSERT(meta);
+ d->superClass = meta;
+}
+
+/*!
+ Returns the flags of the class being constructed by this meta object
+ builder.
+
+ \sa setFlags()
+*/
+QMetaObjectBuilder::MetaObjectFlags QMetaObjectBuilder::flags() const
+{
+ return (QMetaObjectBuilder::MetaObjectFlags)d->flags;
+}
+
+/*!
+ Sets the \a flags of the class being constructed by this meta object
+ builder.
+
+ \sa flags()
+*/
+void QMetaObjectBuilder::setFlags(MetaObjectFlags flags)
+{
+ d->flags = flags;
+}
+
+/*!
+ Returns the number of methods in this class, excluding the number
+ of methods in the base class. These include signals and slots
+ as well as normal member functions.
+
+ \sa addMethod(), method(), removeMethod(), indexOfMethod()
+*/
+int QMetaObjectBuilder::methodCount() const
+{
+ return d->methods.size();
+}
+
+/*!
+ Returns the number of constructors in this class.
+
+ \sa addConstructor(), constructor(), removeConstructor(), indexOfConstructor()
+*/
+int QMetaObjectBuilder::constructorCount() const
+{
+ return d->constructors.size();
+}
+
+/*!
+ Returns the number of properties in this class, excluding the number
+ of properties in the base class.
+
+ \sa addProperty(), property(), removeProperty(), indexOfProperty()
+*/
+int QMetaObjectBuilder::propertyCount() const
+{
+ return d->properties.size();
+}
+
+/*!
+ Returns the number of enumerators in this class, excluding the
+ number of enumerators in the base class.
+
+ \sa addEnumerator(), enumerator(), removeEnumerator()
+ \sa indexOfEnumerator()
+*/
+int QMetaObjectBuilder::enumeratorCount() const
+{
+ return d->enumerators.size();
+}
+
+/*!
+ Returns the number of items of class information in this class,
+ exclusing the number of items of class information in the base class.
+
+ \sa addClassInfo(), classInfoName(), classInfoValue(), removeClassInfo()
+ \sa indexOfClassInfo()
+*/
+int QMetaObjectBuilder::classInfoCount() const
+{
+ return d->classInfoNames.size();
+}
+
+/*!
+ Returns the number of related meta objects that are associated
+ with this class.
+
+ Related meta objects are used when resolving the enumerated type
+ associated with a property, where the enumerated type is in a
+ different class from the property.
+
+ \sa addRelatedMetaObject(), relatedMetaObject()
+ \sa removeRelatedMetaObject()
+*/
+int QMetaObjectBuilder::relatedMetaObjectCount() const
+{
+ return d->relatedMetaObjects.size();
+}
+
+/*!
+ Adds a new public method to this class with the specified \a signature.
+ Returns an object that can be used to adjust the other attributes
+ of the method. The \a signature will be normalized before it is
+ added to the class.
+
+ \sa method(), methodCount(), removeMethod(), indexOfMethod()
+*/
+QMetaMethodBuilder QMetaObjectBuilder::addMethod(const QByteArray& signature)
+{
+ int index = d->methods.size();
+ d->methods.append(QMetaMethodBuilderPrivate(QMetaMethod::Method, signature));
+ return QMetaMethodBuilder(this, index);
+}
+
+/*!
+ Adds a new public method to this class with the specified
+ \a signature and \a returnType. Returns an object that can be
+ used to adjust the other attributes of the method. The \a signature
+ and \a returnType will be normalized before they are added to
+ the class. If \a returnType is empty, then it indicates that
+ the method has \c{void} as its return type.
+
+ \sa method(), methodCount(), removeMethod(), indexOfMethod()
+*/
+QMetaMethodBuilder QMetaObjectBuilder::addMethod
+ (const QByteArray& signature, const QByteArray& returnType)
+{
+ int index = d->methods.size();
+ d->methods.append(QMetaMethodBuilderPrivate
+ (QMetaMethod::Method, signature, returnType));
+ return QMetaMethodBuilder(this, index);
+}
+
+/*!
+ Adds a new public method to this class that has the same information as
+ \a prototype. This is used to clone the methods of an existing
+ QMetaObject. Returns an object that can be used to adjust the
+ attributes of the method.
+
+ This function will detect if \a prototype is an ordinary method,
+ signal, slot, or constructor and act accordingly.
+
+ \sa method(), methodCount(), removeMethod(), indexOfMethod()
+*/
+QMetaMethodBuilder QMetaObjectBuilder::addMethod(const QMetaMethod& prototype)
+{
+ QMetaMethodBuilder method;
+ if (prototype.methodType() == QMetaMethod::Method)
+ method = addMethod(prototype.signature());
+ else if (prototype.methodType() == QMetaMethod::Signal)
+ method = addSignal(prototype.signature());
+ else if (prototype.methodType() == QMetaMethod::Slot)
+ method = addSlot(prototype.signature());
+ else if (prototype.methodType() == QMetaMethod::Constructor)
+ method = addConstructor(prototype.signature());
+ method.setReturnType(prototype.typeName());
+ method.setParameterNames(prototype.parameterNames());
+ method.setTag(prototype.tag());
+ method.setAccess(prototype.access());
+ method.setAttributes(prototype.attributes());
+ return method;
+}
+
+/*!
+ Adds a new public slot to this class with the specified \a signature.
+ Returns an object that can be used to adjust the other attributes
+ of the slot. The \a signature will be normalized before it is
+ added to the class.
+
+ \sa addMethod(), addSignal(), indexOfSlot()
+*/
+QMetaMethodBuilder QMetaObjectBuilder::addSlot(const QByteArray& signature)
+{
+ int index = d->methods.size();
+ d->methods.append(QMetaMethodBuilderPrivate(QMetaMethod::Slot, signature));
+ return QMetaMethodBuilder(this, index);
+}
+
+/*!
+ Adds a new signal to this class with the specified \a signature.
+ Returns an object that can be used to adjust the other attributes
+ of the signal. The \a signature will be normalized before it is
+ added to the class.
+
+ \sa addMethod(), addSlot(), indexOfSignal()
+*/
+QMetaMethodBuilder QMetaObjectBuilder::addSignal(const QByteArray& signature)
+{
+ int index = d->methods.size();
+ d->methods.append(QMetaMethodBuilderPrivate
+ (QMetaMethod::Signal, signature, QByteArray(), QMetaMethod::Protected));
+ return QMetaMethodBuilder(this, index);
+}
+
+/*!
+ Adds a new constructor to this class with the specified \a signature.
+ Returns an object that can be used to adjust the other attributes
+ of the constructor. The \a signature will be normalized before it is
+ added to the class.
+
+ \sa constructor(), constructorCount(), removeConstructor()
+ \sa indexOfConstructor()
+*/
+QMetaMethodBuilder QMetaObjectBuilder::addConstructor(const QByteArray& signature)
+{
+ int index = d->constructors.size();
+ d->constructors.append(QMetaMethodBuilderPrivate(QMetaMethod::Constructor, signature));
+ return QMetaMethodBuilder(this, -(index + 1));
+}
+
+/*!
+ Adds a new constructor to this class that has the same information as
+ \a prototype. This is used to clone the constructors of an existing
+ QMetaObject. Returns an object that can be used to adjust the
+ attributes of the constructor.
+
+ This function requires that \a prototype be a constructor.
+
+ \sa constructor(), constructorCount(), removeConstructor()
+ \sa indexOfConstructor()
+*/
+QMetaMethodBuilder QMetaObjectBuilder::addConstructor(const QMetaMethod& prototype)
+{
+ Q_ASSERT(prototype.methodType() == QMetaMethod::Constructor);
+ QMetaMethodBuilder ctor = addConstructor(prototype.signature());
+ ctor.setReturnType(prototype.typeName());
+ ctor.setParameterNames(prototype.parameterNames());
+ ctor.setTag(prototype.tag());
+ ctor.setAccess(prototype.access());
+ ctor.setAttributes(prototype.attributes());
+ return ctor;
+}
+
+/*!
+ Adds a new readable/writable property to this class with the
+ specified \a name and \a type. Returns an object that can be used
+ to adjust the other attributes of the property. The \a type will
+ be normalized before it is added to the class. \a notifierId will
+ be registered as the property's \e notify signal.
+
+ \sa property(), propertyCount(), removeProperty(), indexOfProperty()
+*/
+QMetaPropertyBuilder QMetaObjectBuilder::addProperty
+ (const QByteArray& name, const QByteArray& type, int notifierId)
+{
+ int index = d->properties.size();
+ d->properties.append(QMetaPropertyBuilderPrivate(name, type, notifierId));
+ return QMetaPropertyBuilder(this, index);
+}
+
+/*!
+ Adds a new property to this class that has the same information as
+ \a prototype. This is used to clone the properties of an existing
+ QMetaObject. Returns an object that can be used to adjust the
+ attributes of the property.
+
+ \sa property(), propertyCount(), removeProperty(), indexOfProperty()
+*/
+QMetaPropertyBuilder QMetaObjectBuilder::addProperty(const QMetaProperty& prototype)
+{
+ QMetaPropertyBuilder property = addProperty(prototype.name(), prototype.typeName());
+ property.setReadable(prototype.isReadable());
+ property.setWritable(prototype.isWritable());
+ property.setResettable(prototype.isResettable());
+ property.setDesignable(prototype.isDesignable());
+ property.setScriptable(prototype.isScriptable());
+ property.setStored(prototype.isStored());
+ property.setEditable(prototype.isEditable());
+ property.setUser(prototype.isUser());
+ property.setStdCppSet(prototype.hasStdCppSet());
+ property.setEnumOrFlag(prototype.isEnumType());
+ if (prototype.hasNotifySignal()) {
+ // Find an existing method for the notify signal, or add a new one.
+ QMetaMethod method = prototype.notifySignal();
+ int index = indexOfMethod(method.signature());
+ if (index == -1)
+ index = addMethod(method).index();
+ d->properties[property._index].notifySignal = index;
+ d->properties[property._index].setFlag(Notify, true);
+ }
+ return property;
+}
+
+/*!
+ Adds a new enumerator to this class with the specified
+ \a name. Returns an object that can be used to adjust
+ the other attributes of the enumerator.
+
+ \sa enumerator(), enumeratorCount(), removeEnumerator(),
+ \sa indexOfEnumerator()
+*/
+QMetaEnumBuilder QMetaObjectBuilder::addEnumerator(const QByteArray& name)
+{
+ int index = d->enumerators.size();
+ d->enumerators.append(QMetaEnumBuilderPrivate(name));
+ return QMetaEnumBuilder(this, index);
+}
+
+/*!
+ Adds a new enumerator to this class that has the same information as
+ \a prototype. This is used to clone the enumerators of an existing
+ QMetaObject. Returns an object that can be used to adjust the
+ attributes of the enumerator.
+
+ \sa enumerator(), enumeratorCount(), removeEnumerator(),
+ \sa indexOfEnumerator()
+*/
+QMetaEnumBuilder QMetaObjectBuilder::addEnumerator(const QMetaEnum& prototype)
+{
+ QMetaEnumBuilder en = addEnumerator(prototype.name());
+ en.setIsFlag(prototype.isFlag());
+ int count = prototype.keyCount();
+ for (int index = 0; index < count; ++index)
+ en.addKey(prototype.key(index), prototype.value(index));
+ return en;
+}
+
+/*!
+ Adds \a name and \a value as an item of class information to this class.
+ Returns the index of the new item of class information.
+
+ \sa classInfoCount(), classInfoName(), classInfoValue(), removeClassInfo()
+ \sa indexOfClassInfo()
+*/
+int QMetaObjectBuilder::addClassInfo(const QByteArray& name, const QByteArray& value)
+{
+ int index = d->classInfoNames.size();
+ d->classInfoNames += name;
+ d->classInfoValues += value;
+ return index;
+}
+
+/*!
+ Adds \a meta to this class as a related meta object. Returns
+ the index of the new related meta object entry.
+
+ Related meta objects are used when resolving the enumerated type
+ associated with a property, where the enumerated type is in a
+ different class from the property.
+
+ \sa relatedMetaObjectCount(), relatedMetaObject()
+ \sa removeRelatedMetaObject()
+*/
+#ifdef Q_NO_DATA_RELOCATION
+int QMetaObjectBuilder::addRelatedMetaObject(const QMetaObjectAccessor &meta)
+#else
+int QMetaObjectBuilder::addRelatedMetaObject(const QMetaObject *meta)
+#endif
+{
+ Q_ASSERT(meta);
+ int index = d->relatedMetaObjects.size();
+ d->relatedMetaObjects.append(meta);
+ return index;
+}
+
+/*!
+ Adds the contents of \a prototype to this meta object builder.
+ This function is useful for cloning the contents of an existing QMetaObject.
+
+ The \a members parameter indicates which members of \a prototype
+ should be added. The default is AllMembers.
+*/
+void QMetaObjectBuilder::addMetaObject
+ (const QMetaObject *prototype, QMetaObjectBuilder::AddMembers members)
+{
+ Q_ASSERT(prototype);
+ int index;
+
+ if ((members & ClassName) != 0)
+ d->className = prototype->className();
+
+ if ((members & SuperClass) != 0)
+ d->superClass = prototype->superClass();
+
+ if ((members & (Methods | Signals | Slots)) != 0) {
+ for (index = prototype->methodOffset(); index < prototype->methodCount(); ++index) {
+ QMetaMethod method = prototype->method(index);
+ if (method.methodType() != QMetaMethod::Signal) {
+ if (method.access() == QMetaMethod::Public && (members & PublicMethods) == 0)
+ continue;
+ if (method.access() == QMetaMethod::Private && (members & PrivateMethods) == 0)
+ continue;
+ if (method.access() == QMetaMethod::Protected && (members & ProtectedMethods) == 0)
+ continue;
+ }
+ if (method.methodType() == QMetaMethod::Method && (members & Methods) != 0) {
+ addMethod(method);
+ } else if (method.methodType() == QMetaMethod::Signal &&
+ (members & Signals) != 0) {
+ addMethod(method);
+ } else if (method.methodType() == QMetaMethod::Slot &&
+ (members & Slots) != 0) {
+ addMethod(method);
+ }
+ }
+ }
+
+ if ((members & Constructors) != 0) {
+ for (index = 0; index < prototype->constructorCount(); ++index)
+ addConstructor(prototype->constructor(index));
+ }
+
+ if ((members & Properties) != 0) {
+ for (index = prototype->propertyOffset(); index < prototype->propertyCount(); ++index)
+ addProperty(prototype->property(index));
+ }
+
+ if ((members & Enumerators) != 0) {
+ for (index = prototype->enumeratorOffset(); index < prototype->enumeratorCount(); ++index)
+ addEnumerator(prototype->enumerator(index));
+ }
+
+ if ((members & ClassInfos) != 0) {
+ for (index = prototype->classInfoOffset(); index < prototype->classInfoCount(); ++index) {
+ QMetaClassInfo ci = prototype->classInfo(index);
+ addClassInfo(ci.name(), ci.value());
+ }
+ }
+
+ if ((members & RelatedMetaObjects) != 0) {
+#ifdef Q_NO_DATA_RELOCATION
+ const QMetaObjectAccessor *objects = 0;
+#else
+ const QMetaObject **objects;
+ if (priv(prototype->d.data)->revision < 2) {
+ objects = (const QMetaObject **)(prototype->d.extradata);
+ } else
+#endif
+ {
+ const QMetaObjectExtraData *extra = (const QMetaObjectExtraData *)(prototype->d.extradata);
+ if (extra)
+ objects = extra->objects;
+ else
+ objects = 0;
+ }
+ if (objects) {
+ while (*objects != 0) {
+ addRelatedMetaObject(*objects);
+ ++objects;
+ }
+ }
+ }
+
+ if ((members & StaticMetacall) != 0) {
+ if (priv(prototype->d.data)->revision >= 2) {
+ const QMetaObjectExtraData *extra =
+ (const QMetaObjectExtraData *)(prototype->d.extradata);
+ if (extra && extra->static_metacall)
+ setStaticMetacallFunction(extra->static_metacall);
+ }
+ }
+}
+
+/*!
+ Returns the method at \a index in this class.
+
+ \sa methodCount(), addMethod(), removeMethod(), indexOfMethod()
+*/
+QMetaMethodBuilder QMetaObjectBuilder::method(int index) const
+{
+ if (index >= 0 && index < d->methods.size())
+ return QMetaMethodBuilder(this, index);
+ else
+ return QMetaMethodBuilder();
+}
+
+/*!
+ Returns the constructor at \a index in this class.
+
+ \sa methodCount(), addMethod(), removeMethod(), indexOfConstructor()
+*/
+QMetaMethodBuilder QMetaObjectBuilder::constructor(int index) const
+{
+ if (index >= 0 && index < d->constructors.size())
+ return QMetaMethodBuilder(this, -(index + 1));
+ else
+ return QMetaMethodBuilder();
+}
+
+/*!
+ Returns the property at \a index in this class.
+
+ \sa methodCount(), addMethod(), removeMethod(), indexOfProperty()
+*/
+QMetaPropertyBuilder QMetaObjectBuilder::property(int index) const
+{
+ if (index >= 0 && index < d->properties.size())
+ return QMetaPropertyBuilder(this, index);
+ else
+ return QMetaPropertyBuilder();
+}
+
+/*!
+ Returns the enumerator at \a index in this class.
+
+ \sa enumeratorCount(), addEnumerator(), removeEnumerator()
+ \sa indexOfEnumerator()
+*/
+QMetaEnumBuilder QMetaObjectBuilder::enumerator(int index) const
+{
+ if (index >= 0 && index < d->enumerators.size())
+ return QMetaEnumBuilder(this, index);
+ else
+ return QMetaEnumBuilder();
+}
+
+/*!
+ Returns the related meta object at \a index in this class.
+
+ Related meta objects are used when resolving the enumerated type
+ associated with a property, where the enumerated type is in a
+ different class from the property.
+
+ \sa relatedMetaObjectCount(), addRelatedMetaObject()
+ \sa removeRelatedMetaObject()
+*/
+const QMetaObject *QMetaObjectBuilder::relatedMetaObject(int index) const
+{
+ if (index >= 0 && index < d->relatedMetaObjects.size())
+#ifdef Q_NO_DATA_RELOCATION
+ return &((*(d->relatedMetaObjects[index]))());
+#else
+ return d->relatedMetaObjects[index];
+#endif
+ else
+ return 0;
+}
+
+/*!
+ Returns the name of the item of class information at \a index
+ in this class.
+
+ \sa classInfoCount(), addClassInfo(), classInfoValue(), removeClassInfo()
+ \sa indexOfClassInfo()
+*/
+QByteArray QMetaObjectBuilder::classInfoName(int index) const
+{
+ if (index >= 0 && index < d->classInfoNames.size())
+ return d->classInfoNames[index];
+ else
+ return QByteArray();
+}
+
+/*!
+ Returns the value of the item of class information at \a index
+ in this class.
+
+ \sa classInfoCount(), addClassInfo(), classInfoName(), removeClassInfo()
+ \sa indexOfClassInfo()
+*/
+QByteArray QMetaObjectBuilder::classInfoValue(int index) const
+{
+ if (index >= 0 && index < d->classInfoValues.size())
+ return d->classInfoValues[index];
+ else
+ return QByteArray();
+}
+
+/*!
+ Removes the method at \a index from this class. The indices of
+ all following methods will be adjusted downwards by 1. If the
+ method is registered as a notify signal on a property, then the
+ notify signal will be removed from the property.
+
+ \sa methodCount(), addMethod(), method(), indexOfMethod()
+*/
+void QMetaObjectBuilder::removeMethod(int index)
+{
+ if (index >= 0 && index < d->methods.size()) {
+ d->methods.removeAt(index);
+ for (int prop = 0; prop < d->properties.size(); ++prop) {
+ // Adjust the indices of property notify signal references.
+ if (d->properties[prop].notifySignal == index) {
+ d->properties[prop].notifySignal = -1;
+ d->properties[prop].setFlag(Notify, false);
+ } else if (d->properties[prop].notifySignal > index)
+ (d->properties[prop].notifySignal)--;
+ }
+ }
+}
+
+/*!
+ Removes the constructor at \a index from this class. The indices of
+ all following constructors will be adjusted downwards by 1.
+
+ \sa constructorCount(), addConstructor(), constructor()
+ \sa indexOfConstructor()
+*/
+void QMetaObjectBuilder::removeConstructor(int index)
+{
+ if (index >= 0 && index < d->constructors.size())
+ d->constructors.removeAt(index);
+}
+
+/*!
+ Removes the property at \a index from this class. The indices of
+ all following properties will be adjusted downwards by 1.
+
+ \sa propertyCount(), addProperty(), property(), indexOfProperty()
+*/
+void QMetaObjectBuilder::removeProperty(int index)
+{
+ if (index >= 0 && index < d->properties.size())
+ d->properties.removeAt(index);
+}
+
+/*!
+ Removes the enumerator at \a index from this class. The indices of
+ all following enumerators will be adjusted downwards by 1.
+
+ \sa enumertorCount(), addEnumerator(), enumerator()
+ \sa indexOfEnumerator()
+*/
+void QMetaObjectBuilder::removeEnumerator(int index)
+{
+ if (index >= 0 && index < d->enumerators.size())
+ d->enumerators.removeAt(index);
+}
+
+/*!
+ Removes the item of class information at \a index from this class.
+ The indices of all following items will be adjusted downwards by 1.
+
+ \sa classInfoCount(), addClassInfo(), classInfoName(), classInfoValue()
+ \sa indexOfClassInfo()
+*/
+void QMetaObjectBuilder::removeClassInfo(int index)
+{
+ if (index >= 0 && index < d->classInfoNames.size()) {
+ d->classInfoNames.removeAt(index);
+ d->classInfoValues.removeAt(index);
+ }
+}
+
+/*!
+ Removes the related meta object at \a index from this class.
+ The indices of all following related meta objects will be adjusted
+ downwards by 1.
+
+ Related meta objects are used when resolving the enumerated type
+ associated with a property, where the enumerated type is in a
+ different class from the property.
+
+ \sa relatedMetaObjectCount(), addRelatedMetaObject()
+ \sa relatedMetaObject()
+*/
+void QMetaObjectBuilder::removeRelatedMetaObject(int index)
+{
+ if (index >= 0 && index < d->relatedMetaObjects.size())
+ d->relatedMetaObjects.removeAt(index);
+}
+
+/*!
+ Finds a method with the specified \a signature and returns its index;
+ otherwise returns -1. The \a signature will be normalized by this method.
+
+ \sa method(), methodCount(), addMethod(), removeMethod()
+*/
+int QMetaObjectBuilder::indexOfMethod(const QByteArray& signature)
+{
+ QByteArray sig = QMetaObject::normalizedSignature(signature);
+ for (int index = 0; index < d->methods.size(); ++index) {
+ if (sig == d->methods[index].signature)
+ return index;
+ }
+ return -1;
+}
+
+/*!
+ Finds a signal with the specified \a signature and returns its index;
+ otherwise returns -1. The \a signature will be normalized by this method.
+
+ \sa indexOfMethod(), indexOfSlot()
+*/
+int QMetaObjectBuilder::indexOfSignal(const QByteArray& signature)
+{
+ QByteArray sig = QMetaObject::normalizedSignature(signature);
+ for (int index = 0; index < d->methods.size(); ++index) {
+ if (sig == d->methods[index].signature &&
+ d->methods[index].methodType() == QMetaMethod::Signal)
+ return index;
+ }
+ return -1;
+}
+
+/*!
+ Finds a slot with the specified \a signature and returns its index;
+ otherwise returns -1. The \a signature will be normalized by this method.
+
+ \sa indexOfMethod(), indexOfSignal()
+*/
+int QMetaObjectBuilder::indexOfSlot(const QByteArray& signature)
+{
+ QByteArray sig = QMetaObject::normalizedSignature(signature);
+ for (int index = 0; index < d->methods.size(); ++index) {
+ if (sig == d->methods[index].signature &&
+ d->methods[index].methodType() == QMetaMethod::Slot)
+ return index;
+ }
+ return -1;
+}
+
+/*!
+ Finds a constructor with the specified \a signature and returns its index;
+ otherwise returns -1. The \a signature will be normalized by this method.
+
+ \sa constructor(), constructorCount(), addConstructor(), removeConstructor()
+*/
+int QMetaObjectBuilder::indexOfConstructor(const QByteArray& signature)
+{
+ QByteArray sig = QMetaObject::normalizedSignature(signature);
+ for (int index = 0; index < d->constructors.size(); ++index) {
+ if (sig == d->constructors[index].signature)
+ return index;
+ }
+ return -1;
+}
+
+/*!
+ Finds a property with the specified \a name and returns its index;
+ otherwise returns -1.
+
+ \sa property(), propertyCount(), addProperty(), removeProperty()
+*/
+int QMetaObjectBuilder::indexOfProperty(const QByteArray& name)
+{
+ for (int index = 0; index < d->properties.size(); ++index) {
+ if (name == d->properties[index].name)
+ return index;
+ }
+ return -1;
+}
+
+/*!
+ Finds an enumerator with the specified \a name and returns its index;
+ otherwise returns -1.
+
+ \sa enumertor(), enumeratorCount(), addEnumerator(), removeEnumerator()
+*/
+int QMetaObjectBuilder::indexOfEnumerator(const QByteArray& name)
+{
+ for (int index = 0; index < d->enumerators.size(); ++index) {
+ if (name == d->enumerators[index].name)
+ return index;
+ }
+ return -1;
+}
+
+/*!
+ Finds an item of class information with the specified \a name and
+ returns its index; otherwise returns -1.
+
+ \sa classInfoName(), classInfoValue(), classInfoCount(), addClassInfo()
+ \sa removeClassInfo()
+*/
+int QMetaObjectBuilder::indexOfClassInfo(const QByteArray& name)
+{
+ for (int index = 0; index < d->classInfoNames.size(); ++index) {
+ if (name == d->classInfoNames[index])
+ return index;
+ }
+ return -1;
+}
+
+// Align on a specific type boundary.
+#define ALIGN(size,type) \
+ (size) = ((size) + sizeof(type) - 1) & ~(sizeof(type) - 1)
+
+// Build a string into a QMetaObject representation. Returns the
+// position in the string table where the string was placed.
+static int buildString
+ (char *buf, char *str, int *offset, const QByteArray& value, int empty)
+{
+ if (value.size() == 0 && empty >= 0)
+ return empty;
+ if (buf) {
+ memcpy(str + *offset, value.constData(), value.size());
+ str[*offset + value.size()] = '\0';
+ }
+ int posn = *offset;
+ *offset += value.size() + 1;
+ return posn;
+}
+
+// Build the parameter array string for a method.
+static QByteArray buildParameterNames
+ (const QByteArray& signature, const QList<QByteArray>& parameterNames)
+{
+ // If the parameter name list is specified, then concatenate them.
+ if (!parameterNames.isEmpty()) {
+ QByteArray names;
+ bool first = true;
+ foreach (QByteArray name, parameterNames) {
+ if (first)
+ first = false;
+ else
+ names += (char)',';
+ names += name;
+ }
+ return names;
+ }
+
+ // Count commas in the signature, excluding those inside template arguments.
+ int index = signature.indexOf('(');
+ if (index < 0)
+ return QByteArray();
+ ++index;
+ if (index >= signature.size())
+ return QByteArray();
+ if (signature[index] == ')')
+ return QByteArray();
+ int count = 1;
+ int brackets = 0;
+ while (index < signature.size() && signature[index] != ',') {
+ char ch = signature[index++];
+ if (ch == '<')
+ ++brackets;
+ else if (ch == '>')
+ --brackets;
+ else if (ch == ',' && brackets <= 0)
+ ++count;
+ }
+ return QByteArray(count - 1, ',');
+}
+
+// Build a QMetaObject in "buf" based on the information in "d".
+// If "buf" is null, then return the number of bytes needed to
+// build the QMetaObject. Returns -1 if the metaobject if
+// relocatable is set, but the metaobject contains extradata.
+static int buildMetaObject(QMetaObjectBuilderPrivate *d, char *buf,
+ bool relocatable)
+{
+ int size = 0;
+ int dataIndex;
+ int enumIndex;
+ int index;
+ bool hasNotifySignals = false;
+
+ if (relocatable &&
+ (d->relatedMetaObjects.size() > 0 || d->staticMetacallFunction))
+ return -1;
+
+ // Create the main QMetaObject structure at the start of the buffer.
+ QMetaObject *meta = reinterpret_cast<QMetaObject *>(buf);
+ size += sizeof(QMetaObject);
+ ALIGN(size, int);
+ if (buf) {
+ if (!relocatable) meta->d.superdata = d->superClass;
+ meta->d.extradata = 0;
+ }
+
+ // Populate the QMetaObjectPrivate structure.
+ QMetaObjectPrivate *pmeta
+ = reinterpret_cast<QMetaObjectPrivate *>(buf + size);
+ int pmetaSize = size;
+ dataIndex = 13; // Number of fields in the QMetaObjectPrivate.
+ for (index = 0; index < d->properties.size(); ++index) {
+ if (d->properties[index].notifySignal != -1) {
+ hasNotifySignals = true;
+ break;
+ }
+ }
+ if (buf) {
+ pmeta->revision = 3;
+ pmeta->flags = d->flags;
+ pmeta->className = 0; // Class name is always the first string.
+
+ pmeta->classInfoCount = d->classInfoNames.size();
+ pmeta->classInfoData = dataIndex;
+ dataIndex += 2 * d->classInfoNames.size();
+
+ pmeta->methodCount = d->methods.size();
+ pmeta->methodData = dataIndex;
+ dataIndex += 5 * d->methods.size();
+
+ pmeta->propertyCount = d->properties.size();
+ pmeta->propertyData = dataIndex;
+ dataIndex += 3 * d->properties.size();
+ if (hasNotifySignals)
+ dataIndex += d->properties.size();
+
+ pmeta->enumeratorCount = d->enumerators.size();
+ pmeta->enumeratorData = dataIndex;
+ dataIndex += 4 * d->enumerators.size();
+
+ pmeta->constructorCount = d->constructors.size();
+ pmeta->constructorData = dataIndex;
+ dataIndex += 5 * d->constructors.size();
+ } else {
+ dataIndex += 2 * d->classInfoNames.size();
+ dataIndex += 5 * d->methods.size();
+ dataIndex += 3 * d->properties.size();
+ if (hasNotifySignals)
+ dataIndex += d->properties.size();
+ dataIndex += 4 * d->enumerators.size();
+ dataIndex += 5 * d->constructors.size();
+ }
+
+ // Allocate space for the enumerator key names and values.
+ enumIndex = dataIndex;
+ for (index = 0; index < d->enumerators.size(); ++index) {
+ QMetaEnumBuilderPrivate *enumerator = &(d->enumerators[index]);
+ dataIndex += 2 * enumerator->keys.size();
+ }
+
+ // Zero terminator at the end of the data offset table.
+ ++dataIndex;
+
+ // Find the start of the data and string tables.
+ int *data = reinterpret_cast<int *>(pmeta);
+ size += dataIndex * sizeof(int);
+ char *str = reinterpret_cast<char *>(buf + size);
+ if (buf) {
+ if (relocatable) {
+ meta->d.stringdata = reinterpret_cast<const char *>((intptr_t)size);
+ meta->d.data = reinterpret_cast<uint *>((intptr_t)pmetaSize);
+ } else {
+ meta->d.stringdata = str;
+ meta->d.data = reinterpret_cast<uint *>(data);
+ }
+ }
+
+ // Reset the current data position to just past the QMetaObjectPrivate.
+ dataIndex = 13;
+
+ // Add the class name to the string table.
+ int offset = 0;
+ buildString(buf, str, &offset, d->className, -1);
+
+ // Add a common empty string, which is used to indicate "void"
+ // method returns, empty tag strings, etc.
+ int empty = buildString(buf, str, &offset, QByteArray(), -1);
+
+ // Output the class infos,
+ for (index = 0; index < d->classInfoNames.size(); ++index) {
+ int name = buildString(buf, str, &offset, d->classInfoNames[index], empty);
+ int value = buildString(buf, str, &offset, d->classInfoValues[index], empty);
+ if (buf) {
+ data[dataIndex] = name;
+ data[dataIndex + 1] = value;
+ }
+ dataIndex += 2;
+ }
+
+ // Output the methods in the class.
+ for (index = 0; index < d->methods.size(); ++index) {
+ QMetaMethodBuilderPrivate *method = &(d->methods[index]);
+ int sig = buildString(buf, str, &offset, method->signature, empty);
+ int params;
+ QByteArray names = buildParameterNames
+ (method->signature, method->parameterNames);
+ params = buildString(buf, str, &offset, names, empty);
+ int ret = buildString(buf, str, &offset, method->returnType, empty);
+ int tag = buildString(buf, str, &offset, method->tag, empty);
+ int attrs = method->attributes;
+ if (buf) {
+ data[dataIndex] = sig;
+ data[dataIndex + 1] = params;
+ data[dataIndex + 2] = ret;
+ data[dataIndex + 3] = tag;
+ data[dataIndex + 4] = attrs;
+ }
+ dataIndex += 5;
+ }
+
+ // Output the properties in the class.
+ for (index = 0; index < d->properties.size(); ++index) {
+ QMetaPropertyBuilderPrivate *prop = &(d->properties[index]);
+ int name = buildString(buf, str, &offset, prop->name, empty);
+ int type = buildString(buf, str, &offset, prop->type, empty);
+ int flags = prop->flags;
+
+ if (!isVariantType(prop->type)) {
+ flags |= EnumOrFlag;
+ } else {
+ flags |= qvariant_nameToType(prop->type) << 24;
+ }
+
+ if (buf) {
+ data[dataIndex] = name;
+ data[dataIndex + 1] = type;
+ data[dataIndex + 2] = flags;
+ }
+ dataIndex += 3;
+ }
+ if (hasNotifySignals) {
+ for (index = 0; index < d->properties.size(); ++index) {
+ QMetaPropertyBuilderPrivate *prop = &(d->properties[index]);
+ if (buf) {
+ if (prop->notifySignal != -1)
+ data[dataIndex] = prop->notifySignal;
+ else
+ data[dataIndex] = 0;
+ }
+ ++dataIndex;
+ }
+ }
+
+ // Output the enumerators in the class.
+ for (index = 0; index < d->enumerators.size(); ++index) {
+ QMetaEnumBuilderPrivate *enumerator = &(d->enumerators[index]);
+ int name = buildString(buf, str, &offset, enumerator->name, empty);
+ int isFlag = (int)(enumerator->isFlag);
+ int count = enumerator->keys.size();
+ int enumOffset = enumIndex;
+ if (buf) {
+ data[dataIndex] = name;
+ data[dataIndex + 1] = isFlag;
+ data[dataIndex + 2] = count;
+ data[dataIndex + 3] = enumOffset;
+ }
+ for (int key = 0; key < count; ++key) {
+ int keyIndex = buildString(buf, str, &offset, enumerator->keys[key], empty);
+ if (buf) {
+ data[enumOffset++] = keyIndex;
+ data[enumOffset++] = enumerator->values[key];
+ }
+ }
+ dataIndex += 4;
+ enumIndex += 2 * count;
+ }
+
+ // Output the constructors in the class.
+ for (index = 0; index < d->constructors.size(); ++index) {
+ QMetaMethodBuilderPrivate *method = &(d->constructors[index]);
+ int sig = buildString(buf, str, &offset, method->signature, empty);
+ int params;
+ QByteArray names = buildParameterNames
+ (method->signature, method->parameterNames);
+ params = buildString(buf, str, &offset, names, empty);
+ int ret = buildString(buf, str, &offset, method->returnType, empty);
+ int tag = buildString(buf, str, &offset, method->tag, empty);
+ int attrs = method->attributes;
+ if (buf) {
+ data[dataIndex] = sig;
+ data[dataIndex + 1] = params;
+ data[dataIndex + 2] = ret;
+ data[dataIndex + 3] = tag;
+ data[dataIndex + 4] = attrs;
+ }
+ dataIndex += 5;
+ }
+
+ // One more empty string to act as a terminator.
+ buildString(buf, str, &offset, QByteArray(), -1);
+ size += offset;
+
+ // Output the zero terminator in the data array.
+ if (buf)
+ data[enumIndex] = 0;
+
+ // Create the extradata block if we need one.
+ if (d->relatedMetaObjects.size() > 0 || d->staticMetacallFunction) {
+ ALIGN(size, QMetaObject **);
+ ALIGN(size, QMetaObjectBuilder::StaticMetacallFunction);
+ QMetaObjectExtraData *extra =
+ reinterpret_cast<QMetaObjectExtraData *>(buf + size);
+ size += sizeof(QMetaObjectExtraData);
+ ALIGN(size, QMetaObject *);
+#ifdef Q_NO_DATA_RELOCATION
+ QMetaObjectAccessor *objects =
+ reinterpret_cast<QMetaObjectAccessor *>(buf + size);
+#else
+ const QMetaObject **objects =
+ reinterpret_cast<const QMetaObject **>(buf + size);
+#endif
+ if (buf) {
+ if (d->relatedMetaObjects.size() > 0) {
+ extra->objects = objects;
+ for (index = 0; index < d->relatedMetaObjects.size(); ++index)
+ objects[index] = d->relatedMetaObjects[index];
+ objects[index] = 0;
+ } else {
+ extra->objects = 0;
+ }
+ extra->static_metacall = d->staticMetacallFunction;
+ meta->d.extradata = reinterpret_cast<void *>(extra);
+ }
+ if (d->relatedMetaObjects.size() > 0)
+ size += sizeof(QMetaObject *) * (d->relatedMetaObjects.size() + 1);
+ }
+
+ // Align the final size and return it.
+ ALIGN(size, void *);
+ return size;
+}
+
+/*!
+ Converts this meta object builder into a concrete QMetaObject.
+ The return value should be deallocated using qFree() once it
+ is no longer needed.
+
+ The returned meta object is a snapshot of the state of the
+ QMetaObjectBuilder. Any further modifications to the QMetaObjectBuilder
+ will not be reflected in previous meta objects returned by
+ this method.
+*/
+QMetaObject *QMetaObjectBuilder::toMetaObject() const
+{
+ int size = buildMetaObject(d, 0, false);
+ char *buf = reinterpret_cast<char *>(qMalloc(size));
+ buildMetaObject(d, buf, false);
+ return reinterpret_cast<QMetaObject *>(buf);
+}
+
+/*
+ \internal
+
+ Converts this meta object builder into relocatable data. This data can
+ be stored, copied and later passed to fromRelocatableData() to create a
+ concrete QMetaObject.
+
+ The data is specific to the architecture on which it was created, but is not
+ specific to the process that created it. Not all meta object builder's can
+ be converted to data in this way. If \a ok is provided, it will be set to
+ true if the conversion succeeds, and false otherwise. If a
+ staticMetacallFunction() or any relatedMetaObject()'s are specified the
+ conversion to relocatable data will fail.
+*/
+QByteArray QMetaObjectBuilder::toRelocatableData(bool *ok) const
+{
+ int size = buildMetaObject(d, 0, true);
+ if (size == -1) {
+ if (ok) *ok = false;
+ return QByteArray();
+ }
+
+ QByteArray data;
+ data.resize(size);
+ char *buf = data.data();
+ buildMetaObject(d, buf, true);
+ if (ok) *ok = true;
+ return data;
+}
+
+/*
+ \internal
+
+ Sets the \a data returned from toRelocatableData() onto a concrete
+ QMetaObject instance, \a output. As the meta object's super class is not
+ saved in the relocatable data, it must be passed as \a superClass.
+*/
+void QMetaObjectBuilder::fromRelocatableData(QMetaObject *output,
+ const QMetaObject *superclass,
+ const QByteArray &data)
+{
+ if (!output)
+ return;
+
+ const char *buf = data.constData();
+ const QMetaObject *dataMo = reinterpret_cast<const QMetaObject *>(buf);
+
+ intptr_t stringdataOffset = (intptr_t)dataMo->d.stringdata;
+ intptr_t dataOffset = (intptr_t)dataMo->d.data;
+
+ output->d.superdata = superclass;
+ output->d.stringdata = buf + stringdataOffset;
+ output->d.data = reinterpret_cast<const uint *>(buf + dataOffset);
+}
+
+/*!
+ \typedef QMetaObjectBuilder::StaticMetacallFunction
+
+ Typedef for static metacall functions. The three parameters are
+ the call type value, the constructor index, and the
+ array of parameters.
+*/
+
+/*!
+ Returns the static metacall function to use to construct objects
+ of this class. The default value is null.
+
+ \sa setStaticMetacallFunction()
+*/
+QMetaObjectBuilder::StaticMetacallFunction QMetaObjectBuilder::staticMetacallFunction() const
+{
+ return d->staticMetacallFunction;
+}
+
+/*!
+ Sets the static metacall function to use to construct objects
+ of this class to \a value. The default value is null.
+
+ \sa staticMetacallFunction()
+*/
+void QMetaObjectBuilder::setStaticMetacallFunction
+ (QMetaObjectBuilder::StaticMetacallFunction value)
+{
+ d->staticMetacallFunction = value;
+}
+
+#ifndef QT_NO_DATASTREAM
+
+/*!
+ Serializes the contents of the meta object builder onto \a stream.
+
+ \sa deserialize()
+*/
+void QMetaObjectBuilder::serialize(QDataStream& stream) const
+{
+ int index;
+
+ // Write the class and super class names.
+ stream << d->className;
+ if (d->superClass)
+ stream << QByteArray(d->superClass->className());
+ else
+ stream << QByteArray();
+
+ // Write the counts for each type of class member.
+ stream << d->classInfoNames.size();
+ stream << d->methods.size();
+ stream << d->properties.size();
+ stream << d->enumerators.size();
+ stream << d->constructors.size();
+ stream << d->relatedMetaObjects.size();
+
+ // Write the items of class information.
+ for (index = 0; index < d->classInfoNames.size(); ++index) {
+ stream << d->classInfoNames[index];
+ stream << d->classInfoValues[index];
+ }
+
+ // Write the methods.
+ for (index = 0; index < d->methods.size(); ++index) {
+ const QMetaMethodBuilderPrivate *method = &(d->methods[index]);
+ stream << method->signature;
+ stream << method->returnType;
+ stream << method->parameterNames;
+ stream << method->tag;
+ stream << method->attributes;
+ }
+
+ // Write the properties.
+ for (index = 0; index < d->properties.size(); ++index) {
+ const QMetaPropertyBuilderPrivate *property = &(d->properties[index]);
+ stream << property->name;
+ stream << property->type;
+ stream << property->flags;
+ stream << property->notifySignal;
+ }
+
+ // Write the enumerators.
+ for (index = 0; index < d->enumerators.size(); ++index) {
+ const QMetaEnumBuilderPrivate *enumerator = &(d->enumerators[index]);
+ stream << enumerator->name;
+ stream << enumerator->isFlag;
+ stream << enumerator->keys;
+ stream << enumerator->values;
+ }
+
+ // Write the constructors.
+ for (index = 0; index < d->constructors.size(); ++index) {
+ const QMetaMethodBuilderPrivate *method = &(d->constructors[index]);
+ stream << method->signature;
+ stream << method->returnType;
+ stream << method->parameterNames;
+ stream << method->tag;
+ stream << method->attributes;
+ }
+
+ // Write the related meta objects.
+#ifdef Q_NO_DATA_RELOCATION
+ //### What do we do here?
+#else
+ for (index = 0; index < d->relatedMetaObjects.size(); ++index) {
+ const QMetaObject *meta = d->relatedMetaObjects[index];
+ stream << QByteArray(meta->className());
+ }
+#endif
+
+ // Add an extra empty QByteArray for additional data in future versions.
+ // This should help maintain backwards compatibility, allowing older
+ // versions to read newer data.
+ stream << QByteArray();
+}
+
+// Resolve a class name using the name reference map.
+static const QMetaObject *resolveClassName
+ (const QMap<QByteArray, const QMetaObject *>& references,
+ const QByteArray& name)
+{
+ if (name == QByteArray("QObject"))
+ return &QObject::staticMetaObject;
+ else
+ return references.value(name, 0);
+}
+
+/*!
+ Deserializes a meta object builder from \a stream into
+ this meta object builder.
+
+ The \a references parameter specifies a mapping from class names
+ to QMetaObject instances for resolving the super class name and
+ related meta objects in the object that is deserialized.
+ The meta object for QObject is implicitly added to \a references
+ and does not need to be supplied.
+
+ The QDataStream::status() value on \a stream will be set to
+ QDataStream::ReadCorruptData if the input data is corrupt.
+ The status will be set to QDataStream::ReadPastEnd if the
+ input was exhausted before the full meta object was read.
+
+ \sa serialize()
+*/
+void QMetaObjectBuilder::deserialize
+ (QDataStream& stream,
+ const QMap<QByteArray, const QMetaObject *>& references)
+{
+ QByteArray name;
+ const QMetaObject *cl;
+ int index;
+
+ // Clear all members in the builder to their default states.
+ d->className.clear();
+ d->superClass = &QObject::staticMetaObject;
+ d->classInfoNames.clear();
+ d->classInfoValues.clear();
+ d->methods.clear();
+ d->properties.clear();
+ d->enumerators.clear();
+ d->constructors.clear();
+ d->relatedMetaObjects.clear();
+ d->staticMetacallFunction = 0;
+
+ // Read the class and super class names.
+ stream >> d->className;
+ stream >> name;
+ if (name.isEmpty()) {
+ d->superClass = 0;
+ } else if ((cl = resolveClassName(references, name)) != 0) {
+ d->superClass = cl;
+ } else {
+ stream.setStatus(QDataStream::ReadCorruptData);
+ return;
+ }
+
+ // Read the counts for each type of class member.
+ int classInfoCount, methodCount, propertyCount;
+ int enumeratorCount, constructorCount, relatedMetaObjectCount;
+ stream >> classInfoCount;
+ stream >> methodCount;
+ stream >> propertyCount;
+ stream >> enumeratorCount;
+ stream >> constructorCount;
+ stream >> relatedMetaObjectCount;
+ if (classInfoCount < 0 || methodCount < 0 ||
+ propertyCount < 0 || enumeratorCount < 0 ||
+ constructorCount < 0 || relatedMetaObjectCount < 0) {
+ stream.setStatus(QDataStream::ReadCorruptData);
+ return;
+ }
+
+ // Read the items of class information.
+ for (index = 0; index < classInfoCount; ++index) {
+ if (stream.status() != QDataStream::Ok)
+ return;
+ QByteArray value;
+ stream >> name;
+ stream >> value;
+ addClassInfo(name, value);
+ }
+
+ // Read the member methods.
+ for (index = 0; index < methodCount; ++index) {
+ if (stream.status() != QDataStream::Ok)
+ return;
+ stream >> name;
+ addMethod(name);
+ QMetaMethodBuilderPrivate *method = &(d->methods[index]);
+ stream >> method->returnType;
+ stream >> method->parameterNames;
+ stream >> method->tag;
+ stream >> method->attributes;
+ if (method->methodType() == QMetaMethod::Constructor) {
+ // Cannot add a constructor in this set of methods.
+ stream.setStatus(QDataStream::ReadCorruptData);
+ return;
+ }
+ }
+
+ // Read the properties.
+ for (index = 0; index < propertyCount; ++index) {
+ if (stream.status() != QDataStream::Ok)
+ return;
+ QByteArray type;
+ stream >> name;
+ stream >> type;
+ addProperty(name, type);
+ QMetaPropertyBuilderPrivate *property = &(d->properties[index]);
+ stream >> property->flags;
+ stream >> property->notifySignal;
+ if (property->notifySignal < -1 ||
+ property->notifySignal >= d->methods.size()) {
+ // Notify signal method index is out of range.
+ stream.setStatus(QDataStream::ReadCorruptData);
+ return;
+ }
+ if (property->notifySignal >= 0 &&
+ d->methods[property->notifySignal].methodType() != QMetaMethod::Signal) {
+ // Notify signal method index does not refer to a signal.
+ stream.setStatus(QDataStream::ReadCorruptData);
+ return;
+ }
+ }
+
+ // Read the enumerators.
+ for (index = 0; index < enumeratorCount; ++index) {
+ if (stream.status() != QDataStream::Ok)
+ return;
+ stream >> name;
+ addEnumerator(name);
+ QMetaEnumBuilderPrivate *enumerator = &(d->enumerators[index]);
+ stream >> enumerator->isFlag;
+ stream >> enumerator->keys;
+ stream >> enumerator->values;
+ if (enumerator->keys.size() != enumerator->values.size()) {
+ // Mismatch between number of keys and number of values.
+ stream.setStatus(QDataStream::ReadCorruptData);
+ return;
+ }
+ }
+
+ // Read the constructor methods.
+ for (index = 0; index < constructorCount; ++index) {
+ if (stream.status() != QDataStream::Ok)
+ return;
+ stream >> name;
+ addConstructor(name);
+ QMetaMethodBuilderPrivate *method = &(d->constructors[index]);
+ stream >> method->returnType;
+ stream >> method->parameterNames;
+ stream >> method->tag;
+ stream >> method->attributes;
+ if (method->methodType() != QMetaMethod::Constructor) {
+ // The type must be Constructor.
+ stream.setStatus(QDataStream::ReadCorruptData);
+ return;
+ }
+ }
+
+ // Read the related meta objects.
+#ifdef Q_NO_DATA_RELOCATION
+ //### What do we do here
+#else
+ for (index = 0; index < relatedMetaObjectCount; ++index) {
+ if (stream.status() != QDataStream::Ok)
+ return;
+ stream >> name;
+ cl = resolveClassName(references, name);
+ if (!cl) {
+ stream.setStatus(QDataStream::ReadCorruptData);
+ return;
+ }
+ addRelatedMetaObject(cl);
+ }
+#endif
+
+ // Read the extra data block, which is reserved for future use.
+ stream >> name;
+}
+
+#endif // !QT_NO_DATASTREAM
+
+/*!
+ \class QMetaMethodBuilder
+ \internal
+ \brief The QMetaMethodBuilder class enables modifications to a method definition on a meta object builder.
+*/
+
+QMetaMethodBuilderPrivate *QMetaMethodBuilder::d_func() const
+{
+ // Positive indices indicate methods, negative indices indicate constructors.
+ if (_mobj && _index >= 0 && _index < _mobj->d->methods.size())
+ return &(_mobj->d->methods[_index]);
+ else if (_mobj && -_index >= 1 && -_index <= _mobj->d->constructors.size())
+ return &(_mobj->d->constructors[(-_index) - 1]);
+ else
+ return 0;
+}
+
+/*!
+ \fn QMetaMethodBuilder::QMetaMethodBuilder()
+ \internal
+*/
+
+/*!
+ Returns the index of this method within its QMetaObjectBuilder.
+*/
+int QMetaMethodBuilder::index() const
+{
+ if (_index >= 0)
+ return _index; // Method, signal, or slot
+ else
+ return (-_index) - 1; // Constructor
+}
+
+/*!
+ Returns the type of this method (signal, slot, method, or constructor).
+*/
+QMetaMethod::MethodType QMetaMethodBuilder::methodType() const
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ return d->methodType();
+ else
+ return QMetaMethod::Method;
+}
+
+/*!
+ Returns the signature of this method.
+
+ \sa parameterNames(), returnType()
+*/
+QByteArray QMetaMethodBuilder::signature() const
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ return d->signature;
+ else
+ return QByteArray();
+}
+
+/*!
+ Returns the return type for this method; empty if the method's
+ return type is \c{void}.
+
+ \sa setReturnType(), signature()
+*/
+QByteArray QMetaMethodBuilder::returnType() const
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ return d->returnType;
+ else
+ return QByteArray();
+}
+
+/*!
+ Sets the return type for this method to \a value. If \a value
+ is empty, then the method's return type is \c{void}. The \a value
+ will be normalized before it is added to the method.
+
+ \sa returnType(), signature()
+*/
+void QMetaMethodBuilder::setReturnType(const QByteArray& value)
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ d->returnType = QMetaObject::normalizedType(value);
+}
+
+/*!
+ Returns the list of parameter names for this method.
+
+ \sa setParameterNames()
+*/
+QList<QByteArray> QMetaMethodBuilder::parameterNames() const
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ return d->parameterNames;
+ else
+ return QList<QByteArray>();
+}
+
+/*!
+ Sets the list of parameter names for this method to \a value.
+
+ \sa parameterNames()
+*/
+void QMetaMethodBuilder::setParameterNames(const QList<QByteArray>& value)
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ d->parameterNames = value;
+}
+
+/*!
+ Returns the tag associated with this method.
+
+ \sa setTag()
+*/
+QByteArray QMetaMethodBuilder::tag() const
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ return d->tag;
+ else
+ return QByteArray();
+}
+
+/*!
+ Sets the tag associated with this method to \a value.
+
+ \sa setTag()
+*/
+void QMetaMethodBuilder::setTag(const QByteArray& value)
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ d->tag = value;
+}
+
+/*!
+ Returns the access specification of this method (private, protected,
+ or public). The default value is QMetaMethod::Public for methods,
+ slots, and constructors. The default value is QMetaMethod::Protected
+ for signals.
+
+ \sa setAccess()
+*/
+QMetaMethod::Access QMetaMethodBuilder::access() const
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ return d->access();
+ else
+ return QMetaMethod::Public;
+}
+
+/*!
+ Sets the access specification of this method (private, protected,
+ or public) to \a value. If the method is a signal, this function
+ will be ignored.
+
+ \sa access()
+*/
+void QMetaMethodBuilder::setAccess(QMetaMethod::Access value)
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d && d->methodType() != QMetaMethod::Signal)
+ d->setAccess(value);
+}
+
+/*!
+ Returns the additional attributes for this method.
+
+ \sa setAttributes()
+*/
+int QMetaMethodBuilder::attributes() const
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ return (d->attributes >> 4);
+ else
+ return 0;
+}
+
+/*!
+ Sets the additional attributes for this method to \a value.
+
+ \sa attributes()
+*/
+void QMetaMethodBuilder::setAttributes(int value)
+{
+ QMetaMethodBuilderPrivate *d = d_func();
+ if (d)
+ d->attributes = ((d->attributes & 0x0f) | (value << 4));
+}
+
+/*!
+ \class QMetaPropertyBuilder
+ \internal
+ \brief The QMetaPropertyBuilder class enables modifications to a property definition on a meta object builder.
+*/
+
+QMetaPropertyBuilderPrivate *QMetaPropertyBuilder::d_func() const
+{
+ if (_mobj && _index >= 0 && _index < _mobj->d->properties.size())
+ return &(_mobj->d->properties[_index]);
+ else
+ return 0;
+}
+
+/*!
+ \fn QMetaPropertyBuilder::QMetaPropertyBuilder()
+ \internal
+*/
+
+/*!
+ \fn int QMetaPropertyBuilder::index() const
+
+ Returns the index of this property within its QMetaObjectBuilder.
+*/
+
+/*!
+ Returns the name associated with this property.
+
+ \sa type()
+*/
+QByteArray QMetaPropertyBuilder::name() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->name;
+ else
+ return QByteArray();
+}
+
+/*!
+ Returns the type associated with this property.
+
+ \sa name()
+*/
+QByteArray QMetaPropertyBuilder::type() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->type;
+ else
+ return QByteArray();
+}
+
+/*!
+ Returns true if this property has a notify signal; false otherwise.
+
+ \sa notifySignal(), setNotifySignal(), removeNotifySignal()
+*/
+bool QMetaPropertyBuilder::hasNotifySignal() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(Notify);
+ else
+ return false;
+}
+
+/*!
+ Returns the notify signal associated with this property.
+
+ \sa hasNotifySignal(), setNotifySignal(), removeNotifySignal()
+*/
+QMetaMethodBuilder QMetaPropertyBuilder::notifySignal() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d && d->notifySignal >= 0)
+ return QMetaMethodBuilder(_mobj, d->notifySignal);
+ else
+ return QMetaMethodBuilder();
+}
+
+/*!
+ Sets the notify signal associated with this property to \a value.
+
+ \sa hasNotifySignal(), notifySignal(), removeNotifySignal()
+*/
+void QMetaPropertyBuilder::setNotifySignal(const QMetaMethodBuilder& value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d) {
+ if (value._mobj) {
+ d->notifySignal = value._index;
+ d->setFlag(Notify, true);
+ } else {
+ d->notifySignal = -1;
+ d->setFlag(Notify, false);
+ }
+ }
+}
+
+/*!
+ Removes the notify signal from this property.
+
+ \sa hasNotifySignal(), notifySignal(), setNotifySignal()
+*/
+void QMetaPropertyBuilder::removeNotifySignal()
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d) {
+ d->notifySignal = -1;
+ d->setFlag(Notify, false);
+ }
+}
+
+/*!
+ Returns true if this property is readable; otherwise returns false.
+ The default value is true.
+
+ \sa setReadable(), isWritable()
+*/
+bool QMetaPropertyBuilder::isReadable() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(Readable);
+ else
+ return false;
+}
+
+/*!
+ Returns true if this property is writable; otherwise returns false.
+ The default value is true.
+
+ \sa setWritable(), isReadable()
+*/
+bool QMetaPropertyBuilder::isWritable() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(Writable);
+ else
+ return false;
+}
+
+/*!
+ Returns true if this property can be reset to a default value; otherwise
+ returns false. The default value is false.
+
+ \sa setResettable()
+*/
+bool QMetaPropertyBuilder::isResettable() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(Resettable);
+ else
+ return false;
+}
+
+/*!
+ Returns true if this property is designable; otherwise returns false.
+ This default value is false.
+
+ \sa setDesignable(), isScriptable(), isStored()
+*/
+bool QMetaPropertyBuilder::isDesignable() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(Designable);
+ else
+ return false;
+}
+
+/*!
+ Returns true if the property is scriptable; otherwise returns false.
+ This default value is false.
+
+ \sa setScriptable(), isDesignable(), isStored()
+*/
+bool QMetaPropertyBuilder::isScriptable() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(Scriptable);
+ else
+ return false;
+}
+
+/*!
+ Returns true if the property is stored; otherwise returns false.
+ This default value is false.
+
+ \sa setStored(), isDesignable(), isScriptable()
+*/
+bool QMetaPropertyBuilder::isStored() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(Stored);
+ else
+ return false;
+}
+
+/*!
+ Returns true if the property is editable; otherwise returns false.
+ This default value is false.
+
+ \sa setEditable(), isDesignable(), isScriptable(), isStored()
+*/
+bool QMetaPropertyBuilder::isEditable() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(Editable);
+ else
+ return false;
+}
+
+/*!
+ Returns true if this property is designated as the \c USER
+ property, i.e., the one that the user can edit or that is
+ significant in some other way. Otherwise it returns
+ false. This default value is false.
+
+ \sa setUser(), isDesignable(), isScriptable()
+*/
+bool QMetaPropertyBuilder::isUser() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(User);
+ else
+ return false;
+}
+
+/*!
+ Returns true if the property has a C++ setter function that
+ follows Qt's standard "name" / "setName" pattern. Designer and uic
+ query hasStdCppSet() in order to avoid expensive
+ QObject::setProperty() calls. All properties in Qt [should] follow
+ this pattern. The default value is false.
+
+ \sa setStdCppSet()
+*/
+bool QMetaPropertyBuilder::hasStdCppSet() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(StdCppSet);
+ else
+ return false;
+}
+
+/*!
+ Returns true if the property is an enumerator or flag type;
+ otherwise returns false. This default value is false.
+
+ \sa setEnumOrFlag()
+*/
+bool QMetaPropertyBuilder::isEnumOrFlag() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(EnumOrFlag);
+ else
+ return false;
+}
+
+/*!
+ Returns true if the property has the dynamic flag set;
+ otherwise returns false. The default value is false.
+
+ \sa setDynamic()
+*/
+bool QMetaPropertyBuilder::isDynamic() const
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ return d->flag(Dynamic);
+ else
+ return false;
+}
+
+/*!
+ Sets this property to readable if \a value is true.
+
+ \sa isReadable(), setWritable()
+*/
+void QMetaPropertyBuilder::setReadable(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(Readable, value);
+}
+
+/*!
+ Sets this property to writable if \a value is true.
+
+ \sa isWritable(), setReadable()
+*/
+void QMetaPropertyBuilder::setWritable(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(Writable, value);
+}
+
+/*!
+ Sets this property to resettable if \a value is true.
+
+ \sa isResettable()
+*/
+void QMetaPropertyBuilder::setResettable(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(Resettable, value);
+}
+
+/*!
+ Sets this property to designable if \a value is true.
+
+ \sa isDesignable(), setScriptable(), setStored()
+*/
+void QMetaPropertyBuilder::setDesignable(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(Designable, value);
+}
+
+/*!
+ Sets this property to scriptable if \a value is true.
+
+ \sa isScriptable(), setDesignable(), setStored()
+*/
+void QMetaPropertyBuilder::setScriptable(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(Scriptable, value);
+}
+
+/*!
+ Sets this property to storable if \a value is true.
+
+ \sa isStored(), setDesignable(), setScriptable()
+*/
+void QMetaPropertyBuilder::setStored(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(Stored, value);
+}
+
+/*!
+ Sets this property to editable if \a value is true.
+
+ \sa isEditable(), setDesignable(), setScriptable(), setStored()
+*/
+void QMetaPropertyBuilder::setEditable(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(Editable, value);
+}
+
+/*!
+ Sets the \c USER flag on this property to \a value.
+
+ \sa isUser(), setDesignable(), setScriptable()
+*/
+void QMetaPropertyBuilder::setUser(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(User, value);
+}
+
+/*!
+ Sets the C++ setter flag on this property to \a value, which is
+ true if the property has a C++ setter function that follows Qt's
+ standard "name" / "setName" pattern.
+
+ \sa hasStdCppSet()
+*/
+void QMetaPropertyBuilder::setStdCppSet(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(StdCppSet, value);
+}
+
+/*!
+ Sets this property to be of an enumerator or flag type if
+ \a value is true.
+
+ \sa isEnumOrFlag()
+*/
+void QMetaPropertyBuilder::setEnumOrFlag(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(EnumOrFlag, value);
+}
+
+/*!
+ Sets this property to have the dynamic flag if \a value is
+ true.
+
+ \sa isDynamic()
+*/
+void QMetaPropertyBuilder::setDynamic(bool value)
+{
+ QMetaPropertyBuilderPrivate *d = d_func();
+ if (d)
+ d->setFlag(Dynamic, value);
+}
+
+/*!
+ \class QMetaEnumBuilder
+ \internal
+ \brief The QMetaEnumBuilder class enables modifications to an enumerator definition on a meta object builder.
+*/
+
+QMetaEnumBuilderPrivate *QMetaEnumBuilder::d_func() const
+{
+ if (_mobj && _index >= 0 && _index < _mobj->d->enumerators.size())
+ return &(_mobj->d->enumerators[_index]);
+ else
+ return 0;
+}
+
+/*!
+ \fn QMetaEnumBuilder::QMetaEnumBuilder()
+ \internal
+*/
+
+/*!
+ \fn int QMetaEnumBuilder::index() const
+
+ Returns the index of this enumerator within its QMetaObjectBuilder.
+*/
+
+/*!
+ Returns the name of the enumerator (without the scope).
+*/
+QByteArray QMetaEnumBuilder::name() const
+{
+ QMetaEnumBuilderPrivate *d = d_func();
+ if (d)
+ return d->name;
+ else
+ return QByteArray();
+}
+
+/*!
+ Returns true if this enumerator is used as a flag; otherwise returns
+ false.
+
+ \sa setIsFlag()
+*/
+bool QMetaEnumBuilder::isFlag() const
+{
+ QMetaEnumBuilderPrivate *d = d_func();
+ if (d)
+ return d->isFlag;
+ else
+ return false;
+}
+
+/*!
+ Sets this enumerator to be used as a flag if \a value is true.
+
+ \sa isFlag()
+*/
+void QMetaEnumBuilder::setIsFlag(bool value)
+{
+ QMetaEnumBuilderPrivate *d = d_func();
+ if (d)
+ d->isFlag = value;
+}
+
+/*!
+ Returns the number of keys.
+
+ \sa key(), addKey()
+*/
+int QMetaEnumBuilder::keyCount() const
+{
+ QMetaEnumBuilderPrivate *d = d_func();
+ if (d)
+ return d->keys.size();
+ else
+ return 0;
+}
+
+/*!
+ Returns the key with the given \a index, or an empty QByteArray
+ if no such key exists.
+
+ \sa keyCount(), addKey(), value()
+*/
+QByteArray QMetaEnumBuilder::key(int index) const
+{
+ QMetaEnumBuilderPrivate *d = d_func();
+ if (d && index >= 0 && index < d->keys.size())
+ return d->keys[index];
+ else
+ return QByteArray();
+}
+
+/*!
+ Returns the value with the given \a index; or returns -1 if there
+ is no such value.
+
+ \sa keyCount(), addKey(), key()
+*/
+int QMetaEnumBuilder::value(int index) const
+{
+ QMetaEnumBuilderPrivate *d = d_func();
+ if (d && index >= 0 && index < d->keys.size())
+ return d->values[index];
+ else
+ return -1;
+}
+
+/*!
+ Adds a new key called \a name to this enumerator, associated
+ with \a value. Returns the index of the new key.
+
+ \sa keyCount(), key(), value(), removeKey()
+*/
+int QMetaEnumBuilder::addKey(const QByteArray& name, int value)
+{
+ QMetaEnumBuilderPrivate *d = d_func();
+ if (d) {
+ int index = d->keys.size();
+ d->keys += name;
+ d->values += value;
+ return index;
+ } else {
+ return -1;
+ }
+}
+
+/*!
+ Removes the key at \a index from this enumerator.
+
+ \sa addKey()
+*/
+void QMetaEnumBuilder::removeKey(int index)
+{
+ QMetaEnumBuilderPrivate *d = d_func();
+ if (d && index >= 0 && index < d->keys.size()) {
+ d->keys.removeAt(index);
+ d->values.removeAt(index);
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmetaobjectbuilder_p.h b/src/declarative/qml/qmetaobjectbuilder_p.h
new file mode 100644
index 0000000..3eff4ff
--- /dev/null
+++ b/src/declarative/qml/qmetaobjectbuilder_p.h
@@ -0,0 +1,321 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMETAOBJECTBUILDER_H
+#define QMETAOBJECTBUILDER_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of moc. This header file may change from version to version without notice,
+// or even be removed.
+//
+// We mean it.
+//
+
+#include <QtCore/qobject.h>
+#include <QtCore/qmetaobject.h>
+#include <QtCore/qdatastream.h>
+#include <QtCore/qmap.h>
+
+QT_BEGIN_NAMESPACE
+
+class QMetaObjectBuilderPrivate;
+class QMetaMethodBuilder;
+class QMetaMethodBuilderPrivate;
+class QMetaPropertyBuilder;
+class QMetaPropertyBuilderPrivate;
+class QMetaEnumBuilder;
+class QMetaEnumBuilderPrivate;
+
+class Q_DECLARATIVE_EXPORT QMetaObjectBuilder
+{
+public:
+ enum AddMember
+ {
+ ClassName = 0x00000001,
+ SuperClass = 0x00000002,
+ Methods = 0x00000004,
+ Signals = 0x00000008,
+ Slots = 0x00000010,
+ Constructors = 0x00000020,
+ Properties = 0x00000040,
+ Enumerators = 0x00000080,
+ ClassInfos = 0x00000100,
+ RelatedMetaObjects = 0x00000200,
+ StaticMetacall = 0x00000400,
+ PublicMethods = 0x00000800,
+ ProtectedMethods = 0x00001000,
+ PrivateMethods = 0x00002000,
+ AllMembers = 0x7FFFFFFF,
+ AllPrimaryMembers = 0x7FFFFBFC
+ };
+ Q_DECLARE_FLAGS(AddMembers, AddMember)
+
+ enum MetaObjectFlag {
+ DynamicMetaObject = 0x01
+ };
+ Q_DECLARE_FLAGS(MetaObjectFlags, MetaObjectFlag)
+
+ QMetaObjectBuilder();
+ explicit QMetaObjectBuilder(const QMetaObject *prototype, QMetaObjectBuilder::AddMembers members = AllMembers);
+ virtual ~QMetaObjectBuilder();
+
+ QByteArray className() const;
+ void setClassName(const QByteArray& name);
+
+ const QMetaObject *superClass() const;
+ void setSuperClass(const QMetaObject *meta);
+
+ MetaObjectFlags flags() const;
+ void setFlags(MetaObjectFlags);
+
+ int methodCount() const;
+ int constructorCount() const;
+ int propertyCount() const;
+ int enumeratorCount() const;
+ int classInfoCount() const;
+ int relatedMetaObjectCount() const;
+
+ QMetaMethodBuilder addMethod(const QByteArray& signature);
+ QMetaMethodBuilder addMethod(const QByteArray& signature, const QByteArray& returnType);
+ QMetaMethodBuilder addMethod(const QMetaMethod& prototype);
+
+ QMetaMethodBuilder addSlot(const QByteArray& signature);
+ QMetaMethodBuilder addSignal(const QByteArray& signature);
+
+ QMetaMethodBuilder addConstructor(const QByteArray& signature);
+ QMetaMethodBuilder addConstructor(const QMetaMethod& prototype);
+
+ QMetaPropertyBuilder addProperty(const QByteArray& name, const QByteArray& type, int notifierId=-1);
+ QMetaPropertyBuilder addProperty(const QMetaProperty& prototype);
+
+ QMetaEnumBuilder addEnumerator(const QByteArray& name);
+ QMetaEnumBuilder addEnumerator(const QMetaEnum& prototype);
+
+ int addClassInfo(const QByteArray& name, const QByteArray& value);
+
+#ifdef Q_NO_DATA_RELOCATION
+ int addRelatedMetaObject(const QMetaObjectAccessor &meta);
+#else
+ int addRelatedMetaObject(const QMetaObject *meta);
+#endif
+
+ void addMetaObject(const QMetaObject *prototype, QMetaObjectBuilder::AddMembers members = AllMembers);
+
+ QMetaMethodBuilder method(int index) const;
+ QMetaMethodBuilder constructor(int index) const;
+ QMetaPropertyBuilder property(int index) const;
+ QMetaEnumBuilder enumerator(int index) const;
+ const QMetaObject *relatedMetaObject(int index) const;
+
+ QByteArray classInfoName(int index) const;
+ QByteArray classInfoValue(int index) const;
+
+ void removeMethod(int index);
+ void removeConstructor(int index);
+ void removeProperty(int index);
+ void removeEnumerator(int index);
+ void removeClassInfo(int index);
+ void removeRelatedMetaObject(int index);
+
+ int indexOfMethod(const QByteArray& signature);
+ int indexOfSignal(const QByteArray& signature);
+ int indexOfSlot(const QByteArray& signature);
+ int indexOfConstructor(const QByteArray& signature);
+ int indexOfProperty(const QByteArray& name);
+ int indexOfEnumerator(const QByteArray& name);
+ int indexOfClassInfo(const QByteArray& name);
+
+ typedef int (*StaticMetacallFunction)(QMetaObject::Call, int, void **);
+
+ QMetaObjectBuilder::StaticMetacallFunction staticMetacallFunction() const;
+ void setStaticMetacallFunction(QMetaObjectBuilder::StaticMetacallFunction value);
+
+ QMetaObject *toMetaObject() const;
+ QByteArray toRelocatableData(bool * = 0) const;
+ static void fromRelocatableData(QMetaObject *, const QMetaObject *, const QByteArray &);
+
+#ifndef QT_NO_DATASTREAM
+ void serialize(QDataStream& stream) const;
+ void deserialize
+ (QDataStream& stream,
+ const QMap<QByteArray, const QMetaObject *>& references);
+#endif
+
+private:
+ Q_DISABLE_COPY(QMetaObjectBuilder)
+
+ QMetaObjectBuilderPrivate *d;
+
+ friend class QMetaMethodBuilder;
+ friend class QMetaPropertyBuilder;
+ friend class QMetaEnumBuilder;
+};
+
+class Q_DECLARATIVE_EXPORT QMetaMethodBuilder
+{
+public:
+ QMetaMethodBuilder() : _mobj(0), _index(0) {}
+
+ int index() const;
+
+ QMetaMethod::MethodType methodType() const;
+ QByteArray signature() const;
+
+ QByteArray returnType() const;
+ void setReturnType(const QByteArray& value);
+
+ QList<QByteArray> parameterNames() const;
+ void setParameterNames(const QList<QByteArray>& value);
+
+ QByteArray tag() const;
+ void setTag(const QByteArray& value);
+
+ QMetaMethod::Access access() const;
+ void setAccess(QMetaMethod::Access value);
+
+ int attributes() const;
+ void setAttributes(int value);
+
+private:
+ const QMetaObjectBuilder *_mobj;
+ int _index;
+
+ friend class QMetaObjectBuilder;
+ friend class QMetaPropertyBuilder;
+
+ QMetaMethodBuilder(const QMetaObjectBuilder *mobj, int index)
+ : _mobj(mobj), _index(index) {}
+
+ QMetaMethodBuilderPrivate *d_func() const;
+};
+
+class Q_DECLARATIVE_EXPORT QMetaPropertyBuilder
+{
+public:
+ QMetaPropertyBuilder() : _mobj(0), _index(0) {}
+
+ int index() const { return _index; }
+
+ QByteArray name() const;
+ QByteArray type() const;
+
+ bool hasNotifySignal() const;
+ QMetaMethodBuilder notifySignal() const;
+ void setNotifySignal(const QMetaMethodBuilder& value);
+ void removeNotifySignal();
+
+ bool isReadable() const;
+ bool isWritable() const;
+ bool isResettable() const;
+ bool isDesignable() const;
+ bool isScriptable() const;
+ bool isStored() const;
+ bool isEditable() const;
+ bool isUser() const;
+ bool hasStdCppSet() const;
+ bool isEnumOrFlag() const;
+ bool isDynamic() const;
+
+ void setReadable(bool value);
+ void setWritable(bool value);
+ void setResettable(bool value);
+ void setDesignable(bool value);
+ void setScriptable(bool value);
+ void setStored(bool value);
+ void setEditable(bool value);
+ void setUser(bool value);
+ void setStdCppSet(bool value);
+ void setEnumOrFlag(bool value);
+ void setDynamic(bool value);
+
+private:
+ const QMetaObjectBuilder *_mobj;
+ int _index;
+
+ friend class QMetaObjectBuilder;
+
+ QMetaPropertyBuilder(const QMetaObjectBuilder *mobj, int index)
+ : _mobj(mobj), _index(index) {}
+
+ QMetaPropertyBuilderPrivate *d_func() const;
+};
+
+class Q_DECLARATIVE_EXPORT QMetaEnumBuilder
+{
+public:
+ QMetaEnumBuilder() : _mobj(0), _index(0) {}
+
+ int index() const { return _index; }
+
+ QByteArray name() const;
+
+ bool isFlag() const;
+ void setIsFlag(bool value);
+
+ int keyCount() const;
+ QByteArray key(int index) const;
+ int value(int index) const;
+
+ int addKey(const QByteArray& name, int value);
+ void removeKey(int index);
+
+private:
+ const QMetaObjectBuilder *_mobj;
+ int _index;
+
+ friend class QMetaObjectBuilder;
+
+ QMetaEnumBuilder(const QMetaObjectBuilder *mobj, int index)
+ : _mobj(mobj), _index(index) {}
+
+ QMetaEnumBuilderPrivate *d_func() const;
+};
+
+Q_DECLARE_OPERATORS_FOR_FLAGS(QMetaObjectBuilder::AddMembers)
+Q_DECLARE_OPERATORS_FOR_FLAGS(QMetaObjectBuilder::MetaObjectFlags)
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/declarative/qml/qml.h b/src/declarative/qml/qml.h
new file mode 100644
index 0000000..c009093
--- /dev/null
+++ b/src/declarative/qml/qml.h
@@ -0,0 +1,155 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QML_H
+#define QML_H
+
+#include "qmlmetatype.h"
+#include "qmlmetaproperty.h"
+#include "qmlparserstatus.h"
+#include "qmlpropertyvaluesource.h"
+#include "qmllist.h"
+
+#include <QtCore/qbytearray.h>
+#include <QtCore/qstringlist.h>
+#include <QtCore/qurl.h>
+#include <QtCore/qmetaobject.h>
+
+QT_BEGIN_HEADER
+
+QT_MODULE(Declarative)
+
+#define QML_DECLARE_TYPE(TYPE) \
+ Q_DECLARE_METATYPE(TYPE *) \
+ Q_DECLARE_METATYPE(QList<TYPE *> *) \
+ Q_DECLARE_METATYPE(QmlList<TYPE *> *)
+
+#define QML_DECLARE_TYPE_HASMETATYPE(TYPE) \
+ Q_DECLARE_METATYPE(QList<TYPE *> *) \
+ Q_DECLARE_METATYPE(QmlList<TYPE *> *)
+
+#define QML_DECLARE_INTERFACE(INTERFACE) \
+ QML_DECLARE_TYPE(INTERFACE)
+
+#define QML_DECLARE_INTERFACE_HASMETATYPE(INTERFACE) \
+ QML_DECLARE_TYPE_HASMETATYPE(INTERFACE)
+
+enum { /* TYPEINFO flags */
+ QML_HAS_ATTACHED_PROPERTIES = 0x01,
+};
+
+#define QML_DECLARE_TYPEINFO(TYPE, FLAGS) \
+template <> \
+class QmlTypeInfo<TYPE > \
+{ \
+public: \
+ enum { \
+ hasAttachedProperties = (((FLAGS) & QML_HAS_ATTACHED_PROPERTIES) == QML_HAS_ATTACHED_PROPERTIES) \
+ }; \
+};
+
+QT_BEGIN_NAMESPACE
+
+#if defined(Q_OS_SYMBIAN)
+#define QML_DEFINE_INTERFACE(INTERFACE) \
+ static int defineInterface##INTERFACE = qmlRegisterInterface<INTERFACE>(#INTERFACE);
+
+#define QML_DEFINE_EXTENDED_TYPE(URI, VERSION_MAJ, VERSION_MIN, NAME, TYPE, EXTENSION) \
+ static int registerExtended##TYPE = qmlRegisterExtendedType<TYPE,EXTENSION>(#URI, VERSION_MAJ, VERSION_MIN, #NAME, #TYPE);
+
+#define QML_DEFINE_TYPE(URI, VERSION_MAJ, VERSION_MIN, NAME, TYPE) \
+ static int defineType##TYPE = qmlRegisterType<TYPE>(#URI, VERSION_MAJ, VERSION_MIN, #NAME, #TYPE);
+
+#define QML_DEFINE_EXTENDED_NOCREATE_TYPE(TYPE, EXTENSION) \
+ static int registerExtendedNoCreate##TYPE = qmlRegisterExtendedType<TYPE,EXTENSION>(#TYPE);
+
+#define QML_DEFINE_NOCREATE_TYPE(TYPE) \
+ static int registerNoCreate##TYPE = qmlRegisterType<TYPE>(#TYPE);
+
+#else
+
+#define QML_DEFINE_INTERFACE(INTERFACE) \
+ template<> QmlPrivate::InstanceType QmlPrivate::Define<INTERFACE *,0,0>::instance(qmlRegisterInterface<INTERFACE>(#INTERFACE));
+
+#define QML_DEFINE_EXTENDED_TYPE(URI, VERSION_MAJ, VERSION_MIN, NAME, TYPE, EXTENSION) \
+ template<> QmlPrivate::InstanceType QmlPrivate::Define<TYPE *,(VERSION_MAJ), (VERSION_MIN)>::instance(qmlRegisterExtendedType<TYPE,EXTENSION>(#URI, VERSION_MAJ, VERSION_MIN, #NAME, #TYPE));
+
+#define QML_DEFINE_TYPE(URI, VERSION_MAJ, VERSION_MIN, NAME, TYPE) \
+ template<> QmlPrivate::InstanceType QmlPrivate::Define<TYPE *,(VERSION_MAJ), (VERSION_MIN)>::instance(qmlRegisterType<TYPE>(#URI, VERSION_MAJ, VERSION_MIN, #NAME, #TYPE));
+
+#define QML_DEFINE_EXTENDED_NOCREATE_TYPE(TYPE, EXTENSION) \
+ template<> QmlPrivate::InstanceType QmlPrivate::Define<TYPE *,0,0>::instance(qmlRegisterExtendedType<TYPE,EXTENSION>(#TYPE));
+
+#define QML_DEFINE_NOCREATE_TYPE(TYPE) \
+ template<> QmlPrivate::InstanceType QmlPrivate::Define<TYPE *,0,0>::instance(qmlRegisterType<TYPE>(#TYPE));
+
+#endif
+
+class QmlContext;
+class QmlEngine;
+Q_DECLARATIVE_EXPORT void qmlExecuteDeferred(QObject *);
+Q_DECLARATIVE_EXPORT QmlContext *qmlContext(const QObject *);
+Q_DECLARATIVE_EXPORT QmlEngine *qmlEngine(const QObject *);
+Q_DECLARATIVE_EXPORT QObject *qmlAttachedPropertiesObjectById(int, const QObject *, bool create = true);
+
+template<typename T>
+QObject *qmlAttachedPropertiesObject(const QObject *obj, bool create = true)
+{
+ // ### is this threadsafe?
+ static int idx = -1;
+
+ if (idx == -1)
+ idx = QmlMetaType::attachedPropertiesFuncId(&T::staticMetaObject);
+
+ if (idx == -1 || !obj)
+ return 0;
+
+ return qmlAttachedPropertiesObjectById(idx, obj, create);
+}
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QObject)
+Q_DECLARE_METATYPE(QVariant)
+
+QT_END_HEADER
+
+#endif // QML_H
diff --git a/src/declarative/qml/qml.pri b/src/declarative/qml/qml.pri
new file mode 100644
index 0000000..cd2fbff
--- /dev/null
+++ b/src/declarative/qml/qml.pri
@@ -0,0 +1,123 @@
+INCLUDEPATH += $$PWD
+SOURCES += \
+ $$PWD/qmlparser.cpp \
+ $$PWD/qmlinstruction.cpp \
+ $$PWD/qmlvmemetaobject.cpp \
+ $$PWD/qmlengine.cpp \
+ $$PWD/qmlexpression.cpp \
+ $$PWD/qmlbinding.cpp \
+ $$PWD/qmlmetaproperty.cpp \
+ $$PWD/qmlmoduleplugin.cpp \
+ $$PWD/qmlcomponent.cpp \
+ $$PWD/qmlcontext.cpp \
+ $$PWD/qmlcustomparser.cpp \
+ $$PWD/qmlpropertyvaluesource.cpp \
+ $$PWD/qmlpropertyvalueinterceptor.cpp \
+ $$PWD/qmlproxymetaobject.cpp \
+ $$PWD/qmlvme.cpp \
+ $$PWD/qmlcompiler.cpp \
+ $$PWD/qmlcompileddata.cpp \
+ $$PWD/qmlboundsignal.cpp \
+ $$PWD/qmldom.cpp \
+ $$PWD/qmlrefcount.cpp \
+ $$PWD/qmlprivate.cpp \
+ $$PWD/qmlmetatype.cpp \
+ $$PWD/qmlstringconverters.cpp \
+ $$PWD/qmlclassfactory.cpp \
+ $$PWD/qmlparserstatus.cpp \
+ $$PWD/qmlcompositetypemanager.cpp \
+ $$PWD/qmlinfo.cpp \
+ $$PWD/qmlerror.cpp \
+ $$PWD/qmlscriptparser.cpp \
+ $$PWD/qmlenginedebug.cpp \
+ $$PWD/qmlrewrite.cpp \
+ $$PWD/qmlvaluetype.cpp \
+ $$PWD/qmlcompiledbindings.cpp \
+ $$PWD/qmlxmlhttprequest.cpp \
+ $$PWD/qmlsqldatabase.cpp \
+ $$PWD/qmetaobjectbuilder.cpp \
+ $$PWD/qmlwatcher.cpp \
+ $$PWD/qmlscript.cpp \
+ $$PWD/qmlcleanup.cpp \
+ $$PWD/qmlpropertycache.cpp \
+ $$PWD/qmlintegercache.cpp \
+ $$PWD/qmltypenamecache.cpp \
+ $$PWD/qmlscriptstring.cpp \
+ $$PWD/qmlobjectscriptclass.cpp \
+ $$PWD/qmlcontextscriptclass.cpp \
+ $$PWD/qmlglobalscriptclass.cpp \
+ $$PWD/qmlvaluetypescriptclass.cpp \
+ $$PWD/qmltypenamescriptclass.cpp \
+ $$PWD/qmllistscriptclass.cpp \
+ $$PWD/qmlworkerscript.cpp \
+ $$PWD/qmlnetworkaccessmanagerfactory.cpp
+HEADERS += \
+ $$PWD/qmlparser_p.h \
+ $$PWD/qmlglobal_p.h \
+ $$PWD/qmlinstruction_p.h \
+ $$PWD/qmlvmemetaobject_p.h \
+ $$PWD/qml.h \
+ $$PWD/qmlbinding.h \
+ $$PWD/qmlbinding_p.h \
+ $$PWD/qmlmetaproperty.h \
+ $$PWD/qmlmoduleplugin.h \
+ $$PWD/qmlcomponent.h \
+ $$PWD/qmlcomponent_p.h \
+ $$PWD/qmlcustomparser_p.h \
+ $$PWD/qmlcustomparser_p_p.h \
+ $$PWD/qmlpropertyvaluesource.h \
+ $$PWD/qmlpropertyvalueinterceptor.h \
+ $$PWD/qmlboundsignal_p.h \
+ $$PWD/qmlparserstatus.h \
+ $$PWD/qmlproxymetaobject_p.h \
+ $$PWD/qmlvme_p.h \
+ $$PWD/qmlcompiler_p.h \
+ $$PWD/qmlengine_p.h \
+ $$PWD/qmlexpression_p.h \
+ $$PWD/qmlprivate.h \
+ $$PWD/qmldom.h \
+ $$PWD/qmldom_p.h \
+ $$PWD/qmlrefcount_p.h \
+ $$PWD/qmlmetatype.h \
+ $$PWD/qmlengine.h \
+ $$PWD/qmlcontext.h \
+ $$PWD/qmlexpression.h \
+ $$PWD/qmlstringconverters_p.h \
+ $$PWD/qmlclassfactory_p.h \
+ $$PWD/qmlinfo.h \
+ $$PWD/qmlmetaproperty_p.h \
+ $$PWD/qmlcontext_p.h \
+ $$PWD/qmlcompositetypedata_p.h \
+ $$PWD/qmlcompositetypemanager_p.h \
+ $$PWD/qmllist.h \
+ $$PWD/qmldeclarativedata_p.h \
+ $$PWD/qmlerror.h \
+ $$PWD/qmlscriptparser_p.h \
+ $$PWD/qmlenginedebug_p.h \
+ $$PWD/qmlrewrite_p.h \
+ $$PWD/qpodvector_p.h \
+ $$PWD/qbitfield_p.h \
+ $$PWD/qmlvaluetype_p.h \
+ $$PWD/qmlcompiledbindings_p.h \
+ $$PWD/qmlxmlhttprequest_p.h \
+ $$PWD/qmlsqldatabase_p.h \
+ $$PWD/qmetaobjectbuilder_p.h \
+ $$PWD/qmlwatcher_p.h \
+ $$PWD/qmlcleanup_p.h \
+ $$PWD/qmlpropertycache_p.h \
+ $$PWD/qmlintegercache_p.h \
+ $$PWD/qmltypenamecache_p.h \
+ $$PWD/qmlscriptstring.h \
+ $$PWD/qmlobjectscriptclass_p.h \
+ $$PWD/qmlcontextscriptclass_p.h \
+ $$PWD/qmlglobalscriptclass_p.h \
+ $$PWD/qmlvaluetypescriptclass_p.h \
+ $$PWD/qmltypenamescriptclass_p.h \
+ $$PWD/qmllistscriptclass_p.h \
+ $$PWD/qmlworkerscript_p.h \
+ $$PWD/qmlscriptclass_p.h \
+ $$PWD/qmlguard_p.h \
+ $$PWD/qmlnetworkaccessmanagerfactory.h
+QT += sql
+include(parser/parser.pri)
+include(rewriter/rewriter.pri)
diff --git a/src/declarative/qml/qmlbinding.cpp b/src/declarative/qml/qmlbinding.cpp
new file mode 100644
index 0000000..3e29a3c
--- /dev/null
+++ b/src/declarative/qml/qmlbinding.cpp
@@ -0,0 +1,304 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlbinding.h"
+#include "qmlbinding_p.h"
+
+#include "qml.h"
+#include "qmlcontext.h"
+#include "qmlinfo.h"
+#include "qmlcontext_p.h"
+#include "qmldeclarativedata_p.h"
+#include "qmlstringconverters_p.h"
+
+#include <qfxperf_p_p.h>
+
+#include <QVariant>
+#include <QtCore/qdebug.h>
+
+Q_DECLARE_METATYPE(QList<QObject *>);
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_NOCREATE_TYPE(QmlBinding);
+
+QmlBindingData::QmlBindingData()
+: updating(false), enabled(false)
+{
+}
+
+QmlBindingData::~QmlBindingData()
+{
+ removeError();
+}
+
+void QmlBindingData::refresh()
+{
+ if (enabled && !updating && q) {
+ QmlBinding *b = static_cast<QmlBinding *>(QmlExpressionPrivate::get(q));
+ b->update();
+ }
+}
+
+QmlBindingPrivate::QmlBindingPrivate()
+: QmlExpressionPrivate(new QmlBindingData)
+{
+}
+
+QmlBinding::QmlBinding(void *data, QmlRefCount *rc, QObject *obj, QmlContext *ctxt, const QString &url, int lineNumber, QObject *parent)
+: QmlExpression(ctxt, data, rc, obj, url, lineNumber, *new QmlBindingPrivate)
+{
+ setParent(parent);
+}
+
+QmlBinding::QmlBinding(const QString &str, QObject *obj, QmlContext *ctxt, QObject *parent)
+: QmlExpression(ctxt, str, obj, *new QmlBindingPrivate)
+{
+ setParent(parent);
+}
+
+QmlBinding::~QmlBinding()
+{
+}
+
+void QmlBinding::setTarget(const QmlMetaProperty &prop)
+{
+ Q_D(QmlBinding);
+ d->bindingData()->property = prop;
+
+ update();
+}
+
+QmlMetaProperty QmlBinding::property() const
+{
+ Q_D(const QmlBinding);
+ return d->bindingData()->property;
+}
+
+void QmlBinding::update(QmlMetaProperty::WriteFlags flags)
+{
+ Q_D(QmlBinding);
+
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::BindableValueUpdate> bu;
+#endif
+ QmlBindingData *data = d->bindingData();
+
+ if (!data->enabled)
+ return;
+
+ data->addref();
+
+ if (!data->updating) {
+ data->updating = true;
+
+ if (data->property.propertyCategory() == QmlMetaProperty::Bindable) {
+
+ int idx = data->property.coreIndex();
+ Q_ASSERT(idx != -1);
+
+
+ QmlBinding *t = this;
+ int status = -1;
+ void *a[] = { &t, 0, &status, &flags };
+ QMetaObject::metacall(data->property.object(),
+ QMetaObject::WriteProperty,
+ idx, a);
+
+ } else {
+ bool isUndefined = false;
+ QVariant value = this->value(&isUndefined);
+
+ if (isUndefined && !data->error.isValid() && data->property.isResettable()) {
+
+ data->property.reset();
+
+ } else if (isUndefined && !data->error.isValid()) {
+
+ QUrl url = QUrl(data->url);
+ int line = data->line;
+ if (url.isEmpty()) url = QUrl(QLatin1String("<Unknown File>"));
+
+ data->error.setUrl(url);
+ data->error.setLine(line);
+ data->error.setColumn(-1);
+ data->error.setDescription(QLatin1String("Unable to assign [undefined] to ") + QLatin1String(QMetaType::typeName(data->property.propertyType())));
+
+ } else if (!isUndefined && data->property.object() &&
+ !data->property.write(value, flags)) {
+
+ QUrl url = QUrl(data->url);
+ int line = data->line;
+ if (url.isEmpty()) url = QUrl(QLatin1String("<Unknown File>"));
+
+ const char *valueType = 0;
+ if (value.userType() == QVariant::Invalid) valueType = "null";
+ else valueType = QMetaType::typeName(value.userType());
+
+ data->error.setUrl(url);
+ data->error.setLine(line);
+ data->error.setColumn(-1);
+ data->error.setDescription(QLatin1String("Unable to assign ") +
+ QLatin1String(valueType) +
+ QLatin1String(" to ") +
+ QLatin1String(QMetaType::typeName(data->property.propertyType())));
+ }
+
+ if (data->error.isValid()) {
+ QmlEnginePrivate *p = (data->context() && data->context()->engine())?
+ QmlEnginePrivate::get(data->context()->engine()):0;
+ if (!data->addError(p))
+ qWarning().nospace() << qPrintable(this->error().toString());
+ } else {
+ data->removeError();
+ }
+ }
+
+ data->updating = false;
+ } else {
+ qmlInfo(data->property.object()) << tr("Binding loop detected for property \"%1\"").arg(data->property.name());
+ }
+
+ data->release();
+}
+
+void QmlBinding::emitValueChanged()
+{
+ update();
+ // don't bother calling valueChanged()
+}
+
+void QmlBinding::setEnabled(bool e, QmlMetaProperty::WriteFlags flags)
+{
+ Q_D(QmlBinding);
+ d->bindingData()->enabled = e;
+ setTrackChange(e);
+
+ QmlAbstractBinding::setEnabled(e, flags);
+
+ if (e) {
+ addToObject(d->bindingData()->property.object());
+ update(flags);
+ } else {
+ removeFromObject();
+ }
+}
+
+int QmlBinding::propertyIndex()
+{
+ Q_D(QmlBinding);
+ return d->bindingData()->property.coreIndex();
+}
+
+bool QmlBinding::enabled() const
+{
+ Q_D(const QmlBinding);
+
+ return d->bindingData()->enabled;
+}
+
+QString QmlBinding::expression() const
+{
+ return QmlExpression::expression();
+}
+
+QmlAbstractBinding::QmlAbstractBinding()
+: m_object(0), m_mePtr(0), m_prevBinding(0), m_nextBinding(0)
+{
+}
+
+QmlAbstractBinding::~QmlAbstractBinding()
+{
+ removeFromObject();
+ if (m_mePtr)
+ *m_mePtr = 0;
+}
+
+void QmlAbstractBinding::destroy()
+{
+ delete this;
+}
+
+void QmlAbstractBinding::addToObject(QObject *object)
+{
+ Q_ASSERT(object);
+
+ removeFromObject();
+
+ Q_ASSERT(!m_prevBinding);
+
+ QmlDeclarativeData *data = QmlDeclarativeData::get(object, true);
+ m_nextBinding = data->bindings;
+ if (m_nextBinding) m_nextBinding->m_prevBinding = &m_nextBinding;
+ m_prevBinding = &data->bindings;
+ data->bindings = this;
+ m_object = object;
+
+ data->setBindingBit(m_object, propertyIndex());
+}
+
+void QmlAbstractBinding::removeFromObject()
+{
+ if (m_prevBinding) {
+ Q_ASSERT(m_object);
+
+ *m_prevBinding = m_nextBinding;
+ if (m_nextBinding) m_nextBinding->m_prevBinding = m_prevBinding;
+ m_prevBinding = 0;
+ m_nextBinding = 0;
+
+ QmlDeclarativeData *data = QmlDeclarativeData::get(m_object, false);
+ if (data) data->clearBindingBit(propertyIndex());
+ m_object = 0;
+ }
+}
+
+QString QmlAbstractBinding::expression() const
+{
+ return QLatin1String("<Unknown>");
+}
+
+void QmlAbstractBinding::setEnabled(bool e, QmlMetaProperty::WriteFlags)
+{
+ if (e) m_mePtr = 0;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlbinding.h b/src/declarative/qml/qmlbinding.h
new file mode 100644
index 0000000..cefb4fe
--- /dev/null
+++ b/src/declarative/qml/qmlbinding.h
@@ -0,0 +1,129 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLBINDING_H
+#define QMLBINDING_H
+
+#include "qml.h"
+#include "qmlpropertyvaluesource.h"
+#include "qmlexpression.h"
+
+#include <QtCore/QObject>
+#include <QtCore/QMetaProperty>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class Q_DECLARATIVE_EXPORT QmlAbstractBinding
+{
+public:
+ QmlAbstractBinding();
+ virtual ~QmlAbstractBinding();
+
+ virtual void destroy();
+
+ virtual QString expression() const;
+
+ void setEnabled(bool e) { setEnabled(e, QmlMetaProperty::DontRemoveBinding); }
+ virtual void setEnabled(bool, QmlMetaProperty::WriteFlags) = 0;
+ virtual int propertyIndex() = 0;
+
+ void update() { update(QmlMetaProperty::DontRemoveBinding); }
+ virtual void update(QmlMetaProperty::WriteFlags) = 0;
+
+ void addToObject(QObject *);
+ void removeFromObject();
+
+private:
+ friend class QmlDeclarativeData;
+ friend class QmlMetaProperty;
+ friend class QmlMetaPropertyPrivate;
+ friend class QmlVME;
+
+ QObject *m_object;
+ QmlAbstractBinding **m_mePtr;
+ QmlAbstractBinding **m_prevBinding;
+ QmlAbstractBinding *m_nextBinding;
+};
+
+class QmlContext;
+class QmlBindingPrivate;
+class Q_DECLARATIVE_EXPORT QmlBinding : public QmlExpression,
+ public QmlAbstractBinding
+{
+Q_OBJECT
+public:
+ QmlBinding(const QString &, QObject *, QmlContext *, QObject *parent=0);
+ QmlBinding(void *, QmlRefCount *, QObject *, QmlContext *, const QString &, int,
+ QObject *parent);
+ ~QmlBinding();
+
+ void setTarget(const QmlMetaProperty &);
+ QmlMetaProperty property() const;
+
+ bool enabled() const;
+
+ // Inherited from QmlAbstractBinding
+ virtual void setEnabled(bool, QmlMetaProperty::WriteFlags flags);
+ virtual int propertyIndex();
+ virtual void update(QmlMetaProperty::WriteFlags flags);
+ virtual QString expression() const;
+
+public Q_SLOTS:
+ void update() { update(QmlMetaProperty::DontRemoveBinding); }
+
+protected:
+ void emitValueChanged();
+
+private:
+ Q_DECLARE_PRIVATE(QmlBinding)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlBinding);
+
+QT_END_HEADER
+
+#endif // QMLBINDING_H
diff --git a/src/declarative/qml/qmlbinding_p.h b/src/declarative/qml/qmlbinding_p.h
new file mode 100644
index 0000000..c6c1935
--- /dev/null
+++ b/src/declarative/qml/qmlbinding_p.h
@@ -0,0 +1,89 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLBINDING_P_H
+#define QMLBINDING_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 "qmlbinding.h"
+
+#include "qmlmetaproperty.h"
+#include "qmlexpression_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlBindingData : public QmlExpressionData
+{
+public:
+ QmlBindingData();
+ virtual ~QmlBindingData();
+
+ bool updating:1;
+ bool enabled:1;
+
+ QmlMetaProperty property;
+
+ virtual void refresh();
+};
+
+class QmlBindingPrivate : public QmlExpressionPrivate
+{
+ Q_DECLARE_PUBLIC(QmlBinding)
+public:
+ QmlBindingPrivate();
+
+ QmlBindingData *bindingData() { return static_cast<QmlBindingData *>(data); }
+ const QmlBindingData *bindingData() const { return static_cast<const QmlBindingData *>(data); }
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLBINDING_P_H
diff --git a/src/declarative/qml/qmlboundsignal.cpp b/src/declarative/qml/qmlboundsignal.cpp
new file mode 100644
index 0000000..d42e7ba
--- /dev/null
+++ b/src/declarative/qml/qmlboundsignal.cpp
@@ -0,0 +1,264 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlboundsignal_p.h"
+
+#include "qmetaobjectbuilder_p.h"
+#include "qmlengine_p.h"
+#include "qmlexpression_p.h"
+#include "qmlcontext_p.h"
+#include "qmlmetatype.h"
+#include "qml.h"
+#include "qmlcontext.h"
+#include "qmlglobal_p.h"
+
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlBoundSignalParameters : public QObject
+{
+Q_OBJECT
+public:
+ QmlBoundSignalParameters(const QMetaMethod &, QObject * = 0);
+ ~QmlBoundSignalParameters();
+
+ void setValues(void **);
+ void clearValues();
+
+private:
+ friend class MetaObject;
+ int metaCall(QMetaObject::Call, int _id, void **);
+ struct MetaObject : public QAbstractDynamicMetaObject {
+ MetaObject(QmlBoundSignalParameters *b)
+ : parent(b) {}
+
+ int metaCall(QMetaObject::Call c, int id, void **a) {
+ return parent->metaCall(c, id, a);
+ }
+ QmlBoundSignalParameters *parent;
+ };
+
+ int *types;
+ void **values;
+ QMetaObject *myMetaObject;
+};
+
+static int evaluateIdx = -1;
+
+QmlAbstractBoundSignal::QmlAbstractBoundSignal(QObject *parent)
+: QObject(parent)
+{
+}
+
+QmlAbstractBoundSignal::~QmlAbstractBoundSignal()
+{
+}
+
+QmlBoundSignal::QmlBoundSignal(QObject *scope, const QMetaMethod &signal,
+ QObject *parent)
+: m_expression(0), m_signal(signal), m_paramsValid(false), m_params(0)
+{
+ // A cached evaluation of the QmlExpression::value() slot index.
+ //
+ // This is thread safe. Although it may be updated by two threads, they
+ // will both set it to the same value - so the worst thing that can happen
+ // is that they both do the work to figure it out. Boo hoo.
+ if (evaluateIdx == -1) evaluateIdx = metaObject()->methodCount();
+
+ QmlGraphics_setParent_noEvent(this, parent);
+ QMetaObject::connect(scope, m_signal.methodIndex(), this, evaluateIdx);
+}
+
+QmlBoundSignal::QmlBoundSignal(QmlContext *ctxt, const QString &val,
+ QObject *scope, const QMetaMethod &signal,
+ QObject *parent)
+: m_expression(0), m_signal(signal), m_paramsValid(false), m_params(0)
+{
+ // A cached evaluation of the QmlExpression::value() slot index.
+ //
+ // This is thread safe. Although it may be updated by two threads, they
+ // will both set it to the same value - so the worst thing that can happen
+ // is that they both do the work to figure it out. Boo hoo.
+ if (evaluateIdx == -1) evaluateIdx = metaObject()->methodCount();
+
+ QmlGraphics_setParent_noEvent(this, parent);
+ QMetaObject::connect(scope, m_signal.methodIndex(), this, evaluateIdx);
+
+ m_expression = new QmlExpression(ctxt, val, scope);
+ m_expression->setTrackChange(false);
+}
+
+QmlBoundSignal::~QmlBoundSignal()
+{
+ delete m_expression;
+ m_expression = 0;
+}
+
+int QmlBoundSignal::index() const
+{
+ return m_signal.methodIndex();
+}
+
+/*!
+ Returns the signal expression.
+*/
+QmlExpression *QmlBoundSignal::expression() const
+{
+ return m_expression;
+}
+
+/*!
+ Sets the signal expression to \a e. Returns the current signal expression,
+ or null if there is no signal expression.
+
+ The QmlBoundSignal instance takes ownership of \a e. The caller is
+ assumes ownership of the returned QmlExpression.
+*/
+QmlExpression *QmlBoundSignal::setExpression(QmlExpression *e)
+{
+ QmlExpression *rv = m_expression;
+ m_expression = e;
+ if (m_expression) m_expression->setTrackChange(false);
+ return rv;
+}
+
+QmlBoundSignal *QmlBoundSignal::cast(QObject *o)
+{
+ QmlAbstractBoundSignal *s = qobject_cast<QmlAbstractBoundSignal*>(o);
+ return static_cast<QmlBoundSignal *>(s);
+}
+
+int QmlBoundSignal::qt_metacall(QMetaObject::Call c, int id, void **a)
+{
+ if (c == QMetaObject::InvokeMetaMethod && id == evaluateIdx) {
+ if (!m_paramsValid) {
+ if (!m_signal.parameterTypes().isEmpty())
+ m_params = new QmlBoundSignalParameters(m_signal, this);
+ m_paramsValid = true;
+ }
+
+ if (m_params) m_params->setValues(a);
+ if (m_expression) {
+ QmlExpressionPrivate::get(m_expression)->value(m_params);
+ if (m_expression && m_expression->hasError())
+ qWarning().nospace() << qPrintable(m_expression->error().toString());
+ }
+ if (m_params) m_params->clearValues();
+ return -1;
+ } else {
+ return QObject::qt_metacall(c, id, a);
+ }
+}
+
+QmlBoundSignalParameters::QmlBoundSignalParameters(const QMetaMethod &method,
+ QObject *parent)
+: QObject(parent), types(0), values(0)
+{
+ MetaObject *mo = new MetaObject(this);
+
+ // ### Optimize!
+ // ### Ensure only supported types are allowed, otherwise it might crash
+ QMetaObjectBuilder mob;
+ mob.setSuperClass(&QmlBoundSignalParameters::staticMetaObject);
+ mob.setClassName("QmlBoundSignalParameters");
+
+ QList<QByteArray> paramTypes = method.parameterTypes();
+ QList<QByteArray> paramNames = method.parameterNames();
+ types = new int[paramTypes.count()];
+ for (int ii = 0; ii < paramTypes.count(); ++ii) {
+ const QByteArray &type = paramTypes.at(ii);
+ const QByteArray &name = paramNames.at(ii);
+
+ if (name.isEmpty() || type.isEmpty()) {
+ types[ii] = 0;
+ continue;
+ }
+
+ QVariant::Type t = (QVariant::Type)QMetaType::type(type.constData());
+ if (QmlMetaType::isQObject(t)) {
+ types[ii] = QMetaType::QObjectStar;
+ QMetaPropertyBuilder prop = mob.addProperty(name, "QObject*");
+ prop.setWritable(false);
+ } else {
+ types[ii] = t;
+ QMetaPropertyBuilder prop = mob.addProperty(name, type);
+ prop.setWritable(false);
+ }
+ }
+ myMetaObject = mob.toMetaObject();
+ *static_cast<QMetaObject *>(mo) = *myMetaObject;
+
+ d_ptr->metaObject = mo;
+}
+
+QmlBoundSignalParameters::~QmlBoundSignalParameters()
+{
+ delete [] types;
+ qFree(myMetaObject);
+}
+
+void QmlBoundSignalParameters::setValues(void **v)
+{
+ values = v;
+}
+
+void QmlBoundSignalParameters::clearValues()
+{
+ values = 0;
+}
+
+int QmlBoundSignalParameters::metaCall(QMetaObject::Call c, int id, void **a)
+{
+ if (!values)
+ return -1;
+
+ if (c == QMetaObject::ReadProperty && id >= 1) {
+ QmlMetaType::copy(types[id - 1], a[0], values[id]);
+ return -1;
+ } else {
+ return qt_metacall(c, id, a);
+ }
+}
+
+QT_END_NAMESPACE
+
+#include <qmlboundsignal.moc>
diff --git a/src/declarative/qml/qmlboundsignal_p.h b/src/declarative/qml/qmlboundsignal_p.h
new file mode 100644
index 0000000..971fc89
--- /dev/null
+++ b/src/declarative/qml/qmlboundsignal_p.h
@@ -0,0 +1,100 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLBOUNDSIGNAL_P_H
+#define QMLBOUNDSIGNAL_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 "qmlexpression.h"
+
+#include <QtCore/qmetaobject.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlAbstractBoundSignal : public QObject
+{
+ Q_OBJECT
+public:
+ QmlAbstractBoundSignal(QObject *parent = 0);
+ virtual ~QmlAbstractBoundSignal() = 0;
+};
+
+class QmlBoundSignalParameters;
+class QmlBoundSignal : public QmlAbstractBoundSignal
+{
+public:
+ QmlBoundSignal(QObject *scope, const QMetaMethod &signal, QObject *parent);
+ QmlBoundSignal(QmlContext *ctxt, const QString &val, QObject *scope,
+ const QMetaMethod &signal, QObject *parent);
+ virtual ~QmlBoundSignal();
+
+ int index() const;
+
+ QmlExpression *expression() const;
+ QmlExpression *setExpression(QmlExpression *);
+
+ static QmlBoundSignal *cast(QObject *);
+
+protected:
+ virtual int qt_metacall(QMetaObject::Call c, int id, void **a);
+
+private:
+ QmlExpression *m_expression;
+ QMetaMethod m_signal;
+ bool m_paramsValid;
+ QmlBoundSignalParameters *m_params;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLBOUNDSIGNAL_P_H
diff --git a/src/declarative/qml/qmlclassfactory.cpp b/src/declarative/qml/qmlclassfactory.cpp
new file mode 100644
index 0000000..3c19c2f
--- /dev/null
+++ b/src/declarative/qml/qmlclassfactory.cpp
@@ -0,0 +1,50 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlclassfactory_p.h"
+
+QT_BEGIN_NAMESPACE
+
+QmlClassFactory::~QmlClassFactory()
+{
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlclassfactory_p.h b/src/declarative/qml/qmlclassfactory_p.h
new file mode 100644
index 0000000..91f616e
--- /dev/null
+++ b/src/declarative/qml/qmlclassfactory_p.h
@@ -0,0 +1,74 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCLASSFACTORY_P_H
+#define QMLCLASSFACTORY_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 QmlEngine;
+class QByteArray;
+class QUrl;
+class QmlComponent;
+
+class QmlClassFactory
+{
+public:
+ virtual ~QmlClassFactory();
+ virtual QmlComponent *create(const QByteArray &, const QUrl& baseUrl, QmlEngine*) = 0;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLCLASSFACTORY_P_H
diff --git a/src/declarative/qml/qmlcleanup.cpp b/src/declarative/qml/qmlcleanup.cpp
new file mode 100644
index 0000000..599e4e7
--- /dev/null
+++ b/src/declarative/qml/qmlcleanup.cpp
@@ -0,0 +1,85 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlcleanup_p.h"
+
+#include "qmlengine_p.h"
+
+/*!
+\internal
+\class QmlCleanup
+\brief The QmlCleanup provides a callback when a QmlEngine is deleted.
+
+Any object that needs cleanup to occur before the QmlEngine's QScriptEngine is
+destroyed should inherit from QmlCleanup. The clear() virtual method will be
+called by QmlEngine just before it deletes the QScriptEngine.
+*/
+
+/*!
+\internal
+
+Create a QmlCleanup for \a engine
+*/
+QmlCleanup::QmlCleanup(QmlEngine *engine)
+: prev(0), next(0)
+{
+ if (!engine)
+ return;
+
+ QmlEnginePrivate *p = QmlEnginePrivate::get(engine);
+
+ if (p->cleanup) next = p->cleanup;
+ p->cleanup = this;
+ prev = &p->cleanup;
+ if (next) next->prev = &next;
+}
+
+/*!
+\internal
+*/
+QmlCleanup::~QmlCleanup()
+{
+ if (prev) *prev = next;
+ if (next) next->prev = prev;
+ prev = 0;
+ next = 0;
+}
+
diff --git a/src/declarative/qml/qmlcleanup_p.h b/src/declarative/qml/qmlcleanup_p.h
new file mode 100644
index 0000000..c140e43
--- /dev/null
+++ b/src/declarative/qml/qmlcleanup_p.h
@@ -0,0 +1,79 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCLEANUP_P_H
+#define QMLCLEANUP_P_H
+
+#include <QtCore/qglobal.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 QmlEngine;
+class QmlCleanup
+{
+public:
+ QmlCleanup(QmlEngine *);
+ virtual ~QmlCleanup();
+
+protected:
+ virtual void clear() = 0;
+
+private:
+ friend class QmlEnginePrivate;
+ QmlCleanup **prev;
+ QmlCleanup *next;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLCLEANUP_P_H
+
diff --git a/src/declarative/qml/qmlcompiledbindings.cpp b/src/declarative/qml/qmlcompiledbindings.cpp
new file mode 100644
index 0000000..b5fbab9
--- /dev/null
+++ b/src/declarative/qml/qmlcompiledbindings.cpp
@@ -0,0 +1,2720 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlcompiledbindings_p.h"
+
+#include <QtDeclarative/qmlinfo.h>
+#include <private/qmlcontext_p.h>
+#include <private/qmljsast_p.h>
+#include <private/qmljsengine_p.h>
+#include <private/qmlexpression_p.h>
+#include <QtCore/qdebug.h>
+#include <QtCore/qnumeric.h>
+#include <private/qmlgraphicsanchors_p_p.h>
+
+QT_BEGIN_NAMESPACE
+
+using namespace QmlJS;
+
+namespace {
+// Supported types: int, qreal, QString (needs constr/destr), QObject*, bool
+struct Register {
+ void setUndefined() { type = 0; }
+ void setUnknownButDefined() { type = -1; }
+ void setNaN() { setqreal(qSNaN()); }
+ bool isUndefined() const { return type == 0; }
+
+ void setQObject(QObject *o) { *((QObject **)data) = o; type = QMetaType::QObjectStar; }
+ QObject *getQObject() const { return *((QObject **)data); }
+
+ void setqreal(qreal v) { *((qreal *)data) = v; type = QMetaType::QReal; }
+ qreal getqreal() const { return *((qreal *)data); }
+
+ void setint(int v) { *((int *)data) = v; type = QMetaType::Int; }
+ int getint() const { return *((int *)data); }
+
+ void setbool(bool v) { *((bool *)data) = v; type = QMetaType::Bool; }
+ bool getbool() const { return *((bool *)data); }
+
+ QVariant *getvariantptr() { return (QVariant *)typeDataPtr(); }
+ QString *getstringptr() { return (QString *)typeDataPtr(); }
+ QUrl *geturlptr() { return (QUrl *)typeDataPtr(); }
+ const QVariant *getvariantptr() const { return (QVariant *)typeDataPtr(); }
+ const QString *getstringptr() const { return (QString *)typeDataPtr(); }
+ const QUrl *geturlptr() const { return (QUrl *)typeDataPtr(); }
+
+ void *typeDataPtr() { return (void *)&data; }
+ void *typeMemory() { return (void *)data; }
+ const void *typeDataPtr() const { return (void *)&data; }
+ const void *typeMemory() const { return (void *)data; }
+
+ int gettype() const { return type; }
+ void settype(int t) { type = t; }
+
+ int type; // Optional type
+ void *data[2]; // Object stored here
+};
+}
+
+class QmlCompiledBindingsPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlCompiledBindings)
+
+public:
+ QmlCompiledBindingsPrivate();
+ virtual ~QmlCompiledBindingsPrivate();
+
+ struct Binding : public QmlAbstractBinding, public QmlDelayedError {
+ Binding() : enabled(false), updating(0), property(0),
+ scope(0), target(0), parent(0) {}
+
+ // Inherited from QmlAbstractBinding
+ virtual void setEnabled(bool, QmlMetaProperty::WriteFlags flags);
+ virtual int propertyIndex();
+ virtual void update(QmlMetaProperty::WriteFlags flags);
+ virtual void destroy();
+
+ int index:30;
+ bool enabled:1;
+ bool updating:1;
+ int property;
+ QObject *scope;
+ QObject *target;
+
+ QmlCompiledBindingsPrivate *parent;
+ };
+
+ struct Subscription {
+ struct Signal {
+ QmlGuard<QObject> source;
+ int notifyIndex;
+ };
+
+ enum { InvalidType, SignalType, IdType } type;
+ inline Subscription();
+ inline ~Subscription();
+ bool isSignal() const { return type == SignalType; }
+ bool isId() const { return type == IdType; }
+ inline Signal *signal();
+ inline QmlContextPrivate::IdNotifier *id();
+ union {
+ char signalData[sizeof(Signal)];
+ char idData[sizeof(QmlContextPrivate::IdNotifier)];
+ };
+ };
+ Subscription *subscriptions;
+ QScriptDeclarativeClass::PersistentIdentifier *identifiers;
+
+ void run(Binding *);
+
+ const char *programData;
+ Binding *m_bindings;
+ quint32 *m_signalTable;
+
+ static int methodCount;
+
+ void init();
+ void run(int instr, QmlContextPrivate *context,
+ QmlDelayedError *error, QObject *scope, QObject *output);
+
+
+ inline void unsubscribe(int subIndex);
+ inline void subscribeId(QmlContextPrivate *p, int idIndex, int subIndex);
+ inline void subscribe(QObject *o, int notifyIndex, int subIndex);
+
+ QmlPropertyCache::Data *findproperty(QObject *obj,
+ const QScriptDeclarativeClass::Identifier &name,
+ QmlEnginePrivate *enginePriv,
+ QmlPropertyCache::Data &local);
+ bool findproperty(QObject *obj,
+ Register *output,
+ QmlEnginePrivate *enginePriv,
+ int subIdx,
+ const QScriptDeclarativeClass::Identifier &name,
+ bool isTerminal);
+ void findgeneric(Register *output, // value output
+ int subIdx, // Subscription index in config
+ QmlContextPrivate *context, // Context to search in
+ const QScriptDeclarativeClass::Identifier &name,
+ bool isTerminal);
+};
+
+QmlCompiledBindingsPrivate::QmlCompiledBindingsPrivate()
+: subscriptions(0), identifiers(0)
+{
+}
+
+QmlCompiledBindingsPrivate::~QmlCompiledBindingsPrivate()
+{
+ delete [] subscriptions; subscriptions = 0;
+ delete [] identifiers; identifiers = 0;
+}
+
+QmlCompiledBindingsPrivate::Subscription::Subscription()
+: type(InvalidType)
+{
+}
+
+QmlCompiledBindingsPrivate::Subscription::~Subscription()
+{
+ if (type == SignalType) ((Signal *)signalData)->~Signal();
+ else if (type == IdType) ((QmlContextPrivate::IdNotifier *)idData)->~IdNotifier();
+}
+
+
+int QmlCompiledBindingsPrivate::methodCount = -1;
+
+QmlCompiledBindings::QmlCompiledBindings(const char *program, QmlContext *context)
+: QObject(*(new QmlCompiledBindingsPrivate))
+{
+ Q_D(QmlCompiledBindings);
+
+ if (d->methodCount == -1)
+ d->methodCount = QmlCompiledBindings::staticMetaObject.methodCount();
+
+ d->programData = program;
+
+ d->init();
+
+ QmlAbstractExpression::setContext(context);
+}
+
+QmlCompiledBindings::~QmlCompiledBindings()
+{
+ Q_D(QmlCompiledBindings);
+
+ delete [] d->m_bindings;
+}
+
+QmlAbstractBinding *QmlCompiledBindings::configBinding(int index, QObject *target,
+ QObject *scope, int property)
+{
+ Q_D(QmlCompiledBindings);
+
+ QmlCompiledBindingsPrivate::Binding *rv = d->m_bindings + index;
+
+ rv->index = index;
+ rv->property = property;
+ rv->target = target;
+ rv->scope = scope;
+ rv->parent = d;
+
+ addref(); // This is decremented in Binding::destroy()
+
+ return rv;
+}
+
+void QmlCompiledBindingsPrivate::Binding::setEnabled(bool e, QmlMetaProperty::WriteFlags flags)
+{
+ if (e) {
+ addToObject(target);
+ update(flags);
+ } else {
+ removeFromObject();
+ }
+
+ QmlAbstractBinding::setEnabled(e, flags);
+
+ if (enabled != e) {
+ enabled = e;
+
+ if (e) update(flags);
+ }
+}
+
+int QmlCompiledBindingsPrivate::Binding::propertyIndex()
+{
+ return property & 0xFFFF;
+}
+
+void QmlCompiledBindingsPrivate::Binding::update(QmlMetaProperty::WriteFlags)
+{
+ parent->run(this);
+}
+
+void QmlCompiledBindingsPrivate::Binding::destroy()
+{
+ enabled = false;
+ removeFromObject();
+ parent->q_func()->release();
+}
+
+int QmlCompiledBindings::qt_metacall(QMetaObject::Call c, int id, void **)
+{
+ Q_D(QmlCompiledBindings);
+
+ if (c == QMetaObject::InvokeMetaMethod && id >= d->methodCount) {
+ id -= d->methodCount;
+
+ quint32 *reeval = d->m_signalTable + d->m_signalTable[id];
+ quint32 count = *reeval;
+ ++reeval;
+ for (quint32 ii = 0; ii < count; ++ii) {
+ d->run(d->m_bindings + reeval[ii]);
+ }
+ }
+ return -1;
+}
+
+void QmlCompiledBindingsPrivate::run(Binding *binding)
+{
+ Q_Q(QmlCompiledBindings);
+
+ if (!binding->enabled)
+ return;
+ if (binding->updating)
+ qWarning("ERROR: Circular binding");
+
+ QmlContext *context = q->QmlAbstractExpression::context();
+ if (!context) {
+ qWarning("QmlCompiledBindings: Attempted to evaluate an expression in an invalid context");
+ return;
+ }
+ QmlContextPrivate *cp = QmlContextPrivate::get(context);
+
+ if (binding->property & 0xFFFF0000) {
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(cp->engine);
+
+ QmlValueType *vt = ep->valueTypes[(binding->property >> 16) & 0xFF];
+ Q_ASSERT(vt);
+ vt->read(binding->target, binding->property & 0xFFFF);
+
+ QObject *target = vt;
+ run(binding->index, cp, binding, binding->scope, target);
+
+ vt->write(binding->target, binding->property & 0xFFFF,
+ QmlMetaProperty::DontRemoveBinding);
+ } else {
+ run(binding->index, cp, binding, binding->scope, binding->target);
+ }
+}
+
+QmlCompiledBindingsPrivate::Subscription::Signal *QmlCompiledBindingsPrivate::Subscription::signal()
+{
+ if (type == IdType) ((QmlContextPrivate::IdNotifier *)idData)->~IdNotifier();
+ if (type != SignalType) new (signalData) Signal;
+ type = SignalType;
+ return (Signal *)signalData;
+}
+
+QmlContextPrivate::IdNotifier *QmlCompiledBindingsPrivate::Subscription::id()
+{
+ if (type == SignalType) ((Signal *)signalData)->~Signal();
+ if (type != IdType) new (idData) QmlContextPrivate::IdNotifier;
+ type = IdType;
+ return (QmlContextPrivate::IdNotifier *)idData;
+}
+
+namespace {
+// This structure is exactly 8-bytes in size
+struct Instr {
+ enum {
+ Noop,
+
+ Subscribe, // subscribe
+ SubscribeId, // subscribe
+
+ LoadId, // load
+ LoadScope, // load
+ LoadRoot, // load
+ LoadAttached, // attached
+
+ ConvertIntToReal, // unaryop
+ ConvertRealToInt, // unaryop
+
+ Real, // real_value
+ Int, // int_value
+ Bool, // bool_value
+ String, // string_value
+
+ AddReal, // binaryop
+ AddInt, // binaryop
+ AddString, // binaryop
+
+ MinusReal, // binaryop
+ MinusInt, // binaryop
+
+ CompareReal, // binaryop
+ CompareString, // binaryop
+
+ NotCompareReal, // binaryop
+ NotCompareString, // binaryop
+
+ GreaterThanReal, // binaryop
+ MaxReal, // binaryop
+ MinReal, // binaryop
+
+ NewString, // construct
+ NewUrl, // construct
+
+ CleanupUrl, // cleanup
+ CleanupString, // cleanup
+
+ Copy, // copy
+ Fetch, // fetch
+ Store, // store
+
+ Skip, // skip
+
+ Done,
+
+ // Speculative property resolution
+ InitString, // initstring
+ FindGeneric, // find
+ FindGenericTerminal, // find
+ FindProperty, // find
+ FindPropertyTerminal, // find
+ CleanupGeneric, // cleanup
+ ConvertGenericToReal, // unaryop
+ ConvertGenericToBool, // unaryop
+ ConvertGenericToString, // unaryop
+ ConvertGenericToUrl, // unaryop
+ };
+
+ union {
+ struct {
+ quint8 type;
+ quint8 packing[7];
+ } common;
+ struct {
+ quint8 type;
+ quint8 packing[3];
+ quint16 subscriptions;
+ quint16 identifiers;
+ } init;
+ struct {
+ quint8 type;
+ qint8 reg;
+ quint16 offset;
+ quint32 index;
+ } subscribe;
+ struct {
+ quint8 type;
+ qint8 reg;
+ quint8 packing[2];
+ quint32 index;
+ } load;
+ struct {
+ quint8 type;
+ qint8 output;
+ qint8 reg;
+ quint8 exceptionId;
+ quint32 index;
+ } attached;
+ struct {
+ quint8 type;
+ qint8 output;
+ qint8 reg;
+ quint8 exceptionId;
+ quint32 index;
+ } store;
+ struct {
+ quint8 type;
+ qint8 output;
+ qint8 objectReg;
+ quint8 exceptionId;
+ quint32 index;
+ } fetch;
+ struct {
+ quint8 type;
+ qint8 reg;
+ qint8 src;
+ quint8 packing[5];
+ } copy;
+ struct {
+ quint8 type;
+ qint8 reg;
+ quint8 packing[6];
+ } construct;
+ struct {
+ quint8 type;
+ qint8 reg;
+ quint8 packing[2];
+ float value;
+ } real_value;
+ struct {
+ quint8 type;
+ qint8 reg;
+ quint8 packing[2];
+ int value;
+ } int_value;
+ struct {
+ quint8 type;
+ qint8 reg;
+ bool value;
+ quint8 packing[5];
+ } bool_value;
+ struct {
+ quint8 type;
+ qint8 reg;
+ quint16 length;
+ quint32 offset;
+ } string_value;
+ struct {
+ quint8 type;
+ qint8 output;
+ qint8 src1;
+ qint8 src2;
+ quint8 packing[4];
+ } binaryop;
+ struct {
+ quint8 type;
+ qint8 output;
+ qint8 src;
+ quint8 packing[5];
+ } unaryop;
+ struct {
+ quint8 type;
+ qint8 reg;
+ quint8 packing[2];
+ quint32 count;
+ } skip;
+ struct {
+ quint8 type;
+ qint8 reg;
+ qint8 src;
+ quint8 exceptionId;
+ quint16 name;
+ quint16 subscribeIndex;
+ } find;
+ struct {
+ quint8 type;
+ qint8 reg;
+ quint8 packing[6];
+ } cleanup;
+ struct {
+ quint8 type;
+ quint8 packing[1];
+ quint16 offset;
+ quint32 dataIdx;
+ } initstring;
+ };
+};
+
+struct Program {
+ quint32 bindings;
+ quint32 dataLength;
+ quint32 signalTableOffset;
+ quint32 exceptionDataOffset;
+ quint16 subscriptions;
+ quint16 identifiers;
+ quint16 instructionCount;
+ quint16 dummy;
+
+ const char *data() const { return ((const char *)this) + sizeof(Program); }
+ const Instr *instructions() const { return (const Instr *)(data() + dataLength); }
+};
+}
+
+struct QmlBindingCompilerPrivate
+{
+ struct Result {
+ Result() : unknownType(false), metaObject(0), type(-1), reg(-1) {}
+ bool operator==(const Result &o) const {
+ return unknownType == o.unknownType &&
+ metaObject == o.metaObject &&
+ type == o.type &&
+ reg == o.reg;
+ }
+ bool operator!=(const Result &o) const {
+ return !(*this == o);
+ }
+ bool unknownType;
+ const QMetaObject *metaObject;
+ int type;
+ int reg;
+
+ QSet<QString> subscriptionSet;
+ };
+
+ QmlBindingCompilerPrivate() : registers(0) {}
+
+ void resetInstanceState();
+ int commitCompile();
+
+ QmlParser::Object *context;
+ QmlParser::Object *component;
+ QmlParser::Property *destination;
+ QHash<QString, QmlParser::Object *> ids;
+ QmlEnginePrivate::Imports imports;
+ QmlEnginePrivate *engine;
+
+ QString contextName() const { return QLatin1String("$$$SCOPE_") + QString::number((intptr_t)context, 16); }
+
+ bool compile(QmlJS::AST::Node *);
+
+ bool parseExpression(QmlJS::AST::Node *, Result &);
+
+ bool tryName(QmlJS::AST::Node *);
+ bool parseName(QmlJS::AST::Node *, Result &);
+
+ bool tryArith(QmlJS::AST::Node *);
+ bool parseArith(QmlJS::AST::Node *, Result &);
+ bool numberArith(Result &, const Result &, const Result &, QSOperator::Op op);
+ bool stringArith(Result &, const Result &, const Result &, QSOperator::Op op);
+
+ bool tryLogic(QmlJS::AST::Node *);
+ bool parseLogic(QmlJS::AST::Node *, Result &);
+
+ bool tryConditional(QmlJS::AST::Node *);
+ bool parseConditional(QmlJS::AST::Node *, Result &);
+
+ bool tryConstant(QmlJS::AST::Node *);
+ bool parseConstant(QmlJS::AST::Node *, Result &);
+
+ bool tryMethod(QmlJS::AST::Node *);
+ bool parseMethod(QmlJS::AST::Node *, Result &);
+
+ bool buildName(QStringList &, QmlJS::AST::Node *, QList<QmlJS::AST::ExpressionNode *> *nodes = 0);
+ bool fetch(Result &type, const QMetaObject *, int reg, int idx, const QStringList &, QmlJS::AST::ExpressionNode *);
+
+ quint32 registers;
+ QHash<int, QPair<int, int> > registerCleanups;
+ int acquireReg(int cleanup = Instr::Noop, int cleanupType = 0);
+ void registerCleanup(int reg, int cleanup, int cleanupType = 0);
+ void releaseReg(int);
+
+ int registerLiteralString(const QString &);
+ int registerString(const QString &);
+ QHash<QString, QPair<int, int> > registeredStrings;
+ QByteArray data;
+
+ bool subscription(const QStringList &, Result *);
+ int subscriptionIndex(const QStringList &);
+ bool subscriptionNeutral(const QSet<QString> &base, const QSet<QString> &lhs, const QSet<QString> &rhs);
+
+ quint8 exceptionId(QmlJS::AST::ExpressionNode *);
+ QVector<quint64> exceptions;
+
+ QSet<int> usedSubscriptionIds;
+ QSet<QString> subscriptionSet;
+ QHash<QString, int> subscriptionIds;
+ QVector<Instr> bytecode;
+
+ // Committed binding data
+ struct {
+ QList<int> offsets;
+ QList<QSet<int> > dependencies;
+
+ QVector<Instr> bytecode;
+ QByteArray data;
+ QHash<QString, int> subscriptionIds;
+ QVector<quint64> exceptions;
+
+ QHash<QString, QPair<int, int> > registeredStrings;
+
+ int count() const { return offsets.count(); }
+ } committed;
+
+ QByteArray buildSignalTable() const;
+ QByteArray buildExceptionData() const;
+};
+
+void QmlCompiledBindingsPrivate::unsubscribe(int subIndex)
+{
+ Q_Q(QmlCompiledBindings);
+
+ QmlCompiledBindingsPrivate::Subscription *sub = (subscriptions + subIndex);
+ if (sub->isSignal()) {
+ QmlCompiledBindingsPrivate::Subscription::Signal *s = sub->signal();
+ if (s->source)
+#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 2))
+ QMetaObject::disconnectOne(s->source, s->notifyIndex,
+ q, methodCount + subIndex);
+#else
+ // QTBUG-6781
+ QMetaObject::disconnect(s->source, s->notifyIndex,
+ q, methodCount + subIndex);
+#endif
+ } else if (sub->isId()) {
+ sub->id()->clear();
+ }
+}
+
+void QmlCompiledBindingsPrivate::subscribeId(QmlContextPrivate *p, int idIndex, int subIndex)
+{
+ Q_Q(QmlCompiledBindings);
+
+ unsubscribe(subIndex);
+
+ if (p->idValues[idIndex]) {
+ QmlCompiledBindingsPrivate::Subscription *sub = (subscriptions + subIndex);
+ QmlContextPrivate::IdNotifier *i = sub->id();
+
+ i->next = p->idValues[idIndex].bindings;
+ i->prev = &p->idValues[idIndex].bindings;
+ p->idValues[idIndex].bindings = i;
+ if (i->next) i->next->prev = &i->next;
+
+ i->target = q;
+ i->methodIndex = methodCount + subIndex;
+ }
+}
+
+void QmlCompiledBindingsPrivate::subscribe(QObject *o, int notifyIndex, int subIndex)
+{
+ Q_Q(QmlCompiledBindings);
+
+ QmlCompiledBindingsPrivate::Subscription *sub = (subscriptions + subIndex);
+
+ if (sub->isId())
+ unsubscribe(subIndex);
+
+ QmlCompiledBindingsPrivate::Subscription::Signal *s = sub->signal();
+ if (o != s->source || notifyIndex != s->notifyIndex) {
+ if (s->source)
+#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 2))
+ QMetaObject::disconnectOne(s->source, s->notifyIndex,
+ q, methodCount + subIndex);
+#else
+ // QTBUG-6781
+ QMetaObject::disconnect(s->source, s->notifyIndex,
+ q, methodCount + subIndex);
+#endif
+ s->source = o;
+ s->notifyIndex = notifyIndex;
+ if (s->source && s->notifyIndex != -1)
+ QMetaObject::connect(s->source, s->notifyIndex, q,
+ methodCount + subIndex, Qt::DirectConnection);
+ }
+}
+
+// Conversion functions - these MUST match the QtScript expression path
+inline static qreal toReal(Register *reg, int type, bool *ok = 0)
+{
+ if (ok) *ok = true;
+
+ if (type == QMetaType::QReal) {
+ return reg->getqreal();
+ } else if (type == qMetaTypeId<QVariant>()) {
+ return reg->getvariantptr()->toReal();
+ } else {
+ if (ok) *ok = false;
+ return 0;
+ }
+}
+
+inline static QString toString(Register *reg, int type, bool *ok = 0)
+{
+ if (ok) *ok = true;
+
+ if (type == QMetaType::QReal) {
+ return QString::number(reg->getqreal());
+ } else if (type == QMetaType::Int) {
+ return QString::number(reg->getint());
+ } else if (type == qMetaTypeId<QVariant>()) {
+ return reg->getvariantptr()->toString();
+ } else if (type == QMetaType::QString) {
+ return *reg->getstringptr();
+ } else {
+ if (ok) *ok = false;
+ return QString();
+ }
+}
+
+inline static bool toBool(Register *reg, int type, bool *ok = 0)
+{
+ if (ok) *ok = true;
+
+ if (type == QMetaType::Bool) {
+ return reg->getbool();
+ } else if (type == qMetaTypeId<QVariant>()) {
+ return reg->getvariantptr()->toBool();
+ } else {
+ if (ok) *ok = false;
+ return false;
+ }
+}
+
+inline static QUrl toUrl(Register *reg, int type, QmlContextPrivate *context, bool *ok = 0)
+{
+ if (ok) *ok = true;
+
+ QUrl base;
+ if (type == qMetaTypeId<QVariant>()) {
+ QVariant *var = reg->getvariantptr();
+ int vt = var->type();
+ if (vt == QVariant::Url) {
+ base = var->toUrl();
+ } else if (vt == QVariant::ByteArray) {
+ base = QUrl(QString::fromUtf8(var->toByteArray()));
+ } else if (vt == QVariant::String) {
+ base = QUrl(var->toString());
+ } else {
+ if (ok) *ok = false;
+ return QUrl();
+ }
+ } else if (type == QMetaType::QString) {
+ base = QUrl(*reg->getstringptr());
+ } else {
+ if (ok) *ok = false;
+ return QUrl();
+ }
+
+ if (!base.isEmpty() && base.isRelative())
+ return context->url.resolved(base);
+ else
+ return base;
+}
+
+static QObject *variantToQObject(const QVariant &value, bool *ok)
+{
+ if (ok) *ok = true;
+
+ if (value.userType() == QMetaType::QObjectStar) {
+ return qvariant_cast<QObject*>(value);
+ } else {
+ if (ok) *ok = false;
+ return 0;
+ }
+}
+
+bool QmlCompiledBindingsPrivate::findproperty(QObject *obj, Register *output,
+ QmlEnginePrivate *enginePriv,
+ int subIdx, const QScriptDeclarativeClass::Identifier &name,
+ bool isTerminal)
+{
+ if (!obj) {
+ output->setUndefined();
+ return false;
+ }
+
+ QmlPropertyCache::Data local;
+ QmlPropertyCache::Data *property =
+ QmlPropertyCache::property(QmlEnginePrivate::get(enginePriv), obj, name, local);
+
+ if (property) {
+ if (subIdx != -1)
+ subscribe(obj, property->notifyIndex, subIdx);
+
+ if (property->flags & QmlPropertyCache::Data::IsQObjectDerived) {
+ void *args[] = { output->typeDataPtr(), 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, property->coreIndex, args);
+ output->settype(QMetaType::QObjectStar);
+ } else if (property->propType == qMetaTypeId<QVariant>()) {
+ QVariant v;
+ void *args[] = { &v, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, property->coreIndex, args);
+
+ if (isTerminal) {
+ new (output->typeDataPtr()) QVariant(v);
+ output->settype(qMetaTypeId<QVariant>());
+ } else {
+ bool ok;
+ output->setQObject(variantToQObject(v, &ok));
+ if (!ok)
+ output->setUndefined();
+ else
+ output->settype(QMetaType::QObjectStar);
+ }
+
+ } else {
+ if (!isTerminal) {
+ output->setUndefined();
+ } else if (property->propType == QMetaType::QReal) {
+ void *args[] = { output->typeDataPtr(), 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, property->coreIndex, args);
+ output->settype(QMetaType::QReal);
+ } else if (property->propType == QMetaType::Int) {
+ void *args[] = { output->typeDataPtr(), 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, property->coreIndex, args);
+ output->settype(QMetaType::Int);
+ } else if (property->propType == QMetaType::Bool) {
+ void *args[] = { output->typeDataPtr(), 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, property->coreIndex, args);
+ output->settype(QMetaType::Bool);
+ } else if (property->propType == QMetaType::QString) {
+ new (output->typeDataPtr()) QString();
+ void *args[] = { output->typeDataPtr(), 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, property->coreIndex, args);
+ output->settype(QMetaType::QString);
+ } else {
+ new (output->typeDataPtr())
+ QVariant(obj->metaObject()->property(property->coreIndex).read(obj));
+ output->settype(qMetaTypeId<QVariant>());
+ }
+ }
+
+ return true;
+ } else {
+ output->setUndefined();
+ return false;
+ }
+}
+
+void QmlCompiledBindingsPrivate::findgeneric(Register *output,
+ int subIdx,
+ QmlContextPrivate *context,
+ const QScriptDeclarativeClass::Identifier &name,
+ bool isTerminal)
+{
+ QmlEnginePrivate *enginePriv = QmlEnginePrivate::get(context->engine);
+
+ while (context) {
+
+ int contextPropertyIndex = context->propertyNames?context->propertyNames->value(name):-1;
+
+
+ if (contextPropertyIndex != -1) {
+
+ if (subIdx != -1)
+ subscribe(QmlContextPrivate::get(context), contextPropertyIndex + context->notifyIndex, subIdx);
+
+ if (contextPropertyIndex < context->idValueCount) {
+ output->setQObject(context->idValues[contextPropertyIndex]);
+ output->settype(QMetaType::QObjectStar);
+ } else {
+ const QVariant &value = context->propertyValues.at(contextPropertyIndex);
+ if (isTerminal) {
+ new (output->typeDataPtr()) QVariant(value);
+ output->settype(qMetaTypeId<QVariant>());
+ } else {
+ bool ok;
+ output->setQObject(variantToQObject(value, &ok));
+ if (!ok) { output->setUndefined(); }
+ else { output->settype(QMetaType::QObjectStar); }
+ return;
+ }
+ }
+
+ return;
+ }
+
+ for (int ii = 0; ii < context->scripts.count(); ++ii) {
+ QScriptValue function = QScriptDeclarativeClass::function(context->scripts.at(ii), name);
+ if (function.isValid()) {
+ qFatal("Binding optimizer resolved name to QScript method");
+ }
+ }
+
+ if (QObject *root = context->defaultObjects.isEmpty()?0:context->defaultObjects.first()) {
+
+ if (findproperty(root, output, enginePriv, subIdx, name, isTerminal))
+ return;
+
+ }
+
+ if (context->parent) {
+ context = QmlContextPrivate::get(context->parent);
+ } else {
+ context = 0;
+ }
+ }
+
+ output->setUndefined();
+}
+
+void QmlCompiledBindingsPrivate::init()
+{
+ Program *program = (Program *)programData;
+ if (program->subscriptions)
+ subscriptions = new QmlCompiledBindingsPrivate::Subscription[program->subscriptions];
+ if (program->identifiers)
+ identifiers = new QScriptDeclarativeClass::PersistentIdentifier[program->identifiers];
+
+ m_signalTable = (quint32 *)(program->data() + program->signalTableOffset);
+ m_bindings = new QmlCompiledBindingsPrivate::Binding[program->bindings];
+}
+
+static void throwException(int id, QmlDelayedError *error,
+ Program *program, QmlContextPrivate *context,
+ const QString &description = QString())
+{
+ error->error.setUrl(context->url);
+ if (description.isEmpty())
+ error->error.setDescription(QLatin1String("TypeError: Result of expression is not an object"));
+ else
+ error->error.setDescription(description);
+ if (id != 0xFF) {
+ quint64 e = *((quint64 *)(program->data() + program->exceptionDataOffset) + id);
+ error->error.setLine((e >> 32) & 0xFFFFFFFF);
+ error->error.setColumn(e & 0xFFFFFFFF);
+ } else {
+ error->error.setLine(-1);
+ error->error.setColumn(-1);
+ }
+ if (!context->engine || !error->addError(QmlEnginePrivate::get(context->engine)))
+ qWarning() << error->error;
+}
+
+void QmlCompiledBindingsPrivate::run(int instrIndex,
+ QmlContextPrivate *context, QmlDelayedError *error,
+ QObject *scope, QObject *output)
+{
+ error->removeError();
+
+ Register registers[32];
+ int storeFlags = 0;
+
+ QmlEnginePrivate *engine = QmlEnginePrivate::get(context->engine);
+ Program *program = (Program *)programData;
+ const Instr *instr = program->instructions();
+ instr += instrIndex;
+ const char *data = program->data();
+
+ while (instr) {
+
+ switch (instr->common.type) {
+ case Instr::Noop:
+ break;
+
+ case Instr::SubscribeId:
+ subscribeId(context, instr->subscribe.index, instr->subscribe.offset);
+ break;
+
+ case Instr::Subscribe:
+ {
+ QObject *o = 0;
+ const Register &object = registers[instr->subscribe.reg];
+ if (!object.isUndefined()) o = object.getQObject();
+ subscribe(o, instr->subscribe.index, instr->subscribe.offset);
+ }
+ break;
+
+ case Instr::LoadId:
+ registers[instr->load.reg].setQObject(context->idValues[instr->load.index].data());
+ break;
+
+ case Instr::LoadScope:
+ registers[instr->load.reg].setQObject(scope);
+ break;
+
+ case Instr::LoadRoot:
+ registers[instr->load.reg].setQObject(context->defaultObjects.at(0));
+ break;
+
+ case Instr::LoadAttached:
+ {
+ const Register &input = registers[instr->attached.reg];
+ Register &output = registers[instr->attached.output];
+ if (input.isUndefined()) {
+ throwException(instr->attached.exceptionId, error, program, context);
+ return;
+ }
+
+ QObject *object = registers[instr->attached.reg].getQObject();
+ if (!object) {
+ output.setUndefined();
+ } else {
+ QObject *attached =
+ qmlAttachedPropertiesObjectById(instr->attached.index,
+ registers[instr->attached.reg].getQObject(),
+ true);
+ Q_ASSERT(attached);
+ output.setQObject(attached);
+ }
+ }
+ break;
+
+ case Instr::ConvertIntToReal:
+ {
+ const Register &input = registers[instr->unaryop.src];
+ Register &output = registers[instr->unaryop.output];
+ if (input.isUndefined()) output.setUndefined();
+ else output.setqreal(qreal(input.getint()));
+ }
+ break;
+
+ case Instr::ConvertRealToInt:
+ {
+ const Register &input = registers[instr->unaryop.src];
+ Register &output = registers[instr->unaryop.output];
+ if (input.isUndefined()) output.setUndefined();
+ else output.setint(int(input.getqreal()));
+ }
+ break;
+
+ case Instr::Real:
+ registers[instr->real_value.reg].setqreal(instr->real_value.value);
+ break;
+
+ case Instr::Int:
+ registers[instr->int_value.reg].setint(instr->int_value.value);
+ break;
+
+ case Instr::Bool:
+ registers[instr->bool_value.reg].setbool(instr->bool_value.value);
+ break;
+
+ case Instr::String:
+ {
+ Register &output = registers[instr->string_value.reg];
+ new (output.getstringptr())
+ QString((QChar *)(data + instr->string_value.offset), instr->string_value.length);
+ output.settype(QMetaType::QString);
+ }
+ break;
+
+ case Instr::AddReal:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setNaN();
+ else output.setqreal(lhs.getqreal() + rhs.getqreal());
+ }
+ break;
+
+ case Instr::AddInt:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setNaN();
+ else output.setint(lhs.getint() + rhs.getint());
+ }
+ break;
+
+ case Instr::AddString:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() && rhs.isUndefined()) { output.setNaN(); }
+ else {
+ if (lhs.isUndefined())
+ new (output.getstringptr())
+ QString(QLatin1String("undefined") + *registers[instr->binaryop.src2].getstringptr());
+ else if (rhs.isUndefined())
+ new (output.getstringptr())
+ QString(*registers[instr->binaryop.src1].getstringptr() + QLatin1String("undefined"));
+ else
+ new (output.getstringptr())
+ QString(*registers[instr->binaryop.src1].getstringptr() +
+ *registers[instr->binaryop.src2].getstringptr());
+ output.settype(QMetaType::QString);
+ }
+ }
+ break;
+
+ case Instr::MinusReal:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setNaN();
+ else output.setqreal(lhs.getqreal() - rhs.getqreal());
+ }
+ break;
+
+ case Instr::MinusInt:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setNaN();
+ else output.setint(lhs.getint() - rhs.getint());
+ }
+ break;
+
+ case Instr::CompareReal:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setbool(lhs.isUndefined() == rhs.isUndefined());
+ else output.setbool(lhs.getqreal() == rhs.getqreal());
+ }
+ break;
+
+ case Instr::CompareString:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setbool(lhs.isUndefined() == rhs.isUndefined());
+ else output.setbool(*lhs.getstringptr() == *rhs.getstringptr());
+ }
+ break;
+
+ case Instr::NotCompareReal:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setbool(lhs.isUndefined() != rhs.isUndefined());
+ else output.setbool(lhs.getqreal() != rhs.getqreal());
+ }
+ break;
+
+ case Instr::NotCompareString:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setbool(lhs.isUndefined() != rhs.isUndefined());
+ else output.setbool(*lhs.getstringptr() != *rhs.getstringptr());
+ }
+ break;
+
+ case Instr::GreaterThanReal:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setbool(false);
+ else output.setbool(lhs.getqreal() > rhs.getqreal());
+ }
+ break;
+
+ case Instr::MaxReal:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setNaN();
+ else output.setqreal(qMax(lhs.getqreal(), rhs.getqreal()));
+ }
+ break;
+
+ case Instr::MinReal:
+ {
+ const Register &lhs = registers[instr->binaryop.src1];
+ const Register &rhs = registers[instr->binaryop.src2];
+ Register &output = registers[instr->binaryop.output];
+ if (lhs.isUndefined() || rhs.isUndefined()) output.setNaN();
+ else output.setqreal(qMin(lhs.getqreal(), rhs.getqreal()));
+ }
+ break;
+
+ case Instr::NewString:
+ {
+ Register &output = registers[instr->construct.reg];
+ new (output.getstringptr()) QString;
+ output.settype(QMetaType::QString);
+ }
+ break;
+
+ case Instr::NewUrl:
+ {
+ Register &output = registers[instr->construct.reg];
+ new (output.geturlptr()) QUrl;
+ output.settype(QMetaType::QUrl);
+ }
+ break;
+
+ case Instr::CleanupString:
+ registers[instr->cleanup.reg].getstringptr()->~QString();
+ break;
+
+ case Instr::CleanupUrl:
+ registers[instr->cleanup.reg].geturlptr()->~QUrl();
+ break;
+
+ case Instr::Fetch:
+ {
+ const Register &input = registers[instr->fetch.objectReg];
+ Register &output = registers[instr->fetch.output];
+
+ if (input.isUndefined()) {
+ throwException(instr->fetch.exceptionId, error, program, context);
+ return;
+ }
+
+ QObject *object = input.getQObject();
+ if (!object) {
+ output.setUndefined();
+ } else {
+ void *argv[] = { output.typeDataPtr(), 0 };
+ QMetaObject::metacall(object, QMetaObject::ReadProperty, instr->fetch.index, argv);
+ }
+ }
+ break;
+
+ case Instr::Store:
+ {
+ Register &data = registers[instr->store.reg];
+ if (data.isUndefined()) {
+ throwException(instr->store.exceptionId, error, program, context,
+ QLatin1String("Unable to assign undefined value"));
+ return;
+ }
+
+ int status = -1;
+ void *argv[] = { data.typeDataPtr(), 0, &status, &storeFlags };
+ QMetaObject::metacall(output, QMetaObject::WriteProperty,
+ instr->store.index, argv);
+ }
+ break;
+
+ case Instr::Copy:
+ registers[instr->copy.reg] = registers[instr->copy.src];
+ break;
+
+ case Instr::Skip:
+ if (instr->skip.reg == -1 || !registers[instr->skip.reg].getbool())
+ instr += instr->skip.count;
+ break;
+
+ case Instr::Done:
+ return;
+
+ case Instr::InitString:
+ if (!identifiers[instr->initstring.offset].identifier) {
+ quint32 len = *(quint32 *)(data + instr->initstring.dataIdx);
+ QChar *strdata = (QChar *)(data + instr->initstring.dataIdx + sizeof(quint32));
+
+ QString str = QString::fromRawData(strdata, len);
+
+ identifiers[instr->initstring.offset] = engine->objectClass->createPersistentIdentifier(str);
+ }
+ break;
+
+ case Instr::FindGenericTerminal:
+ case Instr::FindGeneric:
+ // We start the search in the parent context, as we know that the
+ // name is not present in the current context or it would have been
+ // found during the static compile
+ findgeneric(registers + instr->find.reg, instr->find.subscribeIndex,
+ QmlContextPrivate::get(context->parent),
+ identifiers[instr->find.name].identifier,
+ instr->common.type == Instr::FindGenericTerminal);
+ break;
+
+ case Instr::FindPropertyTerminal:
+ case Instr::FindProperty:
+ {
+ const Register &object = registers[instr->find.src];
+ if (object.isUndefined()) {
+ throwException(instr->find.exceptionId, error, program, context);
+ return;
+ }
+
+ findproperty(object.getQObject(), registers + instr->find.reg,
+ QmlEnginePrivate::get(context->engine),
+ instr->find.subscribeIndex, identifiers[instr->find.name].identifier,
+ instr->common.type == Instr::FindPropertyTerminal);
+ }
+ break;
+
+ case Instr::CleanupGeneric:
+ {
+ int type = registers[instr->cleanup.reg].gettype();
+ if (type == qMetaTypeId<QVariant>()) {
+ registers[instr->cleanup.reg].getvariantptr()->~QVariant();
+ } else if (type == QMetaType::QString) {
+ registers[instr->cleanup.reg].getstringptr()->~QString();
+ } else if (type == QMetaType::QUrl) {
+ registers[instr->cleanup.reg].geturlptr()->~QUrl();
+ }
+ }
+ break;
+
+ case Instr::ConvertGenericToReal:
+ {
+ Register &output = registers[instr->unaryop.output];
+ Register &input = registers[instr->unaryop.src];
+ bool ok = true;
+ output.setqreal(toReal(&input, input.gettype(), &ok));
+ if (!ok) output.setUndefined();
+ }
+ break;
+
+ case Instr::ConvertGenericToBool:
+ {
+ Register &output = registers[instr->unaryop.output];
+ Register &input = registers[instr->unaryop.src];
+ bool ok = true;
+ output.setbool(toBool(&input, input.gettype(), &ok));
+ if (!ok) output.setUndefined();
+ }
+ break;
+
+ case Instr::ConvertGenericToString:
+ {
+ Register &output = registers[instr->unaryop.output];
+ Register &input = registers[instr->unaryop.src];
+ bool ok = true;
+ QString str = toString(&input, input.gettype(), &ok);
+ if (ok) { new (output.getstringptr()) QString(str); output.settype(QMetaType::QString); }
+ else { output.setUndefined(); }
+ }
+ break;
+
+ case Instr::ConvertGenericToUrl:
+ {
+ Register &output = registers[instr->unaryop.output];
+ Register &input = registers[instr->unaryop.src];
+ bool ok = true;
+ QUrl url = toUrl(&input, input.gettype(), context, &ok);
+ if (ok) { new (output.geturlptr()) QUrl(url); output.settype(QMetaType::QUrl); }
+ else { output.setUndefined(); }
+ }
+ break;
+
+ default:
+ qFatal("EEK");
+ break;
+ }
+
+ instr++;
+ }
+}
+
+void QmlBindingCompiler::dump(const QByteArray &programData)
+{
+ const Program *program = (const Program *)programData.constData();
+
+ qWarning() << "Program.bindings:" << program->bindings;
+ qWarning() << "Program.dataLength:" << program->dataLength;
+ qWarning() << "Program.subscriptions:" << program->subscriptions;
+ qWarning() << "Program.indentifiers:" << program->identifiers;
+
+ int count = program->instructionCount;
+ const Instr *instr = program->instructions();
+
+ while (count--) {
+
+ switch (instr->common.type) {
+ case Instr::Noop:
+ qWarning().nospace() << "Noop";
+ break;
+ case Instr::Subscribe:
+ qWarning().nospace() << "Subscribe" << "\t\t" << instr->subscribe.offset << "\t" << instr->subscribe.reg << "\t" << instr->subscribe.index;
+ break;
+ case Instr::SubscribeId:
+ qWarning().nospace() << "SubscribeId" << "\t\t" << instr->subscribe.offset << "\t" << instr->subscribe.reg << "\t" << instr->subscribe.index;
+ break;
+ case Instr::LoadId:
+ qWarning().nospace() << "LoadId" << "\t\t\t" << instr->load.index << "\t" << instr->load.reg;
+ break;
+ case Instr::LoadScope:
+ qWarning().nospace() << "LoadScope" << "\t\t" << instr->load.index << "\t" << instr->load.reg;
+ break;
+ case Instr::LoadRoot:
+ qWarning().nospace() << "LoadRoot" << "\t\t" << instr->load.index << "\t" << instr->load.reg;
+ break;
+ case Instr::LoadAttached:
+ qWarning().nospace() << "LoadAttached" << "\t\t" << instr->attached.output << "\t" << instr->attached.reg << "\t" << instr->attached.index;
+ break;
+ case Instr::ConvertIntToReal:
+ qWarning().nospace() << "ConvertIntToReal" << "\t" << instr->unaryop.output << "\t" << instr->unaryop.src;
+ break;
+ case Instr::ConvertRealToInt:
+ qWarning().nospace() << "ConvertRealToInt" << "\t" << instr->unaryop.output << "\t" << instr->unaryop.src;
+ break;
+ case Instr::Real:
+ qWarning().nospace() << "Real" << "\t\t\t" << instr->real_value.reg << "\t" << instr->real_value.value;
+ break;
+ case Instr::Int:
+ qWarning().nospace() << "Int" << "\t\t\t" << instr->int_value.reg << "\t" << instr->int_value.value;
+ break;
+ case Instr::Bool:
+ qWarning().nospace() << "Bool" << "\t\t\t" << instr->bool_value.reg << "\t" << instr->bool_value.value;
+ break;
+ case Instr::String:
+ qWarning().nospace() << "String" << "\t\t\t" << instr->string_value.reg << "\t" << instr->string_value.offset << "\t" << instr->string_value.length;
+ break;
+ case Instr::AddReal:
+ qWarning().nospace() << "AddReal" << "\t\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::AddInt:
+ qWarning().nospace() << "AddInt" << "\t\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::AddString:
+ qWarning().nospace() << "AddString" << "\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::MinusReal:
+ qWarning().nospace() << "MinusReal" << "\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::MinusInt:
+ qWarning().nospace() << "MinusInt" << "\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::CompareReal:
+ qWarning().nospace() << "CompareReal" << "\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::CompareString:
+ qWarning().nospace() << "CompareString" << "\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::NotCompareReal:
+ qWarning().nospace() << "NotCompareReal" << "\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::NotCompareString:
+ qWarning().nospace() << "NotCompareString" << "\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::GreaterThanReal:
+ qWarning().nospace() << "GreaterThanReal" << "\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::MaxReal:
+ qWarning().nospace() << "MaxReal" << "\t\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::MinReal:
+ qWarning().nospace() << "MinReal" << "\t\t\t" << instr->binaryop.output << "\t" << instr->binaryop.src1 << "\t" << instr->binaryop.src2;
+ break;
+ case Instr::NewString:
+ qWarning().nospace() << "NewString" << "\t\t" << instr->construct.reg;
+ break;
+ case Instr::NewUrl:
+ qWarning().nospace() << "NewUrl" << "\t\t\t" << instr->construct.reg;
+ break;
+ case Instr::CleanupString:
+ qWarning().nospace() << "CleanupString" << "\t\t" << instr->cleanup.reg;
+ break;
+ case Instr::CleanupUrl:
+ qWarning().nospace() << "CleanupUrl" << "\t\t" << instr->cleanup.reg;
+ break;
+ case Instr::Fetch:
+ qWarning().nospace() << "Fetch" << "\t\t\t" << instr->fetch.output << "\t" << instr->fetch.index << "\t" << instr->fetch.objectReg;
+ break;
+ case Instr::Store:
+ qWarning().nospace() << "Store" << "\t\t\t" << instr->store.output << "\t" << instr->store.index << "\t" << instr->store.reg;
+ break;
+ case Instr::Copy:
+ qWarning().nospace() << "Copy" << "\t\t\t" << instr->copy.reg << "\t" << instr->copy.src;
+ break;
+ case Instr::Skip:
+ qWarning().nospace() << "Skip" << "\t\t\t" << instr->skip.reg << "\t" << instr->skip.count;
+ break;
+ case Instr::Done:
+ qWarning().nospace() << "Done";
+ break;
+ case Instr::InitString:
+ qWarning().nospace() << "InitString" << "\t\t" << instr->initstring.offset << "\t" << instr->initstring.dataIdx;
+ break;
+ case Instr::FindGeneric:
+ qWarning().nospace() << "FindGeneric" << "\t\t" << instr->find.reg << "\t" << instr->find.name;
+ break;
+ case Instr::FindGenericTerminal:
+ qWarning().nospace() << "FindGenericTerminal" << "\t" << instr->find.reg << "\t" << instr->find.name;
+ break;
+ case Instr::FindProperty:
+ qWarning().nospace() << "FindProperty" << "\t\t" << instr->find.reg << "\t" << instr->find.src << "\t" << instr->find.name;
+ break;
+ case Instr::FindPropertyTerminal:
+ qWarning().nospace() << "FindPropertyTerminal" << "\t" << instr->find.reg << "\t" << instr->find.src << "\t" << instr->find.name;
+ break;
+ case Instr::CleanupGeneric:
+ qWarning().nospace() << "CleanupGeneric" << "\t\t" << instr->cleanup.reg;
+ break;
+ case Instr::ConvertGenericToReal:
+ qWarning().nospace() << "ConvertGenericToReal" << "\t" << instr->unaryop.output << "\t" << instr->unaryop.src;
+ break;
+ case Instr::ConvertGenericToBool:
+ qWarning().nospace() << "ConvertGenericToBool" << "\t" << instr->unaryop.output << "\t" << instr->unaryop.src;
+ break;
+ case Instr::ConvertGenericToString:
+ qWarning().nospace() << "ConvertGenericToString" << "\t" << instr->unaryop.output << "\t" << instr->unaryop.src;
+ break;
+ case Instr::ConvertGenericToUrl:
+ qWarning().nospace() << "ConvertGenericToUrl" << "\t" << instr->unaryop.output << "\t" << instr->unaryop.src;
+ break;
+ default:
+ qWarning().nospace() << "Unknown";
+ break;
+ }
+
+ ++instr;
+ }
+}
+
+/*!
+Clear the state associated with attempting to compile a specific binding.
+This does not clear the global "commited binding" states.
+*/
+void QmlBindingCompilerPrivate::resetInstanceState()
+{
+ registers = 0;
+ registerCleanups.clear();
+ data = committed.data;
+ exceptions = committed.exceptions;
+ usedSubscriptionIds.clear();
+ subscriptionSet.clear();
+ subscriptionIds = committed.subscriptionIds;
+ registeredStrings = committed.registeredStrings;
+ bytecode.clear();
+}
+
+/*!
+Mark the last compile as successful, and add it to the "committed data"
+section.
+
+Returns the index for the committed binding.
+*/
+int QmlBindingCompilerPrivate::commitCompile()
+{
+ int rv = committed.count();
+ committed.offsets << committed.bytecode.count();
+ committed.dependencies << usedSubscriptionIds;
+ committed.bytecode << bytecode;
+ committed.data = data;
+ committed.exceptions = exceptions;
+ committed.subscriptionIds = subscriptionIds;
+ committed.registeredStrings = registeredStrings;
+ return rv;
+}
+
+bool QmlBindingCompilerPrivate::compile(QmlJS::AST::Node *node)
+{
+ resetInstanceState();
+
+ Result type;
+
+ if (!parseExpression(node, type))
+ return false;
+
+ if (subscriptionSet.count() > 0xFFFF ||
+ registeredStrings.count() > 0xFFFF)
+ return false;
+
+ if (type.unknownType) {
+ if (destination->type != QMetaType::QReal &&
+ destination->type != QVariant::String &&
+ destination->type != QMetaType::Bool &&
+ destination->type != QVariant::Url)
+ return false;
+
+ int convertReg = acquireReg();
+
+ if (destination->type == QMetaType::QReal) {
+ Instr convert;
+ convert.common.type = Instr::ConvertGenericToReal;
+ convert.unaryop.output = convertReg;
+ convert.unaryop.src = type.reg;
+ bytecode << convert;
+ } else if (destination->type == QVariant::String) {
+ Instr convert;
+ convert.common.type = Instr::ConvertGenericToString;
+ convert.unaryop.output = convertReg;
+ convert.unaryop.src = type.reg;
+ bytecode << convert;
+ } else if (destination->type == QMetaType::Bool) {
+ Instr convert;
+ convert.common.type = Instr::ConvertGenericToBool;
+ convert.unaryop.output = convertReg;
+ convert.unaryop.src = type.reg;
+ bytecode << convert;
+ } else if (destination->type == QVariant::Url) {
+ Instr convert;
+ convert.common.type = Instr::ConvertGenericToUrl;
+ convert.unaryop.output = convertReg;
+ convert.unaryop.src = type.reg;
+ bytecode << convert;
+ }
+
+ Instr cleanup;
+ cleanup.common.type = Instr::CleanupGeneric;
+ cleanup.cleanup.reg = type.reg;
+ bytecode << cleanup;
+
+ Instr instr;
+ instr.common.type = Instr::Store;
+ instr.store.output = 0;
+ instr.store.index = destination->index;
+ instr.store.reg = convertReg;
+ instr.store.exceptionId = exceptionId(node->expressionCast());
+ bytecode << instr;
+
+ if (destination->type == QVariant::String) {
+ Instr cleanup;
+ cleanup.common.type = Instr::CleanupString;
+ cleanup.cleanup.reg = convertReg;
+ bytecode << cleanup;
+ } else if (destination->type == QVariant::Url) {
+ Instr cleanup;
+ cleanup.common.type = Instr::CleanupUrl;
+ cleanup.cleanup.reg = convertReg;
+ bytecode << cleanup;
+ }
+
+ releaseReg(convertReg);
+
+ Instr done;
+ done.common.type = Instr::Done;
+ bytecode << done;
+
+ return true;
+ } else {
+ // Can we store the final value?
+ if (type.type == QVariant::Int &&
+ destination->type == QMetaType::QReal) {
+ Instr instr;
+ instr.common.type = Instr::ConvertIntToReal;
+ instr.unaryop.output = type.reg;
+ instr.unaryop.src = type.reg;
+ bytecode << instr;
+ type.type = QMetaType::QReal;
+ } else if (type.type == QMetaType::QReal &&
+ destination->type == QVariant::Int) {
+ Instr instr;
+ instr.common.type = Instr::ConvertRealToInt;
+ instr.unaryop.output = type.reg;
+ instr.unaryop.src = type.reg;
+ bytecode << instr;
+ type.type = QVariant::Int;
+ } else if (type.type == destination->type) {
+ } else {
+ const QMetaObject *from = type.metaObject;
+ const QMetaObject *to = engine->rawMetaObjectForType(destination->type);
+
+ if (QmlMetaPropertyPrivate::canConvert(from, to))
+ type.type = destination->type;
+ }
+
+ if (type.type == destination->type) {
+ Instr instr;
+ instr.common.type = Instr::Store;
+ instr.store.output = 0;
+ instr.store.index = destination->index;
+ instr.store.reg = type.reg;
+ instr.store.exceptionId = exceptionId(node->expressionCast());
+ bytecode << instr;
+
+ releaseReg(type.reg);
+
+ Instr done;
+ done.common.type = Instr::Done;
+ bytecode << done;
+
+ return true;
+ } else {
+ return false;
+ }
+ }
+}
+
+bool QmlBindingCompilerPrivate::parseExpression(QmlJS::AST::Node *node, Result &type)
+{
+ while (node->kind == AST::Node::Kind_NestedExpression)
+ node = static_cast<AST::NestedExpression *>(node)->expression;
+
+ if (tryArith(node)) {
+ if (!parseArith(node, type)) return false;
+ } else if (tryLogic(node)) {
+ if (!parseLogic(node, type)) return false;
+ } else if (tryConditional(node)) {
+ if (!parseConditional(node, type)) return false;
+ } else if (tryName(node)) {
+ if (!parseName(node, type)) return false;
+ } else if (tryConstant(node)) {
+ if (!parseConstant(node, type)) return false;
+ } else if (tryMethod(node)) {
+ if (!parseMethod(node, type)) return false;
+ } else {
+ return false;
+ }
+ return true;
+}
+
+bool QmlBindingCompilerPrivate::tryName(QmlJS::AST::Node *node)
+{
+ return node->kind == AST::Node::Kind_IdentifierExpression ||
+ node->kind == AST::Node::Kind_FieldMemberExpression;
+}
+
+bool QmlBindingCompilerPrivate::parseName(AST::Node *node, Result &type)
+{
+ QStringList nameParts;
+ QList<AST::ExpressionNode *> nameNodes;
+ if (!buildName(nameParts, node, &nameNodes))
+ return false;
+
+ int reg = acquireReg();
+ if (reg == -1)
+ return false;
+ type.reg = reg;
+
+ QmlParser::Object *absType = 0;
+
+ QStringList subscribeName;
+
+ bool wasAttachedObject = false;
+
+ for (int ii = 0; ii < nameParts.count(); ++ii) {
+ const QString &name = nameParts.at(ii);
+
+ // We don't handle signal properties or attached properties
+ if (name.length() > 2 && name.startsWith(QLatin1String("on")) &&
+ name.at(2).isUpper())
+ return false;
+
+ QmlType *attachType = 0;
+ if (name.at(0).isUpper()) {
+ // Could be an attached property
+ if (ii == nameParts.count() - 1)
+ return false;
+ if (nameParts.at(ii + 1).at(0).isUpper())
+ return false;
+
+ QmlEnginePrivate::ImportedNamespace *ns = 0;
+ if (!engine->resolveType(imports, name.toUtf8(), &attachType, 0, 0, 0, &ns))
+ return false;
+ if (ns || !attachType || !attachType->attachedPropertiesType())
+ return false;
+
+ wasAttachedObject = true;
+ }
+
+ if (ii == 0) {
+
+ if (attachType) {
+ Instr instr;
+ instr.common.type = Instr::LoadScope;
+ instr.load.index = 0;
+ instr.load.reg = reg;
+ bytecode << instr;
+
+ Instr attach;
+ attach.common.type = Instr::LoadAttached;
+ attach.attached.output = reg;
+ attach.attached.reg = reg;
+ attach.attached.index = attachType->index();
+ attach.attached.exceptionId = exceptionId(nameNodes.at(ii));
+ bytecode << attach;
+
+ subscribeName << contextName();
+ subscribeName << QLatin1String("$$$ATTACH_") + name;
+
+ absType = 0;
+ type.metaObject = attachType->attachedPropertiesType();
+
+ continue;
+ } else if (ids.contains(name)) {
+ QmlParser::Object *idObject = ids.value(name);
+ absType = idObject;
+ type.metaObject = absType->metaObject();
+
+ // We check if the id object is the root or
+ // scope object to avoid a subscription
+ if (idObject == component) {
+ Instr instr;
+ instr.common.type = Instr::LoadRoot;
+ instr.load.index = 0;
+ instr.load.reg = reg;
+ bytecode << instr;
+ } else if (idObject == context) {
+ Instr instr;
+ instr.common.type = Instr::LoadScope;
+ instr.load.index = 0;
+ instr.load.reg = reg;
+ bytecode << instr;
+ } else {
+ Instr instr;
+ instr.common.type = Instr::LoadId;
+ instr.load.index = idObject->idIndex;
+ instr.load.reg = reg;
+ bytecode << instr;
+
+ subscribeName << QLatin1String("$$$ID_") + name;
+
+ if (subscription(subscribeName, &type)) {
+ Instr sub;
+ sub.common.type = Instr::SubscribeId;
+ sub.subscribe.offset = subscriptionIndex(subscribeName);
+ sub.subscribe.reg = reg;
+ sub.subscribe.index = instr.load.index;
+ bytecode << sub;
+ }
+ }
+
+ } else {
+
+ QByteArray utf8Name = name.toUtf8();
+ const char *cname = utf8Name.constData();
+
+ int d0Idx = (context == component)?-1:context->metaObject()->indexOfProperty(cname);
+ int d1Idx = -1;
+ if (d0Idx == -1)
+ d1Idx = component->metaObject()->indexOfProperty(cname);
+
+ if (d0Idx != -1) {
+ Instr instr;
+ instr.common.type = Instr::LoadScope;
+ instr.load.index = 0;
+ instr.load.reg = reg;
+ bytecode << instr;
+
+ subscribeName << contextName();
+ subscribeName << name;
+
+ fetch(type, context->metaObject(), reg, d0Idx, subscribeName, nameNodes.at(ii));
+ } else if(d1Idx != -1) {
+ Instr instr;
+ instr.common.type = Instr::LoadRoot;
+ instr.load.index = 0;
+ instr.load.reg = reg;
+ bytecode << instr;
+
+ subscribeName << QLatin1String("$$$ROOT");
+ subscribeName << name;
+
+ fetch(type, component->metaObject(), reg, d1Idx, subscribeName, nameNodes.at(ii));
+ } else {
+ Instr find;
+ if (nameParts.count() == 1)
+ find.common.type = Instr::FindGenericTerminal;
+ else
+ find.common.type = Instr::FindGeneric;
+
+ find.find.reg = reg;
+ find.find.src = -1;
+ find.find.name = registerString(name);
+ find.find.exceptionId = exceptionId(nameNodes.at(ii));
+
+ subscribeName << QString(QLatin1String("$$$Generic_") + name);
+ if (subscription(subscribeName, &type))
+ find.find.subscribeIndex = subscriptionIndex(subscribeName);
+ else
+ find.find.subscribeIndex = -1;
+
+ bytecode << find;
+ type.unknownType = true;
+ }
+
+ if (!type.unknownType && type.type == -1)
+ return false; // Couldn't fetch that type
+ }
+
+ } else {
+
+ if (attachType) {
+ Instr attach;
+ attach.common.type = Instr::LoadAttached;
+ attach.attached.output = reg;
+ attach.attached.reg = reg;
+ attach.attached.index = attachType->index();
+ bytecode << attach;
+
+ absType = 0;
+ type.metaObject = attachType->attachedPropertiesType();
+
+ subscribeName << QLatin1String("$$$ATTACH_") + name;
+ continue;
+ }
+
+ const QMetaObject *mo = 0;
+ if (absType)
+ mo = absType->metaObject();
+ else if (type.metaObject)
+ mo = type.metaObject;
+
+ QByteArray utf8Name = name.toUtf8();
+ const char *cname = utf8Name.constData();
+ int idx = mo?mo->indexOfProperty(cname):-1;
+ if (absType && idx == -1)
+ return false;
+
+ subscribeName << name;
+
+ if (absType || (wasAttachedObject && idx != -1) || (mo && mo->property(idx).isFinal())) {
+ absType = 0;
+ fetch(type, mo, reg, idx, subscribeName, nameNodes.at(ii));
+ if (type.type == -1)
+ return false;
+ } else {
+
+ Instr prop;
+ if (ii == nameParts.count() -1 )
+ prop.common.type = Instr::FindPropertyTerminal;
+ else
+ prop.common.type = Instr::FindProperty;
+
+ prop.find.reg = reg;
+ prop.find.src = reg;
+ prop.find.name = registerString(name);
+ prop.find.exceptionId = exceptionId(nameNodes.at(ii));
+
+ if (subscription(subscribeName, &type))
+ prop.find.subscribeIndex = subscriptionIndex(subscribeName);
+ else
+ prop.find.subscribeIndex = -1;
+
+ type.unknownType = true;
+ type.metaObject = 0;
+ type.type = -1;
+ type.reg = reg;
+ bytecode << prop;
+ }
+ }
+
+ wasAttachedObject = false;
+ }
+
+ return true;
+}
+
+bool QmlBindingCompilerPrivate::tryArith(QmlJS::AST::Node *node)
+{
+ if (node->kind != AST::Node::Kind_BinaryExpression)
+ return false;
+
+ AST::BinaryExpression *expression = static_cast<AST::BinaryExpression *>(node);
+ if (expression->op == QSOperator::Add ||
+ expression->op == QSOperator::Sub)
+ return true;
+ else
+ return false;
+}
+
+bool QmlBindingCompilerPrivate::parseArith(QmlJS::AST::Node *node, Result &type)
+{
+ AST::BinaryExpression *expression = static_cast<AST::BinaryExpression *>(node);
+
+ type.reg = acquireReg();
+
+ Result lhs;
+ Result rhs;
+
+ if (!parseExpression(expression->left, lhs)) return false;
+ if (!parseExpression(expression->right, rhs)) return false;
+
+ if ((lhs.type == QVariant::Int || lhs.type == QMetaType::QReal) &&
+ (rhs.type == QVariant::Int || rhs.type == QMetaType::QReal))
+ return numberArith(type, lhs, rhs, (QSOperator::Op)expression->op);
+ else if(expression->op == QSOperator::Sub)
+ return numberArith(type, lhs, rhs, (QSOperator::Op)expression->op);
+ else if ((lhs.type == QMetaType::QString || lhs.unknownType) &&
+ (rhs.type == QMetaType::QString || rhs.unknownType) &&
+ (lhs.type == QMetaType::QString || rhs.type == QMetaType::QString))
+ return stringArith(type, lhs, rhs, (QSOperator::Op)expression->op);
+ else
+ return false;
+}
+
+bool QmlBindingCompilerPrivate::numberArith(Result &type, const Result &lhs, const Result &rhs, QSOperator::Op op)
+{
+ bool nativeReal = rhs.type == QMetaType::QReal ||
+ lhs.type == QMetaType::QReal ||
+ lhs.unknownType ||
+ rhs.unknownType;
+
+ if (nativeReal && lhs.type == QMetaType::Int) {
+ Instr convert;
+ convert.common.type = Instr::ConvertIntToReal;
+ convert.unaryop.output = lhs.reg;
+ convert.unaryop.src = lhs.reg;
+ bytecode << convert;
+ }
+
+ if (nativeReal && rhs.type == QMetaType::Int) {
+ Instr convert;
+ convert.common.type = Instr::ConvertIntToReal;
+ convert.unaryop.output = rhs.reg;
+ convert.unaryop.src = rhs.reg;
+ bytecode << convert;
+ }
+
+ int lhsTmp = -1;
+ int rhsTmp = -1;
+ if (lhs.unknownType) {
+ lhsTmp = acquireReg();
+
+ Instr conv;
+ conv.common.type = Instr::ConvertGenericToReal;
+ conv.unaryop.output = lhsTmp;
+ conv.unaryop.src = lhs.reg;
+ bytecode << conv;
+ }
+
+ if (rhs.unknownType) {
+ rhsTmp = acquireReg();
+
+ Instr conv;
+ conv.common.type = Instr::ConvertGenericToReal;
+ conv.unaryop.output = rhsTmp;
+ conv.unaryop.src = rhs.reg;
+ bytecode << conv;
+ }
+
+ Instr arith;
+ if (op == QSOperator::Add) {
+ arith.common.type = nativeReal?Instr::AddReal:Instr::AddInt;
+ } else if (op == QSOperator::Sub) {
+ arith.common.type = nativeReal?Instr::MinusReal:Instr::MinusInt;
+ } else {
+ qFatal("Unsupported arithmetic operator");
+ }
+
+ arith.binaryop.output = type.reg;
+ arith.binaryop.src1 = (lhsTmp == -1)?lhs.reg:lhsTmp;
+ arith.binaryop.src2 = (rhsTmp == -1)?rhs.reg:rhsTmp;
+ bytecode << arith;
+
+ type.metaObject = 0;
+ type.type = nativeReal?QMetaType::QReal:QMetaType::Int;
+ type.subscriptionSet.unite(lhs.subscriptionSet);
+ type.subscriptionSet.unite(rhs.subscriptionSet);
+
+ if (lhsTmp != -1) releaseReg(lhsTmp);
+ if (rhsTmp != -1) releaseReg(rhsTmp);
+ releaseReg(lhs.reg);
+ releaseReg(rhs.reg);
+
+ return true;
+}
+
+bool QmlBindingCompilerPrivate::stringArith(Result &type, const Result &lhs, const Result &rhs, QSOperator::Op op)
+{
+ if (op != QSOperator::Add)
+ return false;
+
+ int lhsTmp = -1;
+ int rhsTmp = -1;
+
+ if (lhs.unknownType) {
+ lhsTmp = acquireReg(Instr::CleanupString);
+
+ Instr convert;
+ convert.common.type = Instr::ConvertGenericToString;
+ convert.unaryop.output = lhsTmp;
+ convert.unaryop.src = lhs.reg;
+ bytecode << convert;
+ }
+
+ if (rhs.unknownType) {
+ rhsTmp = acquireReg(Instr::CleanupString);
+
+ Instr convert;
+ convert.common.type = Instr::ConvertGenericToString;
+ convert.unaryop.output = rhsTmp;
+ convert.unaryop.src = rhs.reg;
+ bytecode << convert;
+ }
+
+ type.reg = acquireReg(Instr::CleanupString);
+ type.type = QMetaType::QString;
+
+ Instr add;
+ add.common.type = Instr::AddString;
+ add.binaryop.output = type.reg;
+ add.binaryop.src1 = (lhsTmp == -1)?lhs.reg:lhsTmp;
+ add.binaryop.src2 = (rhsTmp == -1)?rhs.reg:rhsTmp;
+ bytecode << add;
+
+ if (lhsTmp != -1) releaseReg(lhsTmp);
+ if (rhsTmp != -1) releaseReg(rhsTmp);
+
+ return true;
+}
+
+bool QmlBindingCompilerPrivate::tryLogic(QmlJS::AST::Node *node)
+{
+ if (node->kind != AST::Node::Kind_BinaryExpression)
+ return false;
+
+ AST::BinaryExpression *expression = static_cast<AST::BinaryExpression *>(node);
+ if (expression->op == QSOperator::Gt ||
+ expression->op == QSOperator::Equal ||
+ expression->op == QSOperator::NotEqual)
+ return true;
+ else
+ return false;
+}
+
+bool QmlBindingCompilerPrivate::parseLogic(QmlJS::AST::Node *node, Result &type)
+{
+ AST::BinaryExpression *expression = static_cast<AST::BinaryExpression *>(node);
+
+ Result lhs;
+ Result rhs;
+
+ if (!parseExpression(expression->left, lhs)) return false;
+ if (!parseExpression(expression->right, rhs)) return false;
+
+ type.reg = acquireReg();
+ type.metaObject = 0;
+ type.type = QVariant::Bool;
+
+ if (lhs.type == QMetaType::QReal && rhs.type == QMetaType::QReal) {
+
+ Instr op;
+ if (expression->op == QSOperator::Gt)
+ op.common.type = Instr::GreaterThanReal;
+ else if (expression->op == QSOperator::Equal)
+ op.common.type = Instr::CompareReal;
+ else if (expression->op == QSOperator::NotEqual)
+ op.common.type = Instr::NotCompareReal;
+ else
+ return false;
+ op.binaryop.output = type.reg;
+ op.binaryop.src1 = lhs.reg;
+ op.binaryop.src2 = rhs.reg;
+ bytecode << op;
+
+
+ } else if (lhs.type == QMetaType::QString && rhs.type == QMetaType::QString) {
+
+ Instr op;
+ if (expression->op == QSOperator::Equal)
+ op.common.type = Instr::CompareString;
+ else if (expression->op == QSOperator::NotEqual)
+ op.common.type = Instr::NotCompareString;
+ else
+ return false;
+ op.binaryop.output = type.reg;
+ op.binaryop.src1 = lhs.reg;
+ op.binaryop.src2 = rhs.reg;
+ bytecode << op;
+
+ } else {
+ return false;
+ }
+
+ releaseReg(lhs.reg);
+ releaseReg(rhs.reg);
+
+ return true;
+}
+
+bool QmlBindingCompilerPrivate::tryConditional(QmlJS::AST::Node *node)
+{
+ return (node->kind == AST::Node::Kind_ConditionalExpression);
+}
+
+bool QmlBindingCompilerPrivate::parseConditional(QmlJS::AST::Node *node, Result &type)
+{
+ AST::ConditionalExpression *expression = static_cast<AST::ConditionalExpression *>(node);
+
+ AST::Node *test = expression->expression;
+ if (test->kind == AST::Node::Kind_NestedExpression)
+ test = static_cast<AST::NestedExpression*>(test)->expression;
+
+ Result etype;
+ if (!parseExpression(test, etype)) return false;
+
+ if (etype.type != QVariant::Bool)
+ return false;
+
+ Instr skip;
+ skip.common.type = Instr::Skip;
+ skip.skip.reg = etype.reg;
+ skip.skip.count = 0;
+ int skipIdx = bytecode.count();
+ bytecode << skip;
+
+ // Release to allow reuse of reg
+ releaseReg(etype.reg);
+
+ QSet<QString> preSubSet = subscriptionSet;
+
+ // int preConditionalSubscriptions = subscriptionSet.count();
+
+ Result ok;
+ if (!parseExpression(expression->ok, ok)) return false;
+ if (ok.unknownType) return false;
+
+ int skipIdx2 = bytecode.count();
+ skip.skip.reg = -1;
+ bytecode << skip;
+
+ // Release to allow reuse of reg
+ releaseReg(ok.reg);
+ bytecode[skipIdx].skip.count = bytecode.count() - skipIdx - 1;
+
+ subscriptionSet = preSubSet;
+
+ Result ko;
+ if (!parseExpression(expression->ko, ko)) return false;
+ if (ko.unknownType) return false;
+
+ // Release to allow reuse of reg
+ releaseReg(ko.reg);
+ bytecode[skipIdx2].skip.count = bytecode.count() - skipIdx2 - 1;
+
+ if (ok != ko)
+ return false; // Must be same type and in same register
+
+ subscriptionSet = preSubSet;
+
+ if (!subscriptionNeutral(subscriptionSet, ok.subscriptionSet, ko.subscriptionSet))
+ return false; // Conditionals cannot introduce new subscriptions
+
+ type = ok;
+
+ return true;
+}
+
+bool QmlBindingCompilerPrivate::tryConstant(QmlJS::AST::Node *node)
+{
+ return node->kind == AST::Node::Kind_TrueLiteral ||
+ node->kind == AST::Node::Kind_FalseLiteral ||
+ node->kind == AST::Node::Kind_NumericLiteral ||
+ node->kind == AST::Node::Kind_StringLiteral;
+}
+
+bool QmlBindingCompilerPrivate::parseConstant(QmlJS::AST::Node *node, Result &type)
+{
+ type.metaObject = 0;
+ type.type = -1;
+ type.reg = acquireReg();
+
+ if (node->kind == AST::Node::Kind_TrueLiteral) {
+ type.type = QVariant::Bool;
+ Instr instr;
+ instr.common.type = Instr::Bool;
+ instr.bool_value.reg = type.reg;
+ instr.bool_value.value = true;
+ bytecode << instr;
+ return true;
+ } else if (node->kind == AST::Node::Kind_FalseLiteral) {
+ type.type = QVariant::Bool;
+ Instr instr;
+ instr.common.type = Instr::Bool;
+ instr.bool_value.reg = type.reg;
+ instr.bool_value.value = false;
+ bytecode << instr;
+ return true;
+ } else if (node->kind == AST::Node::Kind_NumericLiteral) {
+ qreal value = qreal(static_cast<AST::NumericLiteral *>(node)->value);
+
+ if (qreal(float(value)) != value)
+ return false;
+
+ type.type = QMetaType::QReal;
+ Instr instr;
+ instr.common.type = Instr::Real;
+ instr.real_value.reg = type.reg;
+ instr.real_value.value = float(value);
+ bytecode << instr;
+ return true;
+ } else if (node->kind == AST::Node::Kind_StringLiteral) {
+ QString str = static_cast<AST::StringLiteral *>(node)->value->asString();
+ type.type = QMetaType::QString;
+ type.reg = registerLiteralString(str);
+ return true;
+ } else {
+ return false;
+ }
+}
+
+bool QmlBindingCompilerPrivate::tryMethod(QmlJS::AST::Node *node)
+{
+ return node->kind == AST::Node::Kind_CallExpression;
+}
+
+bool QmlBindingCompilerPrivate::parseMethod(QmlJS::AST::Node *node, Result &result)
+{
+ AST::CallExpression *expr = static_cast<AST::CallExpression *>(node);
+
+ QStringList name;
+ if (!buildName(name, expr->base))
+ return false;
+
+ if (name.count() != 2 || name.at(0) != QLatin1String("Math"))
+ return false;
+
+ QString method = name.at(1);
+
+ AST::ArgumentList *args = expr->arguments;
+ if (!args) return false;
+ AST::ExpressionNode *arg0 = args->expression;
+ args = args->next;
+ if (!args) return false;
+ AST::ExpressionNode *arg1 = args->expression;
+ if (args->next != 0) return false;
+ if (!arg0 || !arg1) return false;
+
+ Result r0;
+ if (!parseExpression(arg0, r0)) return false;
+ Result r1;
+ if (!parseExpression(arg1, r1)) return false;
+
+ if (r0.type != QMetaType::QReal || r1.type != QMetaType::QReal)
+ return false;
+
+ Instr op;
+ if (method == QLatin1String("max")) {
+ op.common.type = Instr::MaxReal;
+ } else if (method == QLatin1String("min")) {
+ op.common.type = Instr::MinReal;
+ } else {
+ return false;
+ }
+ // We release early to reuse registers
+ releaseReg(r0.reg);
+ releaseReg(r1.reg);
+
+ op.binaryop.output = acquireReg();
+ op.binaryop.src1 = r0.reg;
+ op.binaryop.src2 = r1.reg;
+ bytecode << op;
+
+ result.type = QMetaType::QReal;
+ result.reg = op.binaryop.output;
+
+ return true;
+}
+
+bool QmlBindingCompilerPrivate::buildName(QStringList &name,
+ QmlJS::AST::Node *node,
+ QList<QmlJS::AST::ExpressionNode *> *nodes)
+{
+ if (node->kind == AST::Node::Kind_IdentifierExpression) {
+ name << static_cast<AST::IdentifierExpression*>(node)->name->asString();
+ if (nodes) *nodes << static_cast<AST::IdentifierExpression*>(node);
+ } else if (node->kind == AST::Node::Kind_FieldMemberExpression) {
+ AST::FieldMemberExpression *expr =
+ static_cast<AST::FieldMemberExpression *>(node);
+
+ if (!buildName(name, expr->base, nodes))
+ return false;
+
+ name << expr->name->asString();
+ if (nodes) *nodes << expr;
+ } else {
+ return false;
+ }
+
+ return true;
+}
+
+
+bool QmlBindingCompilerPrivate::fetch(Result &rv, const QMetaObject *mo, int reg,
+ int idx, const QStringList &subName, QmlJS::AST::ExpressionNode *node)
+{
+ QMetaProperty prop = mo->property(idx);
+ rv.metaObject = 0;
+ rv.type = 0;
+
+ if (subscription(subName, &rv) && prop.hasNotifySignal() && prop.notifySignalIndex() != -1) {
+ Instr sub;
+ sub.common.type = Instr::Subscribe;
+ sub.subscribe.offset = subscriptionIndex(subName);
+ sub.subscribe.reg = reg;
+ sub.subscribe.index = prop.notifySignalIndex();
+ bytecode << sub;
+ }
+
+ Instr fetch;
+ fetch.common.type = Instr::Fetch;
+ fetch.fetch.objectReg = reg;
+ fetch.fetch.index = idx;
+ fetch.fetch.output = reg;
+ fetch.fetch.exceptionId = exceptionId(node);
+
+ rv.type = prop.userType();
+ rv.metaObject = engine->metaObjectForType(rv.type);
+ rv.reg = reg;
+
+ if (rv.type == QMetaType::QString) {
+ int tmp = acquireReg();
+ Instr copy;
+ copy.common.type = Instr::Copy;
+ copy.copy.reg = tmp;
+ copy.copy.src = reg;
+ bytecode << copy;
+ releaseReg(tmp);
+ fetch.fetch.objectReg = tmp;
+
+ Instr setup;
+ setup.common.type = Instr::NewString;
+ setup.construct.reg = reg;
+ bytecode << setup;
+ registerCleanup(reg, Instr::CleanupString);
+ }
+
+ bytecode << fetch;
+
+ if (!rv.metaObject &&
+ rv.type != QMetaType::QReal &&
+ rv.type != QMetaType::Int &&
+ rv.type != QMetaType::Bool &&
+ rv.type != qMetaTypeId<QmlGraphicsAnchorLine>() &&
+ rv.type != QMetaType::QString) {
+ rv.metaObject = 0;
+ rv.type = 0;
+ return false; // Unsupported type (string not supported yet);
+ }
+
+ return true;
+}
+
+void QmlBindingCompilerPrivate::registerCleanup(int reg, int cleanup, int cleanupType)
+{
+ registerCleanups.insert(reg, qMakePair(cleanup, cleanupType));
+}
+
+int QmlBindingCompilerPrivate::acquireReg(int cleanup, int cleanupType)
+{
+ for (int ii = 0; ii < 32; ++ii) {
+ if (!(registers & (1 << ii))) {
+ registers |= (1 << ii);
+
+ if (cleanup != Instr::Noop)
+ registerCleanup(ii, cleanup, cleanupType);
+
+ return ii;
+ }
+ }
+ return -1;
+}
+
+void QmlBindingCompilerPrivate::releaseReg(int reg)
+{
+ Q_ASSERT(reg >= 0 && reg <= 31);
+
+ if (registerCleanups.contains(reg)) {
+ QPair<int, int> c = registerCleanups[reg];
+ registerCleanups.remove(reg);
+ Instr cleanup;
+ cleanup.common.type = (quint8)c.first;
+ cleanup.cleanup.reg = reg;
+ bytecode << cleanup;
+ }
+
+ quint32 mask = 1 << reg;
+ registers &= ~mask;
+}
+
+// Returns a reg
+int QmlBindingCompilerPrivate::registerLiteralString(const QString &str)
+{
+ QByteArray strdata((const char *)str.constData(), str.length() * sizeof(QChar));
+ int offset = data.count();
+ data += strdata;
+
+ int reg = acquireReg(Instr::CleanupString);
+
+ Instr string;
+ string.common.type = Instr::String;
+ string.string_value.reg = reg;
+ string.string_value.offset = offset;
+ string.string_value.length = str.length();
+ bytecode << string;
+
+ return reg;
+}
+
+// Returns an identifier offset
+int QmlBindingCompilerPrivate::registerString(const QString &string)
+{
+ Q_ASSERT(!string.isEmpty());
+
+ QHash<QString, QPair<int, int> >::ConstIterator iter = registeredStrings.find(string);
+
+ if (iter == registeredStrings.end()) {
+ quint32 len = string.length();
+ QByteArray lendata((const char *)&len, sizeof(quint32));
+ QByteArray strdata((const char *)string.constData(), string.length() * sizeof(QChar));
+ strdata.prepend(lendata);
+ int rv = data.count();
+ data += strdata;
+
+ iter = registeredStrings.insert(string, qMakePair(registeredStrings.count(), rv));
+ }
+
+ Instr reg;
+ reg.common.type = Instr::InitString;
+ reg.initstring.offset = iter->first;
+ reg.initstring.dataIdx = iter->second;
+ bytecode << reg;
+ return reg.initstring.offset;
+}
+
+bool QmlBindingCompilerPrivate::subscription(const QStringList &sub, Result *result)
+{
+ QString str = sub.join(QLatin1String("."));
+ result->subscriptionSet.insert(str);
+
+ if (subscriptionSet.contains(str)) {
+ return false;
+ } else {
+ subscriptionSet.insert(str);
+ return true;
+ }
+}
+
+int QmlBindingCompilerPrivate::subscriptionIndex(const QStringList &sub)
+{
+ QString str = sub.join(QLatin1String("."));
+ QHash<QString, int>::ConstIterator iter = subscriptionIds.find(str);
+ if (iter == subscriptionIds.end())
+ iter = subscriptionIds.insert(str, subscriptionIds.count());
+ usedSubscriptionIds.insert(*iter);
+ return *iter;
+}
+
+/*
+ Returns true if lhs contains no subscriptions that aren't also in base or rhs AND
+ rhs contains no subscriptions that aren't also in base or lhs.
+*/
+bool QmlBindingCompilerPrivate::subscriptionNeutral(const QSet<QString> &base,
+ const QSet<QString> &lhs,
+ const QSet<QString> &rhs)
+{
+ QSet<QString> difflhs = lhs;
+ difflhs.subtract(rhs);
+ QSet<QString> diffrhs = rhs;
+ diffrhs.subtract(lhs);
+
+ difflhs.unite(diffrhs);
+ difflhs.subtract(base);
+
+ return difflhs.isEmpty();
+}
+
+quint8 QmlBindingCompilerPrivate::exceptionId(QmlJS::AST::ExpressionNode *n)
+{
+ quint8 rv = 0xFF;
+ if (n && exceptions.count() < 0xFF) {
+ rv = (quint8)exceptions.count();
+ QmlJS::AST::SourceLocation l = n->firstSourceLocation();
+ quint64 e = l.startLine;
+ e <<= 32;
+ e |= l.startColumn;
+ exceptions.append(e);
+ }
+ return rv;
+}
+
+QmlBindingCompiler::QmlBindingCompiler()
+: d(new QmlBindingCompilerPrivate)
+{
+}
+
+QmlBindingCompiler::~QmlBindingCompiler()
+{
+ delete d; d = 0;
+}
+
+/*
+Returns true if any bindings were compiled.
+*/
+bool QmlBindingCompiler::isValid() const
+{
+ return !d->committed.bytecode.isEmpty();
+}
+
+/*
+-1 on failure, otherwise the binding index to use.
+*/
+int QmlBindingCompiler::compile(const Expression &expression, QmlEnginePrivate *engine)
+{
+ if (!expression.expression.asAST()) return false;
+
+ d->context = expression.context;
+ d->component = expression.component;
+ d->destination = expression.property;
+ d->ids = expression.ids;
+ d->imports = expression.imports;
+ d->engine = engine;
+
+ if (d->compile(expression.expression.asAST())) {
+ return d->commitCompile();
+ } else {
+ return -1;
+ }
+}
+
+
+QByteArray QmlBindingCompilerPrivate::buildSignalTable() const
+{
+ QHash<int, QList<int> > table;
+
+ for (int ii = 0; ii < committed.count(); ++ii) {
+ const QSet<int> &deps = committed.dependencies.at(ii);
+ for (QSet<int>::ConstIterator iter = deps.begin(); iter != deps.end(); ++iter)
+ table[*iter].append(ii);
+ }
+
+ QVector<quint32> header;
+ QVector<quint32> data;
+ for (int ii = 0; ii < committed.subscriptionIds.count(); ++ii) {
+ header.append(committed.subscriptionIds.count() + data.count());
+ const QList<int> &bindings = table[ii];
+ data.append(bindings.count());
+ for (int jj = 0; jj < bindings.count(); ++jj)
+ data.append(bindings.at(jj));
+ }
+ header << data;
+
+ return QByteArray((const char *)header.constData(), header.count() * sizeof(quint32));
+}
+
+QByteArray QmlBindingCompilerPrivate::buildExceptionData() const
+{
+ QByteArray rv;
+ rv.resize(committed.exceptions.count() * sizeof(quint64));
+ ::memcpy(rv.data(), committed.exceptions.constData(), rv.size());
+ return rv;
+}
+
+/*
+Returns the compiled program.
+*/
+QByteArray QmlBindingCompiler::program() const
+{
+ QByteArray programData;
+
+ if (isValid()) {
+ Program prog;
+ prog.bindings = d->committed.count();
+
+ QVector<Instr> bytecode;
+ Instr skip;
+ skip.common.type = Instr::Skip;
+ skip.skip.reg = -1;
+ for (int ii = 0; ii < d->committed.count(); ++ii) {
+ skip.skip.count = d->committed.count() - ii - 1;
+ skip.skip.count+= d->committed.offsets.at(ii);
+ bytecode << skip;
+ }
+ bytecode << d->committed.bytecode;
+
+ QByteArray data = d->committed.data;
+ while (data.count() % 4) data.append('\0');
+ prog.signalTableOffset = data.count();
+ data += d->buildSignalTable();
+ while (data.count() % 4) data.append('\0');
+ prog.exceptionDataOffset = data.count();
+ data += d->buildExceptionData();
+
+ prog.dataLength = 4 * ((data.size() + 3) / 4);
+ prog.subscriptions = d->committed.subscriptionIds.count();
+ prog.identifiers = d->committed.registeredStrings.count();
+ prog.instructionCount = bytecode.count();
+ int size = sizeof(Program) + bytecode.count() * sizeof(Instr);
+ size += prog.dataLength;
+
+ programData.resize(size);
+ memcpy(programData.data(), &prog, sizeof(Program));
+ if (prog.dataLength)
+ memcpy((char *)((Program *)programData.data())->data(), data.constData(),
+ data.size());
+ memcpy((char *)((Program *)programData.data())->instructions(), bytecode.constData(),
+ bytecode.count() * sizeof(Instr));
+ }
+
+ return programData;
+}
+
+
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlcompiledbindings_p.h b/src/declarative/qml/qmlcompiledbindings_p.h
new file mode 100644
index 0000000..1d8fac4
--- /dev/null
+++ b/src/declarative/qml/qmlcompiledbindings_p.h
@@ -0,0 +1,116 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLBINDINGOPTIMIZATIONS_P_H
+#define QMLBINDINGOPTIMIZATIONS_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 "qmlexpression_p.h"
+#include "qmlbinding.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+class QmlBindingCompilerPrivate;
+class QmlBindingCompiler
+{
+public:
+ QmlBindingCompiler();
+ ~QmlBindingCompiler();
+
+ // Returns true if bindings were compiled
+ bool isValid() const;
+
+ struct Expression
+ {
+ QmlParser::Object *component;
+ QmlParser::Object *context;
+ QmlParser::Property *property;
+ QmlParser::Variant expression;
+ QHash<QString, QmlParser::Object *> ids;
+ QmlEnginePrivate::Imports imports;
+ };
+
+ // -1 on failure, otherwise the binding index to use
+ int compile(const Expression &, QmlEnginePrivate *);
+
+ // Returns the compiled program
+ QByteArray program() const;
+
+ static void dump(const QByteArray &);
+private:
+ QmlBindingCompilerPrivate *d;
+};
+
+class QmlCompiledBindingsPrivate;
+class QmlCompiledBindings : public QObject, public QmlAbstractExpression, public QmlRefCount
+{
+public:
+ QmlCompiledBindings(const char *program, QmlContext *context);
+ virtual ~QmlCompiledBindings();
+
+ QmlAbstractBinding *configBinding(int index, QObject *target, QObject *scope, int property);
+
+protected:
+ int qt_metacall(QMetaObject::Call, int, void **);
+
+private:
+ Q_DISABLE_COPY(QmlCompiledBindings);
+ Q_DECLARE_PRIVATE(QmlCompiledBindings);
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLBINDINGOPTIMIZATIONS_P_H
+
diff --git a/src/declarative/qml/qmlcompileddata.cpp b/src/declarative/qml/qmlcompileddata.cpp
new file mode 100644
index 0000000..48a0893
--- /dev/null
+++ b/src/declarative/qml/qmlcompileddata.cpp
@@ -0,0 +1,239 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlcompiler_p.h"
+#include "qmlengine.h"
+#include "qmlcomponent.h"
+#include "qmlcomponent_p.h"
+#include "qmlcontext.h"
+#include "qmlcontext_p.h"
+
+#include <QtCore/qdebug.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+int QmlCompiledData::pack(const char *data, size_t size)
+{
+ const char *p = packData.constData();
+ unsigned int ps = packData.size();
+
+ for (unsigned int ii = 0; (ii + size) <= ps; ii += sizeof(int)) {
+ if (0 == ::memcmp(p + ii, data, size))
+ return ii;
+ }
+
+ int rv = packData.size();
+ packData.append(data, size);
+ return rv;
+}
+
+int QmlCompiledData::indexForString(const QString &data)
+{
+ int idx = primitives.indexOf(data);
+ if (idx == -1) {
+ idx = primitives.count();
+ primitives << data;
+ }
+ return idx;
+}
+
+int QmlCompiledData::indexForByteArray(const QByteArray &data)
+{
+ int idx = datas.indexOf(data);
+ if (idx == -1) {
+ idx = datas.count();
+ datas << data;
+ }
+ return idx;
+}
+
+int QmlCompiledData::indexForUrl(const QUrl &data)
+{
+ int idx = urls.indexOf(data);
+ if (idx == -1) {
+ idx = urls.count();
+ urls << data;
+ }
+ return idx;
+}
+
+int QmlCompiledData::indexForFloat(float *data, int count)
+{
+ Q_ASSERT(count > 0);
+
+ for (int ii = 0; ii <= floatData.count() - count; ++ii) {
+ bool found = true;
+ for (int jj = 0; jj < count; ++jj) {
+ if (floatData.at(ii + jj) != data[jj]) {
+ found = false;
+ break;
+ }
+ }
+
+ if (found)
+ return ii;
+ }
+
+ int idx = floatData.count();
+ for (int ii = 0; ii < count; ++ii)
+ floatData << data[ii];
+
+ return idx;
+}
+
+int QmlCompiledData::indexForInt(int *data, int count)
+{
+ Q_ASSERT(count > 0);
+
+ for (int ii = 0; ii <= intData.count() - count; ++ii) {
+ bool found = true;
+ for (int jj = 0; jj < count; ++jj) {
+ if (intData.at(ii + jj) != data[jj]) {
+ found = false;
+ break;
+ }
+ }
+
+ if (found)
+ return ii;
+ }
+
+ int idx = intData.count();
+ for (int ii = 0; ii < count; ++ii)
+ intData << data[ii];
+
+ return idx;
+}
+
+int QmlCompiledData::indexForLocation(const QmlParser::Location &l)
+{
+ // ### FIXME
+ int rv = locations.count();
+ locations << l;
+ return rv;
+}
+
+int QmlCompiledData::indexForLocation(const QmlParser::LocationSpan &l)
+{
+ // ### FIXME
+ int rv = locations.count();
+ locations << l.start << l.end;
+ return rv;
+}
+
+QmlCompiledData::QmlCompiledData(QmlEngine *engine)
+: QmlCleanup(engine), importCache(0), root(0), rootPropertyCache(0)
+{
+}
+
+QmlCompiledData::~QmlCompiledData()
+{
+ for (int ii = 0; ii < types.count(); ++ii) {
+ if (types.at(ii).ref)
+ types.at(ii).ref->release();
+ }
+
+ for (int ii = 0; ii < propertyCaches.count(); ++ii)
+ propertyCaches.at(ii)->release();
+
+ for (int ii = 0; ii < contextCaches.count(); ++ii)
+ contextCaches.at(ii)->release();
+
+ if (importCache)
+ importCache->release();
+
+ if (rootPropertyCache)
+ rootPropertyCache->release();
+
+ qDeleteAll(cachedPrograms);
+ qDeleteAll(cachedClosures);
+}
+
+void QmlCompiledData::clear()
+{
+ qDeleteAll(cachedPrograms);
+ qDeleteAll(cachedClosures);
+ for (int ii = 0; ii < cachedClosures.count(); ++ii)
+ cachedClosures[ii] = 0;
+ for (int ii = 0; ii < cachedPrograms.count(); ++ii)
+ cachedPrograms[ii] = 0;
+}
+
+
+QObject *QmlCompiledData::TypeReference::createInstance(QmlContext *ctxt, const QBitField &bindings) const
+{
+ if (type) {
+ QObject *rv = type->create();
+ if (rv)
+ QmlEngine::setContextForObject(rv, ctxt);
+ return rv;
+ } else {
+ Q_ASSERT(component);
+ return QmlComponentPrivate::get(component)->create(ctxt, bindings);
+ }
+}
+
+const QMetaObject *QmlCompiledData::TypeReference::metaObject() const
+{
+ if (type) {
+ return type->metaObject();
+ } else {
+ Q_ASSERT(component);
+ return static_cast<QmlComponentPrivate *>(QObjectPrivate::get(component))->cc->root;
+ }
+}
+
+void QmlCompiledData::dumpInstructions()
+{
+ if (!name.isEmpty())
+ qWarning() << name;
+ qWarning().nospace() << "Index\tLine\tOperation\t\tData1\tData2\tData3\tComments";
+ qWarning().nospace() << "-------------------------------------------------------------------------------";
+ for (int ii = 0; ii < bytecode.count(); ++ii) {
+ dump(&bytecode[ii], ii);
+ }
+ qWarning().nospace() << "-------------------------------------------------------------------------------";
+}
+
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp
new file mode 100644
index 0000000..10150de
--- /dev/null
+++ b/src/declarative/qml/qmlcompiler.cpp
@@ -0,0 +1,2815 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlcompiler_p.h"
+
+#include "qmlcompositetypedata_p.h"
+#include "qmlparser_p.h"
+#include "qmlscriptparser_p.h"
+#include "qmlpropertyvaluesource.h"
+#include "qmlcomponent.h"
+#include "qmetaobjectbuilder_p.h"
+#include "qmlstringconverters_p.h"
+#include "qmlengine_p.h"
+#include "qmlengine.h"
+#include "qmlcontext.h"
+#include "qmlmetatype.h"
+#include "qmlcustomparser_p_p.h"
+#include "qmlcontext_p.h"
+#include "qmlcomponent_p.h"
+#include "parser/qmljsast_p.h"
+#include "qmlvmemetaobject_p.h"
+#include "qmlexpression_p.h"
+#include "qmlmetaproperty_p.h"
+#include "qmlrewrite_p.h"
+#include "qmlscriptstring.h"
+#include "qmlglobal_p.h"
+#include "qmlscriptparser_p.h"
+#include "qmlbinding.h"
+#include "qmlcompiledbindings_p.h"
+
+#include <qfxperf_p_p.h>
+
+#include <QCoreApplication>
+#include <QColor>
+#include <QDebug>
+#include <QPointF>
+#include <QSizeF>
+#include <QRectF>
+#include <QAtomicInt>
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+DEFINE_BOOL_CONFIG_OPTION(compilerDump, QML_COMPILER_DUMP);
+DEFINE_BOOL_CONFIG_OPTION(compilerStatDump, QML_COMPILER_STATISTICS_DUMP);
+DEFINE_BOOL_CONFIG_OPTION(qmlExperimental, QML_EXPERIMENTAL);
+
+using namespace QmlParser;
+
+/*!
+ Instantiate a new QmlCompiler.
+*/
+QmlCompiler::QmlCompiler()
+: output(0), engine(0), unitRoot(0), unit(0)
+{
+}
+
+/*!
+ Returns true if the last call to compile() caused errors.
+
+ \sa errors()
+*/
+bool QmlCompiler::isError() const
+{
+ return !exceptions.isEmpty();
+}
+
+/*!
+ Return the list of errors from the last call to compile(), or an empty list
+ if there were no errors.
+*/
+QList<QmlError> QmlCompiler::errors() const
+{
+ return exceptions;
+}
+
+/*!
+ Returns true if \a val is a legal object id, false otherwise.
+
+ Legal ids must start with a lower-case letter or underscore, and contain only
+ letters, numbers and underscores.
+*/
+bool QmlCompiler::isValidId(const QString &val)
+{
+ if (val.isEmpty())
+ return false;
+
+ // TODO this will be enforced and return false
+ if (val.at(0).isLetter() && !val.at(0).isLower()) {
+ //return false;
+ qWarning().nospace() << "id '" << val << "' is invalid: ids cannot start with uppercase letters. This will be enforced in an upcoming version of QML.";
+ }
+
+ QChar u(QLatin1Char('_'));
+ for (int ii = 0; ii < val.count(); ++ii)
+ if (val.at(ii) != u &&
+ ((ii == 0 && !val.at(ii).isLetter()) ||
+ (ii != 0 && !val.at(ii).isLetterOrNumber())) )
+ return false;
+
+ return true;
+}
+
+/*!
+ Returns true if \a name refers to an attached property, false otherwise.
+
+ Attached property names are those that start with a capital letter.
+*/
+bool QmlCompiler::isAttachedPropertyName(const QByteArray &name)
+{
+ return !name.isEmpty() && name.at(0) >= 'A' && name.at(0) <= 'Z';
+}
+
+/*!
+ Returns true if \a name refers to a signal property, false otherwise.
+
+ Signal property names are those that start with "on", followed by a capital
+ letter.
+*/
+bool QmlCompiler::isSignalPropertyName(const QByteArray &name)
+{
+ return name.length() >= 3 && name.startsWith("on") &&
+ 'A' <= name.at(2) && 'Z' >= name.at(2);
+}
+
+/*!
+ \macro COMPILE_EXCEPTION
+ \internal
+ Inserts an error into the QmlCompiler error list, and returns false
+ (failure).
+
+ \a token is used to source the error line and column, and \a desc is the
+ error itself. \a desc can be an expression that can be piped into QDebug.
+
+ For example:
+
+ \code
+ COMPILE_EXCEPTION(property, QCoreApplication::translate("QmlCompiler","Error for property \"%1\"").arg(QString::fromUtf8(property->name)));
+ \endcode
+*/
+#define COMPILE_EXCEPTION(token, desc) \
+ { \
+ QString exceptionDescription; \
+ QmlError error; \
+ error.setUrl(output->url); \
+ error.setLine((token)->location.start.line); \
+ error.setColumn((token)->location.start.column); \
+ error.setDescription(desc.trimmed()); \
+ exceptions << error; \
+ return false; \
+ }
+
+/*!
+ \macro COMPILE_CHECK
+ \internal
+ Returns false if \a is false, otherwise does nothing.
+*/
+#define COMPILE_CHECK(a) \
+ { \
+ if (!a) return false; \
+ }
+
+/*!
+ Returns true if literal \a v can be assigned to property \a prop, otherwise
+ false.
+
+ This test corresponds to action taken by genLiteralAssignment(). Any change
+ made here, must have a corresponding action in genLiteralAssigment().
+*/
+bool QmlCompiler::testLiteralAssignment(const QMetaProperty &prop,
+ QmlParser::Value *v)
+{
+ QString string = v->value.asScript();
+
+ if (!prop.isWritable())
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: \"%1\" is a read-only property").arg(QString::fromUtf8(prop.name())));
+
+ if (prop.isEnumType()) {
+ int value;
+ if (prop.isFlagType()) {
+ value = prop.enumerator().keysToValue(string.toUtf8().constData());
+ } else
+ value = prop.enumerator().keyToValue(string.toUtf8().constData());
+ if (value == -1)
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: unknown enumeration"));
+ return true;
+ }
+ int type = prop.userType();
+ switch(type) {
+ case -1:
+ break;
+ case QVariant::String:
+ if (!v->value.isString()) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: string expected"));
+ break;
+ case QVariant::Url:
+ if (!v->value.isString()) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: url expected"));
+ break;
+ case QVariant::UInt:
+ {
+ bool ok;
+ string.toUInt(&ok);
+ if (!v->value.isNumber() || !ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: unsigned int expected"));
+ }
+ break;
+ case QVariant::Int:
+ {
+ bool ok;
+ string.toInt(&ok);
+ if (!v->value.isNumber() || !ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: int expected"));
+ }
+ break;
+ case QMetaType::Float:
+ {
+ bool ok;
+ string.toFloat(&ok);
+ if (!v->value.isNumber() || !ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: float expected"));
+ }
+ break;
+ case QVariant::Double:
+ {
+ bool ok;
+ string.toDouble(&ok);
+ if (!v->value.isNumber() || !ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: double expected"));
+ }
+ break;
+ case QVariant::Color:
+ {
+ bool ok;
+ QmlStringConverters::colorFromString(string, &ok);
+ if (!ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: color expected"));
+ }
+ break;
+ case QVariant::Date:
+ {
+ bool ok;
+ QmlStringConverters::dateFromString(string, &ok);
+ if (!ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: date expected"));
+ }
+ break;
+ case QVariant::Time:
+ {
+ bool ok;
+ QmlStringConverters::timeFromString(string, &ok);
+ if (!ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: time expected"));
+ }
+ break;
+ case QVariant::DateTime:
+ {
+ bool ok;
+ QmlStringConverters::dateTimeFromString(string, &ok);
+ if (!ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: datetime expected"));
+ }
+ break;
+ case QVariant::Point:
+ case QVariant::PointF:
+ {
+ bool ok;
+ QPointF point = QmlStringConverters::pointFFromString(string, &ok);
+ if (!ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: point expected"));
+ }
+ break;
+ case QVariant::Size:
+ case QVariant::SizeF:
+ {
+ bool ok;
+ QSizeF size = QmlStringConverters::sizeFFromString(string, &ok);
+ if (!ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: size expected"));
+ }
+ break;
+ case QVariant::Rect:
+ case QVariant::RectF:
+ {
+ bool ok;
+ QRectF rect = QmlStringConverters::rectFFromString(string, &ok);
+ if (!ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: rect expected"));
+ }
+ break;
+ case QVariant::Bool:
+ {
+ if (!v->value.isBoolean()) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: boolean expected"));
+ }
+ break;
+ case QVariant::Vector3D:
+ {
+ bool ok;
+ QmlStringConverters::vector3DFromString(string, &ok);
+ if (!ok) COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: 3D vector expected"));
+ }
+ break;
+ default:
+ {
+ int t = prop.userType();
+ QmlMetaType::StringConverter converter =
+ QmlMetaType::customStringConverter(t);
+ if (!converter)
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: unsupported type \"%1\"").arg(QString::fromLatin1(QVariant::typeToName(prop.type()))));
+ }
+ break;
+ }
+ return true;
+}
+
+/*!
+ Generate a store instruction for assigning literal \a v to property \a prop.
+
+ Any literal assignment that is approved in testLiteralAssignment() must have
+ a corresponding action in this method.
+*/
+void QmlCompiler::genLiteralAssignment(const QMetaProperty &prop,
+ QmlParser::Value *v)
+{
+ QString string = v->value.asScript();
+
+ QmlInstruction instr;
+ instr.line = v->location.start.line;
+ if (prop.isEnumType()) {
+ int value;
+ if (prop.isFlagType()) {
+ value = prop.enumerator().keysToValue(string.toUtf8().constData());
+ } else
+ value = prop.enumerator().keyToValue(string.toUtf8().constData());
+
+ instr.type = QmlInstruction::StoreInteger;
+ instr.storeInteger.propertyIndex = prop.propertyIndex();
+ instr.storeInteger.value = value;
+ output->bytecode << instr;
+ return;
+ }
+
+ int type = prop.userType();
+ switch(type) {
+ case -1:
+ {
+ instr.type = QmlInstruction::StoreVariant;
+ instr.storeString.propertyIndex = prop.propertyIndex();
+ instr.storeString.value = output->indexForString(string);
+ }
+ break;
+ case QVariant::String:
+ {
+ instr.type = QmlInstruction::StoreString;
+ instr.storeString.propertyIndex = prop.propertyIndex();
+ instr.storeString.value = output->indexForString(string);
+ }
+ break;
+ case QVariant::Url:
+ {
+ instr.type = QmlInstruction::StoreUrl;
+ QUrl u = string.isEmpty() ? QUrl() : output->url.resolved(QUrl(string));
+ instr.storeUrl.propertyIndex = prop.propertyIndex();
+ instr.storeUrl.value = output->indexForUrl(u);
+ }
+ break;
+ case QVariant::UInt:
+ {
+ instr.type = QmlInstruction::StoreInteger;
+ instr.storeInteger.propertyIndex = prop.propertyIndex();
+ instr.storeInteger.value = string.toUInt();
+ }
+ break;
+ case QVariant::Int:
+ {
+ instr.type = QmlInstruction::StoreInteger;
+ instr.storeInteger.propertyIndex = prop.propertyIndex();
+ instr.storeInteger.value = string.toInt();
+ }
+ break;
+ case QMetaType::Float:
+ {
+ instr.type = QmlInstruction::StoreFloat;
+ instr.storeFloat.propertyIndex = prop.propertyIndex();
+ instr.storeFloat.value = string.toFloat();
+ }
+ break;
+ case QVariant::Double:
+ {
+ instr.type = QmlInstruction::StoreDouble;
+ instr.storeDouble.propertyIndex = prop.propertyIndex();
+ instr.storeDouble.value = string.toDouble();
+ }
+ break;
+ case QVariant::Color:
+ {
+ QColor c = QmlStringConverters::colorFromString(string);
+ instr.type = QmlInstruction::StoreColor;
+ instr.storeColor.propertyIndex = prop.propertyIndex();
+ instr.storeColor.value = c.rgba();
+ }
+ break;
+ case QVariant::Date:
+ {
+ QDate d = QmlStringConverters::dateFromString(string);
+ instr.type = QmlInstruction::StoreDate;
+ instr.storeDate.propertyIndex = prop.propertyIndex();
+ instr.storeDate.value = d.toJulianDay();
+ }
+ break;
+ case QVariant::Time:
+ {
+ QTime time = QmlStringConverters::timeFromString(string);
+ int data[] = { time.hour(), time.minute(),
+ time.second(), time.msec() };
+ int index = output->indexForInt(data, 4);
+ instr.type = QmlInstruction::StoreTime;
+ instr.storeTime.propertyIndex = prop.propertyIndex();
+ instr.storeTime.valueIndex = index;
+ }
+ break;
+ case QVariant::DateTime:
+ {
+ QDateTime dateTime = QmlStringConverters::dateTimeFromString(string);
+ int data[] = { dateTime.date().toJulianDay(),
+ dateTime.time().hour(),
+ dateTime.time().minute(),
+ dateTime.time().second(),
+ dateTime.time().msec() };
+ int index = output->indexForInt(data, 5);
+ instr.type = QmlInstruction::StoreDateTime;
+ instr.storeDateTime.propertyIndex = prop.propertyIndex();
+ instr.storeDateTime.valueIndex = index;
+ }
+ break;
+ case QVariant::Point:
+ case QVariant::PointF:
+ {
+ bool ok;
+ QPointF point =
+ QmlStringConverters::pointFFromString(string, &ok);
+ float data[] = { point.x(), point.y() };
+ int index = output->indexForFloat(data, 2);
+ if (type == QVariant::PointF)
+ instr.type = QmlInstruction::StorePointF;
+ else
+ instr.type = QmlInstruction::StorePoint;
+ instr.storeRealPair.propertyIndex = prop.propertyIndex();
+ instr.storeRealPair.valueIndex = index;
+ }
+ break;
+ case QVariant::Size:
+ case QVariant::SizeF:
+ {
+ bool ok;
+ QSizeF size = QmlStringConverters::sizeFFromString(string, &ok);
+ float data[] = { size.width(), size.height() };
+ int index = output->indexForFloat(data, 2);
+ if (type == QVariant::SizeF)
+ instr.type = QmlInstruction::StoreSizeF;
+ else
+ instr.type = QmlInstruction::StoreSize;
+ instr.storeRealPair.propertyIndex = prop.propertyIndex();
+ instr.storeRealPair.valueIndex = index;
+ }
+ break;
+ case QVariant::Rect:
+ case QVariant::RectF:
+ {
+ bool ok;
+ QRectF rect = QmlStringConverters::rectFFromString(string, &ok);
+ float data[] = { rect.x(), rect.y(),
+ rect.width(), rect.height() };
+ int index = output->indexForFloat(data, 4);
+ if (type == QVariant::RectF)
+ instr.type = QmlInstruction::StoreRectF;
+ else
+ instr.type = QmlInstruction::StoreRect;
+ instr.storeRect.propertyIndex = prop.propertyIndex();
+ instr.storeRect.valueIndex = index;
+ }
+ break;
+ case QVariant::Bool:
+ {
+ bool b = v->value.asBoolean();
+ instr.type = QmlInstruction::StoreBool;
+ instr.storeBool.propertyIndex = prop.propertyIndex();
+ instr.storeBool.value = b;
+ }
+ break;
+ case QVariant::Vector3D:
+ {
+ bool ok;
+ QVector3D vector =
+ QmlStringConverters::vector3DFromString(string, &ok);
+ float data[] = { vector.x(), vector.y(), vector.z() };
+ int index = output->indexForFloat(data, 3);
+ instr.type = QmlInstruction::StoreVector3D;
+ instr.storeRealPair.propertyIndex = prop.propertyIndex();
+ instr.storeRealPair.valueIndex = index;
+ }
+ break;
+ default:
+ {
+ int t = prop.userType();
+ int index = output->customTypeData.count();
+ instr.type = QmlInstruction::AssignCustomType;
+ instr.assignCustomType.propertyIndex = prop.propertyIndex();
+ instr.assignCustomType.valueIndex = index;
+
+ QmlCompiledData::CustomTypeData data;
+ data.index = output->indexForString(string);
+ data.type = t;
+ output->customTypeData << data;
+ }
+ break;
+ }
+ output->bytecode << instr;
+}
+
+/*!
+ Resets data by clearing the lists that the QmlCompiler modifies.
+*/
+void QmlCompiler::reset(QmlCompiledData *data)
+{
+ data->types.clear();
+ data->primitives.clear();
+ data->floatData.clear();
+ data->intData.clear();
+ data->customTypeData.clear();
+ data->datas.clear();
+ data->bytecode.clear();
+}
+
+/*!
+ Compile \a unit, and store the output in \a out. \a engine is the QmlEngine
+ with which the QmlCompiledData will be associated.
+
+ Returns true on success, false on failure. On failure, the compile errors
+ are available from errors().
+
+ If the environment variant QML_COMPILER_DUMP is set
+ (eg. QML_COMPILER_DUMP=1) the compiled instructions will be dumped to stderr
+ on a successful compiler.
+*/
+bool QmlCompiler::compile(QmlEngine *engine,
+ QmlCompositeTypeData *unit,
+ QmlCompiledData *out)
+{
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::Compilation> pc;
+#endif
+ exceptions.clear();
+
+ Q_ASSERT(out);
+ reset(out);
+
+ output = out;
+
+ // Compile types
+ for (int ii = 0; ii < unit->types.count(); ++ii) {
+ QmlCompositeTypeData::TypeReference &tref = unit->types[ii];
+ QmlCompiledData::TypeReference ref;
+ QmlScriptParser::TypeReference *parserRef = unit->data.referencedTypes().at(ii);
+ if (tref.type)
+ ref.type = tref.type;
+ else if (tref.unit) {
+ ref.component = tref.unit->toComponent(engine);
+
+ if (ref.component->isError()) {
+ QmlError error;
+ error.setUrl(output->url);
+ error.setDescription(QLatin1String("Unable to create type ") +
+ parserRef->name);
+ if (!parserRef->refObjects.isEmpty()) {
+ QmlParser::Object *parserObject = parserRef->refObjects.first();
+ error.setLine(parserObject->location.start.line);
+ error.setColumn(parserObject->location.start.column);
+ }
+
+ exceptions << error;
+ exceptions << ref.component->errors();
+ reset(out);
+ return false;
+ }
+ ref.ref = tref.unit;
+ ref.ref->addref();
+ }
+ ref.className = parserRef->name.toUtf8();
+ out->types << ref;
+ }
+
+ Object *root = unit->data.tree();
+ Q_ASSERT(root);
+
+ this->engine = engine;
+ this->unit = unit;
+ this->unitRoot = root;
+ compileTree(root);
+
+ if (!isError()) {
+ if (compilerDump())
+ out->dumpInstructions();
+ if (compilerStatDump())
+ dumpStats();
+ } else {
+ reset(out);
+ }
+
+ compileState = ComponentCompileState();
+ savedCompileStates.clear();
+ output = 0;
+ this->engine = 0;
+ this->unit = 0;
+ this->unitRoot = 0;
+
+ return !isError();
+}
+
+void QmlCompiler::compileTree(Object *tree)
+{
+ compileState.root = tree;
+
+ if (!buildObject(tree, BindingContext()) || !completeComponentBuild())
+ return;
+
+ QmlInstruction init;
+ init.type = QmlInstruction::Init;
+ init.line = 0;
+ init.init.bindingsSize = compileState.bindings.count();
+ init.init.parserStatusSize = compileState.parserStatusCount;
+ init.init.contextCache = genContextCache();
+ if (compileState.compiledBindingData.isEmpty())
+ init.init.compiledBinding = -1;
+ else
+ init.init.compiledBinding = output->indexForByteArray(compileState.compiledBindingData);
+ output->bytecode << init;
+
+ genObject(tree);
+
+ QmlInstruction def;
+ init.line = 0;
+ def.type = QmlInstruction::SetDefault;
+ output->bytecode << def;
+
+ output->imports = unit->imports;
+ output->importCache = output->imports.cache(engine);
+
+ Q_ASSERT(tree->metatype);
+
+ if (tree->metadata.isEmpty()) {
+ output->root = tree->metatype;
+ } else {
+ static_cast<QMetaObject &>(output->rootData) = *tree->metaObject();
+ output->root = &output->rootData;
+ }
+ if (!tree->metadata.isEmpty())
+ QmlEnginePrivate::get(engine)->registerCompositeType(output);
+}
+
+static bool ValuePtrLessThan(const Value *t1, const Value *t2)
+{
+ return t1->location.start.line < t2->location.start.line ||
+ (t1->location.start.line == t2->location.start.line &&
+ t1->location.start.column < t2->location.start.column);
+}
+
+bool QmlCompiler::buildObject(Object *obj, const BindingContext &ctxt)
+{
+ componentStat.objects++;
+
+ Q_ASSERT (obj->type != -1);
+ const QmlCompiledData::TypeReference &tr =
+ output->types.at(obj->type);
+ obj->metatype = tr.metaObject();
+
+ if (tr.component)
+ obj->url = tr.component->url();
+ if (tr.type)
+ obj->typeName = tr.type->qmlTypeName();
+ obj->className = tr.className;
+
+ // This object is a "Component" element
+ if (tr.type && obj->metatype == &QmlComponent::staticMetaObject) {
+ COMPILE_CHECK(buildComponent(obj, ctxt));
+ return true;
+ }
+
+ // Build any script blocks for this type
+ for (int ii = 0; ii < obj->scriptBlockObjects.count(); ++ii)
+ COMPILE_CHECK(buildScript(obj, obj->scriptBlockObjects.at(ii)));
+
+ // Object instantiations reset the binding context
+ BindingContext objCtxt(obj);
+
+ // Create the synthesized meta object, ignoring aliases
+ COMPILE_CHECK(mergeDynamicMetaProperties(obj));
+ COMPILE_CHECK(buildDynamicMeta(obj, IgnoreAliases));
+
+ // Find the native type and check for the QmlParserStatus interface
+ QmlType *type = toQmlType(obj);
+ Q_ASSERT(type);
+ obj->parserStatusCast = type->parserStatusCast();
+ if (obj->parserStatusCast != -1)
+ compileState.parserStatusCount++;
+
+ // Check if this is a custom parser type. Custom parser types allow
+ // assignments to non-existant properties. These assignments are then
+ // compiled by the type.
+ bool isCustomParser = output->types.at(obj->type).type &&
+ output->types.at(obj->type).type->customParser() != 0;
+ QList<QmlCustomParserProperty> customProps;
+
+ // Fetch the list of deferred properties
+ QStringList deferredList = deferredProperties(obj);
+
+ // Must do id property first. This is to ensure that the id given to any
+ // id reference created matches the order in which the objects are
+ // instantiated
+ foreach(Property *prop, obj->properties) {
+ if (prop->name == "id") {
+ COMPILE_CHECK(buildProperty(prop, obj, objCtxt));
+ break;
+ }
+ }
+
+ // Merge
+ Property *defaultProperty = 0;
+ Property *skipProperty = 0;
+ if (obj->defaultProperty) {
+ const QMetaObject *metaObject = obj->metaObject();
+ Q_ASSERT(metaObject);
+ QMetaProperty p = QmlMetaType::defaultProperty(metaObject);
+ if (p.name()) {
+ Property *explicitProperty = obj->getProperty(p.name(), false);
+ if (explicitProperty && !explicitProperty->value) {
+ skipProperty = explicitProperty;
+
+ defaultProperty = new Property;
+ defaultProperty->parent = obj;
+ defaultProperty->isDefault = true;
+ defaultProperty->location = obj->defaultProperty->location;
+ defaultProperty->listValueRange = obj->defaultProperty->listValueRange;
+ defaultProperty->listCommaPositions = obj->defaultProperty->listCommaPositions;
+
+ defaultProperty->values = obj->defaultProperty->values;
+ defaultProperty->values += explicitProperty->values;
+ foreach(Value *value, defaultProperty->values)
+ value->addref();
+ qSort(defaultProperty->values.begin(), defaultProperty->values.end(), ValuePtrLessThan);
+
+ } else {
+ defaultProperty = obj->defaultProperty;
+ defaultProperty->addref();
+ }
+ } else {
+ defaultProperty = obj->defaultProperty;
+ defaultProperty->addref();
+ }
+ }
+
+ // Build all explicit properties specified
+ foreach(Property *prop, obj->properties) {
+
+ if (prop == skipProperty)
+ continue;
+ if (prop->name == "id")
+ continue;
+
+ bool canDefer = false;
+ if (isCustomParser) {
+ if (doesPropertyExist(prop, obj)) {
+ int ids = compileState.ids.count();
+ COMPILE_CHECK(buildProperty(prop, obj, objCtxt));
+ canDefer = ids == compileState.ids.count();
+ } else {
+ customProps << QmlCustomParserNodePrivate::fromProperty(prop);
+ }
+ } else {
+ if (isSignalPropertyName(prop->name)) {
+ COMPILE_CHECK(buildSignal(prop,obj,objCtxt));
+ } else {
+ int ids = compileState.ids.count();
+ COMPILE_CHECK(buildProperty(prop, obj, objCtxt));
+ canDefer = ids == compileState.ids.count();
+ }
+ }
+
+ if (canDefer && !deferredList.isEmpty() &&
+ deferredList.contains(QString::fromUtf8(prop->name)))
+ prop->isDeferred = true;
+
+ }
+
+ // Build the default property
+ if (defaultProperty) {
+ Property *prop = defaultProperty;
+
+ bool canDefer = false;
+ if (isCustomParser) {
+ if (doesPropertyExist(prop, obj)) {
+ int ids = compileState.ids.count();
+ COMPILE_CHECK(buildProperty(prop, obj, objCtxt));
+ canDefer = ids == compileState.ids.count();
+ } else {
+ customProps << QmlCustomParserNodePrivate::fromProperty(prop);
+ }
+ } else {
+ int ids = compileState.ids.count();
+ COMPILE_CHECK(buildProperty(prop, obj, objCtxt));
+ canDefer = ids == compileState.ids.count();
+ }
+
+ if (canDefer && !deferredList.isEmpty() &&
+ deferredList.contains(QString::fromUtf8(prop->name)))
+ prop->isDeferred = true;
+ }
+
+ if (defaultProperty)
+ defaultProperty->release();
+
+ // Compile custom parser parts
+ if (isCustomParser && !customProps.isEmpty()) {
+ QmlCustomParser *cp = output->types.at(obj->type).type->customParser();
+ cp->clearErrors();
+ obj->custom = cp->compile(customProps);
+ foreach (QmlError err, cp->errors()) {
+ err.setUrl(output->url);
+ exceptions << err;
+ }
+ }
+
+ return true;
+}
+
+void QmlCompiler::genObject(QmlParser::Object *obj)
+{
+ const QmlCompiledData::TypeReference &tr =
+ output->types.at(obj->type);
+ if (tr.type && obj->metatype == &QmlComponent::staticMetaObject) {
+ genComponent(obj);
+ return;
+ }
+
+ // Create the object
+ QmlInstruction create;
+ create.type = QmlInstruction::CreateObject;
+ create.line = obj->location.start.line;
+ create.create.column = obj->location.start.column;
+ create.create.data = -1;
+ if (!obj->custom.isEmpty())
+ create.create.data = output->indexForByteArray(obj->custom);
+ create.create.type = obj->type;
+ if (!output->types.at(create.create.type).type &&
+ !obj->bindingBitmask.isEmpty()) {
+ Q_ASSERT(obj->bindingBitmask.size() % 4 == 0);
+ create.create.bindingBits =
+ output->indexForByteArray(obj->bindingBitmask);
+ } else {
+ create.create.bindingBits = -1;
+ }
+ output->bytecode << create;
+
+ // Setup the synthesized meta object if necessary
+ if (!obj->metadata.isEmpty()) {
+ QmlInstruction meta;
+ meta.type = QmlInstruction::StoreMetaObject;
+ meta.line = 0;
+ meta.storeMeta.data = output->indexForByteArray(obj->metadata);
+ meta.storeMeta.aliasData = output->indexForByteArray(obj->synthdata);
+ meta.storeMeta.propertyCache = output->propertyCaches.count();
+ // ### Surely the creation of this property cache could be more efficient
+ QmlPropertyCache *propertyCache = 0;
+ if (tr.component && QmlComponentPrivate::get(tr.component)->cc->rootPropertyCache) {
+ propertyCache = QmlComponentPrivate::get(tr.component)->cc->rootPropertyCache->copy();
+ } else {
+ propertyCache = QmlPropertyCache::create(engine, obj->metaObject()->superClass());
+ }
+ propertyCache->append(engine, obj->metaObject(), QmlPropertyCache::Data::NoFlags,
+ QmlPropertyCache::Data::IsVMEFunction);
+ if (obj == unitRoot) {
+ propertyCache->addref();
+ output->rootPropertyCache = propertyCache;
+ }
+ output->propertyCaches << propertyCache;
+ output->bytecode << meta;
+ }
+
+ // Set the object id
+ if (!obj->id.isEmpty()) {
+ QmlInstruction id;
+ id.type = QmlInstruction::SetId;
+ id.line = 0;
+ id.setId.value = output->indexForString(obj->id);
+ id.setId.index = obj->idIndex;
+ output->bytecode << id;
+ }
+
+ // Set any script blocks
+ for (int ii = 0; ii < obj->scripts.count(); ++ii) {
+ QmlInstruction script;
+ script.type = QmlInstruction::StoreScript;
+ script.line = 0; // ###
+ int idx = output->scripts.count();
+ output->scripts << obj->scripts.at(ii);
+ script.storeScript.value = idx;
+ output->bytecode << script;
+ }
+
+ // Begin the class
+ if (obj->parserStatusCast != -1) {
+ QmlInstruction begin;
+ begin.type = QmlInstruction::BeginObject;
+ begin.begin.castValue = obj->parserStatusCast;
+ begin.line = obj->location.start.line;
+ output->bytecode << begin;
+ }
+
+ genObjectBody(obj);
+}
+
+void QmlCompiler::genObjectBody(QmlParser::Object *obj)
+{
+ typedef QPair<Property *, int> PropPair;
+ foreach(const PropPair &prop, obj->scriptStringProperties) {
+ QmlInstruction ss;
+ ss.type = QmlInstruction::StoreScriptString;
+ ss.storeScriptString.propertyIndex = prop.first->index;
+ ss.storeScriptString.value =
+ output->indexForString(prop.first->values.at(0)->value.asScript());
+ ss.storeScriptString.scope = prop.second;
+ output->bytecode << ss;
+ }
+
+ bool seenDefer = false;
+ foreach(Property *prop, obj->valueProperties) {
+ if (prop->isDeferred) {
+ seenDefer = true;
+ continue;
+ }
+ genValueProperty(prop, obj);
+ }
+ if (seenDefer) {
+ QmlInstruction defer;
+ defer.type = QmlInstruction::Defer;
+ defer.line = 0;
+ defer.defer.deferCount = 0;
+ int deferIdx = output->bytecode.count();
+ output->bytecode << defer;
+
+ QmlInstruction init;
+ init.type = QmlInstruction::Init;
+ init.init.bindingsSize = compileState.bindings.count(); // XXX - bigger than necessary
+ init.init.parserStatusSize = compileState.parserStatusCount; // XXX - bigger than necessary
+ init.init.contextCache = -1;
+ init.init.compiledBinding = -1;
+ output->bytecode << init;
+
+ foreach(Property *prop, obj->valueProperties) {
+ if (!prop->isDeferred)
+ continue;
+ genValueProperty(prop, obj);
+ }
+
+ output->bytecode[deferIdx].defer.deferCount =
+ output->bytecode.count() - deferIdx - 1;
+ }
+
+ foreach(Property *prop, obj->signalProperties) {
+
+ QmlParser::Value *v = prop->values.at(0);
+
+ if (v->type == Value::SignalObject) {
+
+ genObject(v->object);
+
+ QmlInstruction assign;
+ assign.type = QmlInstruction::AssignSignalObject;
+ assign.line = v->location.start.line;
+ assign.assignSignalObject.signal =
+ output->indexForByteArray(prop->name);
+ output->bytecode << assign;
+
+ } else if (v->type == Value::SignalExpression) {
+
+ QmlInstruction store;
+ store.type = QmlInstruction::StoreSignal;
+ store.line = v->location.start.line;
+ store.storeSignal.signalIndex = prop->index;
+ store.storeSignal.value =
+ output->indexForString(v->value.asScript().trimmed());
+ output->bytecode << store;
+
+ }
+
+ }
+
+ foreach(Property *prop, obj->attachedProperties) {
+ QmlInstruction fetch;
+ fetch.type = QmlInstruction::FetchAttached;
+ fetch.line = prop->location.start.line;
+ fetch.fetchAttached.id = prop->index;
+ output->bytecode << fetch;
+
+ genObjectBody(prop->value);
+
+ QmlInstruction pop;
+ pop.type = QmlInstruction::PopFetchedObject;
+ pop.line = prop->location.start.line;
+ output->bytecode << pop;
+ }
+
+ foreach(Property *prop, obj->groupedProperties) {
+ QmlInstruction fetch;
+ fetch.type = QmlInstruction::FetchObject;
+ fetch.fetch.property = prop->index;
+ fetch.line = prop->location.start.line;
+ output->bytecode << fetch;
+
+ genObjectBody(prop->value);
+
+ QmlInstruction pop;
+ pop.type = QmlInstruction::PopFetchedObject;
+ pop.line = prop->location.start.line;
+ output->bytecode << pop;
+ }
+
+ foreach(Property *prop, obj->valueTypeProperties) {
+ QmlInstruction fetch;
+ fetch.type = QmlInstruction::FetchValueType;
+ fetch.fetchValue.property = prop->index;
+ fetch.fetchValue.type = prop->type;
+ fetch.line = prop->location.start.line;
+
+ output->bytecode << fetch;
+
+ foreach(Property *vprop, prop->value->valueProperties) {
+ genPropertyAssignment(vprop, prop->value, prop);
+ }
+
+ QmlInstruction pop;
+ pop.type = QmlInstruction::PopValueType;
+ pop.fetchValue.property = prop->index;
+ pop.fetchValue.type = prop->type;
+ pop.line = prop->location.start.line;
+ output->bytecode << pop;
+ }
+}
+
+void QmlCompiler::genComponent(QmlParser::Object *obj)
+{
+ QmlParser::Object *root = obj->defaultProperty->values.at(0)->object;
+ Q_ASSERT(root);
+
+ QmlInstruction create;
+ create.type = QmlInstruction::CreateComponent;
+ create.line = root->location.start.line;
+ create.createComponent.column = root->location.start.column;
+ create.createComponent.endLine = root->location.end.line;
+ output->bytecode << create;
+ int count = output->bytecode.count();
+
+ ComponentCompileState oldCompileState = compileState;
+ compileState = componentState(root);
+
+ QmlInstruction init;
+ init.type = QmlInstruction::Init;
+ init.init.bindingsSize = compileState.bindings.count();
+ init.init.parserStatusSize = compileState.parserStatusCount;
+ init.init.contextCache = genContextCache();
+ if (compileState.compiledBindingData.isEmpty())
+ init.init.compiledBinding = -1;
+ else
+ init.init.compiledBinding = output->indexForByteArray(compileState.compiledBindingData);
+ init.line = obj->location.start.line;
+ output->bytecode << init;
+
+ genObject(root);
+
+ QmlInstruction def;
+ init.line = 0;
+ def.type = QmlInstruction::SetDefault;
+ output->bytecode << def;
+
+ output->bytecode[count - 1].createComponent.count =
+ output->bytecode.count() - count;
+
+ compileState = oldCompileState;
+
+ if (!obj->id.isEmpty()) {
+ QmlInstruction id;
+ id.type = QmlInstruction::SetId;
+ id.line = 0;
+ id.setId.value = output->indexForString(obj->id);
+ id.setId.index = obj->idIndex;
+ output->bytecode << id;
+ }
+}
+
+bool QmlCompiler::buildComponent(QmlParser::Object *obj,
+ const BindingContext &ctxt)
+{
+ // The special "Component" element can only have the id property and a
+ // default property, that actually defines the component's tree
+
+ // Find, check and set the "id" property (if any)
+ Property *idProp = 0;
+ if (obj->properties.count() > 1 ||
+ (obj->properties.count() == 1 && obj->properties.begin().key() != "id"))
+ COMPILE_EXCEPTION(*obj->properties.begin(), QCoreApplication::translate("QmlCompiler","Invalid component specification"));
+
+ if (!obj->scriptBlockObjects.isEmpty())
+ COMPILE_EXCEPTION(obj->scriptBlockObjects.first(), QCoreApplication::translate("QmlCompiler","Invalid component specification"));
+
+ if (obj->properties.count())
+ idProp = *obj->properties.begin();
+
+ if (idProp && (idProp->value || idProp->values.count() > 1 || !isValidId(idProp->values.first()->primitive())))
+ COMPILE_EXCEPTION(idProp, QCoreApplication::translate("QmlCompiler","Invalid component id specification"));
+
+ if (idProp) {
+ QString idVal = idProp->values.first()->primitive();
+
+ if (compileState.ids.contains(idVal))
+ COMPILE_EXCEPTION(idProp, QCoreApplication::translate("QmlCompiler","id is not unique"));
+
+ obj->id = idVal;
+ addId(idVal, obj);
+ }
+
+ // Check the Component tree is well formed
+ if (obj->defaultProperty &&
+ (obj->defaultProperty->value || obj->defaultProperty->values.count() > 1 ||
+ (obj->defaultProperty->values.count() == 1 && !obj->defaultProperty->values.first()->object)))
+ COMPILE_EXCEPTION(obj, QCoreApplication::translate("QmlCompiler","Invalid component body specification"));
+
+ Object *root = 0;
+ if (obj->defaultProperty && obj->defaultProperty->values.count())
+ root = obj->defaultProperty->values.first()->object;
+
+ if (!root)
+ COMPILE_EXCEPTION(obj, QCoreApplication::translate("QmlCompiler","Cannot create empty component specification"));
+
+ // Build the component tree
+ COMPILE_CHECK(buildComponentFromRoot(root, ctxt));
+
+ return true;
+}
+
+bool QmlCompiler::buildScript(QmlParser::Object *obj, QmlParser::Object *script)
+{
+ Object::ScriptBlock scriptBlock;
+
+ if (script->properties.count() == 1 &&
+ script->properties.begin().key() == QByteArray("source")) {
+
+ Property *source = *script->properties.begin();
+ if (script->defaultProperty)
+ COMPILE_EXCEPTION(source, QCoreApplication::translate("QmlCompiler","Invalid Script block. Specify either the source property or inline script"));
+
+ if (source->value || source->values.count() != 1 ||
+ source->values.at(0)->object || !source->values.at(0)->value.isStringList())
+ COMPILE_EXCEPTION(source, QCoreApplication::translate("QmlCompiler","Invalid Script source value"));
+
+ QStringList sources = source->values.at(0)->value.asStringList();
+
+ for (int jj = 0; jj < sources.count(); ++jj) {
+ QString sourceUrl = output->url.resolved(QUrl(sources.at(jj))).toString();
+ QString scriptCode;
+ int lineNumber = 1;
+
+ for (int ii = 0; ii < unit->resources.count(); ++ii) {
+ if (unit->resources.at(ii)->url == sourceUrl) {
+ scriptCode = QString::fromUtf8(unit->resources.at(ii)->data);
+ break;
+ }
+ }
+
+ if (!scriptCode.isEmpty()) {
+ scriptBlock.codes.append(scriptCode);
+ scriptBlock.files.append(sourceUrl);
+ scriptBlock.lineNumbers.append(lineNumber);
+ }
+ }
+
+ } else if (!script->properties.isEmpty()) {
+ COMPILE_EXCEPTION(*script->properties.begin(), QCoreApplication::translate("QmlCompiler","Properties cannot be set on Script block"));
+ } else if (script->defaultProperty) {
+
+ QString scriptCode;
+ int lineNumber = 1;
+ QString sourceUrl = output->url.toString();
+
+ QmlParser::Location currentLocation;
+
+ for (int ii = 0; ii < script->defaultProperty->values.count(); ++ii) {
+ Value *v = script->defaultProperty->values.at(ii);
+ if (lineNumber == 1)
+ lineNumber = v->location.start.line;
+ if (v->object || !v->value.isString())
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid Script block"));
+
+ if (ii == 0) {
+ currentLocation = v->location.start;
+ scriptCode.append(QString(currentLocation.column, QLatin1Char(' ')));
+ }
+
+ while (currentLocation.line < v->location.start.line) {
+ scriptCode.append(QLatin1Char('\n'));
+ currentLocation.line++;
+ currentLocation.column = 0;
+ }
+
+ scriptCode.append(QString(v->location.start.column - currentLocation.column, QLatin1Char(' ')));
+
+ scriptCode += v->value.asString();
+ currentLocation = v->location.end;
+ currentLocation.column++;
+ }
+
+ if (!scriptCode.isEmpty()) {
+ scriptBlock.codes.append(scriptCode);
+ scriptBlock.files.append(sourceUrl);
+ scriptBlock.lineNumbers.append(lineNumber);
+ }
+ }
+
+ if (!scriptBlock.codes.isEmpty())
+ obj->scripts << scriptBlock;
+
+ return true;
+}
+
+bool QmlCompiler::buildComponentFromRoot(QmlParser::Object *obj,
+ const BindingContext &ctxt)
+{
+ ComponentCompileState oldComponentCompileState = compileState;
+ ComponentStat oldComponentStat = componentStat;
+
+ compileState = ComponentCompileState();
+ compileState.root = obj;
+
+ componentStat = ComponentStat();
+ componentStat.lineNumber = obj->location.start.line;
+
+ if (obj)
+ COMPILE_CHECK(buildObject(obj, ctxt));
+
+ COMPILE_CHECK(completeComponentBuild());
+
+ compileState = oldComponentCompileState;
+ componentStat = oldComponentStat;
+
+ return true;
+}
+
+
+// Build a sub-object. A sub-object is one that was not created directly by
+// QML - such as a grouped property object, or an attached object. Sub-object's
+// can't have an id, involve a custom parser, have attached properties etc.
+bool QmlCompiler::buildSubObject(Object *obj, const BindingContext &ctxt)
+{
+ Q_ASSERT(obj->metatype);
+ Q_ASSERT(!obj->defaultProperty);
+ Q_ASSERT(ctxt.isSubContext()); // sub-objects must always be in a binding
+ // sub-context
+
+ foreach(Property *prop, obj->properties) {
+ if (isSignalPropertyName(prop->name)) {
+ COMPILE_CHECK(buildSignal(prop, obj, ctxt));
+ } else {
+ COMPILE_CHECK(buildProperty(prop, obj, ctxt));
+ }
+ }
+
+ return true;
+}
+
+int QmlCompiler::componentTypeRef()
+{
+ QmlType *t = QmlMetaType::qmlType("Qt/Component",4,6);
+ for (int ii = output->types.count() - 1; ii >= 0; --ii) {
+ if (output->types.at(ii).type == t)
+ return ii;
+ }
+ QmlCompiledData::TypeReference ref;
+ ref.className = "Component";
+ ref.type = t;
+ output->types << ref;
+ return output->types.count() - 1;
+}
+
+int QmlCompiler::findSignalByName(const QMetaObject *mo, const QByteArray &name)
+{
+ int methods = mo->methodCount();
+ for (int ii = methods - 1; ii >= 0; --ii) {
+ QMetaMethod method = mo->method(ii);
+ QByteArray methodName = method.signature();
+ int idx = methodName.indexOf('(');
+ methodName = methodName.left(idx);
+
+ if (methodName == name)
+ return ii;
+ }
+ return -1;
+}
+
+bool QmlCompiler::buildSignal(QmlParser::Property *prop, QmlParser::Object *obj,
+ const BindingContext &ctxt)
+{
+ Q_ASSERT(obj->metaObject());
+ Q_ASSERT(!prop->isEmpty());
+
+ QByteArray name = prop->name;
+ Q_ASSERT(name.startsWith("on"));
+ name = name.mid(2);
+ if(name[0] >= 'A' && name[0] <= 'Z')
+ name[0] = name[0] - 'A' + 'a';
+
+ int sigIdx = findSignalByName(obj->metaObject(), name);
+
+ if (sigIdx == -1) {
+
+ // If the "on<Signal>" name doesn't resolve into a signal, try it as a
+ // property.
+ COMPILE_CHECK(buildProperty(prop, obj, ctxt));
+
+ } else {
+
+ if (prop->value || prop->values.count() > 1)
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Incorrectly specified signal"));
+
+ prop->index = sigIdx;
+ obj->addSignalProperty(prop);
+
+ if (prop->values.at(0)->object) {
+ COMPILE_CHECK(buildObject(prop->values.at(0)->object, ctxt));
+ prop->values.at(0)->type = Value::SignalObject;
+ } else {
+ prop->values.at(0)->type = Value::SignalExpression;
+
+ QString script = prop->values.at(0)->value.asScript().trimmed();
+ if (script.isEmpty())
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Empty signal assignment"));
+ }
+ }
+
+ return true;
+}
+
+
+/*!
+ Returns true if (value) property \a prop exists on obj, false otherwise.
+*/
+bool QmlCompiler::doesPropertyExist(QmlParser::Property *prop,
+ QmlParser::Object *obj)
+{
+ if(isAttachedPropertyName(prop->name) || prop->name == "id")
+ return true;
+
+ const QMetaObject *mo = obj->metaObject();
+ if (mo) {
+ if (prop->isDefault) {
+ QMetaProperty p = QmlMetaType::defaultProperty(mo);
+ return p.name() != 0;
+ } else {
+ int idx = mo->indexOfProperty(prop->name.constData());
+ return idx != -1;
+ }
+ }
+
+ return false;
+}
+
+bool QmlCompiler::buildProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt)
+{
+ if (prop->isEmpty())
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Empty property assignment"));
+
+ const QMetaObject *metaObject = obj->metaObject();
+ Q_ASSERT(metaObject);
+
+ if (isAttachedPropertyName(prop->name)) {
+ // Setup attached property data
+
+ if (ctxt.isSubContext()) {
+ // Attached properties cannot be used on sub-objects. Sub-objects
+ // always exist in a binding sub-context, which is what we test
+ // for here.
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Attached properties cannot be used here"));
+ }
+
+ QmlType *type = 0;
+ QmlEnginePrivate::ImportedNamespace *typeNamespace = 0;
+ QmlEnginePrivate::get(engine)->resolveType(unit->imports, prop->name,
+ &type, 0, 0, 0, &typeNamespace);
+
+ if (typeNamespace) {
+ // ### We might need to indicate that this property is a namespace
+ // for the DOM API
+ COMPILE_CHECK(buildPropertyInNamespace(typeNamespace, prop, obj,
+ ctxt));
+ return true;
+ } else if (!type || !type->attachedPropertiesType()) {
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Non-existant attached object"));
+ }
+
+ if (!prop->value)
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Invalid attached object assignment"));
+
+ Q_ASSERT(type->attachedPropertiesFunction());
+ prop->index = type->index();
+ prop->value->metatype = type->attachedPropertiesType();
+ } else {
+ // Setup regular property data
+ QMetaProperty p;
+
+ if (prop->isDefault) {
+ p = QmlMetaType::defaultProperty(metaObject);
+
+ if (p.name()) {
+ prop->index = p.propertyIndex();
+ prop->name = p.name();
+ }
+
+ } else {
+ prop->index = metaObject->indexOfProperty(prop->name.constData());
+
+ if (prop->index != -1) {
+ p = metaObject->property(prop->index);
+ Q_ASSERT(p.name());
+ }
+ }
+
+ // We can't error here as the "id" property does not require a
+ // successful index resolution
+ if (p.name()) {
+ prop->type = p.userType();
+ }
+ }
+
+ if (prop->index != -1)
+ prop->parent->setBindingBit(prop->index);
+
+ if (!prop->isDefault && prop->name == "id" && !ctxt.isSubContext()) {
+
+ // The magic "id" behavior doesn't apply when "id" is resolved as a
+ // default property or to sub-objects (which are always in binding
+ // sub-contexts)
+ COMPILE_CHECK(buildIdProperty(prop, obj));
+ if (prop->type == QVariant::String &&
+ prop->values.at(0)->value.isString())
+ COMPILE_CHECK(buildPropertyAssignment(prop, obj, ctxt));
+
+ } else if (isAttachedPropertyName(prop->name)) {
+
+ COMPILE_CHECK(buildAttachedProperty(prop, obj, ctxt));
+
+ } else if (prop->index == -1) {
+
+ if (prop->isDefault) {
+ COMPILE_EXCEPTION(prop->values.first(), QCoreApplication::translate("QmlCompiler","Cannot assign to non-existant default property"));
+ } else {
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Cannot assign to non-existant property \"%1\"").arg(QString::fromUtf8(prop->name)));
+ }
+
+ } else if (prop->value) {
+
+ COMPILE_CHECK(buildGroupedProperty(prop, obj, ctxt));
+
+ } else if (QmlEnginePrivate::get(engine)->isQmlList(prop->type) ||
+ QmlMetaType::isList(prop->type)) {
+
+ COMPILE_CHECK(buildListProperty(prop, obj, ctxt));
+
+ } else if (prop->type == qMetaTypeId<QmlScriptString>()) {
+
+ COMPILE_CHECK(buildScriptStringProperty(prop, obj, ctxt));
+
+ } else {
+
+ COMPILE_CHECK(buildPropertyAssignment(prop, obj, ctxt));
+
+ }
+
+ return true;
+}
+
+bool
+QmlCompiler::buildPropertyInNamespace(QmlEnginePrivate::ImportedNamespace *ns,
+ QmlParser::Property *nsProp,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt)
+{
+ if (!nsProp->value)
+ COMPILE_EXCEPTION(nsProp, QCoreApplication::translate("QmlCompiler","Invalid use of namespace"));
+
+ foreach (Property *prop, nsProp->value->properties) {
+
+ if (!isAttachedPropertyName(prop->name))
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Not an attached property name"));
+
+ // Setup attached property data
+
+ QmlType *type = 0;
+ QmlEnginePrivate::get(engine)->resolveTypeInNamespace(ns, prop->name,
+ &type, 0, 0, 0);
+
+ if (!type || !type->attachedPropertiesType())
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Non-existant attached object"));
+
+ if (!prop->value)
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Invalid attached object assignment"));
+
+ Q_ASSERT(type->attachedPropertiesFunction());
+ prop->index = type->index();
+ prop->value->metatype = type->attachedPropertiesType();
+
+ COMPILE_CHECK(buildAttachedProperty(prop, obj, ctxt));
+ }
+
+ return true;
+}
+
+void QmlCompiler::genValueProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj)
+{
+ if (QmlEnginePrivate::get(engine)->isQmlList(prop->type) ||
+ QmlMetaType::isList(prop->type)) {
+ genListProperty(prop, obj);
+ } else {
+ genPropertyAssignment(prop, obj);
+ }
+}
+
+void QmlCompiler::genListProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj)
+{
+ QmlInstruction::Type fetchType;
+ QmlInstruction::Type storeType;
+ int listType;
+
+ if (QmlEnginePrivate::get(engine)->isQmlList(prop->type)) {
+ fetchType = QmlInstruction::FetchQmlList;
+ storeType = QmlInstruction::StoreObjectQmlList;
+ listType = QmlEnginePrivate::get(engine)->qmlListType(prop->type);
+ } else {
+ fetchType = QmlInstruction::FetchQList;
+ storeType = QmlInstruction::StoreObjectQList;
+ listType = QmlMetaType::listType(prop->type);
+ }
+
+ QmlInstruction fetch;
+ fetch.type = fetchType;
+ fetch.line = prop->location.start.line;
+ fetch.fetchQmlList.property = prop->index;
+ bool listTypeIsInterface = QmlMetaType::isInterface(listType);
+ fetch.fetchQmlList.type = listType;
+ output->bytecode << fetch;
+
+ for (int ii = 0; ii < prop->values.count(); ++ii) {
+ Value *v = prop->values.at(ii);
+
+ if (v->type == Value::CreatedObject) {
+
+ genObject(v->object);
+ if (listTypeIsInterface) {
+ QmlInstruction assign;
+ assign.type = QmlInstruction::AssignObjectList;
+ assign.line = prop->location.start.line;
+ output->bytecode << assign;
+ } else {
+ QmlInstruction store;
+ store.type = storeType;
+ store.line = prop->location.start.line;
+ output->bytecode << store;
+ }
+
+ } else if (v->type == Value::PropertyBinding) {
+
+ genBindingAssignment(v, prop, obj);
+
+ }
+
+ }
+
+ QmlInstruction pop;
+ pop.type = QmlInstruction::PopQList;
+ pop.line = prop->location.start.line;
+ output->bytecode << pop;
+}
+
+void QmlCompiler::genPropertyAssignment(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ QmlParser::Property *valueTypeProperty)
+{
+ for (int ii = 0; ii < prop->values.count(); ++ii) {
+ QmlParser::Value *v = prop->values.at(ii);
+
+ if (v->type == Value::CreatedObject) {
+
+ genObject(v->object);
+
+ if (QmlMetaType::isInterface(prop->type)) {
+
+ QmlInstruction store;
+ store.type = QmlInstruction::StoreInterface;
+ store.line = v->object->location.start.line;
+ store.storeObject.propertyIndex = prop->index;
+ output->bytecode << store;
+
+ } else if (prop->type == -1) {
+
+ QmlInstruction store;
+ store.type = QmlInstruction::StoreVariantObject;
+ store.line = v->object->location.start.line;
+ store.storeObject.propertyIndex = prop->index;
+ output->bytecode << store;
+
+ } else {
+
+ QmlInstruction store;
+ store.type = QmlInstruction::StoreObject;
+ store.line = v->object->location.start.line;
+ store.storeObject.propertyIndex = prop->index;
+ output->bytecode << store;
+
+ }
+ } else if (v->type == Value::ValueSource) {
+ genObject(v->object);
+
+ QmlInstruction store;
+ store.type = QmlInstruction::StoreValueSource;
+ store.line = v->object->location.start.line;
+ if (valueTypeProperty) {
+ store.assignValueSource.property = genValueTypeData(prop, valueTypeProperty);
+ store.assignValueSource.owner = 1;
+ } else {
+ store.assignValueSource.property = genPropertyData(prop);
+ store.assignValueSource.owner = 0;
+ }
+ QmlType *valueType = toQmlType(v->object);
+ store.assignValueSource.castValue = valueType->propertyValueSourceCast();
+ output->bytecode << store;
+
+ } else if (v->type == Value::ValueInterceptor) {
+ genObject(v->object);
+
+ QmlInstruction store;
+ store.type = QmlInstruction::StoreValueInterceptor;
+ store.line = v->object->location.start.line;
+ if (valueTypeProperty) {
+ store.assignValueInterceptor.property = genValueTypeData(prop, valueTypeProperty);
+ store.assignValueInterceptor.owner = 1;
+ } else {
+ store.assignValueInterceptor.property = genPropertyData(prop);
+ store.assignValueInterceptor.owner = 0;
+ }
+ QmlType *valueType = toQmlType(v->object);
+ store.assignValueInterceptor.castValue = valueType->propertyValueInterceptorCast();
+ output->bytecode << store;
+
+ } else if (v->type == Value::PropertyBinding) {
+
+ genBindingAssignment(v, prop, obj, valueTypeProperty);
+
+ } else if (v->type == Value::Literal) {
+
+ QMetaProperty mp = obj->metaObject()->property(prop->index);
+ genLiteralAssignment(mp, v);
+
+ }
+
+ }
+}
+
+bool QmlCompiler::buildIdProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj)
+{
+ if (prop->value ||
+ prop->values.count() > 1 ||
+ prop->values.at(0)->object)
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Invalid use of id property"));
+
+ QmlParser::Value *idValue = prop->values.at(0);
+ QString val = idValue->primitive();
+
+ if (!isValidId(val))
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","\"%1\" is not a valid object id").arg(val));
+
+ // We disallow id's that conflict with import prefixes and types
+ QmlEnginePrivate::ImportedNamespace *ns = 0;
+ QmlType *type = 0;
+ QmlEnginePrivate::get(engine)->resolveType(unit->imports, val.toUtf8(),
+ &type, 0, 0, 0, &ns);
+ if (type)
+ COMPILE_EXCEPTION(idValue, QCoreApplication::translate("QmlCompiler","id conflicts with type name"));
+ if (ns)
+ COMPILE_EXCEPTION(idValue, QCoreApplication::translate("QmlCompiler","id conflicts with namespace prefix"));
+
+ if (compileState.ids.contains(val))
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","id is not unique"));
+
+ prop->values.at(0)->type = Value::Id;
+
+ obj->id = val;
+ addId(val, obj);
+
+ return true;
+}
+
+void QmlCompiler::addId(const QString &id, QmlParser::Object *obj)
+{
+ Q_ASSERT(!compileState.ids.contains(id));
+ Q_ASSERT(obj->id == id);
+ obj->idIndex = compileState.ids.count();
+ compileState.ids.insert(id, obj);
+ compileState.idIndexes.insert(obj->idIndex, obj);
+}
+
+void QmlCompiler::addBindingReference(const BindingReference &ref)
+{
+ Q_ASSERT(ref.value && !compileState.bindings.contains(ref.value));
+ compileState.bindings.insert(ref.value, ref);
+}
+
+void QmlCompiler::saveComponentState()
+{
+ Q_ASSERT(compileState.root);
+ Q_ASSERT(!savedCompileStates.contains(compileState.root));
+
+ savedCompileStates.insert(compileState.root, compileState);
+ savedComponentStats.append(componentStat);
+}
+
+QmlCompiler::ComponentCompileState
+QmlCompiler::componentState(QmlParser::Object *obj)
+{
+ Q_ASSERT(savedCompileStates.contains(obj));
+ return savedCompileStates.value(obj);
+}
+
+// Build attached property object. In this example,
+// Text {
+// GridView.row: 10
+// }
+// GridView is an attached property object.
+bool QmlCompiler::buildAttachedProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt)
+{
+ Q_ASSERT(prop->value);
+ Q_ASSERT(prop->index != -1); // This is set in buildProperty()
+
+ obj->addAttachedProperty(prop);
+
+ COMPILE_CHECK(buildSubObject(prop->value, ctxt.incr()));
+
+ return true;
+}
+
+
+// Build "grouped" properties. In this example:
+// Text {
+// font.pointSize: 12
+// font.family: "Helvetica"
+// }
+// font is a nested property. pointSize and family are not.
+bool QmlCompiler::buildGroupedProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt)
+{
+ Q_ASSERT(prop->type != 0);
+ Q_ASSERT(prop->index != -1);
+
+ if (prop->values.count())
+ COMPILE_EXCEPTION(prop->values.first(), QCoreApplication::translate("QmlCompiler", "Invalid value in grouped property"));
+
+ if (prop->type < (int)QVariant::UserType) {
+ QmlEnginePrivate *ep =
+ static_cast<QmlEnginePrivate *>(QObjectPrivate::get(engine));
+ if (prop->type >= 0 /* QVariant == -1 */ && ep->valueTypes[prop->type]) {
+ COMPILE_CHECK(buildValueTypeProperty(ep->valueTypes[prop->type],
+ prop->value, obj, ctxt.incr()));
+ obj->addValueTypeProperty(prop);
+ } else {
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Invalid grouped property access"));
+ }
+
+ } else {
+ // Load the nested property's meta type
+ prop->value->metatype =
+ QmlEnginePrivate::get(engine)->metaObjectForType(prop->type);
+ if (!prop->value->metatype)
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Invalid grouped property access"));
+
+ obj->addGroupedProperty(prop);
+
+ COMPILE_CHECK(buildSubObject(prop->value, ctxt.incr()));
+ }
+
+ return true;
+}
+
+bool QmlCompiler::buildValueTypeProperty(QObject *type,
+ QmlParser::Object *obj,
+ QmlParser::Object *baseObj,
+ const BindingContext &ctxt)
+{
+ if (obj->defaultProperty)
+ COMPILE_EXCEPTION(obj, QCoreApplication::translate("QmlCompiler","Invalid property use"));
+ obj->metatype = type->metaObject();
+
+ foreach (Property *prop, obj->properties) {
+ int idx = type->metaObject()->indexOfProperty(prop->name.constData());
+ if (idx == -1)
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Cannot assign to non-existant property \"%1\"").arg(QString::fromUtf8(prop->name)));
+ QMetaProperty p = type->metaObject()->property(idx);
+ prop->index = idx;
+ prop->type = p.userType();
+
+ if (prop->value)
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Property assignment expected"));
+
+ if (prop->values.count() != 1)
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Single property assignment expected"));
+
+ Value *value = prop->values.at(0);
+
+ if (value->object) {
+ bool isPropertyValue = output->types.at(value->object->type).type->propertyValueSourceCast() != -1;
+ bool isPropertyInterceptor = output->types.at(value->object->type).type->propertyValueInterceptorCast() != -1;
+ if (!isPropertyValue && !isPropertyInterceptor) {
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Unexpected object assignment"));
+ } else {
+ COMPILE_CHECK(buildObject(value->object, ctxt));
+
+ if (isPropertyInterceptor && baseObj->synthdata.isEmpty())
+ buildDynamicMeta(baseObj, ForceCreation);
+ value->type = isPropertyValue ? Value::ValueSource : Value::ValueInterceptor;
+ }
+ } else if (value->value.isScript()) {
+ // ### Check for writability
+ BindingReference reference;
+ reference.expression = value->value;
+ reference.property = prop;
+ reference.value = value;
+ reference.bindingContext = ctxt;
+ reference.bindingContext.owner++;
+ addBindingReference(reference);
+ value->type = Value::PropertyBinding;
+ } else {
+ COMPILE_CHECK(testLiteralAssignment(p, value));
+ value->type = Value::Literal;
+ }
+ obj->addValueProperty(prop);
+ }
+
+ return true;
+}
+
+// Build assignments to QML lists. QML lists are properties of type
+// QList<T *> * and QmlList<T *> *.
+//
+// QList<T *> * types can accept a list of objects, or a single binding
+// QmlList<T *> * types can accept a list of objects
+bool QmlCompiler::buildListProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt)
+{
+ Q_ASSERT(QmlMetaType::isList(prop->type) ||
+ QmlEnginePrivate::get(engine)->isQmlList(prop->type));
+
+ int t = prop->type;
+
+ obj->addValueProperty(prop);
+
+ if (QmlEnginePrivate::get(engine)->isQmlList(t)) {
+ int listType = QmlEnginePrivate::get(engine)->qmlListType(t);
+ bool listTypeIsInterface = QmlMetaType::isInterface(listType);
+
+ for (int ii = 0; ii < prop->values.count(); ++ii) {
+ Value *v = prop->values.at(ii);
+ if (v->object) {
+ v->type = Value::CreatedObject;
+ COMPILE_CHECK(buildObject(v->object, ctxt));
+
+ // We check object coercian here. We check interface assignment
+ // at runtime.
+ if (!listTypeIsInterface) {
+ if (!canCoerce(listType, v->object)) {
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Cannot assign object to list"));
+ }
+ }
+
+ } else {
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Cannot assign primitives to lists"));
+ }
+ }
+
+ } else {
+ int listType = QmlMetaType::listType(t);
+ bool listTypeIsInterface = QmlMetaType::isInterface(listType);
+
+ bool assignedBinding = false;
+ for (int ii = 0; ii < prop->values.count(); ++ii) {
+ Value *v = prop->values.at(ii);
+ if (v->object) {
+ v->type = Value::CreatedObject;
+ COMPILE_CHECK(buildObject(v->object, ctxt));
+
+ // We check object coercian here. We check interface assignment
+ // at runtime.
+ if (!listTypeIsInterface) {
+ if (!canCoerce(listType, v->object)) {
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Cannot assign object to list"));
+ }
+ }
+
+ } else if (v->value.isScript()) {
+ if (assignedBinding)
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Can only assign one binding to lists"));
+
+ assignedBinding = true;
+ COMPILE_CHECK(buildBinding(v, prop, ctxt));
+ v->type = Value::PropertyBinding;
+ } else {
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Cannot assign primitives to lists"));
+ }
+ }
+
+ }
+
+ return true;
+}
+
+// Compiles an assignment to a QmlScriptString property
+bool QmlCompiler::buildScriptStringProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt)
+{
+ if (prop->values.count() > 1)
+ COMPILE_EXCEPTION(prop->values.at(1), QCoreApplication::translate("QmlCompiler", "Cannot assign multiple values to a script property"));
+
+ if (prop->values.at(0)->object || !prop->values.at(0)->value.isScript())
+ COMPILE_EXCEPTION(prop->values.at(0), QCoreApplication::translate("QmlCompiler", "Invalid property assignment: script expected"));
+
+ obj->addScriptStringProperty(prop, ctxt.stack);
+
+ return true;
+}
+
+// Compile regular property assignments of the form "property: <value>"
+//
+// ### The following problems exist
+//
+// There is no distinction between how "lists" of values are specified. This
+// Item {
+// children: Item {}
+// children: Item {}
+// }
+// is identical to
+// Item {
+// children: [ Item {}, Item {} ]
+// }
+//
+// We allow assignming multiple values to single value properties
+bool QmlCompiler::buildPropertyAssignment(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt)
+{
+ obj->addValueProperty(prop);
+
+ for (int ii = 0; ii < prop->values.count(); ++ii) {
+ Value *v = prop->values.at(ii);
+ if (v->object) {
+
+ COMPILE_CHECK(buildPropertyObjectAssignment(prop, obj, v, ctxt));
+
+ } else {
+
+ COMPILE_CHECK(buildPropertyLiteralAssignment(prop, obj, v, ctxt));
+
+ }
+ }
+
+ return true;
+}
+
+// Compile assigning a single object instance to a regular property
+bool QmlCompiler::buildPropertyObjectAssignment(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ QmlParser::Value *v,
+ const BindingContext &ctxt)
+{
+ Q_ASSERT(prop->index != -1);
+ Q_ASSERT(v->object->type != -1);
+
+ if (!obj->metaObject()->property(prop->index).isWritable())
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: \"%1\" is a read-only property").arg(QString::fromUtf8(prop->name)));
+
+ if (QmlMetaType::isInterface(prop->type)) {
+
+ // Assigning an object to an interface ptr property
+ COMPILE_CHECK(buildObject(v->object, ctxt));
+
+ v->type = Value::CreatedObject;
+
+ } else if (prop->type == -1) {
+
+ // Assigning an object to a QVariant
+ COMPILE_CHECK(buildObject(v->object, ctxt));
+
+ v->type = Value::CreatedObject;
+ } else {
+ // Normally buildObject() will set this up, but we need the static
+ // meta object earlier to test for assignability. It doesn't matter
+ // that there may still be outstanding synthesized meta object changes
+ // on this type, as they are not relevant for assignability testing
+ v->object->metatype = output->types.at(v->object->type).metaObject();
+ Q_ASSERT(v->object->metaObject());
+
+ // Will be true if the assigned type inherits QmlPropertyValueSource
+ bool isPropertyValue = false;
+ // Will be true if the assigned type inherits QmlPropertyValueInterceptor
+ bool isPropertyInterceptor = false;
+ if (QmlType *valueType = toQmlType(v->object)) {
+ isPropertyValue = valueType->propertyValueSourceCast() != -1;
+ isPropertyInterceptor = valueType->propertyValueInterceptorCast() != -1;
+ }
+
+ // We want to raw metaObject here as the raw metaobject is the
+ // actual property type before we applied any extensions that might
+ // effect the properties on the type, but don't effect assignability
+ const QMetaObject *propertyMetaObject =
+ QmlEnginePrivate::get(engine)->rawMetaObjectForType(prop->type);
+
+ // Will be true if the assgned type inherits propertyMetaObject
+ bool isAssignable = false;
+ // Determine isAssignable value
+ if (propertyMetaObject) {
+ const QMetaObject *c = v->object->metatype;
+ while(c) {
+ isAssignable |= (QmlMetaPropertyPrivate::equal(c, propertyMetaObject));
+ c = c->superClass();
+ }
+ }
+
+ if (isAssignable) {
+ // Simple assignment
+ COMPILE_CHECK(buildObject(v->object, ctxt));
+
+ v->type = Value::CreatedObject;
+ } else if (propertyMetaObject == &QmlComponent::staticMetaObject) {
+ // Automatic "Component" insertion
+ QmlParser::Object *root = v->object;
+ QmlParser::Object *component = new QmlParser::Object;
+ component->type = componentTypeRef();
+ component->typeName = "Qt/Component";
+ component->metatype = &QmlComponent::staticMetaObject;
+ component->location = root->location;
+ QmlParser::Value *componentValue = new QmlParser::Value;
+ componentValue->object = root;
+ component->getDefaultProperty()->addValue(componentValue);
+ v->object = component;
+ COMPILE_CHECK(buildPropertyObjectAssignment(prop, obj, v, ctxt));
+ } else if (isPropertyValue || isPropertyInterceptor) {
+ // Assign as a property value source
+ COMPILE_CHECK(buildObject(v->object, ctxt));
+
+ if (isPropertyInterceptor && prop->parent->synthdata.isEmpty())
+ buildDynamicMeta(prop->parent, ForceCreation);
+ v->type = isPropertyValue ? Value::ValueSource : Value::ValueInterceptor;
+ } else {
+ COMPILE_EXCEPTION(v->object, QCoreApplication::translate("QmlCompiler","Cannot assign object to property"));
+ }
+ }
+
+ return true;
+}
+
+// Compile assigning a literal or binding to a regular property
+bool QmlCompiler::buildPropertyLiteralAssignment(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ QmlParser::Value *v,
+ const BindingContext &ctxt)
+{
+ Q_ASSERT(prop->index != -1);
+
+ if (v->value.isScript()) {
+
+ //optimization for <Type>.<EnumValue> enum assignments
+ bool isEnumAssignment = false;
+ COMPILE_CHECK(testQualifiedEnumAssignment(obj->metaObject()->property(prop->index), obj, v, &isEnumAssignment));
+ if (isEnumAssignment) {
+ v->type = Value::Literal;
+ return true;
+ }
+
+ COMPILE_CHECK(buildBinding(v, prop, ctxt));
+
+ v->type = Value::PropertyBinding;
+
+ } else {
+
+ COMPILE_CHECK(testLiteralAssignment(obj->metaObject()->property(prop->index), v));
+
+ v->type = Value::Literal;
+ }
+
+ return true;
+}
+
+bool QmlCompiler::testQualifiedEnumAssignment(const QMetaProperty &prop,
+ QmlParser::Object *obj,
+ QmlParser::Value *v,
+ bool *isAssignment)
+{
+ *isAssignment = false;
+ if (!prop.isEnumType())
+ return true;
+
+ if (!prop.isWritable())
+ COMPILE_EXCEPTION(v, QCoreApplication::translate("QmlCompiler","Invalid property assignment: \"%1\" is a read-only property").arg(QString::fromUtf8(prop.name())));
+
+ QString string = v->value.asString();
+ if (!string.at(0).isUpper())
+ return true;
+
+ QStringList parts = string.split(QLatin1Char('.'));
+ if (parts.count() != 2)
+ return true;
+
+ QString typeName = parts.at(0);
+ QmlType *type = 0;
+ QmlEnginePrivate::get(engine)->resolveType(unit->imports, typeName.toUtf8(),
+ &type, 0, 0, 0, 0);
+
+ if (!type || obj->typeName != type->qmlTypeName())
+ return true;
+
+ QString enumValue = parts.at(1);
+ int value;
+ if (prop.isFlagType()) {
+ value = prop.enumerator().keysToValue(enumValue.toUtf8().constData());
+ } else
+ value = prop.enumerator().keyToValue(enumValue.toUtf8().constData());
+ if (value == -1)
+ return true;
+
+ v->type = Value::Literal;
+ v->value = QmlParser::Variant(enumValue);
+ *isAssignment = true;
+
+ return true;
+}
+
+// Ensures that the dynamic meta specification on obj is valid
+bool QmlCompiler::checkDynamicMeta(QmlParser::Object *obj)
+{
+ QSet<QByteArray> propNames;
+ QSet<QByteArray> methodNames;
+ bool seenDefaultProperty = false;
+
+ // Check properties
+ for (int ii = 0; ii < obj->dynamicProperties.count(); ++ii) {
+ const QmlParser::Object::DynamicProperty &prop =
+ obj->dynamicProperties.at(ii);
+
+ if (prop.isDefaultProperty) {
+ if (seenDefaultProperty)
+ COMPILE_EXCEPTION(&prop, QCoreApplication::translate("QmlCompiler","Duplicate default property"));
+ seenDefaultProperty = true;
+ }
+
+ if (propNames.contains(prop.name))
+ COMPILE_EXCEPTION(&prop, QCoreApplication::translate("QmlCompiler","Duplicate property name"));
+
+ propNames.insert(prop.name);
+ }
+
+ for (int ii = 0; ii < obj->dynamicSignals.count(); ++ii) {
+ QByteArray name = obj->dynamicSignals.at(ii).name;
+ if (methodNames.contains(name))
+ COMPILE_EXCEPTION(obj, QCoreApplication::translate("QmlCompiler","Duplicate signal name"));
+ methodNames.insert(name);
+ }
+ for (int ii = 0; ii < obj->dynamicSlots.count(); ++ii) {
+ QByteArray name = obj->dynamicSlots.at(ii).name;
+ if (methodNames.contains(name))
+ COMPILE_EXCEPTION(obj, QCoreApplication::translate("QmlCompiler","Duplicate method name"));
+ methodNames.insert(name);
+ }
+
+ return true;
+}
+
+bool QmlCompiler::mergeDynamicMetaProperties(QmlParser::Object *obj)
+{
+ for (int ii = 0; ii < obj->dynamicProperties.count(); ++ii) {
+ const Object::DynamicProperty &p = obj->dynamicProperties.at(ii);
+
+ if (!p.defaultValue || p.type == Object::DynamicProperty::Alias)
+ continue;
+
+ Property *property = 0;
+ if (p.isDefaultProperty)
+ property = obj->getDefaultProperty();
+ else
+ property = obj->getProperty(p.name);
+
+ if (property->value)
+ COMPILE_EXCEPTION(property, QCoreApplication::translate("QmlCompiler","Invalid property nesting"));
+
+ for (int ii = 0; ii < p.defaultValue->values.count(); ++ii) {
+ Value *v = p.defaultValue->values.at(ii);
+ v->addref();
+ property->values.append(v);
+ }
+ }
+ return true;
+}
+
+Q_GLOBAL_STATIC(QAtomicInt, classIndexCounter)
+
+bool QmlCompiler::buildDynamicMeta(QmlParser::Object *obj, DynamicMetaMode mode)
+{
+ Q_ASSERT(obj);
+ Q_ASSERT(obj->metatype);
+
+ if (mode != ForceCreation &&
+ obj->dynamicProperties.isEmpty() &&
+ obj->dynamicSignals.isEmpty() &&
+ obj->dynamicSlots.isEmpty())
+ return true;
+
+ COMPILE_CHECK(checkDynamicMeta(obj));
+
+ QByteArray dynamicData(sizeof(QmlVMEMetaData), (char)0);
+
+ QByteArray newClassName = obj->metatype->className();
+ newClassName.append("_QML_");
+ int idx = classIndexCounter()->fetchAndAddRelaxed(1);
+ newClassName.append(QByteArray::number(idx));
+ if (compileState.root == obj) {
+ QString path = output->url.path();
+ int lastSlash = path.lastIndexOf(QLatin1Char('/'));
+ if (lastSlash > -1) {
+ QString nameBase = path.mid(lastSlash + 1, path.length()-lastSlash-5);
+ if (!nameBase.isEmpty() && nameBase.at(0).isUpper())
+ newClassName = nameBase.toUtf8() + "_QMLTYPE_" + QByteArray::number(idx);
+ }
+ }
+
+ QMetaObjectBuilder builder;
+ builder.setClassName(newClassName);
+ builder.setFlags(QMetaObjectBuilder::DynamicMetaObject);
+
+ bool hasAlias = false;
+ for (int ii = 0; ii < obj->dynamicProperties.count(); ++ii) {
+ const Object::DynamicProperty &p = obj->dynamicProperties.at(ii);
+
+ int propIdx =
+ obj->metaObject()->indexOfProperty(p.name.constData());
+ if (-1 != propIdx) {
+ QMetaProperty prop = obj->metaObject()->property(propIdx);
+ if (prop.isFinal())
+ COMPILE_EXCEPTION(&p, QCoreApplication::translate("QmlCompiler","Cannot override FINAL property"));
+ }
+
+ if (p.isDefaultProperty &&
+ (p.type != Object::DynamicProperty::Alias ||
+ mode == ResolveAliases))
+ builder.addClassInfo("DefaultProperty", p.name);
+
+ QByteArray type;
+ int propertyType = 0;
+ bool readonly = false;
+ switch(p.type) {
+ case Object::DynamicProperty::Alias:
+ hasAlias = true;
+ continue;
+ break;
+ case Object::DynamicProperty::CustomList:
+ case Object::DynamicProperty::Custom:
+ {
+ QByteArray customTypeName;
+ QmlType *qmltype = 0;
+ QUrl url;
+ QmlEnginePrivate *priv = QmlEnginePrivate::get(engine);
+ if (!priv->resolveType(unit->imports, p.customType, &qmltype,
+ &url, 0, 0, 0))
+ COMPILE_EXCEPTION(&p, QCoreApplication::translate("QmlCompiler","Invalid property type"));
+
+ if (!qmltype) {
+ QmlCompositeTypeData *tdata = priv->typeManager.get(url);
+ Q_ASSERT(tdata);
+ Q_ASSERT(tdata->status == QmlCompositeTypeData::Complete);
+
+ QmlCompiledData *data = tdata->toCompiledComponent(engine);
+ customTypeName = data->root->className();
+ } else {
+ customTypeName = qmltype->typeName();
+ }
+
+ if (p.type == Object::DynamicProperty::Custom) {
+ type = customTypeName + '*';
+ propertyType = QMetaType::QObjectStar;
+ } else {
+ readonly = true;
+ type = "QmlList<";
+ type.append(customTypeName);
+ type.append("*>*");
+ propertyType = qMetaTypeId<QmlList<QObject*>* >();
+ }
+ }
+ break;
+ case Object::DynamicProperty::Variant:
+ propertyType = -1;
+ type = "QVariant";
+ break;
+ case Object::DynamicProperty::Int:
+ propertyType = QVariant::Int;
+ type = "int";
+ break;
+ case Object::DynamicProperty::Bool:
+ propertyType = QVariant::Bool;
+ type = "bool";
+ break;
+ case Object::DynamicProperty::Real:
+ propertyType = QVariant::Double;
+ type = "double";
+ break;
+ case Object::DynamicProperty::String:
+ propertyType = QVariant::String;
+ type = "QString";
+ break;
+ case Object::DynamicProperty::Url:
+ propertyType = QVariant::Url;
+ type = "QUrl";
+ break;
+ case Object::DynamicProperty::Color:
+ propertyType = QVariant::Color;
+ type = "QColor";
+ break;
+ case Object::DynamicProperty::Date:
+ propertyType = QVariant::Date;
+ type = "QDate";
+ break;
+ }
+
+ ((QmlVMEMetaData *)dynamicData.data())->propertyCount++;
+ QmlVMEMetaData::PropertyData propertyData = { propertyType };
+ dynamicData.append((char *)&propertyData, sizeof(propertyData));
+
+ builder.addSignal(p.name + "Changed()");
+ QMetaPropertyBuilder propBuilder =
+ builder.addProperty(p.name, type, builder.methodCount() - 1);
+ propBuilder.setScriptable(true);
+ propBuilder.setWritable(!readonly);
+ }
+
+ if (mode == ResolveAliases) {
+ for (int ii = 0; ii < obj->dynamicProperties.count(); ++ii) {
+ const Object::DynamicProperty &p = obj->dynamicProperties.at(ii);
+
+ if (p.type == Object::DynamicProperty::Alias) {
+ ((QmlVMEMetaData *)dynamicData.data())->aliasCount++;
+ compileAlias(builder, dynamicData, obj, p);
+ }
+ }
+ }
+
+ for (int ii = 0; ii < obj->dynamicSignals.count(); ++ii) {
+ const Object::DynamicSignal &s = obj->dynamicSignals.at(ii);
+ QByteArray sig(s.name + '(');
+ for (int jj = 0; jj < s.parameterTypes.count(); ++jj) {
+ if (jj) sig.append(',');
+ sig.append(s.parameterTypes.at(jj));
+ }
+ sig.append(')');
+ QMetaMethodBuilder b = builder.addSignal(sig);
+ b.setParameterNames(s.parameterNames);
+ ((QmlVMEMetaData *)dynamicData.data())->signalCount++;
+ }
+
+ QStringList funcScripts;
+
+ for (int ii = 0; ii < obj->dynamicSlots.count(); ++ii) {
+ Object::DynamicSlot &s = obj->dynamicSlots[ii];
+ QByteArray sig(s.name + '(');
+ QString funcScript(QLatin1String("(function("));
+
+ for (int jj = 0; jj < s.parameterNames.count(); ++jj) {
+ if (jj) {
+ sig.append(',');
+ funcScript.append(QLatin1Char(','));
+ }
+ funcScript.append(QLatin1String(s.parameterNames.at(jj)));
+ sig.append("QVariant");
+ }
+ sig.append(')');
+ funcScript.append(QLatin1Char(')'));
+ funcScript.append(s.body);
+ funcScript.append(QLatin1Char(')'));
+ funcScripts << funcScript;
+
+ QMetaMethodBuilder b = builder.addSlot(sig);
+ b.setReturnType("QVariant");
+ b.setParameterNames(s.parameterNames);
+
+ ((QmlVMEMetaData *)dynamicData.data())->methodCount++;
+ QmlVMEMetaData::MethodData methodData =
+ { s.parameterNames.count(), 0, funcScript.length(), 0 };
+
+ dynamicData.append((char *)&methodData, sizeof(methodData));
+ }
+
+ for (int ii = 0; ii < obj->dynamicSlots.count(); ++ii) {
+ const QString &funcScript = funcScripts.at(ii);
+ QmlVMEMetaData::MethodData *data =
+ ((QmlVMEMetaData *)dynamicData.data())->methodData() + ii;
+
+ data->bodyOffset = dynamicData.size();
+
+ dynamicData.append((const char *)funcScript.constData(),
+ (funcScript.length() * sizeof(QChar)));
+ }
+
+ obj->metadata = builder.toRelocatableData();
+ builder.fromRelocatableData(&obj->extObject, obj->metatype, obj->metadata);
+
+ if (mode == IgnoreAliases && hasAlias)
+ compileState.aliasingObjects << obj;
+
+ obj->synthdata = dynamicData;
+
+ return true;
+}
+
+#include <qmljsparser_p.h>
+
+static QStringList astNodeToStringList(QmlJS::AST::Node *node)
+{
+ if (node->kind == QmlJS::AST::Node::Kind_IdentifierExpression) {
+ QString name =
+ static_cast<QmlJS::AST::IdentifierExpression *>(node)->name->asString();
+ return QStringList() << name;
+ } else if (node->kind == QmlJS::AST::Node::Kind_FieldMemberExpression) {
+ QmlJS::AST::FieldMemberExpression *expr = static_cast<QmlJS::AST::FieldMemberExpression *>(node);
+
+ QStringList rv = astNodeToStringList(expr->base);
+ if (rv.isEmpty())
+ return rv;
+ rv.append(expr->name->asString());
+ return rv;
+ }
+ return QStringList();
+}
+
+bool QmlCompiler::compileAlias(QMetaObjectBuilder &builder,
+ QByteArray &data,
+ Object *obj,
+ const Object::DynamicProperty &prop)
+{
+ if (!prop.defaultValue)
+ COMPILE_EXCEPTION(obj, QCoreApplication::translate("QmlCompiler","No property alias location"));
+
+ if (prop.defaultValue->values.count() != 1 ||
+ prop.defaultValue->values.at(0)->object ||
+ !prop.defaultValue->values.at(0)->value.isScript())
+ COMPILE_EXCEPTION(prop.defaultValue, QCoreApplication::translate("QmlCompiler","Invalid alias location"));
+
+ QmlJS::AST::Node *node = prop.defaultValue->values.at(0)->value.asAST();
+ if (!node)
+ COMPILE_EXCEPTION(obj, QCoreApplication::translate("QmlCompiler","No property alias location")); // ### Can this happen?
+
+ QStringList alias = astNodeToStringList(node);
+
+ if (alias.count() != 1 && alias.count() != 2)
+ COMPILE_EXCEPTION(prop.defaultValue, QCoreApplication::translate("QmlCompiler","Invalid alias reference. An alias reference must be specified as <id> or <id>.<property>"));
+
+ if (!compileState.ids.contains(alias.at(0)))
+ COMPILE_EXCEPTION(prop.defaultValue, QCoreApplication::translate("QmlCompiler","Invalid alias reference. Unable to find id \"%1\"").arg(alias.at(0)));
+
+ Object *idObject = compileState.ids[alias.at(0)];
+
+ QByteArray typeName;
+
+ int propIdx = -1;
+ int flags = 0;
+ bool writable = false;
+ if (alias.count() == 2) {
+ propIdx = idObject->metaObject()->indexOfProperty(alias.at(1).toUtf8().constData());
+
+ if (-1 == propIdx)
+ COMPILE_EXCEPTION(prop.defaultValue, QCoreApplication::translate("QmlCompiler","Invalid alias location"));
+
+ QMetaProperty aliasProperty = idObject->metaObject()->property(propIdx);
+ writable = aliasProperty.isWritable();
+
+ if (aliasProperty.isEnumType())
+ typeName = "int"; // Avoid introducing a dependency on the aliased metaobject
+ else
+ typeName = aliasProperty.typeName();
+ } else {
+ typeName = idObject->metaObject()->className();
+
+ //use the base type since it has been registered with metatype system
+ int index = typeName.indexOf("_QML_");
+ if (index != -1) {
+ typeName = typeName.left(index);
+ } else {
+ index = typeName.indexOf("_QMLTYPE_");
+ const QMetaObject *mo = idObject->metaObject();
+ while (index != -1 && mo) {
+ typeName = mo->superClass()->className();
+ index = typeName.indexOf("_QMLTYPE_");
+ mo = mo->superClass();
+ }
+ }
+
+ typeName += '*';
+ }
+
+ if (typeName.endsWith('*'))
+ flags |= QML_ALIAS_FLAG_PTR;
+
+ data.append((const char *)&idObject->idIndex, sizeof(idObject->idIndex));
+ data.append((const char *)&propIdx, sizeof(propIdx));
+ data.append((const char *)&flags, sizeof(flags));
+
+ builder.addSignal(prop.name + "Changed()");
+ QMetaPropertyBuilder propBuilder =
+ builder.addProperty(prop.name, typeName.constData(), builder.methodCount() - 1);
+ propBuilder.setScriptable(true);
+ propBuilder.setWritable(writable);
+ return true;
+}
+
+bool QmlCompiler::buildBinding(QmlParser::Value *value,
+ QmlParser::Property *prop,
+ const BindingContext &ctxt)
+{
+ Q_ASSERT(prop->index != -1);
+ Q_ASSERT(prop->parent);
+ Q_ASSERT(prop->parent->metaObject());
+
+ QMetaProperty mp = prop->parent->metaObject()->property(prop->index);
+ if (!mp.isWritable() && !QmlMetaType::isList(prop->type))
+ COMPILE_EXCEPTION(prop, QCoreApplication::translate("QmlCompiler","Invalid property assignment: \"%1\" is a read-only property").arg(QString::fromUtf8(prop->name)));
+
+ BindingReference reference;
+ reference.expression = value->value;
+ reference.property = prop;
+ reference.value = value;
+ reference.bindingContext = ctxt;
+ addBindingReference(reference);
+
+ return true;
+}
+
+void QmlCompiler::genBindingAssignment(QmlParser::Value *binding,
+ QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ QmlParser::Property *valueTypeProperty)
+{
+ Q_UNUSED(obj);
+ Q_ASSERT(compileState.bindings.contains(binding));
+
+ const BindingReference &ref = compileState.bindings.value(binding);
+ if (ref.dataType == BindingReference::Experimental) {
+ QmlInstruction store;
+ store.type = QmlInstruction::StoreCompiledBinding;
+ store.assignBinding.value = ref.compiledIndex;
+ store.assignBinding.context = ref.bindingContext.stack;
+ store.assignBinding.owner = ref.bindingContext.owner;
+ if (valueTypeProperty)
+ store.assignBinding.property = (valueTypeProperty->index & 0xFFFF) |
+ ((valueTypeProperty->type & 0xFF)) << 16 |
+ ((prop->index & 0xFF) << 24);
+ else
+ store.assignBinding.property = prop->index;
+ store.line = binding->location.start.line;
+ output->bytecode << store;
+ return;
+ }
+
+ QmlInstruction store;
+ store.type = QmlInstruction::StoreBinding;
+ store.assignBinding.value = output->indexForByteArray(ref.compiledData);
+ store.assignBinding.context = ref.bindingContext.stack;
+ store.assignBinding.owner = ref.bindingContext.owner;
+ store.line = binding->location.start.line;
+
+ Q_ASSERT(ref.bindingContext.owner == 0 ||
+ (ref.bindingContext.owner != 0 && valueTypeProperty));
+ if (ref.bindingContext.owner) {
+ store.assignBinding.property = genValueTypeData(prop, valueTypeProperty);
+ } else {
+ store.assignBinding.property = genPropertyData(prop);
+ }
+
+ output->bytecode << store;
+}
+
+int QmlCompiler::genContextCache()
+{
+ if (compileState.ids.count() == 0)
+ return -1;
+
+ QmlIntegerCache *cache = new QmlIntegerCache(engine);
+
+ for (QHash<QString, QmlParser::Object *>::ConstIterator iter = compileState.ids.begin();
+ iter != compileState.ids.end();
+ ++iter)
+ cache->add(iter.key(), (*iter)->idIndex);
+
+ output->contextCaches.append(cache);
+ return output->contextCaches.count() - 1;
+}
+
+int QmlCompiler::genValueTypeData(QmlParser::Property *valueTypeProp,
+ QmlParser::Property *prop)
+{
+ return output->indexForByteArray(QmlMetaPropertyPrivate::saveValueType(prop->parent->metaObject(), prop->index, valueTypeProp->index, valueTypeProp->type));
+}
+
+int QmlCompiler::genPropertyData(QmlParser::Property *prop)
+{
+ return output->indexForByteArray(QmlMetaPropertyPrivate::saveProperty(prop->parent->metaObject(), prop->index));
+}
+
+bool QmlCompiler::completeComponentBuild()
+{
+ componentStat.ids = compileState.ids.count();
+
+ for (int ii = 0; ii < compileState.aliasingObjects.count(); ++ii) {
+ Object *aliasObject = compileState.aliasingObjects.at(ii);
+ COMPILE_CHECK(buildDynamicMeta(aliasObject, ResolveAliases));
+ }
+
+ QmlBindingCompiler::Expression expr;
+ expr.component = compileState.root;
+ expr.ids = compileState.ids;
+
+ QmlBindingCompiler bindingCompiler;
+
+ for (QHash<QmlParser::Value*,BindingReference>::Iterator iter = compileState.bindings.begin(); iter != compileState.bindings.end(); ++iter) {
+ BindingReference &binding = *iter;
+
+ expr.context = binding.bindingContext.object;
+ expr.property = binding.property;
+ expr.expression = binding.expression;
+ expr.imports = unit->imports;
+
+ if (qmlExperimental()) {
+ int index = bindingCompiler.compile(expr, QmlEnginePrivate::get(engine));
+ if (index != -1) {
+ qWarning() << "Accepted for optimization:" << qPrintable(expr.expression.asScript());
+ binding.dataType = BindingReference::Experimental;
+ binding.compiledIndex = index;
+ componentStat.optimizedBindings++;
+ continue;
+ } else {
+ qWarning() << "Rejected for optimization:" << qPrintable(expr.expression.asScript());
+ }
+ }
+
+ binding.dataType = BindingReference::QtScript;
+
+ // Pre-rewrite the expression
+ QString expression = binding.expression.asScript();
+
+ // ### Optimize
+ QmlRewrite::SharedBindingTester sharableTest;
+ bool isSharable = sharableTest.isSharable(expression);
+
+ QmlRewrite::RewriteBinding rewriteBinding;
+ expression = rewriteBinding(expression);
+
+ quint32 length = expression.length();
+ quint32 pc;
+
+ if (isSharable) {
+ pc = output->cachedClosures.count();
+ pc |= 0x80000000;
+ output->cachedClosures.append(0);
+ } else {
+ pc = output->cachedPrograms.length();
+ output->cachedPrograms.append(0);
+ }
+
+ binding.compiledData =
+ QByteArray((const char *)&pc, sizeof(quint32)) +
+ QByteArray((const char *)&length, sizeof(quint32)) +
+ QByteArray((const char *)expression.constData(),
+ expression.length() * sizeof(QChar));
+
+ componentStat.scriptBindings++;
+ }
+
+ if (bindingCompiler.isValid()) {
+ compileState.compiledBindingData = bindingCompiler.program();
+ QmlBindingCompiler::dump(compileState.compiledBindingData);
+ }
+
+ saveComponentState();
+
+ return true;
+}
+
+void QmlCompiler::dumpStats()
+{
+ qWarning().nospace() << "QML Document: " << output->url.toString();
+ for (int ii = 0; ii < savedComponentStats.count(); ++ii) {
+ const ComponentStat &stat = savedComponentStats.at(ii);
+ qWarning().nospace() << " Component Line " << stat.lineNumber;
+ qWarning().nospace() << " Total Objects: " << stat.objects;
+ qWarning().nospace() << " IDs Used: " << stat.ids;
+ qWarning().nospace() << " Optimized Bindings: " << stat.optimizedBindings;
+ qWarning().nospace() << " QScript Bindings: " << stat.scriptBindings;
+ }
+}
+
+/*!
+ Returns true if from can be assigned to a (QObject) property of type
+ to.
+*/
+bool QmlCompiler::canCoerce(int to, QmlParser::Object *from)
+{
+ const QMetaObject *toMo =
+ QmlEnginePrivate::get(engine)->rawMetaObjectForType(to);
+ const QMetaObject *fromMo = from->metaObject();
+
+ while (fromMo) {
+ if (QmlMetaPropertyPrivate::equal(fromMo, toMo))
+ return true;
+ fromMo = fromMo->superClass();
+ }
+ return false;
+}
+
+/*!
+ Returns true if from can be assigned to a (QObject) property of type
+ to.
+*/
+bool QmlCompiler::canCoerce(int to, int from)
+{
+ const QMetaObject *toMo =
+ QmlEnginePrivate::get(engine)->rawMetaObjectForType(to);
+ const QMetaObject *fromMo =
+ QmlEnginePrivate::get(engine)->rawMetaObjectForType(from);
+
+ while (fromMo) {
+ if (QmlMetaPropertyPrivate::equal(fromMo, toMo))
+ return true;
+ fromMo = fromMo->superClass();
+ }
+ return false;
+}
+
+QmlType *QmlCompiler::toQmlType(QmlParser::Object *from)
+{
+ // ### Optimize
+ const QMetaObject *mo = from->metatype;
+ QmlType *type = 0;
+ while (!type && mo) {
+ type = QmlMetaType::qmlType(mo);
+ mo = mo->superClass();
+ }
+ return type;
+}
+
+QStringList QmlCompiler::deferredProperties(QmlParser::Object *obj)
+{
+ const QMetaObject *mo = obj->metatype;
+
+ int idx = mo->indexOfClassInfo("DeferredPropertyNames");
+ if (idx == -1)
+ return QStringList();
+
+ QMetaClassInfo classInfo = mo->classInfo(idx);
+ QStringList rv = QString::fromUtf8(classInfo.value()).split(QLatin1Char(','));
+ return rv;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h
new file mode 100644
index 0000000..f3f266b
--- /dev/null
+++ b/src/declarative/qml/qmlcompiler_p.h
@@ -0,0 +1,337 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCOMPILER_P_H
+#define QMLCOMPILER_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 "qml.h"
+#include "qmlerror.h"
+#include "qmlinstruction_p.h"
+#include "qmlcompositetypemanager_p.h"
+#include "qmlparser_p.h"
+#include "qmlengine_p.h"
+#include "qbitfield_p.h"
+#include "qmlpropertycache_p.h"
+#include "qmlintegercache_p.h"
+#include "qmltypenamecache_p.h"
+
+#include <QtCore/qbytearray.h>
+#include <QtCore/qset.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlEngine;
+class QmlComponent;
+class QmlContext;
+
+class QScriptProgram;
+class Q_AUTOTEST_EXPORT QmlCompiledData : public QmlRefCount, public QmlCleanup
+{
+public:
+ QmlCompiledData(QmlEngine *engine);
+ virtual ~QmlCompiledData();
+
+ QString name;
+ QUrl url;
+ QmlEnginePrivate::Imports imports;
+ QmlTypeNameCache *importCache;
+
+ struct TypeReference
+ {
+ TypeReference()
+ : type(0), component(0), ref(0) {}
+
+ QByteArray className;
+ QmlType *type;
+ QmlComponent *component;
+
+ QmlRefCount *ref;
+ QObject *createInstance(QmlContext *, const QBitField &) const;
+ const QMetaObject *metaObject() const;
+ };
+ QList<TypeReference> types;
+ struct CustomTypeData
+ {
+ int index;
+ int type;
+ };
+
+ const QMetaObject *root;
+ QAbstractDynamicMetaObject rootData;
+ QmlPropertyCache *rootPropertyCache;
+ QList<QString> primitives;
+ QList<float> floatData;
+ QList<int> intData;
+ QList<CustomTypeData> customTypeData;
+ QList<QByteArray> datas;
+ QList<QmlParser::Location> locations;
+ QList<QmlInstruction> bytecode;
+ QList<QScriptProgram *> cachedPrograms;
+ QList<QScriptValue *> cachedClosures;
+ QList<QmlPropertyCache *> propertyCaches;
+ QList<QmlIntegerCache *> contextCaches;
+ QList<QmlParser::Object::ScriptBlock> scripts;
+ QList<QUrl> urls;
+
+ void dumpInstructions();
+
+protected:
+ virtual void clear(); // From QmlCleanup
+
+private:
+ void dump(QmlInstruction *, int idx = -1);
+ QmlCompiledData(const QmlCompiledData &other);
+ QmlCompiledData &operator=(const QmlCompiledData &other);
+ QByteArray packData;
+ friend class QmlCompiler;
+ int pack(const char *, size_t);
+
+ int indexForString(const QString &);
+ int indexForByteArray(const QByteArray &);
+ int indexForFloat(float *, int);
+ int indexForInt(int *, int);
+ int indexForLocation(const QmlParser::Location &);
+ int indexForLocation(const QmlParser::LocationSpan &);
+ int indexForUrl(const QUrl &);
+};
+
+class QMetaObjectBuilder;
+class Q_DECLARATIVE_EXPORT QmlCompiler
+{
+public:
+ QmlCompiler();
+
+ bool compile(QmlEngine *, QmlCompositeTypeData *, QmlCompiledData *);
+
+ bool isError() const;
+ QList<QmlError> errors() const;
+
+ static bool isValidId(const QString &);
+ static bool isAttachedPropertyName(const QByteArray &);
+ static bool isSignalPropertyName(const QByteArray &);
+
+private:
+ static void reset(QmlCompiledData *);
+
+ struct BindingContext {
+ BindingContext()
+ : stack(0), owner(0), object(0) {}
+ BindingContext(QmlParser::Object *o)
+ : stack(0), owner(0), object(o) {}
+ BindingContext incr() const {
+ BindingContext rv(object);
+ rv.stack = stack + 1;
+ return rv;
+ }
+ bool isSubContext() const { return stack != 0; }
+ int stack;
+ int owner;
+ QmlParser::Object *object;
+ };
+
+ void compileTree(QmlParser::Object *tree);
+
+
+ bool buildObject(QmlParser::Object *obj, const BindingContext &);
+ bool buildScript(QmlParser::Object *obj, QmlParser::Object *script);
+ bool buildComponent(QmlParser::Object *obj, const BindingContext &);
+ bool buildSubObject(QmlParser::Object *obj, const BindingContext &);
+ bool buildSignal(QmlParser::Property *prop, QmlParser::Object *obj,
+ const BindingContext &);
+ bool buildProperty(QmlParser::Property *prop, QmlParser::Object *obj,
+ const BindingContext &);
+ bool buildPropertyInNamespace(QmlEnginePrivate::ImportedNamespace *ns,
+ QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &);
+ bool buildIdProperty(QmlParser::Property *prop, QmlParser::Object *obj);
+ bool buildAttachedProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt);
+ bool buildGroupedProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt);
+ bool buildValueTypeProperty(QObject *type,
+ QmlParser::Object *obj,
+ QmlParser::Object *baseObj,
+ const BindingContext &ctxt);
+ bool buildListProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt);
+ bool buildScriptStringProperty(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt);
+ bool buildPropertyAssignment(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ const BindingContext &ctxt);
+ bool buildPropertyObjectAssignment(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ QmlParser::Value *value,
+ const BindingContext &ctxt);
+ bool buildPropertyLiteralAssignment(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ QmlParser::Value *value,
+ const BindingContext &ctxt);
+ bool doesPropertyExist(QmlParser::Property *prop, QmlParser::Object *obj);
+ bool testLiteralAssignment(const QMetaProperty &prop,
+ QmlParser::Value *value);
+ bool testQualifiedEnumAssignment(const QMetaProperty &prop,
+ QmlParser::Object *obj,
+ QmlParser::Value *value,
+ bool *isAssignment);
+ enum DynamicMetaMode { IgnoreAliases, ResolveAliases, ForceCreation };
+ bool mergeDynamicMetaProperties(QmlParser::Object *obj);
+ bool buildDynamicMeta(QmlParser::Object *obj, DynamicMetaMode mode);
+ bool checkDynamicMeta(QmlParser::Object *obj);
+ bool buildBinding(QmlParser::Value *, QmlParser::Property *prop,
+ const BindingContext &ctxt);
+ bool buildComponentFromRoot(QmlParser::Object *obj, const BindingContext &);
+ bool compileAlias(QMetaObjectBuilder &,
+ QByteArray &data,
+ QmlParser::Object *obj,
+ const QmlParser::Object::DynamicProperty &);
+ bool completeComponentBuild();
+
+
+ void genObject(QmlParser::Object *obj);
+ void genObjectBody(QmlParser::Object *obj);
+ void genComponent(QmlParser::Object *obj);
+ void genValueProperty(QmlParser::Property *prop, QmlParser::Object *obj);
+ void genListProperty(QmlParser::Property *prop, QmlParser::Object *obj);
+ void genPropertyAssignment(QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ QmlParser::Property *valueTypeProperty = 0);
+ void genLiteralAssignment(const QMetaProperty &prop,
+ QmlParser::Value *value);
+ void genBindingAssignment(QmlParser::Value *binding,
+ QmlParser::Property *prop,
+ QmlParser::Object *obj,
+ QmlParser::Property *valueTypeProperty = 0);
+ int genContextCache();
+
+ int genValueTypeData(QmlParser::Property *prop, QmlParser::Property *valueTypeProp);
+ int genPropertyData(QmlParser::Property *prop);
+
+ int componentTypeRef();
+
+ static int findSignalByName(const QMetaObject *, const QByteArray &name);
+ static QmlType *toQmlType(QmlParser::Object *from);
+ bool canCoerce(int to, QmlParser::Object *from);
+ bool canCoerce(int to, int from);
+
+ QStringList deferredProperties(QmlParser::Object *);
+
+ void addId(const QString &, QmlParser::Object *);
+
+ void dumpStats();
+
+ struct BindingReference {
+ QmlParser::Variant expression;
+ QmlParser::Property *property;
+ QmlParser::Value *value;
+
+ enum DataType { QtScript, Experimental };
+ DataType dataType;
+
+ int compiledIndex;
+
+ QByteArray compiledData;
+ BindingContext bindingContext;
+ };
+ void addBindingReference(const BindingReference &);
+
+ struct ComponentCompileState
+ {
+ ComponentCompileState()
+ : parserStatusCount(0), pushedProperties(0), root(0) {}
+ QHash<QString, QmlParser::Object *> ids;
+ QHash<int, QmlParser::Object *> idIndexes;
+ int parserStatusCount;
+ int pushedProperties;
+
+ QByteArray compiledBindingData;
+
+ QHash<QmlParser::Value *, BindingReference> bindings;
+ QList<QmlParser::Object *> aliasingObjects;
+ QmlParser::Object *root;
+ };
+ ComponentCompileState compileState;
+
+ struct ComponentStat
+ {
+ ComponentStat()
+ : ids(0), scriptBindings(0), optimizedBindings(0), objects(0) {}
+
+ int lineNumber;
+
+ int ids;
+ int scriptBindings;
+ int optimizedBindings;
+ int objects;
+ };
+ ComponentStat componentStat;
+
+ void saveComponentState();
+
+ ComponentCompileState componentState(QmlParser::Object *);
+ QHash<QmlParser::Object *, ComponentCompileState> savedCompileStates;
+ QList<ComponentStat> savedComponentStats;
+
+ QList<QmlError> exceptions;
+ QmlCompiledData *output;
+ QmlEngine *engine;
+ QmlParser::Object *unitRoot;
+ QmlCompositeTypeData *unit;
+};
+QT_END_NAMESPACE
+
+#endif // QMLCOMPILER_P_H
diff --git a/src/declarative/qml/qmlcomponent.cpp b/src/declarative/qml/qmlcomponent.cpp
new file mode 100644
index 0000000..9e06016
--- /dev/null
+++ b/src/declarative/qml/qmlcomponent.cpp
@@ -0,0 +1,798 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlcomponent.h"
+#include "qmlcomponent_p.h"
+
+#include "qmlcompiler_p.h"
+#include "qmlcontext_p.h"
+#include "qmlcompositetypedata_p.h"
+#include "qmlengine_p.h"
+#include "qmlvme_p.h"
+#include "qml.h"
+#include "qmlengine.h"
+#include "qmlbinding.h"
+#include "qmlbinding_p.h"
+#include "qmlglobal_p.h"
+#include "qmlscriptparser_p.h"
+
+#include <qfxperf_p_p.h>
+
+#include <QStack>
+#include <QStringList>
+#include <QFileInfo>
+#include <QtCore/qdebug.h>
+#include <QApplication>
+
+QT_BEGIN_NAMESPACE
+
+class QByteArray;
+int statusId = qRegisterMetaType<QmlComponent::Status>("QmlComponent::Status");
+
+/*!
+ \class QmlComponent
+ \brief The QmlComponent class encapsulates a QML component description.
+ \mainclass
+*/
+
+/*!
+ \qmlclass Component QmlComponent
+ \brief The Component element encapsulates a QML component description.
+
+ Components are reusable, encapsulated Qml element with a well-defined interface.
+ They are often defined in \l {qmldocuments.html}{Component Files}.
+
+ The \e Component element allows defining components within a QML file.
+ This can be useful for reusing a small component within a single QML
+ file, or for defining a component that logically belongs with the
+ file containing it.
+
+ \qml
+Item {
+ Component {
+ id: redSquare
+ Rectangle {
+ color: "red"
+ width: 10
+ height: 10
+ }
+ }
+ Loader { sourceComponent: redSquare }
+ Loader { sourceComponent: redSquare; x: 20 }
+}
+ \endqml
+
+ \section1 Attached Properties
+
+ \e onCompleted
+
+ Emitted after component "startup" has completed. This can be used to
+ execute script code at startup, once the full QML environment has been
+ established.
+
+ The \c {Component::onCompleted} attached property can be applied to
+ any element. The order of running the \c onCompleted scripts is
+ undefined.
+
+ \qml
+ Rectangle {
+ Component.onCompleted: console.log("Completed Running!")
+ Rectangle {
+ Component.onCompleted: console.log("Nested Completed Running!")
+ }
+ }
+ \endqml
+*/
+QML_DEFINE_TYPE(Qt,4,6,Component,QmlComponent);
+
+/*!
+ \enum QmlComponent::Status
+
+ Specifies the loading status of the QmlComponent.
+
+ \value Null This QmlComponent has no data. Call loadUrl() or setData() to add QML content.
+ \value Ready This QmlComponent is ready and create() may be called.
+ \value Loading This QmlComponent is loading network data.
+ \value Error An error has occured. Calling errorDescription() to retrieve a description.
+*/
+
+void QmlComponentPrivate::typeDataReady()
+{
+ Q_Q(QmlComponent);
+
+ Q_ASSERT(typeData);
+
+ fromTypeData(typeData);
+ typeData = 0;
+
+ emit q->statusChanged(q->status());
+}
+
+void QmlComponentPrivate::updateProgress(qreal p)
+{
+ Q_Q(QmlComponent);
+
+ progress = p;
+ emit q->progressChanged(p);
+}
+
+void QmlComponentPrivate::fromTypeData(QmlCompositeTypeData *data)
+{
+ url = data->imports.baseUrl();
+ QmlCompiledData *c = data->toCompiledComponent(engine);
+
+ if (!c) {
+ Q_ASSERT(data->status == QmlCompositeTypeData::Error);
+
+ state.errors = data->errors;
+
+ } else {
+
+ cc = c;
+
+ }
+
+ data->release();
+}
+
+void QmlComponentPrivate::clear()
+{
+ if (typeData) {
+ typeData->remWaiter(this);
+ typeData->release();
+ typeData = 0;
+ }
+
+ if (cc) {
+ cc->release();
+ cc = 0;
+ }
+}
+
+/*!
+ \internal
+*/
+QmlComponent::QmlComponent(QObject *parent)
+ : QObject(*(new QmlComponentPrivate), parent)
+{
+}
+
+/*!
+ Destruct the QmlComponent.
+*/
+QmlComponent::~QmlComponent()
+{
+ Q_D(QmlComponent);
+
+ if (d->state.completePending) {
+ qWarning("QmlComponent: Component destroyed while completion pending");
+ d->completeCreate();
+ }
+
+ if (d->typeData) {
+ d->typeData->remWaiter(d);
+ d->typeData->release();
+ }
+ if (d->cc)
+ d->cc->release();
+}
+
+/*!
+ \property QmlComponent::status
+ The component's current \l{QmlComponent::Status} {status}.
+ */
+QmlComponent::Status QmlComponent::status() const
+{
+ Q_D(const QmlComponent);
+
+ if (d->typeData)
+ return Loading;
+ else if (!d->state.errors.isEmpty())
+ return Error;
+ else if (d->engine && d->cc)
+ return Ready;
+ else
+ return Null;
+}
+
+/*!
+ \property QmlComponent::isNull
+
+ Is true if the component is in the Null state, false otherwise.
+
+ Equivalent to status() == QmlComponent::Null.
+*/
+bool QmlComponent::isNull() const
+{
+ return status() == Null;
+}
+
+/*!
+ \property QmlComponent::isReady
+
+ Is true if the component is in the Ready state, false otherwise.
+
+ Equivalent to status() == QmlComponent::Ready.
+*/
+bool QmlComponent::isReady() const
+{
+ return status() == Ready;
+}
+
+/*!
+ \property QmlComponent::isError
+
+ Is true if the component is in the Error state, false otherwise.
+
+ Equivalent to status() == QmlComponent::Error.
+*/
+bool QmlComponent::isError() const
+{
+ return status() == Error;
+}
+
+/*!
+ \property QmlComponent::isLoading
+
+ Is true if the component is in the Loading state, false otherwise.
+
+ Equivalent to status() == QmlComponent::Loading.
+*/
+bool QmlComponent::isLoading() const
+{
+ return status() == Loading;
+}
+
+/*!
+ \property QmlComponent::progress
+ The progress of loading the component, from 0.0 (nothing loaded)
+ to 1.0 (finished).
+*/
+qreal QmlComponent::progress() const
+{
+ Q_D(const QmlComponent);
+ return d->progress;
+}
+
+/*!
+ \fn void QmlComponent::progressChanged(qreal progress)
+
+ Emitted whenever the component's loading progress changes. \a progress will be the
+ current progress between 0.0 (nothing loaded) and 1.0 (finished).
+*/
+
+/*!
+ \fn void QmlComponent::statusChanged(QmlComponent::Status status)
+
+ Emitted whenever the component's status changes. \a status will be the
+ new status.
+*/
+
+/*!
+ Create a QmlComponent with no data and give it the specified
+ \a engine and \a parent. Set the data with setData().
+*/
+QmlComponent::QmlComponent(QmlEngine *engine, QObject *parent)
+ : QObject(*(new QmlComponentPrivate), parent)
+{
+ Q_D(QmlComponent);
+ d->engine = engine;
+}
+
+/*!
+ Create a QmlComponent from the given \a url and give it the
+ specified \a parent and \a engine.
+
+ \sa loadUrl()
+*/
+QmlComponent::QmlComponent(QmlEngine *engine, const QUrl &url, QObject *parent)
+: QObject(*(new QmlComponentPrivate), parent)
+{
+ Q_D(QmlComponent);
+ d->engine = engine;
+ loadUrl(url);
+}
+
+/*!
+ Create a QmlComponent from the given \a fileName and give it the specified
+ \a parent and \a engine.
+
+ \sa loadUrl()
+*/
+QmlComponent::QmlComponent(QmlEngine *engine, const QString &fileName,
+ QObject *parent)
+: QObject(*(new QmlComponentPrivate), parent)
+{
+ Q_D(QmlComponent);
+ d->engine = engine;
+ loadUrl(QUrl::fromLocalFile(fileName));
+}
+
+/*!
+ \internal
+*/
+QmlComponent::QmlComponent(QmlEngine *engine, QmlCompiledData *cc, int start, int count, QObject *parent)
+ : QObject(*(new QmlComponentPrivate), parent)
+{
+ Q_D(QmlComponent);
+ d->engine = engine;
+ d->cc = cc;
+ cc->addref();
+ d->start = start;
+ d->count = count;
+ d->url = cc->url;
+ d->progress = 1.0;
+}
+
+/*!
+ Sets the QmlComponent to use the given QML \a data. If \a url
+ is provided, it is used to set the component name and to provide
+ a base path for items resolved by this component.
+*/
+void QmlComponent::setData(const QByteArray &data, const QUrl &url)
+{
+ Q_D(QmlComponent);
+
+ d->clear();
+
+ d->url = url;
+
+ QmlCompositeTypeData *typeData =
+ QmlEnginePrivate::get(d->engine)->typeManager.getImmediate(data, url);
+
+ if (typeData->status == QmlCompositeTypeData::Waiting
+ || typeData->status == QmlCompositeTypeData::WaitingResources)
+ {
+ d->typeData = typeData;
+ d->typeData->addWaiter(d);
+
+ } else {
+
+ d->fromTypeData(typeData);
+
+ }
+
+ d->progress = 1.0;
+ emit statusChanged(status());
+ emit progressChanged(d->progress);
+}
+
+/*!
+Returns the QmlContext the component was created in. This is only
+valid for components created directly from QML.
+*/
+QmlContext *QmlComponent::creationContext() const
+{
+ Q_D(const QmlComponent);
+ if(d->creationContext)
+ return d->creationContext;
+ QmlDeclarativeData *ddata = QmlDeclarativeData::get(this);
+ if (ddata)
+ return ddata->context;
+ else
+ return 0;
+}
+
+/*!
+ \internal
+ Sets the QmlContext the component was created in. This is only
+ desirable for components created in QML script.
+*/
+void QmlComponent::setCreationContext(QmlContext* c)
+{
+ Q_D(QmlComponent);
+ d->creationContext = c;
+}
+
+/*!
+ Load the QmlComponent from the provided \a url.
+*/
+void QmlComponent::loadUrl(const QUrl &url)
+{
+ Q_D(QmlComponent);
+
+ d->clear();
+
+ if (url.isRelative() && !url.isEmpty())
+ d->url = d->engine->baseUrl().resolved(url);
+ else
+ d->url = url;
+
+ QmlCompositeTypeData *data =
+ QmlEnginePrivate::get(d->engine)->typeManager.get(d->url);
+
+ if (data->status == QmlCompositeTypeData::Waiting
+ || data->status == QmlCompositeTypeData::WaitingResources)
+ {
+ d->typeData = data;
+ d->typeData->addWaiter(d);
+ d->progress = data->progress;
+ } else {
+ d->fromTypeData(data);
+ d->progress = 1.0;
+ }
+
+ emit statusChanged(status());
+ emit progressChanged(d->progress);
+}
+
+/*!
+ Return the list of errors that occured during the last compile or create
+ operation. An empty list is returned if isError() is not set.
+*/
+QList<QmlError> QmlComponent::errors() const
+{
+ Q_D(const QmlComponent);
+ if (isError())
+ return d->state.errors;
+ else
+ return QList<QmlError>();
+}
+
+/*!
+ \internal
+ errorsString is only meant as a way to get the errors in script
+*/
+QString QmlComponent::errorsString() const
+{
+ Q_D(const QmlComponent);
+ QString ret;
+ if(!isError())
+ return ret;
+ foreach(const QmlError &e, d->state.errors) {
+ ret += e.url().toString() + QLatin1Char(':') +
+ QString::number(e.line()) + QLatin1Char(' ') +
+ e.description() + QLatin1Char('\n');
+ }
+ return ret;
+}
+
+/*!
+ \property QmlComponent::url
+ The component URL. This is the URL passed to either the constructor,
+ or the loadUrl() or setData() methods.
+*/
+QUrl QmlComponent::url() const
+{
+ Q_D(const QmlComponent);
+ return d->url;
+}
+
+/*!
+ \internal
+*/
+QmlComponent::QmlComponent(QmlComponentPrivate &dd, QObject *parent)
+ : QObject(dd, parent)
+{
+}
+
+
+/*!
+ \internal
+ A version of create which returns a scriptObject, for use in script
+*/
+QScriptValue QmlComponent::createObject()
+{
+ Q_D(QmlComponent);
+ QmlContext* ctxt = creationContext();
+ if(!ctxt){
+ qWarning() << QLatin1String("createObject can only be used in QML");
+ return QScriptValue();
+ }
+ QObject* ret = create(ctxt);
+ return QmlEnginePrivate::qmlScriptObject(ret, d->engine);
+}
+
+/*!
+ Create an object instance from this component. Returns 0 if creation
+ failed. \a context specifies the context within which to create the object
+ instance.
+
+ If \a context is 0 (the default), it will create the instance in the
+ engine' s \l {QmlEngine::rootContext()}{root context}.
+*/
+QObject *QmlComponent::create(QmlContext *context)
+{
+ Q_D(QmlComponent);
+
+ return d->create(context, QBitField());
+}
+
+QObject *QmlComponentPrivate::create(QmlContext *context,
+ const QBitField &bindings)
+{
+ QObject *create(QmlContext *context, const QBitField &);
+ if (!context)
+ context = engine->rootContext();
+
+ if (context->engine() != engine) {
+ qWarning("QmlComponent::create(): Must create component in context from the same QmlEngine");
+ return 0;
+ }
+
+ QObject *rv = beginCreate(context, bindings);
+ completeCreate();
+ return rv;
+}
+
+/*!
+ This method provides more advanced control over component instance creation.
+ In general, programmers should use QmlComponent::create() to create a
+ component.
+
+ Create an object instance from this component. Returns 0 if creation
+ failed. \a context specifies the context within which to create the object
+ instance.
+
+ When QmlComponent constructs an instance, it occurs in three steps:
+ \list 1
+ \i The object hierarchy is created, and constant values are assigned.
+ \i Property bindings are evaluated for the the first time.
+ \i If applicable, QmlParserStatus::componentComplete() is called on objects.
+ \endlist
+ QmlComponent::beginCreate() differs from QmlComponent::create() in that it
+ only performs step 1. QmlComponent::completeCreate() must be called to
+ complete steps 2 and 3.
+
+ This breaking point is sometimes useful when using attached properties to
+ communicate information to an instantiated component, as it allows their
+ initial values to be configured before property bindings take effect.
+*/
+QObject *QmlComponent::beginCreate(QmlContext *context)
+{
+ Q_D(QmlComponent);
+ return d->beginCreate(context, QBitField());
+}
+
+QObject *
+QmlComponentPrivate::beginCreate(QmlContext *context, const QBitField &bindings)
+{
+ Q_Q(QmlComponent);
+ if (!context) {
+ qWarning("QmlComponent::beginCreate(): Cannot create a component in a null context");
+ return 0;
+ }
+
+ if (context->engine() != engine) {
+ qWarning("QmlComponent::beginCreate(): Must create component in context from the same QmlEngine");
+ return 0;
+ }
+
+ if (state.completePending) {
+ qWarning("QmlComponent: Cannot create new component instance before completing the previous");
+ return 0;
+ }
+
+ if (!q->isReady()) {
+ qWarning("QmlComponent: Component is not ready");
+ return 0;
+ }
+
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+
+ QmlContextPrivate *contextPriv =
+ static_cast<QmlContextPrivate *>(QObjectPrivate::get(context));
+ QmlContext *ctxt = new QmlContext(context, 0, true);
+ static_cast<QmlContextPrivate*>(ctxt->d_func())->url = cc->url;
+ static_cast<QmlContextPrivate*>(ctxt->d_func())->imports = cc->importCache;
+ cc->importCache->addref();
+
+ QObject *rv = begin(ctxt, ep, cc, start, count, &state, bindings);
+
+ if (rv) {
+ QmlGraphics_setParent_noEvent(ctxt, rv);
+ } else {
+ delete ctxt;
+ }
+
+ if (rv && !contextPriv->isInternal && ep->isDebugging)
+ contextPriv->instances.append(rv);
+ return rv;
+}
+
+QObject * QmlComponentPrivate::begin(QmlContext *ctxt, QmlEnginePrivate *enginePriv,
+ QmlCompiledData *component, int start, int count,
+ ConstructionState *state, const QBitField &bindings)
+{
+ bool isRoot = !enginePriv->inBeginCreate;
+ enginePriv->inBeginCreate = true;
+
+ QmlVME vme;
+ QObject *rv = vme.run(ctxt, component, start, count, bindings);
+
+ if (vme.isError())
+ state->errors = vme.errors();
+
+ if (isRoot) {
+ enginePriv->inBeginCreate = false;
+
+ state->bindValues = enginePriv->bindValues;
+ state->parserStatus = enginePriv->parserStatus;
+ state->componentAttacheds = enginePriv->componentAttacheds;
+ if (state->componentAttacheds)
+ state->componentAttacheds->prev = &state->componentAttacheds;
+
+ enginePriv->componentAttacheds = 0;
+ enginePriv->bindValues.clear();
+ enginePriv->parserStatus.clear();
+ state->completePending = true;
+ enginePriv->inProgressCreations++;
+ }
+
+ return rv;
+}
+
+void QmlComponentPrivate::beginDeferred(QmlContext *, QmlEnginePrivate *enginePriv,
+ QObject *object, ConstructionState *state)
+{
+ bool isRoot = !enginePriv->inBeginCreate;
+ enginePriv->inBeginCreate = true;
+
+ QmlVME vme;
+ vme.runDeferred(object);
+
+ if (vme.isError())
+ state->errors = vme.errors();
+
+ if (isRoot) {
+ enginePriv->inBeginCreate = false;
+
+ state->bindValues = enginePriv->bindValues;
+ state->parserStatus = enginePriv->parserStatus;
+ state->componentAttacheds = enginePriv->componentAttacheds;
+ if (state->componentAttacheds)
+ state->componentAttacheds->prev = &state->componentAttacheds;
+
+ enginePriv->componentAttacheds = 0;
+ enginePriv->bindValues.clear();
+ enginePriv->parserStatus.clear();
+ state->completePending = true;
+ enginePriv->inProgressCreations++;
+ }
+}
+
+void QmlComponentPrivate::complete(QmlEnginePrivate *enginePriv, ConstructionState *state)
+{
+ if (state->completePending) {
+
+ for (int ii = 0; ii < state->bindValues.count(); ++ii) {
+ QmlEnginePrivate::SimpleList<QmlAbstractBinding> bv =
+ state->bindValues.at(ii);
+ for (int jj = 0; jj < bv.count; ++jj) {
+ if(bv.at(jj))
+ bv.at(jj)->setEnabled(true, QmlMetaProperty::BypassInterceptor |
+ QmlMetaProperty::DontRemoveBinding);
+ }
+ QmlEnginePrivate::clear(bv);
+ }
+
+ for (int ii = 0; ii < state->parserStatus.count(); ++ii) {
+ QmlEnginePrivate::SimpleList<QmlParserStatus> ps =
+ state->parserStatus.at(ii);
+
+ for (int jj = ps.count - 1; jj >= 0; --jj) {
+ QmlParserStatus *status = ps.at(jj);
+ if (status && status->d) {
+ status->d = 0;
+ status->componentComplete();
+ }
+ }
+ QmlEnginePrivate::clear(ps);
+ }
+
+ while (state->componentAttacheds) {
+ QmlComponentAttached *a = state->componentAttacheds;
+ if (a->next) a->next->prev = &state->componentAttacheds;
+ state->componentAttacheds = a->next;
+ a->prev = 0; a->next = 0;
+ emit a->completed();
+ }
+
+ state->bindValues.clear();
+ state->parserStatus.clear();
+ state->completePending = false;
+
+ enginePriv->inProgressCreations--;
+ if (0 == enginePriv->inProgressCreations) {
+ while (enginePriv->erroredBindings) {
+ qWarning().nospace() << qPrintable(enginePriv->erroredBindings->error.toString());
+ enginePriv->erroredBindings->removeError();
+ }
+ }
+ }
+}
+
+/*!
+ This method provides more advanced control over component instance creation.
+ In general, programmers should use QmlComponent::create() to create a
+ component.
+
+ Complete a component creation begin with QmlComponent::beginCreate().
+*/
+void QmlComponent::completeCreate()
+{
+ Q_D(QmlComponent);
+ d->completeCreate();
+}
+
+void QmlComponentPrivate::completeCreate()
+{
+ if (state.completePending) {
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+ complete(ep, &state);
+ }
+}
+
+QmlComponentAttached::QmlComponentAttached(QObject *parent)
+: QObject(parent), prev(0), next(0)
+{
+}
+
+QmlComponentAttached::~QmlComponentAttached()
+{
+ if (prev) *prev = next;
+ if (next) next->prev = prev;
+ prev = 0;
+ next = 0;
+}
+
+/*!
+ \internal
+*/
+QmlComponentAttached *QmlComponent::qmlAttachedProperties(QObject *obj)
+{
+ QmlComponentAttached *a = new QmlComponentAttached(obj);
+
+ QmlEngine *engine = qmlEngine(obj);
+ if (!engine || !QmlEnginePrivate::get(engine)->inBeginCreate)
+ return a;
+
+ QmlEnginePrivate *p = QmlEnginePrivate::get(engine);
+
+ a->next = p->componentAttacheds;
+ a->prev = &p->componentAttacheds;
+ if (a->next) a->next->prev = &a->next;
+ p->componentAttacheds = a;
+
+ return a;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlcomponent.h b/src/declarative/qml/qmlcomponent.h
new file mode 100644
index 0000000..342f503
--- /dev/null
+++ b/src/declarative/qml/qmlcomponent.h
@@ -0,0 +1,134 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCOMPONENT_H
+#define QMLCOMPONENT_H
+
+#include "qml.h"
+#include "qmlerror.h"
+
+#include <QtCore/qobject.h>
+#include <QtCore/qstring.h>
+#include <QtScript/qscriptvalue.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlCompiledData;
+class QByteArray;
+class QmlComponentPrivate;
+class QmlEngine;
+class QmlComponentAttached;
+class Q_DECLARATIVE_EXPORT QmlComponent : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlComponent)
+ Q_PROPERTY(bool isNull READ isNull NOTIFY statusChanged)
+ Q_PROPERTY(bool isReady READ isReady NOTIFY statusChanged)
+ Q_PROPERTY(bool isError READ isError NOTIFY statusChanged)
+ Q_PROPERTY(bool isLoading READ isLoading NOTIFY statusChanged)
+ Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged)
+ Q_PROPERTY(Status status READ status NOTIFY statusChanged)
+ Q_PROPERTY(QUrl url READ url CONSTANT)
+
+public:
+ QmlComponent(QObject *parent = 0);
+ QmlComponent(QmlEngine *, QObject *parent=0);
+ QmlComponent(QmlEngine *, const QString &fileName, QObject *parent = 0);
+ QmlComponent(QmlEngine *, const QUrl &url, QObject *parent = 0);
+ virtual ~QmlComponent();
+
+ Q_ENUMS(Status)
+ enum Status { Null, Ready, Loading, Error };
+ Status status() const;
+
+ bool isNull() const;
+ bool isReady() const;
+ bool isError() const;
+ bool isLoading() const;
+
+ QList<QmlError> errors() const;
+ Q_INVOKABLE QString errorsString() const;
+
+ qreal progress() const;
+
+ QUrl url() const;
+
+ virtual QObject *create(QmlContext *context = 0);
+ virtual QObject *beginCreate(QmlContext *);
+ virtual void completeCreate();
+
+ Q_INVOKABLE QScriptValue createObject();
+
+ void loadUrl(const QUrl &url);
+ void setData(const QByteArray &, const QUrl &baseUrl);
+
+ void setCreationContext(QmlContext*);
+ QmlContext *creationContext() const;
+
+ static QmlComponentAttached *qmlAttachedProperties(QObject *);
+
+Q_SIGNALS:
+ void statusChanged(QmlComponent::Status);
+ void progressChanged(qreal);
+
+protected:
+ QmlComponent(QmlComponentPrivate &dd, QObject* parent);
+
+private:
+ QmlComponent(QmlEngine *, QmlCompiledData *, int, int, QObject *parent);
+
+ friend class QmlVME;
+ friend class QmlCompositeTypeData;
+};
+
+QT_END_NAMESPACE
+
+Q_DECLARE_METATYPE(QmlComponent::Status)
+QML_DECLARE_TYPE(QmlComponent)
+QML_DECLARE_TYPEINFO(QmlComponent, QML_HAS_ATTACHED_PROPERTIES)
+
+QT_END_HEADER
+
+#endif // QMLCOMPONENT_H
diff --git a/src/declarative/qml/qmlcomponent_p.h b/src/declarative/qml/qmlcomponent_p.h
new file mode 100644
index 0000000..4039a61
--- /dev/null
+++ b/src/declarative/qml/qmlcomponent_p.h
@@ -0,0 +1,147 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCOMPONENT_P_H
+#define QMLCOMPONENT_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 "qmlcomponent.h"
+
+#include "qmlengine_p.h"
+#include "qmlcompositetypemanager_p.h"
+#include "qbitfield_p.h"
+#include "qmlerror.h"
+#include "qml.h"
+
+#include <QtCore/QString>
+#include <QtCore/QStringList>
+#include <QtCore/QList>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlComponent;
+class QmlEngine;
+class QmlCompiledData;
+
+class QmlComponentAttached;
+class QmlComponentPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlComponent)
+
+public:
+ QmlComponentPrivate() : typeData(0), progress(0.), start(-1), count(-1), cc(0), engine(0), creationContext(0) {}
+
+ QObject *create(QmlContext *context, const QBitField &);
+ QObject *beginCreate(QmlContext *, const QBitField &);
+ void completeCreate();
+
+ QmlCompositeTypeData *typeData;
+ void typeDataReady();
+ void updateProgress(qreal);
+
+ void fromTypeData(QmlCompositeTypeData *data);
+
+ QUrl url;
+ qreal progress;
+
+ int start;
+ int count;
+ QmlCompiledData *cc;
+
+ struct ConstructionState {
+ ConstructionState() : componentAttacheds(0), completePending(false) {}
+ QList<QmlEnginePrivate::SimpleList<QmlAbstractBinding> > bindValues;
+ QList<QmlEnginePrivate::SimpleList<QmlParserStatus> > parserStatus;
+ QmlComponentAttached *componentAttacheds;
+ QList<QmlError> errors;
+ bool completePending;
+ };
+ ConstructionState state;
+
+ static QObject *begin(QmlContext *ctxt, QmlEnginePrivate *enginePriv,
+ QmlCompiledData *component, int start, int count,
+ ConstructionState *state, const QBitField &bindings = QBitField());
+ static void beginDeferred(QmlContext *ctxt, QmlEnginePrivate *enginePriv,
+ QObject *object, ConstructionState *state);
+ static void complete(QmlEnginePrivate *enginePriv, ConstructionState *state);
+
+ QmlEngine *engine;
+ QmlContext *creationContext;
+
+ void clear();
+
+ static QmlComponentPrivate *get(QmlComponent *c) {
+ return static_cast<QmlComponentPrivate *>(QObjectPrivate::get(c));
+ }
+};
+
+class QmlComponentAttached : public QObject
+{
+ Q_OBJECT
+public:
+ QmlComponentAttached(QObject *parent = 0);
+ ~QmlComponentAttached();
+
+ QmlComponentAttached **prev;
+ QmlComponentAttached *next;
+
+Q_SIGNALS:
+ void completed();
+
+private:
+ friend class QmlComponentPrivate;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLCOMPONENT_P_H
diff --git a/src/declarative/qml/qmlcompositetypedata_p.h b/src/declarative/qml/qmlcompositetypedata_p.h
new file mode 100644
index 0000000..c8b9f25
--- /dev/null
+++ b/src/declarative/qml/qmlcompositetypedata_p.h
@@ -0,0 +1,150 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCOMPOSITETYPEDATA_P_H
+#define QMLCOMPOSITETYPEDATA_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 "qmlengine_p.h"
+
+#include <QtCore/qglobal.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlCompositeTypeResource;
+class QmlCompositeTypeData : public QmlRefCount
+{
+public:
+ QmlCompositeTypeData();
+ virtual ~QmlCompositeTypeData();
+
+ enum Status {
+ Invalid,
+ Complete,
+ Error,
+ Waiting,
+ WaitingResources
+ };
+ Status status;
+ enum ErrorType {
+ NoError,
+ AccessError,
+ GeneralError
+ };
+ ErrorType errorType;
+
+ QList<QmlError> errors;
+
+ QmlEnginePrivate::Imports imports;
+
+ QList<QmlCompositeTypeData *> dependants;
+
+ // Return a QmlComponent if the QmlCompositeTypeData is not in the Waiting
+ // state. The QmlComponent is owned by the QmlCompositeTypeData, so a
+ // reference should be kept to keep the QmlComponent alive.
+ QmlComponent *toComponent(QmlEngine *);
+ // Return a QmlCompiledData if possible, or 0 if an error
+ // occurs
+ QmlCompiledData *toCompiledComponent(QmlEngine *);
+
+ struct TypeReference
+ {
+ TypeReference();
+
+ QmlType *type;
+ QmlCompositeTypeData *unit;
+ };
+
+ QList<TypeReference> types;
+ QList<QmlCompositeTypeResource *> resources;
+
+ // Add or remove p as a waiter. When the QmlCompositeTypeData becomes
+ // ready, the QmlComponentPrivate::typeDataReady() method will be invoked on
+ // p. The waiter is automatically removed when the typeDataReady() method
+ // is invoked, so there is no need to call remWaiter() in this case.
+ void addWaiter(QmlComponentPrivate *p);
+ void remWaiter(QmlComponentPrivate *p);
+
+ qreal progress;
+
+private:
+ friend class QmlCompositeTypeManager;
+ friend class QmlCompiler;
+ friend class QmlDomDocument;
+
+ QmlScriptParser data;
+ QList<QmlComponentPrivate *> waiters;
+ QmlComponent *component;
+ QmlCompiledData *compiledComponent;
+};
+
+class QmlCompositeTypeResource : public QmlRefCount
+{
+public:
+ QmlCompositeTypeResource();
+ virtual ~QmlCompositeTypeResource();
+
+ enum Status {
+ Invalid,
+ Complete,
+ Error,
+ Waiting
+ };
+ Status status;
+
+ QList<QmlCompositeTypeData *> dependants;
+
+ QString url;
+ QByteArray data;
+};
+
+#endif // QMLCOMPOSITETYPEDATA_P_H
+
diff --git a/src/declarative/qml/qmlcompositetypemanager.cpp b/src/declarative/qml/qmlcompositetypemanager.cpp
new file mode 100644
index 0000000..3504fe9
--- /dev/null
+++ b/src/declarative/qml/qmlcompositetypemanager.cpp
@@ -0,0 +1,670 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlcompositetypemanager_p.h"
+
+#include "qmlcompositetypedata_p.h"
+#include "qmlscriptparser_p.h"
+#include "qmlengine.h"
+#include "qmlengine_p.h"
+#include "qmlcomponent.h"
+#include "qmlcomponent_p.h"
+#include "qmlcompiler_p.h"
+
+#include <QtNetwork/qnetworkreply.h>
+#include <QtCore/qdebug.h>
+#include <QtCore/qfile.h>
+
+QT_BEGIN_NAMESPACE
+
+#if (QT_VERSION < QT_VERSION_CHECK(4, 7, 0))
+inline uint qHash(const QUrl &uri)
+{
+ return qHash(uri.toEncoded(QUrl::FormattingOption(0x100)));
+}
+#endif
+
+QmlCompositeTypeData::QmlCompositeTypeData()
+: status(Invalid), errorType(NoError), component(0), compiledComponent(0)
+{
+}
+
+QmlCompositeTypeData::~QmlCompositeTypeData()
+{
+ for (int ii = 0; ii < dependants.count(); ++ii)
+ dependants.at(ii)->release();
+
+ for (int ii = 0; ii < resources.count(); ++ii)
+ resources.at(ii)->release();
+
+ if (compiledComponent)
+ compiledComponent->release();
+
+ if (component)
+ delete component;
+}
+
+QmlCompositeTypeResource::QmlCompositeTypeResource()
+{
+}
+
+QmlCompositeTypeResource::~QmlCompositeTypeResource()
+{
+ for (int ii = 0; ii < dependants.count(); ++ii)
+ dependants.at(ii)->release();
+}
+
+void QmlCompositeTypeData::addWaiter(QmlComponentPrivate *p)
+{
+ waiters << p;
+}
+
+void QmlCompositeTypeData::remWaiter(QmlComponentPrivate *p)
+{
+ waiters.removeAll(p);
+}
+
+QmlComponent *QmlCompositeTypeData::toComponent(QmlEngine *engine)
+{
+ if (!component) {
+
+ QmlCompiledData *cc = toCompiledComponent(engine);
+ if (cc) {
+ component = new QmlComponent(engine, cc, -1, -1, 0);
+ cc->release();
+ } else {
+ component = new QmlComponent(engine, 0);
+ component->d_func()->url = imports.baseUrl();
+ component->d_func()->state.errors = errors;
+ }
+
+ }
+
+ return component;
+}
+
+QmlCompiledData *
+QmlCompositeTypeData::toCompiledComponent(QmlEngine *engine)
+{
+ if (status == Complete && !compiledComponent) {
+
+ compiledComponent = new QmlCompiledData(engine);
+ compiledComponent->url = imports.baseUrl();
+ compiledComponent->name = compiledComponent->url.toString();
+
+ QmlCompiler compiler;
+ if (!compiler.compile(engine, this, compiledComponent)) {
+ status = Error;
+ errors = compiler.errors();
+ compiledComponent->release();
+ compiledComponent = 0;
+ }
+
+ // Data is no longer needed once we have a compiled component
+ data.clear();
+ }
+
+ if (compiledComponent)
+ compiledComponent->addref();
+
+ return compiledComponent;
+}
+
+QmlCompositeTypeData::TypeReference::TypeReference()
+: type(0), unit(0)
+{
+}
+
+QmlCompositeTypeManager::QmlCompositeTypeManager(QmlEngine *e)
+: engine(e)
+{
+}
+
+QmlCompositeTypeManager::~QmlCompositeTypeManager()
+{
+ for (Components::Iterator iter = components.begin(); iter != components.end();) {
+ (*iter)->release();
+ iter = components.erase(iter);
+ }
+ for (Resources::Iterator iter = resources.begin(); iter != resources.end();) {
+ (*iter)->release();
+ iter = resources.erase(iter);
+ }
+}
+
+QmlCompositeTypeData *QmlCompositeTypeManager::get(const QUrl &url)
+{
+ QmlCompositeTypeData *unit = components.value(url);
+
+ if (!unit) {
+ unit = new QmlCompositeTypeData;
+ unit->status = QmlCompositeTypeData::Waiting;
+ unit->progress = 0.0;
+ unit->imports.setBaseUrl(url);
+ components.insert(url, unit);
+
+ loadSource(unit);
+ }
+
+ unit->addref();
+ return unit;
+}
+
+QmlCompositeTypeData *
+QmlCompositeTypeManager::getImmediate(const QByteArray &data, const QUrl &url)
+{
+ QmlCompositeTypeData *unit = new QmlCompositeTypeData;
+ unit->status = QmlCompositeTypeData::Waiting;
+ unit->imports.setBaseUrl(url);
+ setData(unit, data, url);
+ return unit;
+}
+
+void QmlCompositeTypeManager::clearCache()
+{
+ for (Components::Iterator iter = components.begin(); iter != components.end();) {
+ if ((*iter)->status != QmlCompositeTypeData::Waiting) {
+ (*iter)->release();
+ iter = components.erase(iter);
+ } else {
+ ++iter;
+ }
+ }
+
+ for (Resources::Iterator iter = resources.begin(); iter != resources.end();) {
+ if ((*iter)->status != QmlCompositeTypeResource::Waiting) {
+ (*iter)->release();
+ iter = resources.erase(iter);
+ } else {
+ ++iter;
+ }
+ }
+}
+
+void QmlCompositeTypeManager::replyFinished()
+{
+ QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
+
+ QmlCompositeTypeData *unit = components.value(reply->url());
+ Q_ASSERT(unit);
+
+ if (reply->error() != QNetworkReply::NoError) {
+ QString errorDescription;
+ // ### - Fill in error
+ errorDescription = QLatin1String("Network error for URL ") +
+ reply->url().toString();
+
+ unit->status = QmlCompositeTypeData::Error;
+ // ### FIXME
+ QmlError error;
+ error.setDescription(errorDescription);
+ unit->errorType = QmlCompositeTypeData::AccessError;
+ unit->errors << error;
+ doComplete(unit);
+
+ } else {
+ QByteArray data = reply->readAll();
+
+ setData(unit, data, reply->url());
+ }
+
+ reply->deleteLater();
+}
+
+void QmlCompositeTypeManager::resourceReplyFinished()
+{
+ QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
+
+ QmlCompositeTypeResource *resource = resources.value(reply->url());
+ Q_ASSERT(resource);
+
+ if (reply->error() != QNetworkReply::NoError) {
+
+ resource->status = QmlCompositeTypeResource::Error;
+
+ } else {
+
+ resource->status = QmlCompositeTypeResource::Complete;
+ resource->data = reply->readAll();
+
+ }
+
+ doComplete(resource);
+ reply->deleteLater();
+}
+
+static QString toLocalFileOrQrc(const QUrl& url)
+{
+ QString r = url.toLocalFile();
+ if (r.isEmpty() && url.scheme() == QLatin1String("qrc"))
+ r = QLatin1Char(':') + url.path();
+ return r;
+}
+
+void QmlCompositeTypeManager::loadResource(QmlCompositeTypeResource *resource)
+{
+ QUrl url(resource->url);
+
+ QString lf = toLocalFileOrQrc(url);
+ if (!lf.isEmpty()) {
+
+ QFile file(lf);
+ if (file.open(QFile::ReadOnly)) {
+ resource->data = file.readAll();
+ resource->status = QmlCompositeTypeResource::Complete;
+ } else {
+ resource->status = QmlCompositeTypeResource::Error;
+ }
+
+ } else {
+
+ QNetworkReply *reply =
+ engine->networkAccessManager()->get(QNetworkRequest(url));
+ QObject::connect(reply, SIGNAL(finished()),
+ this, SLOT(resourceReplyFinished()));
+
+ }
+}
+
+void QmlCompositeTypeManager::loadSource(QmlCompositeTypeData *unit)
+{
+ QUrl url(unit->imports.baseUrl());
+
+ QString lf = toLocalFileOrQrc(url);
+ if (!lf.isEmpty()) {
+
+ QFile file(lf);
+ if (file.open(QFile::ReadOnly)) {
+ QByteArray data = file.readAll();
+ setData(unit, data, url);
+ } else {
+ QString errorDescription;
+ // ### - Fill in error
+ errorDescription = QLatin1String("File error for URL ") + url.toString();
+ unit->status = QmlCompositeTypeData::Error;
+ // ### FIXME
+ QmlError error;
+ error.setDescription(errorDescription);
+ unit->errorType = QmlCompositeTypeData::AccessError;
+ unit->errors << error;
+ doComplete(unit);
+ }
+
+ } else {
+ QNetworkReply *reply =
+ engine->networkAccessManager()->get(QNetworkRequest(url));
+ QObject::connect(reply, SIGNAL(finished()),
+ this, SLOT(replyFinished()));
+ QObject::connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
+ this, SLOT(requestProgress(qint64,qint64)));
+ }
+}
+
+void QmlCompositeTypeManager::requestProgress(qint64 received, qint64 total)
+{
+ if (total <= 0)
+ return;
+ QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
+
+ QmlCompositeTypeData *unit = components.value(reply->url());
+ Q_ASSERT(unit);
+
+ unit->progress = qreal(received)/total;
+
+ foreach (QmlComponentPrivate *comp, unit->waiters)
+ comp->updateProgress(unit->progress);
+}
+
+void QmlCompositeTypeManager::setData(QmlCompositeTypeData *unit,
+ const QByteArray &data,
+ const QUrl &url)
+{
+ bool ok = true;
+ if (!unit->data.parse(data, url)) {
+ ok = false;
+ unit->errors << unit->data.errors();
+ }
+
+ if (ok) {
+ compile(unit);
+ } else {
+ unit->status = QmlCompositeTypeData::Error;
+ unit->errorType = QmlCompositeTypeData::GeneralError;
+ doComplete(unit);
+ }
+}
+
+void QmlCompositeTypeManager::doComplete(QmlCompositeTypeData *unit)
+{
+ for (int ii = 0; ii < unit->dependants.count(); ++ii) {
+ checkComplete(unit->dependants.at(ii));
+ unit->dependants.at(ii)->release();
+ }
+ unit->dependants.clear();
+
+ while(!unit->waiters.isEmpty()) {
+ QmlComponentPrivate *p = unit->waiters.takeFirst();
+ p->typeDataReady();
+ }
+}
+
+void QmlCompositeTypeManager::doComplete(QmlCompositeTypeResource *resource)
+{
+ for (int ii = 0; ii < resource->dependants.count(); ++ii) {
+ checkComplete(resource->dependants.at(ii));
+ resource->dependants.at(ii)->release();
+ }
+ resource->dependants.clear();
+}
+
+void QmlCompositeTypeManager::checkComplete(QmlCompositeTypeData *unit)
+{
+ if (unit->status != QmlCompositeTypeData::Waiting
+ && unit->status != QmlCompositeTypeData::WaitingResources)
+ return;
+
+ int waiting = 0;
+ for (int ii = 0; ii < unit->resources.count(); ++ii) {
+ QmlCompositeTypeResource *r = unit->resources.at(ii);
+
+ if (!r)
+ continue;
+
+ if (r->status == QmlCompositeTypeResource::Error) {
+ unit->status = QmlCompositeTypeData::Error;
+ QmlError error;
+ error.setUrl(unit->imports.baseUrl());
+ error.setDescription(tr("Resource %1 unavailable").arg(r->url));
+ unit->errors << error;
+ doComplete(unit);
+ return;
+ } else if (r->status == QmlCompositeTypeResource::Waiting) {
+ waiting++;
+ }
+ }
+
+ if (waiting == 0) {
+ if (unit->status == QmlCompositeTypeData::WaitingResources) {
+ waiting += resolveTypes(unit);
+ if (unit->status != QmlCompositeTypeData::Error) {
+ if (waiting)
+ unit->status = QmlCompositeTypeData::Waiting;
+ } else {
+ return;
+ }
+ } else {
+ for (int ii = 0; ii < unit->types.count(); ++ii) {
+ QmlCompositeTypeData *u = unit->types.at(ii).unit;
+
+ if (!u)
+ continue;
+
+ if (u->status == QmlCompositeTypeData::Error) {
+ unit->status = QmlCompositeTypeData::Error;
+ unit->errors = u->errors;
+ doComplete(unit);
+ return;
+ } else if (u->status == QmlCompositeTypeData::Waiting) {
+ waiting++;
+ }
+ }
+ }
+ }
+
+ if (!waiting) {
+ unit->status = QmlCompositeTypeData::Complete;
+ doComplete(unit);
+ }
+}
+
+int QmlCompositeTypeManager::resolveTypes(QmlCompositeTypeData *unit)
+{
+ // not called until all resources are loaded (they include import URLs)
+
+ int waiting = 0;
+
+ foreach (QmlScriptParser::Import imp, unit->data.imports()) {
+ QString qmldir;
+ if (imp.type == QmlScriptParser::Import::File && imp.qualifier.isEmpty()) {
+ QString importUrl = unit->imports.baseUrl().resolved(QUrl(imp.uri + QLatin1String("/qmldir"))).toString();
+ for (int ii = 0; ii < unit->resources.count(); ++ii) {
+ if (unit->resources.at(ii)->url == importUrl) {
+ qmldir = QString::fromUtf8(unit->resources.at(ii)->data);
+ break;
+ }
+ }
+ }
+
+ int vmaj = -1;
+ int vmin = -1;
+ if (!imp.version.isEmpty()) {
+ int dot = imp.version.indexOf(QLatin1Char('.'));
+ if (dot < 0) {
+ vmaj = imp.version.toInt();
+ vmin = 0;
+ } else {
+ vmaj = imp.version.left(dot).toInt();
+ vmin = imp.version.mid(dot+1).toInt();
+ }
+ }
+
+ if (!QmlEnginePrivate::get(engine)->
+ addToImport(&unit->imports, qmldir, imp.uri, imp.qualifier, vmaj, vmin, imp.type))
+ {
+ QmlError error;
+ error.setUrl(unit->imports.baseUrl());
+ error.setDescription(tr("Import %1 unavailable").arg(imp.uri));
+ unit->status = QmlCompositeTypeData::Error;
+ unit->errorType = QmlCompositeTypeData::GeneralError;
+ unit->errors << error;
+ doComplete(unit);
+ return 0;
+ }
+ }
+
+ QList<QmlScriptParser::TypeReference*> types = unit->data.referencedTypes();
+
+ for (int ii = 0; ii < types.count(); ++ii) {
+ QmlScriptParser::TypeReference *parserRef = types.at(ii);
+ QByteArray typeName = parserRef->name.toUtf8();
+
+ QmlCompositeTypeData::TypeReference ref;
+
+ QUrl url;
+ int majorVersion;
+ int minorVersion;
+ QmlEnginePrivate::ImportedNamespace *typeNamespace = 0;
+ if (!QmlEnginePrivate::get(engine)->resolveType(unit->imports, typeName, &ref.type, &url, &majorVersion, &minorVersion, &typeNamespace)
+ || typeNamespace)
+ {
+ // Known to not be a type:
+ // - known to be a namespace (Namespace {})
+ // - type with unknown namespace (UnknownNamespace.SomeType {})
+ QmlError error;
+ error.setUrl(unit->imports.baseUrl());
+ if (typeNamespace)
+ error.setDescription(tr("Namespace %1 cannot be used as a type").arg(QString::fromUtf8(typeName)));
+ else
+ error.setDescription(tr("%1 is not a type").arg(QString::fromUtf8(typeName)));
+ if (!parserRef->refObjects.isEmpty()) {
+ QmlParser::Object *obj = parserRef->refObjects.first();
+ error.setLine(obj->location.start.line);
+ error.setColumn(obj->location.start.column);
+ }
+ unit->status = QmlCompositeTypeData::Error;
+ unit->errorType = QmlCompositeTypeData::GeneralError;
+ unit->errors << error;
+ doComplete(unit);
+ return 0;
+ }
+
+ if (ref.type) {
+ foreach (QmlParser::Object *obj, parserRef->refObjects) {
+ // store namespace for DOM
+ obj->majorVersion = majorVersion;
+ obj->minorVersion = minorVersion;
+ }
+ unit->types << ref;
+ continue;
+ }
+
+ QmlCompositeTypeData *urlUnit = components.value(url);
+
+ if (!urlUnit) {
+ urlUnit = new QmlCompositeTypeData;
+ urlUnit->status = QmlCompositeTypeData::Waiting;
+ urlUnit->imports.setBaseUrl(url);
+ components.insert(url, urlUnit);
+
+ loadSource(urlUnit);
+ }
+
+ ref.unit = urlUnit;
+ switch(urlUnit->status) {
+ case QmlCompositeTypeData::Invalid:
+ case QmlCompositeTypeData::Error:
+ unit->status = QmlCompositeTypeData::Error;
+ {
+ QmlError error;
+ error.setUrl(unit->imports.baseUrl());
+ error.setDescription(tr("Type %1 unavailable").arg(QString::fromUtf8(typeName)));
+ if (!parserRef->refObjects.isEmpty()) {
+ QmlParser::Object *obj = parserRef->refObjects.first();
+ error.setLine(obj->location.start.line);
+ error.setColumn(obj->location.start.column);
+ }
+ unit->errors << error;
+ }
+ if (urlUnit->errorType != QmlCompositeTypeData::AccessError)
+ unit->errors << urlUnit->errors;
+ doComplete(unit);
+ return 0;
+
+ case QmlCompositeTypeData::Complete:
+ break;
+
+ case QmlCompositeTypeData::Waiting:
+ case QmlCompositeTypeData::WaitingResources:
+ unit->addref();
+ ref.unit->dependants << unit;
+ waiting++;
+ break;
+ }
+
+ unit->types << ref;
+ }
+ return waiting;
+}
+
+// ### Check ref counting in here
+void QmlCompositeTypeManager::compile(QmlCompositeTypeData *unit)
+{
+ int waiting = 0;
+
+ QList<QUrl> resourceList = unit->data.referencedResources();
+
+ foreach (QmlScriptParser::Import imp, unit->data.imports()) {
+ if (imp.type == QmlScriptParser::Import::File && imp.qualifier.isEmpty()) {
+ QUrl importUrl = unit->imports.baseUrl().resolved(QUrl(imp.uri + QLatin1String("/qmldir")));
+ if (toLocalFileOrQrc(importUrl).isEmpty()) {
+ // Import requires remote qmldir
+ resourceList.prepend(importUrl);
+ }
+ }
+ }
+
+ for (int ii = 0; ii < resourceList.count(); ++ii) {
+ QUrl url = unit->imports.baseUrl().resolved(resourceList.at(ii));
+
+ QmlCompositeTypeResource *resource = resources.value(url);
+
+ if (!resource) {
+ resource = new QmlCompositeTypeResource;
+ resource->status = QmlCompositeTypeResource::Waiting;
+ resource->url = url.toString();
+ resources.insert(url, resource);
+
+ loadResource(resource);
+ }
+
+ switch(resource->status) {
+ case QmlCompositeTypeResource::Invalid:
+ case QmlCompositeTypeResource::Error:
+ unit->status = QmlCompositeTypeData::Error;
+ {
+ QmlError error;
+ error.setUrl(unit->imports.baseUrl());
+ error.setDescription(tr("Resource %1 unavailable").arg(resource->url));
+ unit->errors << error;
+ }
+ doComplete(unit);
+ return;
+
+ case QmlCompositeTypeData::Complete:
+ break;
+
+ case QmlCompositeTypeData::Waiting:
+ unit->addref();
+ resource->dependants << unit;
+ waiting++;
+ break;
+ }
+
+ resource->addref();
+ unit->resources << resource;
+ }
+
+ if (waiting == 0) {
+ waiting += resolveTypes(unit);
+ if (unit->status != QmlCompositeTypeData::Error) {
+ if (!waiting) {
+ unit->status = QmlCompositeTypeData::Complete;
+ doComplete(unit);
+ } else {
+ unit->status = QmlCompositeTypeData::Waiting;
+ }
+ }
+ } else {
+ unit->status = QmlCompositeTypeData::WaitingResources;
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlcompositetypemanager_p.h b/src/declarative/qml/qmlcompositetypemanager_p.h
new file mode 100644
index 0000000..89e2353
--- /dev/null
+++ b/src/declarative/qml/qmlcompositetypemanager_p.h
@@ -0,0 +1,117 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCOMPOSITETYPEMANAGER_P_H
+#define QMLCOMPOSITETYPEMANAGER_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 "qmlscriptparser_p.h"
+#include "qmlrefcount_p.h"
+#include "qmlerror.h"
+#include "qmlengine.h"
+
+#include <QtCore/qglobal.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlCompiledData;
+class QmlComponentPrivate;
+class QmlComponent;
+class QmlDomDocument;
+
+class QmlCompositeTypeData;
+class QmlCompositeTypeResource;
+
+class QmlCompositeTypeManager : public QObject
+{
+ Q_OBJECT
+public:
+ QmlCompositeTypeManager(QmlEngine *);
+ ~QmlCompositeTypeManager();
+
+ // Return a QmlCompositeTypeData for url. The QmlCompositeTypeData may be
+ // cached.
+ QmlCompositeTypeData *get(const QUrl &url);
+ // Return a QmlCompositeTypeData for data, with the provided base url. The
+ // QmlCompositeTypeData will not be cached.
+ QmlCompositeTypeData *getImmediate(const QByteArray &data, const QUrl &url);
+
+ // Clear cached types. Only types that aren't in the Waiting state will
+ // be cleared.
+ void clearCache();
+
+private Q_SLOTS:
+ void replyFinished();
+ void resourceReplyFinished();
+ void requestProgress(qint64 received, qint64 total);
+
+private:
+ void loadSource(QmlCompositeTypeData *);
+ void loadResource(QmlCompositeTypeResource *);
+ void compile(QmlCompositeTypeData *);
+ void setData(QmlCompositeTypeData *, const QByteArray &, const QUrl &);
+
+ void doComplete(QmlCompositeTypeData *);
+ void doComplete(QmlCompositeTypeResource *);
+ void checkComplete(QmlCompositeTypeData *);
+ int resolveTypes(QmlCompositeTypeData *);
+
+ QmlEngine *engine;
+ typedef QHash<QUrl, QmlCompositeTypeData *> Components;
+ Components components;
+ typedef QHash<QUrl, QmlCompositeTypeResource *> Resources;
+ Resources resources;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLCOMPOSITETYPEMANAGER_P_H
+
diff --git a/src/declarative/qml/qmlcontext.cpp b/src/declarative/qml/qmlcontext.cpp
new file mode 100644
index 0000000..d9fc76b
--- /dev/null
+++ b/src/declarative/qml/qmlcontext.cpp
@@ -0,0 +1,544 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlcontext.h"
+#include "qmlcontext_p.h"
+
+#include "qmlexpression_p.h"
+#include "qmlengine_p.h"
+#include "qmlengine.h"
+#include "qmlcompiledbindings_p.h"
+#include "qmlinfo.h"
+
+#include <qscriptengine.h>
+#include <QtCore/qvarlengtharray.h>
+#include <QtCore/qdebug.h>
+
+#include <private/qscriptdeclarativeclass_p.h>
+
+QT_BEGIN_NAMESPACE
+
+QmlContextPrivate::QmlContextPrivate()
+: parent(0), engine(0), isInternal(false), propertyNames(0),
+ notifyIndex(-1), highPriorityCount(0), imports(0), expressions(0), contextObjects(0),
+ idValues(0), idValueCount(0), optimizedBindings(0)
+{
+}
+
+void QmlContextPrivate::addScript(const QmlParser::Object::ScriptBlock &script, QObject *scopeObject)
+{
+ Q_Q(QmlContext);
+
+ if (!engine)
+ return;
+
+ QmlEnginePrivate *enginePriv = QmlEnginePrivate::get(engine);
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ QScriptContext *scriptContext = QScriptDeclarativeClass::pushCleanContext(scriptEngine);
+ scriptContext->pushScope(enginePriv->contextClass->newContext(q, scopeObject));
+
+ QScriptValue scope = scriptEngine->newObject();
+ scriptContext->setActivationObject(scope);
+
+ for (int ii = 0; ii < script.codes.count(); ++ii) {
+ scriptEngine->evaluate(script.codes.at(ii), script.files.at(ii), script.lineNumbers.at(ii));
+
+ if (scriptEngine->hasUncaughtException()) {
+ QmlError error;
+ QmlExpressionPrivate::exceptionToError(scriptEngine, error);
+ qWarning().nospace() << qPrintable(error.toString());
+ }
+ }
+
+ scriptEngine->popContext();
+
+ scripts.append(scope);
+}
+
+void QmlContextPrivate::destroyed(ContextGuard *guard)
+{
+ Q_Q(QmlContext);
+
+ // process of being deleted (which is *probably* why obj has been destroyed
+ // anyway), as we're about to get deleted which will invalidate all the
+ // expressions that could depend on us
+ QObject *parent = q->parent();
+ if (parent && QObjectPrivate::get(parent)->wasDeleted)
+ return;
+
+ while(guard->bindings) {
+ QObject *o = guard->bindings->target;
+ int mi = guard->bindings->methodIndex;
+ guard->bindings->clear();
+ if (o) o->qt_metacall(QMetaObject::InvokeMetaMethod, mi, 0);
+ }
+
+ for (int ii = 0; ii < idValueCount; ++ii) {
+ if (&idValues[ii] == guard) {
+ QMetaObject::activate(q, ii + notifyIndex, 0);
+ return;
+ }
+ }
+}
+
+void QmlContextPrivate::init()
+{
+ Q_Q(QmlContext);
+
+ if (parent)
+ parent->d_func()->childContexts.insert(q);
+}
+
+/*!
+ \class QmlContext
+ \brief The QmlContext class defines a context within a QML engine.
+ \mainclass
+
+ Contexts allow data to be exposed to the QML components instantiated by the
+ QML engine.
+
+ Each QmlContext contains a set of properties, distinct from
+ its QObject properties, that allow data to be
+ explicitly bound to a context by name. The context properties are defined or
+ updated by calling QmlContext::setContextProperty(). The following example shows
+ a Qt model being bound to a context and then accessed from a QML file.
+
+ \code
+ QmlEngine engine;
+ QmlContext context(engine.rootContext());
+ context.setContextProperty("myModel", modelData);
+
+ QmlComponent component(&engine, "ListView { model=myModel }");
+ component.create(&context);
+ \endcode
+
+ To simplify binding and maintaining larger data sets, QObject's can be
+ added to a QmlContext. These objects are known as the context's default
+ objects. In this case all the properties of the QObject are
+ made available by name in the context, as though they were all individually
+ added by calling QmlContext::setContextProperty(). Changes to the property's
+ values are detected through the property's notify signal. This method is
+ also slightly more faster than manually adding property values.
+
+ The following example has the same effect as the one above, but it is
+ achieved using a default object.
+
+ \code
+ class MyDataSet : ... {
+ ...
+ Q_PROPERTY(QAbstractItemModel *myModel READ model NOTIFY modelChanged)
+ ...
+ };
+
+ MyDataSet myDataSet;
+ QmlEngine engine;
+ QmlContext context(engine.rootContext());
+ context.addDefaultObject(&myDataSet);
+
+ QmlComponent component(&engine, "ListView { model=myModel }");
+ component.create(&context);
+ \endcode
+
+ Default objects added first take precedence over those added later. All properties
+ added explicitly by QmlContext::setContextProperty() take precedence over default
+ object properties.
+
+ Contexts are hierarchal, with the \l {QmlEngine::rootContext()}{root context}
+ being created by the QmlEngine. A component instantiated in a given context
+ has access to that context's data, as well as the data defined by its
+ ancestor contexts. Data values (including those added implicitly by the
+ default objects) in a context override those in ancestor contexts. Data
+ that should be available to all components instantiated by the QmlEngine
+ should be added to the \l {QmlEngine::rootContext()}{root context}.
+
+ In the following example,
+
+ \code
+ QmlEngine engine;
+ QmlContext context1(engine.rootContext());
+ QmlContext context2(&context1);
+ QmlContext context3(&context2);
+
+ context1.setContextProperty("a", 12);
+ context2.setContextProperty("b", 13);
+ context3.setContextProperty("a", 14);
+ context3.setContextProperty("c", 14);
+ \endcode
+
+ a QML component instantiated in context1 would have access to the "a" data,
+ a QML component instantiated in context2 would have access to the "a" and
+ "b" data, and a QML component instantiated in context3 would have access to
+ the "a", "b" and "c" data - although its "a" data would return 14, unlike
+ that in context1 or context2.
+*/
+
+/*! \internal */
+QmlContext::QmlContext(QmlEngine *e, bool)
+: QObject(*(new QmlContextPrivate))
+{
+ Q_D(QmlContext);
+ d->engine = e;
+ d->init();
+}
+
+/*!
+ Create a new QmlContext as a child of \a engine's root context, and the
+ QObject \a parent.
+*/
+QmlContext::QmlContext(QmlEngine *engine, QObject *parent)
+: QObject(*(new QmlContextPrivate), parent)
+{
+ Q_D(QmlContext);
+ QmlContext *parentContext = engine?engine->rootContext():0;
+ d->parent = parentContext;
+ d->engine = parentContext->engine();
+ d->init();
+}
+
+/*!
+ Create a new QmlContext with the given \a parentContext, and the
+ QObject \a parent.
+*/
+QmlContext::QmlContext(QmlContext *parentContext, QObject *parent)
+: QObject(*(new QmlContextPrivate), parent)
+{
+ Q_D(QmlContext);
+ d->parent = parentContext;
+ d->engine = parentContext->engine();
+ d->init();
+}
+
+/*!
+ \internal
+*/
+QmlContext::QmlContext(QmlContext *parentContext, QObject *parent, bool)
+: QObject(*(new QmlContextPrivate), parent)
+{
+ Q_D(QmlContext);
+ d->parent = parentContext;
+ d->engine = parentContext->engine();
+ d->isInternal = true;
+ d->init();
+}
+
+/*!
+ Destroys the QmlContext.
+
+ Any expressions, or sub-contexts dependent on this context will be
+ invalidated, but not destroyed (unless they are parented to the QmlContext
+ object).
+ */
+QmlContext::~QmlContext()
+{
+ Q_D(QmlContext);
+ if (d->parent)
+ d->parent->d_func()->childContexts.remove(this);
+
+ for (QSet<QmlContext *>::ConstIterator iter = d->childContexts.begin();
+ iter != d->childContexts.end();
+ ++iter) {
+ (*iter)->d_func()->invalidateEngines();
+ (*iter)->d_func()->parent = 0;
+ }
+
+ QmlAbstractExpression *expression = d->expressions;
+ while (expression) {
+ QmlAbstractExpression *nextExpression = expression->m_nextExpression;
+
+ expression->m_context = 0;
+ expression->m_prevExpression = 0;
+ expression->m_nextExpression = 0;
+
+ expression = nextExpression;
+ }
+
+ while (d->contextObjects) {
+ QmlDeclarativeData *co = d->contextObjects;
+ d->contextObjects = d->contextObjects->nextContextObject;
+
+ co->context = 0;
+ co->nextContextObject = 0;
+ co->prevContextObject = 0;
+ }
+
+ delete [] d->idValues;
+
+ if (d->propertyNames)
+ d->propertyNames->release();
+
+ if (d->imports)
+ d->imports->release();
+
+ if (d->optimizedBindings)
+ d->optimizedBindings->release();
+}
+
+void QmlContextPrivate::invalidateEngines()
+{
+ if (!engine)
+ return;
+ engine = 0;
+ for (QSet<QmlContext *>::ConstIterator iter = childContexts.begin();
+ iter != childContexts.end();
+ ++iter) {
+ (*iter)->d_func()->invalidateEngines();
+ }
+}
+
+/*
+Refreshes all expressions that could possibly depend on this context.
+Refreshing flushes all context-tree dependent caches in the expressions, and should occur every
+time the context tree *structure* (not values) changes.
+*/
+void QmlContextPrivate::refreshExpressions()
+{
+ for (QSet<QmlContext *>::ConstIterator iter = childContexts.begin();
+ iter != childContexts.end();
+ ++iter) {
+ (*iter)->d_func()->refreshExpressions();
+ }
+
+ QmlAbstractExpression *expression = expressions;
+ while (expression) {
+ expression->refresh();
+ expression = expression->m_nextExpression;
+ }
+}
+
+/*!
+ Return the context's QmlEngine, or 0 if the context has no QmlEngine or the
+ QmlEngine was destroyed.
+*/
+QmlEngine *QmlContext::engine() const
+{
+ Q_D(const QmlContext);
+ return d->engine;
+}
+
+/*!
+ Return the context's parent QmlContext, or 0 if this context has no
+ parent or if the parent has been destroyed.
+*/
+QmlContext *QmlContext::parentContext() const
+{
+ Q_D(const QmlContext);
+ return d->parent;
+}
+
+/*!
+ Add \a defaultObject to this context. The object will be added after
+ any existing default objects.
+*/
+void QmlContext::addDefaultObject(QObject *defaultObject)
+{
+ Q_D(QmlContext);
+ d->defaultObjects.prepend(defaultObject);
+}
+
+/*!
+ Set a the \a value of the \a name property on this context.
+*/
+void QmlContext::setContextProperty(const QString &name, const QVariant &value)
+{
+ Q_D(QmlContext);
+ if (d->notifyIndex == -1)
+ d->notifyIndex = this->metaObject()->methodCount();
+
+ if (d->engine) {
+ bool ok;
+ QObject *o = QmlEnginePrivate::get(d->engine)->toQObject(value, &ok);
+ if (ok) {
+ setContextProperty(name, o);
+ return;
+ }
+ }
+
+ if (!d->propertyNames) d->propertyNames = new QmlIntegerCache(d->engine);
+
+ int idx = d->propertyNames->value(name);
+ if (idx == -1) {
+ d->propertyNames->add(name, d->idValueCount + d->propertyValues.count());
+ d->propertyValues.append(value);
+
+ d->refreshExpressions();
+ } else {
+ d->propertyValues[idx] = value;
+ QMetaObject::activate(this, idx + d->notifyIndex, 0);
+ }
+}
+
+void QmlContextPrivate::setIdProperty(int idx, QObject *obj)
+{
+ if (notifyIndex == -1) {
+ Q_Q(QmlContext);
+ notifyIndex = q->metaObject()->methodCount();
+ }
+
+ idValues[idx].priv = this;
+ idValues[idx] = obj;
+}
+
+void QmlContextPrivate::setIdPropertyData(QmlIntegerCache *data)
+{
+ Q_ASSERT(!propertyNames);
+ propertyNames = data;
+ propertyNames->addref();
+
+ idValueCount = data->count();
+ idValues = new ContextGuard[idValueCount];
+}
+
+/*!
+ Set a the \a value of the \a name property on this context.
+
+ QmlContext does \bold not take ownership of \a value.
+*/
+void QmlContext::setContextProperty(const QString &name, QObject *value)
+{
+ Q_D(QmlContext);
+ if (d->notifyIndex == -1)
+ d->notifyIndex = this->metaObject()->methodCount();
+
+ if (!d->propertyNames) d->propertyNames = new QmlIntegerCache(d->engine);
+ int idx = d->propertyNames->value(name);
+
+ if (idx == -1) {
+ d->propertyNames->add(name, d->idValueCount + d->propertyValues.count());
+ d->propertyValues.append(QVariant::fromValue(value));
+
+ d->refreshExpressions();
+ } else {
+ d->propertyValues[idx] = QVariant::fromValue(value);
+ QMetaObject::activate(this, idx + d->notifyIndex, 0);
+ }
+}
+
+QVariant QmlContext::contextProperty(const QString &name) const
+{
+ Q_D(const QmlContext);
+ QVariant value;
+ int idx = -1;
+ if (d->propertyNames)
+ idx = d->propertyNames->value(name);
+
+ if (idx == -1) {
+ QByteArray utf8Name = name.toUtf8();
+ for (int ii = d->defaultObjects.count() - 1; ii >= 0; --ii) {
+ QObject *obj = d->defaultObjects.at(ii);
+ QmlPropertyCache::Data local;
+ QmlPropertyCache::Data *property = QmlPropertyCache::property(d->engine, obj, name, local);
+
+ if (property) {
+ value = obj->metaObject()->property(property->coreIndex).read(obj);
+ break;
+ }
+ }
+ if (!value.isValid() && parentContext())
+ value = parentContext()->contextProperty(name);
+ } else {
+ value = d->propertyValues[idx];
+ }
+
+ return value;
+}
+
+/*!
+ Resolves the URL \a src relative to the URL of the
+ containing component.
+
+ \sa QmlEngine::baseUrl(), setBaseUrl()
+*/
+QUrl QmlContext::resolvedUrl(const QUrl &src)
+{
+ Q_D(QmlContext);
+ QmlContext *ctxt = this;
+ if (src.isRelative() && !src.isEmpty()) {
+ if (ctxt) {
+ while(ctxt) {
+ if(ctxt->d_func()->url.isValid())
+ break;
+ else
+ ctxt = ctxt->parentContext();
+ }
+
+ if (ctxt)
+ return ctxt->d_func()->url.resolved(src);
+ else if (d->engine)
+ return d->engine->baseUrl().resolved(src);
+ }
+ return QUrl();
+ } else {
+ return src;
+ }
+}
+
+/*!
+ Explicitly sets the url resolvedUrl() will use for relative references to \a baseUrl.
+
+ Calling this function will override the url of the containing
+ component used by default.
+
+ \sa resolvedUrl()
+*/
+void QmlContext::setBaseUrl(const QUrl &baseUrl)
+{
+ d_func()->url = baseUrl;
+}
+
+/*!
+ Returns the base url of the component, or the containing component
+ if none is set.
+*/
+QUrl QmlContext::baseUrl() const
+{
+ const QmlContext* p = this;
+ while (p && p->d_func()->url.isEmpty()) {
+ p = p->parentContext();
+ }
+ if (p)
+ return p->d_func()->url;
+ else
+ return QUrl();
+}
+
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlcontext.h b/src/declarative/qml/qmlcontext.h
new file mode 100644
index 0000000..bf389a0
--- /dev/null
+++ b/src/declarative/qml/qmlcontext.h
@@ -0,0 +1,105 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCONTEXT_H
+#define QMLCONTEXT_H
+
+#include <QtCore/qurl.h>
+#include <QtCore/qobject.h>
+#include <QtScript/qscriptvalue.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QString;
+class QmlEngine;
+class QmlRefCount;
+class QmlContextPrivate;
+class QmlCompositeTypeData;
+
+class Q_DECLARATIVE_EXPORT QmlContext : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlContext)
+
+public:
+ QmlContext(QmlEngine *parent, QObject *objParent=0);
+ QmlContext(QmlContext *parent, QObject *objParent=0);
+ virtual ~QmlContext();
+
+ QmlEngine *engine() const;
+ QmlContext *parentContext() const;
+
+ void addDefaultObject(QObject *);
+ void setContextProperty(const QString &, QObject *);
+ void setContextProperty(const QString &, const QVariant &);
+
+ QVariant contextProperty(const QString &) const;
+
+ QUrl resolvedUrl(const QUrl &);
+
+ void setBaseUrl(const QUrl &);
+ QUrl baseUrl() const;
+
+private:
+ friend class QmlVME;
+ friend class QmlEngine;
+ friend class QmlEnginePrivate;
+ friend class QmlExpression;
+ friend class QmlExpressionPrivate;
+ friend class QmlContextScriptClass;
+ friend class QmlObjectScriptClass;
+ friend class QmlComponent;
+ friend class QmlComponentPrivate;
+ friend class QmlScriptPrivate;
+ friend class QmlBoundSignalProxy;
+ QmlContext(QmlContext *parent, QObject *objParent, bool);
+ QmlContext(QmlEngine *, bool);
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLCONTEXT_H
diff --git a/src/declarative/qml/qmlcontext_p.h b/src/declarative/qml/qmlcontext_p.h
new file mode 100644
index 0000000..cd7e1b6
--- /dev/null
+++ b/src/declarative/qml/qmlcontext_p.h
@@ -0,0 +1,192 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCONTEXT_P_H
+#define QMLCONTEXT_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 "qmlcontext.h"
+
+#include "qmldeclarativedata_p.h"
+#include "qmlengine_p.h"
+#include "qmlintegercache_p.h"
+#include "qmltypenamecache_p.h"
+
+#include <QtCore/qhash.h>
+#include <QtScript/qscriptvalue.h>
+#include <QtCore/qset.h>
+
+#include <private/qobject_p.h>
+#include "qmlguard_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlContext;
+class QmlExpression;
+class QmlEngine;
+class QmlExpression;
+class QmlExpressionPrivate;
+class QmlAbstractExpression;
+class QmlBinding_Id;
+class QmlCompiledBindings;
+
+class Q_DECLARATIVE_EXPORT QmlContextPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlContext)
+public:
+ QmlContextPrivate();
+
+ QmlContext *parent;
+ QmlEngine *engine;
+
+ bool isInternal;
+
+ QmlIntegerCache *propertyNames;
+ QList<QVariant> propertyValues;
+ int notifyIndex;
+
+ QObjectList defaultObjects;
+ int highPriorityCount;
+
+ QList<QScriptValue> scripts;
+ void addScript(const QmlParser::Object::ScriptBlock &, QObject *);
+
+ QUrl url;
+
+ QmlTypeNameCache *imports;
+
+ void init();
+
+ void invalidateEngines();
+ void refreshExpressions();
+ QSet<QmlContext *> childContexts;
+
+ QmlAbstractExpression *expressions;
+
+ QmlDeclarativeData *contextObjects;
+
+ struct IdNotifier
+ {
+ inline IdNotifier();
+ inline ~IdNotifier();
+
+ inline void clear();
+
+ IdNotifier *next;
+ IdNotifier**prev;
+ QObject *target;
+ int methodIndex;
+ };
+
+ struct ContextGuard : public QmlGuard<QObject>
+ {
+ inline ContextGuard();
+ inline ContextGuard &operator=(QObject *obj);
+ inline virtual void objectDestroyed(QObject *);
+
+ QmlContextPrivate *priv;
+ IdNotifier *bindings;
+ };
+ ContextGuard *idValues;
+ int idValueCount;
+ void setIdProperty(int, QObject *);
+ void setIdPropertyData(QmlIntegerCache *);
+ void destroyed(ContextGuard *);
+
+ static QmlContextPrivate *get(QmlContext *context) {
+ return static_cast<QmlContextPrivate *>(QObjectPrivate::get(context));
+ }
+ static QmlContext *get(QmlContextPrivate *context) {
+ return static_cast<QmlContext *>(context->q_func());
+ }
+
+ QmlCompiledBindings *optimizedBindings;
+
+ // Only used for debugging
+ QList<QPointer<QObject> > instances;
+};
+
+QmlContextPrivate::IdNotifier::IdNotifier()
+: next(0), prev(0), target(0), methodIndex(-1)
+{
+}
+
+QmlContextPrivate::IdNotifier::~IdNotifier()
+{
+ clear();
+}
+
+void QmlContextPrivate::IdNotifier::clear()
+{
+ if (next) next->prev = prev;
+ if (prev) *prev = next;
+ next = 0; prev = 0; target = 0;
+ methodIndex = -1;
+}
+
+QmlContextPrivate::ContextGuard::ContextGuard()
+: priv(0), bindings(0)
+{
+}
+
+QmlContextPrivate::ContextGuard &QmlContextPrivate::ContextGuard::operator=(QObject *obj)
+{
+ (QmlGuard<QObject>&)*this = obj; return *this;
+}
+
+void QmlContextPrivate::ContextGuard::objectDestroyed(QObject *)
+{
+ priv->destroyed(this);
+}
+
+QT_END_NAMESPACE
+
+#endif // QMLCONTEXT_P_H
diff --git a/src/declarative/qml/qmlcontextscriptclass.cpp b/src/declarative/qml/qmlcontextscriptclass.cpp
new file mode 100644
index 0000000..80d52ad
--- /dev/null
+++ b/src/declarative/qml/qmlcontextscriptclass.cpp
@@ -0,0 +1,270 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlcontextscriptclass_p.h"
+
+#include "qmlengine_p.h"
+#include "qmlcontext_p.h"
+#include "qmltypenamescriptclass_p.h"
+#include "qmlguard_p.h"
+
+QT_BEGIN_NAMESPACE
+
+struct ContextData : public QScriptDeclarativeClass::Object {
+ ContextData() : isSharedContext(true) {}
+ ContextData(QmlContext *c, QObject *o) : context(c), scopeObject(o), isSharedContext(false) {}
+ QmlGuard<QmlContext> context;
+ QmlGuard<QObject> scopeObject;
+ bool isSharedContext;
+
+ QmlContext *getContext(QmlEngine *engine) {
+ if (isSharedContext) {
+ return QmlEnginePrivate::get(engine)->sharedContext;
+ } else {
+ return context.data();
+ }
+ }
+
+ QObject *getScope(QmlEngine *engine) {
+ if (isSharedContext) {
+ return QmlEnginePrivate::get(engine)->sharedScope;
+ } else {
+ return scopeObject.data();
+ }
+ }
+};
+
+/*
+ The QmlContextScriptClass handles property access for a QmlContext
+ via QtScript.
+ */
+QmlContextScriptClass::QmlContextScriptClass(QmlEngine *bindEngine)
+: QmlScriptClass(QmlEnginePrivate::getScriptEngine(bindEngine)), engine(bindEngine),
+ lastScopeObject(0), lastContext(0), lastData(0), lastPropertyIndex(-1), lastDefaultObject(-1)
+{
+}
+
+QmlContextScriptClass::~QmlContextScriptClass()
+{
+}
+
+QScriptValue QmlContextScriptClass::newContext(QmlContext *context, QObject *scopeObject)
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ return newObject(scriptEngine, this, new ContextData(context, scopeObject));
+}
+
+QScriptValue QmlContextScriptClass::newSharedContext()
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ return newObject(scriptEngine, this, new ContextData());
+}
+
+QmlContext *QmlContextScriptClass::contextFromValue(const QScriptValue &v)
+{
+ if (scriptClass(v) != this)
+ return 0;
+
+ ContextData *data = (ContextData *)object(v);
+ return data->getContext(engine);
+}
+
+QScriptClass::QueryFlags
+QmlContextScriptClass::queryProperty(Object *object, const Identifier &name,
+ QScriptClass::QueryFlags flags)
+{
+ Q_UNUSED(flags);
+
+ lastScopeObject = 0;
+ lastContext = 0;
+ lastData = 0;
+ lastPropertyIndex = -1;
+ lastDefaultObject = -1;
+
+ QmlContext *bindContext = ((ContextData *)object)->getContext(engine);
+ QObject *scopeObject = ((ContextData *)object)->getScope(engine);
+ if (!bindContext)
+ return 0;
+
+ bool includeTypes = true;
+ while (bindContext) {
+ QScriptClass::QueryFlags rv =
+ queryProperty(bindContext, scopeObject, name, flags, includeTypes);
+ scopeObject = 0; // Only applies to the first context
+ includeTypes = false; // Only applies to the first context
+ if (rv) return rv;
+ bindContext = bindContext->parentContext();
+ }
+
+ return 0;
+}
+
+QScriptClass::QueryFlags
+QmlContextScriptClass::queryProperty(QmlContext *bindContext, QObject *scopeObject,
+ const Identifier &name,
+ QScriptClass::QueryFlags flags,
+ bool includeTypes)
+{
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+ QmlContextPrivate *cp = QmlContextPrivate::get(bindContext);
+
+ lastPropertyIndex = cp->propertyNames?cp->propertyNames->value(name):-1;
+ if (lastPropertyIndex != -1) {
+ lastContext = bindContext;
+ return QScriptClass::HandlesReadAccess;
+ }
+
+ if (includeTypes && cp->imports) {
+ QmlTypeNameCache::Data *data = cp->imports->data(name);
+
+ if (data) {
+ lastData = data;
+ lastContext = bindContext;
+ return QScriptClass::HandlesReadAccess;
+ }
+ }
+
+ for (int ii = 0; ii < cp->scripts.count(); ++ii) {
+ lastFunction = QScriptDeclarativeClass::function(cp->scripts.at(ii), name);
+ if (lastFunction.isValid()) {
+ lastContext = bindContext;
+ return QScriptClass::HandlesReadAccess;
+ }
+ }
+
+ if (scopeObject) {
+ QScriptClass::QueryFlags rv =
+ ep->objectClass->queryProperty(scopeObject, name, flags, bindContext,
+ QmlObjectScriptClass::ImplicitObject | QmlObjectScriptClass::SkipAttachedProperties);
+ if (rv) {
+ lastScopeObject = scopeObject;
+ lastContext = bindContext;
+ return rv;
+ }
+ }
+
+ for (int ii = cp->defaultObjects.count() - 1; ii >= 0; --ii) {
+ QScriptClass::QueryFlags rv =
+ ep->objectClass->queryProperty(cp->defaultObjects.at(ii), name, flags, bindContext,
+ QmlObjectScriptClass::ImplicitObject | QmlObjectScriptClass::SkipAttachedProperties);
+
+ if (rv) {
+ lastDefaultObject = ii;
+ lastContext = bindContext;
+ return rv;
+ }
+ }
+
+ return 0;
+}
+
+QmlContextScriptClass::ScriptValue
+QmlContextScriptClass::property(Object *object, const Identifier &name)
+{
+ Q_UNUSED(object);
+
+ QmlContext *bindContext = lastContext;
+ Q_ASSERT(bindContext);
+
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+ QmlContextPrivate *cp = QmlContextPrivate::get(bindContext);
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ if (lastScopeObject) {
+
+ return ep->objectClass->property(lastScopeObject, name);
+
+ } else if (lastData) {
+
+ if (lastData->type)
+ return Value(scriptEngine, ep->typeNameClass->newObject(cp->defaultObjects.at(0), lastData->type));
+ else
+ return Value(scriptEngine, ep->typeNameClass->newObject(cp->defaultObjects.at(0), lastData->typeNamespace));
+
+ } else if (lastPropertyIndex != -1) {
+
+ QScriptValue rv;
+ if (lastPropertyIndex < cp->idValueCount) {
+ rv = ep->objectClass->newQObject(cp->idValues[lastPropertyIndex].data());
+ } else {
+ QVariant value = cp->propertyValues.at(lastPropertyIndex);
+ rv = ep->scriptValueFromVariant(value);
+ }
+
+ ep->capturedProperties <<
+ QmlEnginePrivate::CapturedProperty(bindContext, -1, lastPropertyIndex + cp->notifyIndex);
+
+ return Value(scriptEngine, rv);
+ } else if(lastDefaultObject != -1) {
+
+ // Default object property
+ return ep->objectClass->property(cp->defaultObjects.at(lastDefaultObject), name);
+
+ } else {
+
+ return Value(scriptEngine, lastFunction);
+
+ }
+}
+
+void QmlContextScriptClass::setProperty(Object *object, const Identifier &name,
+ const QScriptValue &value)
+{
+ Q_UNUSED(object);
+ Q_ASSERT(lastScopeObject || lastDefaultObject != -1);
+
+ QmlContext *bindContext = lastContext;
+ Q_ASSERT(bindContext);
+
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+ QmlContextPrivate *cp = QmlContextPrivate::get(bindContext);
+
+ if (lastScopeObject) {
+ ep->objectClass->setProperty(lastScopeObject, name, value, bindContext);
+ } else {
+ ep->objectClass->setProperty(cp->defaultObjects.at(lastDefaultObject), name, value,
+ bindContext);
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlcontextscriptclass_p.h b/src/declarative/qml/qmlcontextscriptclass_p.h
new file mode 100644
index 0000000..f98d44f
--- /dev/null
+++ b/src/declarative/qml/qmlcontextscriptclass_p.h
@@ -0,0 +1,101 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCONTEXTSCRIPTCLASS_P_H
+#define QMLCONTEXTSCRIPTCLASS_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 "qmltypenamecache_p.h"
+#include "qmlscriptclass_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlEngine;
+class QmlContext;
+class QmlContextScriptClass : public QmlScriptClass
+{
+public:
+ QmlContextScriptClass(QmlEngine *);
+ ~QmlContextScriptClass();
+
+ QScriptValue newContext(QmlContext *, QObject * = 0);
+ QScriptValue newSharedContext();
+
+ QmlContext *contextFromValue(const QScriptValue &);
+
+protected:
+ virtual QScriptClass::QueryFlags queryProperty(Object *, const Identifier &,
+ QScriptClass::QueryFlags flags);
+ virtual ScriptValue property(Object *, const Identifier &);
+ virtual void setProperty(Object *, const Identifier &name, const QScriptValue &);
+
+private:
+ QScriptClass::QueryFlags queryProperty(QmlContext *, QObject *scopeObject,
+ const Identifier &,
+ QScriptClass::QueryFlags flags,
+ bool includeTypes);
+
+ QmlEngine *engine;
+
+ QObject *lastScopeObject;
+ QmlContext *lastContext;
+ QmlTypeNameCache::Data *lastData;
+ int lastPropertyIndex;
+ int lastDefaultObject;
+ QScriptValue lastFunction;
+
+ uint m_id;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLCONTEXTSCRIPTCLASS_P_H
+
diff --git a/src/declarative/qml/qmlcustomparser.cpp b/src/declarative/qml/qmlcustomparser.cpp
new file mode 100644
index 0000000..116644a
--- /dev/null
+++ b/src/declarative/qml/qmlcustomparser.cpp
@@ -0,0 +1,263 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlcustomparser_p.h"
+#include "qmlcustomparser_p_p.h"
+
+#include "qmlparser_p.h"
+
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+using namespace QmlParser;
+
+/*!
+ \class QmlCustomParser
+ \brief The QmlCustomParser class allows you to add new arbitrary types to QML.
+ \internal
+
+ By subclassing QmlCustomParser, you can add a parser for
+ building a particular type.
+
+ The subclass must implement compile() and setCustomData(), and define
+ itself in the meta type system with the macro:
+
+ \code
+ QML_DEFINE_CUSTOM_TYPE(Module, MajorVersion, MinorVersion, Name, TypeClass, ParserClass)
+ \endcode
+*/
+
+/*
+ \fn QByteArray QmlCustomParser::compile(const QList<QmlCustomParserProperty> & properties)
+
+ The custom parser processes \a properties, and returns
+ a QByteArray containing data meaningful only to the
+ custom parser; the type engine will pass this same data to
+ setCustomData() when making an instance of the data.
+
+ Errors must be reported via the error() functions.
+
+ The QByteArray may be cached between executions of the system, so
+ it must contain correctly-serialized data (not, for example,
+ pointers to stack objects).
+*/
+
+/*
+ \fn void QmlCustomParser::setCustomData(QObject *object, const QByteArray &data)
+
+ This function sets \a object to have the properties defined
+ by \a data, which is a block of data previously returned by a call
+ to compile().
+
+ The \a object will be an instance of the TypeClass specified by QML_DEFINE_CUSTOM_TYPE.
+*/
+
+QmlCustomParserNode
+QmlCustomParserNodePrivate::fromObject(QmlParser::Object *root)
+{
+ QmlCustomParserNode rootNode;
+ rootNode.d->name = root->typeName;
+ rootNode.d->location = root->location.start;
+
+ for(QHash<QByteArray, Property *>::Iterator iter = root->properties.begin();
+ iter != root->properties.end();
+ ++iter) {
+
+ Property *p = *iter;
+
+ rootNode.d->properties << fromProperty(p);
+ }
+
+ return rootNode;
+}
+
+QmlCustomParserProperty
+QmlCustomParserNodePrivate::fromProperty(QmlParser::Property *p)
+{
+ QmlCustomParserProperty prop;
+ prop.d->name = p->name;
+ prop.d->isList = (p->values.count() > 1);
+ prop.d->location = p->location.start;
+
+ if (p->value) {
+ QmlCustomParserNode node = fromObject(p->value);
+ QList<QmlCustomParserProperty> props = node.properties();
+ for (int ii = 0; ii < props.count(); ++ii)
+ prop.d->values << QVariant::fromValue(props.at(ii));
+ } else {
+ for(int ii = 0; ii < p->values.count(); ++ii) {
+ Value *v = p->values.at(ii);
+ v->type = QmlParser::Value::Literal;
+
+ if(v->object) {
+ QmlCustomParserNode node = fromObject(v->object);
+ prop.d->values << QVariant::fromValue(node);
+ } else {
+ prop.d->values << QVariant::fromValue(v->value);
+ }
+
+ }
+ }
+
+ return prop;
+}
+
+QmlCustomParserNode::QmlCustomParserNode()
+: d(new QmlCustomParserNodePrivate)
+{
+}
+
+QmlCustomParserNode::QmlCustomParserNode(const QmlCustomParserNode &other)
+: d(new QmlCustomParserNodePrivate)
+{
+ *this = other;
+}
+
+QmlCustomParserNode &QmlCustomParserNode::operator=(const QmlCustomParserNode &other)
+{
+ d->name = other.d->name;
+ d->properties = other.d->properties;
+ d->location = other.d->location;
+ return *this;
+}
+
+QmlCustomParserNode::~QmlCustomParserNode()
+{
+ delete d; d = 0;
+}
+
+QByteArray QmlCustomParserNode::name() const
+{
+ return d->name;
+}
+
+QList<QmlCustomParserProperty> QmlCustomParserNode::properties() const
+{
+ return d->properties;
+}
+
+QmlParser::Location QmlCustomParserNode::location() const
+{
+ return d->location;
+}
+
+QmlCustomParserProperty::QmlCustomParserProperty()
+: d(new QmlCustomParserPropertyPrivate)
+{
+}
+
+QmlCustomParserProperty::QmlCustomParserProperty(const QmlCustomParserProperty &other)
+: d(new QmlCustomParserPropertyPrivate)
+{
+ *this = other;
+}
+
+QmlCustomParserProperty &QmlCustomParserProperty::operator=(const QmlCustomParserProperty &other)
+{
+ d->name = other.d->name;
+ d->isList = other.d->isList;
+ d->values = other.d->values;
+ d->location = other.d->location;
+ return *this;
+}
+
+QmlCustomParserProperty::~QmlCustomParserProperty()
+{
+ delete d; d = 0;
+}
+
+QByteArray QmlCustomParserProperty::name() const
+{
+ return d->name;
+}
+
+bool QmlCustomParserProperty::isList() const
+{
+ return d->isList;
+}
+
+QmlParser::Location QmlCustomParserProperty::location() const
+{
+ return d->location;
+}
+
+QList<QVariant> QmlCustomParserProperty::assignedValues() const
+{
+ return d->values;
+}
+
+void QmlCustomParser::clearErrors()
+{
+ exceptions.clear();
+}
+
+/*!
+ Reports an error in parsing \a prop, with the given \a description.
+
+ An error is generated referring to the position of \a node in the source file.
+*/
+void QmlCustomParser::error(const QmlCustomParserProperty& prop, const QString& description)
+{
+ QmlError error;
+ QString exceptionDescription;
+ error.setLine(prop.location().line);
+ error.setColumn(prop.location().column);
+ error.setDescription(description);
+ exceptions << error;
+}
+
+/*!
+ Reports an error in parsing \a node, with the given \a description.
+
+ An error is generated referring to the position of \a node in the source file.
+*/
+void QmlCustomParser::error(const QmlCustomParserNode& node, const QString& description)
+{
+ QmlError error;
+ QString exceptionDescription;
+ error.setLine(node.location().line);
+ error.setColumn(node.location().column);
+ error.setDescription(description);
+ exceptions << error;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlcustomparser_p.h b/src/declarative/qml/qmlcustomparser_p.h
new file mode 100644
index 0000000..9502b08
--- /dev/null
+++ b/src/declarative/qml/qmlcustomparser_p.h
@@ -0,0 +1,146 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCUSTOMPARSER_H
+#define QMLCUSTOMPARSER_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 "qmlmetatype.h"
+#include "qmlerror.h"
+#include "qmlparser_p.h"
+
+#include <QtCore/qbytearray.h>
+#include <QtCore/qxmlstream.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlCustomParserPropertyPrivate;
+class Q_DECLARATIVE_EXPORT QmlCustomParserProperty
+{
+public:
+ QmlCustomParserProperty();
+ QmlCustomParserProperty(const QmlCustomParserProperty &);
+ QmlCustomParserProperty &operator=(const QmlCustomParserProperty &);
+ ~QmlCustomParserProperty();
+
+ QByteArray name() const;
+ QmlParser::Location location() const;
+
+ bool isList() const;
+ // Will be one of QmlParser::Variant, QmlCustomParserProperty or
+ // QmlCustomParserNode
+ QList<QVariant> assignedValues() const;
+
+private:
+ friend class QmlCustomParserNodePrivate;
+ friend class QmlCustomParserPropertyPrivate;
+ QmlCustomParserPropertyPrivate *d;
+};
+
+class QmlCustomParserNodePrivate;
+class Q_DECLARATIVE_EXPORT QmlCustomParserNode
+{
+public:
+ QmlCustomParserNode();
+ QmlCustomParserNode(const QmlCustomParserNode &);
+ QmlCustomParserNode &operator=(const QmlCustomParserNode &);
+ ~QmlCustomParserNode();
+
+ QByteArray name() const;
+ QmlParser::Location location() const;
+
+ QList<QmlCustomParserProperty> properties() const;
+
+private:
+ friend class QmlCustomParserNodePrivate;
+ QmlCustomParserNodePrivate *d;
+};
+
+class Q_DECLARATIVE_EXPORT QmlCustomParser
+{
+public:
+ virtual ~QmlCustomParser() {}
+
+ void clearErrors();
+
+ virtual QByteArray compile(const QList<QmlCustomParserProperty> &)=0;
+ virtual void setCustomData(QObject *, const QByteArray &)=0;
+
+ QList<QmlError> errors() const { return exceptions; }
+
+protected:
+ void error(const QmlCustomParserProperty&, const QString& description);
+ void error(const QmlCustomParserNode&, const QString& description);
+
+private:
+ QList<QmlError> exceptions;
+};
+
+#if defined(Q_OS_SYMBIAN)
+# define QML_DEFINE_CUSTOM_TYPE(URI, VERSION_MAJ, VERSION_MIN, NAME, TYPE, CUSTOMTYPE) \
+ static int defineCustomType##NAME = qmlRegisterCustomType<TYPE>(#URI, VERSION_MAJ, VERSION_MIN, #NAME, #TYPE, new CUSTOMTYPE);
+#else
+# define QML_DEFINE_CUSTOM_TYPE(URI, VERSION_MAJ, VERSION_MIN, NAME, TYPE, CUSTOMTYPE) \
+ template<> QmlPrivate::InstanceType QmlPrivate::Define<TYPE *,(VERSION_MAJ), (VERSION_MIN)>::instance(qmlRegisterCustomType<TYPE>(#URI, VERSION_MAJ, VERSION_MIN, #NAME, #TYPE, new CUSTOMTYPE));
+#endif
+
+QT_END_NAMESPACE
+
+Q_DECLARE_METATYPE(QmlCustomParserProperty)
+Q_DECLARE_METATYPE(QmlCustomParserNode)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/qml/qmlcustomparser_p_p.h b/src/declarative/qml/qmlcustomparser_p_p.h
new file mode 100644
index 0000000..c27a5bc
--- /dev/null
+++ b/src/declarative/qml/qmlcustomparser_p_p.h
@@ -0,0 +1,89 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCUSTOMPARSER_P_H
+#define QMLCUSTOMPARSER_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 "qmlcustomparser_p.h"
+
+#include "qmlparser_p.h"
+
+#include <QtCore/qglobal.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlCustomParserNodePrivate
+{
+public:
+ QByteArray name;
+ QList<QmlCustomParserProperty> properties;
+ QmlParser::Location location;
+
+ static QmlCustomParserNode fromObject(QmlParser::Object *);
+ static QmlCustomParserProperty fromProperty(QmlParser::Property *);
+};
+
+class QmlCustomParserPropertyPrivate
+{
+public:
+ QmlCustomParserPropertyPrivate()
+ : isList(false) {}
+
+ QByteArray name;
+ bool isList;
+ QmlParser::Location location;
+ QList<QVariant> values;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLCUSTOMPARSER_P_H
diff --git a/src/declarative/qml/qmldeclarativedata_p.h b/src/declarative/qml/qmldeclarativedata_p.h
new file mode 100644
index 0000000..e2717e0
--- /dev/null
+++ b/src/declarative/qml/qmldeclarativedata_p.h
@@ -0,0 +1,138 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLDECLARATIVEDATA_P_H
+#define QMLDECLARATIVEDATA_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 <QtScript/qscriptvalue.h>
+#include <private/qobject_p.h>
+#include "qmlguard_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlCompiledData;
+class QmlAbstractBinding;
+class QmlContext;
+class QmlPropertyCache;
+class Q_AUTOTEST_EXPORT QmlDeclarativeData : public QDeclarativeData
+{
+public:
+ QmlDeclarativeData(QmlContext *ctxt = 0)
+ : context(ctxt), bindings(0), nextContextObject(0), prevContextObject(0),
+ bindingBitsSize(0), bindingBits(0), outerContext(0), lineNumber(0),
+ columnNumber(0), deferredComponent(0), deferredIdx(0), attachedProperties(0),
+ propertyCache(0), guards(0) {}
+
+ virtual void destroyed(QObject *);
+
+ QmlContext *context;
+ QmlAbstractBinding *bindings;
+
+ // Linked list for QmlContext::contextObjects
+ QmlDeclarativeData *nextContextObject;
+ QmlDeclarativeData**prevContextObject;
+
+ int bindingBitsSize;
+ quint32 *bindingBits;
+ bool hasBindingBit(int) const;
+ void clearBindingBit(int);
+ void setBindingBit(QObject *obj, int);
+
+ QmlContext *outerContext; // Can't this be found from context?
+ ushort lineNumber;
+ ushort columnNumber;
+
+ QmlCompiledData *deferredComponent; // Can't this be found from the context?
+ unsigned int deferredIdx;
+
+ QHash<int, QObject *> *attachedProperties;
+
+ QScriptValue scriptValue;
+ QmlPropertyCache *propertyCache;
+
+ QmlGuard<QObject> *guards;
+
+ static QmlDeclarativeData *get(const QObject *object, bool create = false) {
+ QObjectPrivate *priv = QObjectPrivate::get(const_cast<QObject *>(object));
+ if (priv->declarativeData) {
+ return static_cast<QmlDeclarativeData *>(priv->declarativeData);
+ } else if (create) {
+ priv->declarativeData = new QmlDeclarativeData;
+ return static_cast<QmlDeclarativeData *>(priv->declarativeData);
+ } else {
+ return 0;
+ }
+ }
+};
+
+template<class T>
+void QmlGuard<T>::addGuard()
+{
+ QmlDeclarativeData *data = QmlDeclarativeData::get(o, true);
+ next = data->guards;
+ if (next) reinterpret_cast<QmlGuard<T> *>(next)->prev = &next;
+ data->guards = reinterpret_cast<QmlGuard<QObject> *>(this);
+ prev = &data->guards;
+}
+
+template<class T>
+void QmlGuard<T>::remGuard()
+{
+ if (next) reinterpret_cast<QmlGuard<T> *>(next)->prev = prev;
+ *prev = next;
+ next = 0;
+ prev = 0;
+}
+
+QT_END_NAMESPACE
+
+#endif // QMLDECLARATIVEDATA_P_H
diff --git a/src/declarative/qml/qmldom.cpp b/src/declarative/qml/qmldom.cpp
new file mode 100644
index 0000000..52530db
--- /dev/null
+++ b/src/declarative/qml/qmldom.cpp
@@ -0,0 +1,1837 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmldom.h"
+#include "qmldom_p.h"
+
+#include "qmlcompositetypedata_p.h"
+#include "qmlcompiler_p.h"
+#include "qmlengine_p.h"
+#include "qmlscriptparser_p.h"
+#include "qmlglobal_p.h"
+
+#include <QtCore/QByteArray>
+#include <QtCore/QDebug>
+#include <QtCore/QString>
+
+QT_BEGIN_NAMESPACE
+
+QmlDomDocumentPrivate::QmlDomDocumentPrivate()
+: root(0)
+{
+}
+
+QmlDomDocumentPrivate::~QmlDomDocumentPrivate()
+{
+ if (root) root->release();
+}
+
+/*!
+ \class QmlDomDocument
+ \internal
+ \brief The QmlDomDocument class represents the root of a QML document
+
+ A QML document is a self-contained snippet of QML, usually contained in a
+ single file. Each document has a root object, accessible through
+ QmlDomDocument::rootObject().
+
+ The QmlDomDocument class allows the programmer to inspect a QML document by
+ calling QmlDomDocument::load().
+
+ The following example loads a QML file from disk, and prints out its root
+ object type and the properties assigned in the root object.
+ \code
+ QFile file(inputFileName);
+ file.open(QIODevice::ReadOnly);
+ QByteArray xmlData = file.readAll();
+
+ QmlDomDocument document;
+ document.load(qmlengine, xmlData);
+
+ QmlDomObject rootObject = document.rootObject();
+ qDebug() << rootObject.objectType();
+ foreach(QmlDomProperty property, rootObject.properties())
+ qDebug() << property.propertyName();
+ \endcode
+*/
+
+/*!
+ Construct an empty QmlDomDocument.
+*/
+QmlDomDocument::QmlDomDocument()
+: d(new QmlDomDocumentPrivate)
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomDocument.
+*/
+QmlDomDocument::QmlDomDocument(const QmlDomDocument &other)
+: d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomDocument
+*/
+QmlDomDocument::~QmlDomDocument()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomDocument.
+*/
+QmlDomDocument &QmlDomDocument::operator=(const QmlDomDocument &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ Returns all import statements in qml.
+*/
+QList<QmlDomImport> QmlDomDocument::imports() const
+{
+ return d->imports;
+}
+
+/*!
+ Loads a QmlDomDocument from \a data. \a data should be valid QML
+ data. On success, true is returned. If the \a data is malformed, false
+ is returned and QmlDomDocument::errors() contains an error description.
+
+ \sa QmlDomDocument::loadError()
+*/
+bool QmlDomDocument::load(QmlEngine *engine, const QByteArray &data, const QUrl &url)
+{
+ d->errors.clear();
+ d->imports.clear();
+
+ QmlCompiledData *component = new QmlCompiledData(engine);
+ QmlCompiler compiler;
+
+ QmlCompositeTypeData *td = ((QmlEnginePrivate *)QmlEnginePrivate::get(engine))->typeManager.getImmediate(data, url);
+
+ if(td->status == QmlCompositeTypeData::Error) {
+ d->errors = td->errors;
+ td->release();
+ component->release();
+ return false;
+ } else if(td->status == QmlCompositeTypeData::Waiting ||
+ td->status == QmlCompositeTypeData::WaitingResources) {
+ QmlError error;
+ error.setDescription(QLatin1String("QmlDomDocument supports local types only"));
+ d->errors << error;
+ td->release();
+ component->release();
+ return false;
+ }
+
+ compiler.compile(engine, td, component);
+
+ if (compiler.isError()) {
+ d->errors = compiler.errors();
+ td->release();
+ component->release();
+ return false;
+ }
+
+ for (int i = 0; i < td->data.imports().size(); ++i) {
+ QmlScriptParser::Import parserImport = td->data.imports().at(i);
+ QmlDomImport domImport;
+ domImport.d->type = static_cast<QmlDomImportPrivate::Type>(parserImport.type);
+ domImport.d->uri = parserImport.uri;
+ domImport.d->qualifier = parserImport.qualifier;
+ domImport.d->version = parserImport.version;
+ d->imports += domImport;
+ }
+
+ if (td->data.tree()) {
+ d->root = td->data.tree();
+ d->root->addref();
+ }
+
+ component->release();
+ return true;
+}
+
+/*!
+ Returns the last load errors. The load errors will be reset after a
+ successful call to load().
+
+ \sa load()
+*/
+QList<QmlError> QmlDomDocument::errors() const
+{
+ return d->errors;
+}
+
+/*!
+ Returns the document's root object, or an invalid QmlDomObject if the
+ document has no root.
+
+ In the sample QML below, the root object will be the QmlGraphicsItem type.
+ \qml
+Item {
+ Text {
+ text: "Hello World"
+ }
+}
+ \endqml
+*/
+QmlDomObject QmlDomDocument::rootObject() const
+{
+ QmlDomObject rv;
+ rv.d->object = d->root;
+ if (rv.d->object) rv.d->object->addref();
+ return rv;
+}
+
+QmlDomPropertyPrivate::QmlDomPropertyPrivate()
+: property(0)
+{
+}
+
+QmlDomPropertyPrivate::~QmlDomPropertyPrivate()
+{
+ if (property) property->release();
+}
+
+QmlDomDynamicPropertyPrivate::QmlDomDynamicPropertyPrivate():
+ valid(false)
+{
+}
+
+QmlDomDynamicPropertyPrivate::~QmlDomDynamicPropertyPrivate()
+{
+ if (valid && property.defaultValue) property.defaultValue->release();
+}
+
+/*!
+ \class QmlDomProperty
+ \internal
+ \brief The QmlDomProperty class represents one property assignment in the
+ QML DOM tree
+
+ Properties in QML can be assigned QML \l {QmlDomValue}{values}.
+
+ \sa QmlDomObject
+*/
+
+/*!
+ Construct an invalid QmlDomProperty.
+*/
+QmlDomProperty::QmlDomProperty()
+: d(new QmlDomPropertyPrivate)
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomProperty.
+*/
+QmlDomProperty::QmlDomProperty(const QmlDomProperty &other)
+: d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomProperty.
+*/
+QmlDomProperty::~QmlDomProperty()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomProperty.
+*/
+QmlDomProperty &QmlDomProperty::operator=(const QmlDomProperty &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ Returns true if this is a valid QmlDomProperty, false otherwise.
+*/
+bool QmlDomProperty::isValid() const
+{
+ return d->property != 0;
+}
+
+
+/*!
+ Return the name of this property.
+
+ \qml
+Text {
+ x: 10
+ y: 10
+ font.bold: true
+}
+ \endqml
+
+ As illustrated above, a property name can be a simple string, such as "x" or
+ "y", or a more complex "dot property", such as "font.bold". In both cases
+ the full name is returned ("x", "y" and "font.bold") by this method.
+
+ For dot properties, a split version of the name can be accessed by calling
+ QmlDomProperty::propertyNameParts().
+
+ \sa QmlDomProperty::propertyNameParts()
+*/
+QByteArray QmlDomProperty::propertyName() const
+{
+ return d->propertyName;
+}
+
+/*!
+ Return the name of this property, split into multiple parts in the case
+ of dot properties.
+
+ \qml
+Text {
+ x: 10
+ y: 10
+ font.bold: true
+}
+ \endqml
+
+ For each of the properties shown above, this method would return ("x"),
+ ("y") and ("font", "bold").
+
+ \sa QmlDomProperty::propertyName()
+*/
+QList<QByteArray> QmlDomProperty::propertyNameParts() const
+{
+ if (d->propertyName.isEmpty()) return QList<QByteArray>();
+ else return d->propertyName.split('.');
+}
+
+/*!
+ Return true if this property is used as a default property in the QML
+ document.
+
+ \qml
+<Text text="hello"/>
+<Text>hello</Text>
+ \endqml
+
+ The above two examples return the same DOM tree, except that the second has
+ the default property flag set on the text property. Observe that whether
+ or not a property has isDefaultProperty set is determined by how the
+ property is used, and not only by whether the property is the types default
+ property.
+*/
+bool QmlDomProperty::isDefaultProperty() const
+{
+ return d->property && d->property->isDefault;
+}
+
+/*!
+ Returns the QmlDomValue that is assigned to this property, or an invalid
+ QmlDomValue if no value is assigned.
+*/
+QmlDomValue QmlDomProperty::value() const
+{
+ QmlDomValue rv;
+ if (d->property) {
+ rv.d->property = d->property;
+ rv.d->value = d->property->values.at(0);
+ rv.d->property->addref();
+ rv.d->value->addref();
+ }
+ return rv;
+}
+
+/*!
+ Returns the position in the input data where the property ID startd, or -1 if
+ the property is invalid.
+*/
+int QmlDomProperty::position() const
+{
+ if (d && d->property) {
+ return d->property->location.range.offset;
+ } else
+ return -1;
+}
+
+/*!
+ Returns the length in the input data from where the property ID started upto
+ the end of it, or -1 if the property is invalid.
+*/
+int QmlDomProperty::length() const
+{
+ if (d && d->property)
+ return d->property->location.range.length;
+ else
+ return -1;
+}
+
+/*!
+ Construct an invalid QmlDomDynamicProperty.
+*/
+QmlDomDynamicProperty::QmlDomDynamicProperty():
+ d(new QmlDomDynamicPropertyPrivate)
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomDynamicProperty.
+*/
+QmlDomDynamicProperty::QmlDomDynamicProperty(const QmlDomDynamicProperty &other):
+ d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomDynamicProperty.
+*/
+QmlDomDynamicProperty::~QmlDomDynamicProperty()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomDynamicProperty.
+*/
+QmlDomDynamicProperty &QmlDomDynamicProperty::operator=(const QmlDomDynamicProperty &other)
+{
+ d = other.d;
+ return *this;
+}
+
+bool QmlDomDynamicProperty::isValid() const
+{
+ return d && d->valid;
+}
+
+/*!
+ Return the name of this dynamic property.
+
+ \qml
+Item {
+ property int count: 10;
+}
+ \endqml
+
+ As illustrated above, a dynamic property name can have a name and a
+ default value ("10").
+*/
+QByteArray QmlDomDynamicProperty::propertyName() const
+{
+ if (isValid())
+ return d->property.name;
+ else
+ return QByteArray();
+}
+
+/*!
+ Returns the type of the dynamic property. Note that when the property is an
+ alias property, this will return -1. Use QmlDomProperty::isAlias() to check
+ if the property is an alias.
+*/
+int QmlDomDynamicProperty::propertyType() const
+{
+ if (isValid()) {
+ switch (d->property.type) {
+ case QmlParser::Object::DynamicProperty::Bool:
+ return QMetaType::type("bool");
+
+ case QmlParser::Object::DynamicProperty::Color:
+ return QMetaType::type("QColor");
+
+ case QmlParser::Object::DynamicProperty::Date:
+ return QMetaType::type("QDate");
+
+ case QmlParser::Object::DynamicProperty::Int:
+ return QMetaType::type("int");
+
+ case QmlParser::Object::DynamicProperty::Real:
+ return QMetaType::type("double");
+
+ case QmlParser::Object::DynamicProperty::String:
+ return QMetaType::type("QString");
+
+ case QmlParser::Object::DynamicProperty::Url:
+ return QMetaType::type("QUrl");
+
+ case QmlParser::Object::DynamicProperty::Variant:
+ return QMetaType::type("QVariant");
+
+ default:
+ break;
+ }
+ }
+
+ return -1;
+}
+
+QByteArray QmlDomDynamicProperty::propertyTypeName() const
+{
+ if (isValid())
+ return d->property.customType;
+
+ return QByteArray();
+}
+
+/*!
+ Return true if this property is used as a default property in the QML
+ document.
+
+ \qml
+<Text text="hello"/>
+<Text>hello</Text>
+ \endqml
+
+ The above two examples return the same DOM tree, except that the second has
+ the default property flag set on the text property. Observe that whether
+ or not a property has isDefaultProperty set is determined by how the
+ property is used, and not only by whether the property is the types default
+ property.
+*/
+bool QmlDomDynamicProperty::isDefaultProperty() const
+{
+ if (isValid())
+ return d->property.isDefaultProperty;
+ else
+ return false;
+}
+
+/*!
+ Returns the default value as a QmlDomProperty.
+*/
+QmlDomProperty QmlDomDynamicProperty::defaultValue() const
+{
+ QmlDomProperty rp;
+
+ if (isValid() && d->property.defaultValue) {
+ rp.d->property = d->property.defaultValue;
+ rp.d->propertyName = propertyName();
+ rp.d->property->addref();
+ }
+
+ return rp;
+}
+
+/*!
+ Returns true if this dynamic property is an alias for another property,
+ false otherwise.
+*/
+bool QmlDomDynamicProperty::isAlias() const
+{
+ if (isValid())
+ return d->property.type == QmlParser::Object::DynamicProperty::Alias;
+ else
+ return false;
+}
+
+/*!
+ Returns the position in the input data where the property ID startd, or 0 if
+ the property is invalid.
+*/
+int QmlDomDynamicProperty::position() const
+{
+ if (isValid()) {
+ return d->property.location.range.offset;
+ } else
+ return -1;
+}
+
+/*!
+ Returns the length in the input data from where the property ID started upto
+ the end of it, or 0 if the property is invalid.
+*/
+int QmlDomDynamicProperty::length() const
+{
+ if (isValid())
+ return d->property.location.range.length;
+ else
+ return -1;
+}
+
+QmlDomObjectPrivate::QmlDomObjectPrivate()
+: object(0)
+{
+}
+
+QmlDomObjectPrivate::~QmlDomObjectPrivate()
+{
+ if (object) object->release();
+}
+
+QmlDomObjectPrivate::Properties
+QmlDomObjectPrivate::properties() const
+{
+ Properties rv;
+
+ for (QHash<QByteArray, QmlParser::Property *>::ConstIterator iter =
+ object->properties.begin();
+ iter != object->properties.end();
+ ++iter) {
+
+ rv << properties(*iter);
+
+ }
+ return rv;
+}
+
+QmlDomObjectPrivate::Properties
+QmlDomObjectPrivate::properties(QmlParser::Property *property) const
+{
+ Properties rv;
+
+ if (property->value) {
+
+ for (QHash<QByteArray, QmlParser::Property *>::ConstIterator iter =
+ property->value->properties.begin();
+ iter != property->value->properties.end();
+ ++iter) {
+
+ rv << properties(*iter);
+
+ }
+
+ QByteArray name(property->name + '.');
+ for (Properties::Iterator iter = rv.begin(); iter != rv.end(); ++iter)
+ iter->second.prepend(name);
+
+ } else {
+ rv << qMakePair(property, property->name);
+ }
+
+ return rv;
+}
+
+/*!
+ \class QmlDomObject
+ \internal
+ \brief The QmlDomObject class represents an object instantiation.
+
+ Each object instantiated in a QML file has a corresponding QmlDomObject
+ node in the QML DOM.
+
+ In addition to the type information that determines the object to
+ instantiate, QmlDomObject's also have a set of associated QmlDomProperty's.
+ Each QmlDomProperty represents a QML property assignment on the instantiated
+ object. For example,
+
+ \qml
+QGraphicsWidget {
+ opacity: 0.5
+ size: "100x100"
+}
+ \endqml
+
+ describes a single QmlDomObject - "QGraphicsWidget" - with two properties,
+ "opacity" and "size". Obviously QGraphicsWidget has many more properties than just
+ these two, but the QML DOM representation only contains those assigned
+ values (or bindings) in the QML file.
+*/
+
+/*!
+ Construct an invalid QmlDomObject.
+*/
+QmlDomObject::QmlDomObject()
+: d(new QmlDomObjectPrivate)
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomObject.
+*/
+QmlDomObject::QmlDomObject(const QmlDomObject &other)
+: d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomObject.
+*/
+QmlDomObject::~QmlDomObject()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomObject.
+*/
+QmlDomObject &QmlDomObject::operator=(const QmlDomObject &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ Returns true if this is a valid QmlDomObject, false otherwise.
+*/
+bool QmlDomObject::isValid() const
+{
+ return d->object != 0;
+}
+
+/*!
+ Returns the fully-qualified type name of this object.
+
+ For example, the type of this object would be "Qt/4.6/Rectangle".
+ \qml
+Rectangle { }
+ \endqml
+*/
+QByteArray QmlDomObject::objectType() const
+{
+ if (d->object) return d->object->typeName;
+ else return QByteArray();
+}
+
+/*!
+ Returns the type name as referenced in the qml file.
+
+ For example, the type of this object would be "Rectangle".
+ \qml
+Rectangle { }
+ \endqml
+*/
+QByteArray QmlDomObject::objectClassName() const
+{
+ if (d->object)
+ return d->object->className;
+ else
+ return QByteArray();
+}
+
+int QmlDomObject::objectTypeMajorVersion() const
+{
+ if (d->object)
+ return d->object->majorVersion;
+ else
+ return -1;
+}
+
+int QmlDomObject::objectTypeMinorVersion() const
+{
+ if (d->object)
+ return d->object->minorVersion;
+ else
+ return -1;
+}
+
+/*!
+ Returns the QML id assigned to this object, or an empty QByteArray if no id
+ has been assigned.
+
+ For example, the object id of this object would be "MyText".
+ \qml
+Text { id: myText }
+ \endqml
+*/
+QString QmlDomObject::objectId() const
+{
+ if (d->object) {
+ return d->object->id;
+ } else {
+ return QString();
+ }
+}
+
+/*!
+ Returns the list of assigned properties on this object.
+
+ In the following example, "text" and "x" properties would be returned.
+ \qml
+Text {
+ text: "Hello world!"
+ x: 100
+}
+ \endqml
+*/
+QList<QmlDomProperty> QmlDomObject::properties() const
+{
+ QList<QmlDomProperty> rv;
+
+ if (!d->object || isComponent())
+ return rv;
+
+ QmlDomObjectPrivate::Properties properties = d->properties();
+ for (int ii = 0; ii < properties.count(); ++ii) {
+
+ QmlDomProperty domProperty;
+ domProperty.d->property = properties.at(ii).first;
+ domProperty.d->property->addref();
+ domProperty.d->propertyName = properties.at(ii).second;
+ rv << domProperty;
+
+ }
+
+ if (d->object->defaultProperty) {
+ QmlDomProperty domProperty;
+ domProperty.d->property = d->object->defaultProperty;
+ domProperty.d->property->addref();
+ domProperty.d->propertyName = d->object->defaultProperty->name;
+ rv << domProperty;
+ }
+
+ return rv;
+}
+
+/*!
+ Returns the object's \a name property if a value has been assigned to
+ it, or an invalid QmlDomProperty otherwise.
+
+ In the example below, \c {object.property("source")} would return a valid
+ QmlDomProperty, and \c {object.property("tile")} an invalid QmlDomProperty.
+
+ \qml
+Image { source: "sample.jpg" }
+ \endqml
+*/
+QmlDomProperty QmlDomObject::property(const QByteArray &name) const
+{
+ QList<QmlDomProperty> props = properties();
+ for (int ii = 0; ii < props.count(); ++ii)
+ if (props.at(ii).propertyName() == name)
+ return props.at(ii);
+ return QmlDomProperty();
+}
+
+QList<QmlDomDynamicProperty> QmlDomObject::dynamicProperties() const
+{
+ QList<QmlDomDynamicProperty> properties;
+
+ for (int i = 0; i < d->object->dynamicProperties.size(); ++i) {
+ QmlDomDynamicProperty p;
+ p.d = new QmlDomDynamicPropertyPrivate;
+ p.d->property = d->object->dynamicProperties.at(i);
+ p.d->valid = true;
+
+ if (p.d->property.defaultValue)
+ p.d->property.defaultValue->addref();
+
+ properties.append(p);
+ }
+
+ return properties;
+}
+
+QmlDomDynamicProperty QmlDomObject::dynamicProperty(const QByteArray &name) const
+{
+ QmlDomDynamicProperty p;
+
+ if (!isValid())
+ return p;
+
+ for (int i = 0; i < d->object->dynamicProperties.size(); ++i) {
+ if (d->object->dynamicProperties.at(i).name == name) {
+ p.d = new QmlDomDynamicPropertyPrivate;
+ p.d->property = d->object->dynamicProperties.at(i);
+ if (p.d->property.defaultValue) p.d->property.defaultValue->addref();
+ p.d->valid = true;
+ }
+ }
+
+ return p;
+}
+
+/*!
+ Returns true if this object is a custom type. Custom types are special
+ types that allow embeddeding non-QML data, such as SVG or HTML data,
+ directly into QML files.
+
+ \note Currently this method will always return false, and is a placekeeper
+ for future functionality.
+
+ \sa QmlDomObject::customTypeData()
+*/
+bool QmlDomObject::isCustomType() const
+{
+ return false;
+}
+
+/*!
+ If this object represents a custom type, returns the data associated with
+ the custom type, otherwise returns an empty QByteArray().
+ QmlDomObject::isCustomType() can be used to check if this object represents
+ a custom type.
+*/
+QByteArray QmlDomObject::customTypeData() const
+{
+ return QByteArray();
+}
+
+/*!
+ Returns true if this object is a sub-component object. Sub-component
+ objects can be converted into QmlDomComponent instances by calling
+ QmlDomObject::toComponent().
+
+ \sa QmlDomObject::toComponent()
+*/
+bool QmlDomObject::isComponent() const
+{
+ return (d->object && d->object->typeName == "Qt/Component");
+}
+
+/*!
+ Returns a QmlDomComponent for this object if it is a sub-component, or
+ an invalid QmlDomComponent if not. QmlDomObject::isComponent() can be used
+ to check if this object represents a sub-component.
+
+ \sa QmlDomObject::isComponent()
+*/
+QmlDomComponent QmlDomObject::toComponent() const
+{
+ QmlDomComponent rv;
+ if (isComponent())
+ rv.d = d;
+ return rv;
+}
+
+/*!
+ Returns the position in the input data where the property assignment started
+, or -1 if the property is invalid.
+*/
+int QmlDomObject::position() const
+{
+ if (d && d->object)
+ return d->object->location.range.offset;
+ else
+ return -1;
+}
+
+/*!
+ Returns the length in the input data from where the property assignment star
+ted upto the end of it, or -1 if the property is invalid.
+*/
+int QmlDomObject::length() const
+{
+ if (d && d->object)
+ return d->object->location.range.length;
+ else
+ return -1;
+}
+
+// Returns the URL of the type, if it is an external type, or an empty URL if
+// not
+QUrl QmlDomObject::url() const
+{
+ if (d && d->object)
+ return d->object->url;
+ else
+ return QUrl();
+}
+
+QmlDomBasicValuePrivate::QmlDomBasicValuePrivate()
+: value(0)
+{
+}
+
+QmlDomBasicValuePrivate::~QmlDomBasicValuePrivate()
+{
+ if (value) value->release();
+}
+
+/*!
+ \class QmlDomValueLiteral
+ \internal
+ \brief The QmlDomValueLiteral class represents a literal value.
+
+ A literal value is a simple value, written inline with the QML. In the
+ example below, the "x", "y" and "color" properties are being assigned
+ literal values.
+
+ \qml
+Rectangle {
+ x: 10
+ y: 10
+ color: "red"
+}
+ \endqml
+*/
+
+/*!
+ Construct an empty QmlDomValueLiteral.
+*/
+QmlDomValueLiteral::QmlDomValueLiteral():
+ d(new QmlDomBasicValuePrivate)
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomValueLiteral.
+*/
+QmlDomValueLiteral::QmlDomValueLiteral(const QmlDomValueLiteral &other)
+: d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomValueLiteral.
+*/
+QmlDomValueLiteral::~QmlDomValueLiteral()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomValueLiteral.
+*/
+QmlDomValueLiteral &QmlDomValueLiteral::operator=(const QmlDomValueLiteral &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ Return the literal value.
+
+ In the example below, the literal value will be the string "10".
+ \qml
+Rectangle { x: 10 }
+ \endqml
+*/
+QString QmlDomValueLiteral::literal() const
+{
+ if (d->value) return d->value->primitive();
+ else return QString();
+}
+
+/*!
+ \class QmlDomValueBinding
+ \internal
+ \brief The QmlDomValueBinding class represents a property binding.
+
+ A property binding is an ECMAScript expression assigned to a property. In
+ the example below, the "x" property is being assigned a property binding.
+
+ \qml
+Rectangle { x: Other.x }
+ \endqml
+*/
+
+/*!
+ Construct an empty QmlDomValueBinding.
+*/
+QmlDomValueBinding::QmlDomValueBinding():
+ d(new QmlDomBasicValuePrivate)
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomValueBinding.
+*/
+QmlDomValueBinding::QmlDomValueBinding(const QmlDomValueBinding &other)
+: d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomValueBinding.
+*/
+QmlDomValueBinding::~QmlDomValueBinding()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomValueBinding.
+*/
+QmlDomValueBinding &QmlDomValueBinding::operator=(const QmlDomValueBinding &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ Return the binding expression.
+
+ In the example below, the string "Other.x" will be returned.
+ \qml
+Rectangle { x: Other.x }
+ \endqml
+*/
+QString QmlDomValueBinding::binding() const
+{
+ if (d->value)
+ return d->value->value.asScript();
+ else
+ return QString();
+}
+
+/*!
+ \class QmlDomValueValueSource
+ \internal
+ \brief The QmlDomValueValueSource class represents a value source assignment value.
+
+ In QML, value sources are special value generating types that may be
+ assigned to properties. Value sources inherit the QmlPropertyValueSource
+ class. In the example below, the "x" property is being assigned the
+ NumberAnimation value source.
+
+ \qml
+Rectangle {
+ x: NumberAnimation {
+ from: 0
+ to: 100
+ repeat: true
+ running: true
+ }
+}
+ \endqml
+*/
+
+/*!
+ Construct an empty QmlDomValueValueSource.
+*/
+QmlDomValueValueSource::QmlDomValueValueSource():
+ d(new QmlDomBasicValuePrivate)
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomValueValueSource.
+*/
+QmlDomValueValueSource::QmlDomValueValueSource(const QmlDomValueValueSource &other)
+: d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomValueValueSource.
+*/
+QmlDomValueValueSource::~QmlDomValueValueSource()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomValueValueSource.
+*/
+QmlDomValueValueSource &QmlDomValueValueSource::operator=(const QmlDomValueValueSource &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ Return the value source object.
+
+ In the example below, an object representing the NumberAnimation will be
+ returned.
+ \qml
+Rectangle {
+ x: NumberAnimation {
+ from: 0
+ to: 100
+ repeat: true
+ running: true
+ }
+}
+ \endqml
+*/
+QmlDomObject QmlDomValueValueSource::object() const
+{
+ QmlDomObject rv;
+ if (d->value) {
+ rv.d->object = d->value->object;
+ rv.d->object->addref();
+ }
+ return rv;
+}
+
+/*!
+ \class QmlDomValueValueInterceptor
+ \internal
+ \brief The QmlDomValueValueInterceptor class represents a value interceptor assignment value.
+
+ In QML, value interceptor are special write-intercepting types that may be
+ assigned to properties. Value interceptor inherit the QmlPropertyValueInterceptor
+ class. In the example below, the "x" property is being assigned the
+ Behavior value interceptor.
+
+ \qml
+Rectangle {
+ x: Behavior { NumberAnimation { duration: 500 } }
+}
+ \endqml
+*/
+
+/*!
+ Construct an empty QmlDomValueValueInterceptor.
+*/
+QmlDomValueValueInterceptor::QmlDomValueValueInterceptor():
+ d(new QmlDomBasicValuePrivate)
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomValueValueInterceptor.
+*/
+QmlDomValueValueInterceptor::QmlDomValueValueInterceptor(const QmlDomValueValueInterceptor &other)
+: d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomValueValueInterceptor.
+*/
+QmlDomValueValueInterceptor::~QmlDomValueValueInterceptor()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomValueValueInterceptor.
+*/
+QmlDomValueValueInterceptor &QmlDomValueValueInterceptor::operator=(const QmlDomValueValueInterceptor &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ Return the value interceptor object.
+
+ In the example below, an object representing the Behavior will be
+ returned.
+ \qml
+Rectangle {
+ x: Behavior { NumberAnimation { duration: 500 } }
+}
+ \endqml
+*/
+QmlDomObject QmlDomValueValueInterceptor::object() const
+{
+ QmlDomObject rv;
+ if (d->value) {
+ rv.d->object = d->value->object;
+ rv.d->object->addref();
+ }
+ return rv;
+}
+
+QmlDomValuePrivate::QmlDomValuePrivate()
+: property(0), value(0)
+{
+}
+
+QmlDomValuePrivate::~QmlDomValuePrivate()
+{
+ if (property) property->release();
+ if (value) value->release();
+}
+
+/*!
+ \class QmlDomValue
+ \internal
+ \brief The QmlDomValue class represents a generic Qml value.
+
+ QmlDomValue's can be assigned to QML \l {QmlDomProperty}{properties}. In
+ QML, properties can be assigned various different values, including basic
+ literals, property bindings, property value sources, objects and lists of
+ values. The QmlDomValue class allows a programmer to determine the specific
+ value type being assigned and access more detailed information through a
+ corresponding value type class.
+
+ For example, in the following example,
+
+ \qml
+Text {
+ text: "Hello World!"
+ y: Other.y
+}
+ \endqml
+
+ The text property is being assigned a literal, and the y property a property
+ binding. To output the values assigned to the text and y properties in the
+ above example from C++,
+
+ \code
+ QmlDomDocument document;
+ QmlDomObject root = document.rootObject();
+
+ QmlDomProperty text = root.property("text");
+ if (text.value().isLiteral()) {
+ QmlDomValueLiteral literal = text.value().toLiteral();
+ qDebug() << literal.literal();
+ }
+
+ QmlDomProperty y = root.property("y");
+ if (y.value().isBinding()) {
+ QmlDomValueBinding binding = y.value().toBinding();
+ qDebug() << binding.binding();
+ }
+ \endcode
+*/
+
+/*!
+ Construct an invalid QmlDomValue.
+*/
+QmlDomValue::QmlDomValue()
+: d(new QmlDomValuePrivate)
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomValue.
+*/
+QmlDomValue::QmlDomValue(const QmlDomValue &other)
+: d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomValue
+*/
+QmlDomValue::~QmlDomValue()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomValue.
+*/
+QmlDomValue &QmlDomValue::operator=(const QmlDomValue &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ \enum QmlDomValue::Type
+
+ The type of the QmlDomValue node.
+
+ \value Invalid The QmlDomValue is invalid.
+ \value Literal The QmlDomValue is a literal value assignment. Use QmlDomValue::toLiteral() to access the type instance.
+ \value PropertyBinding The QmlDomValue is a property binding. Use QmlDomValue::toBinding() to access the type instance.
+ \value ValueSource The QmlDomValue is a property value source. Use QmlDomValue::toValueSource() to access the type instance.
+ \value ValueInterceptor The QmlDomValue is a property value interceptor. Use QmlDomValue::toValueInterceptor() to access the type instance.
+ \value Object The QmlDomValue is an object assignment. Use QmlDomValue::toObject() to access the type instnace.
+ \value List The QmlDomValue is a list of other values. Use QmlDomValue::toList() to access the type instance.
+*/
+
+/*!
+ Returns the type of this QmlDomValue.
+*/
+QmlDomValue::Type QmlDomValue::type() const
+{
+ if (d->property)
+ if (QmlMetaType::isList(d->property->type) ||
+ QmlMetaType::isQmlList(d->property->type) ||
+ (d->property && d->property->values.count() > 1))
+ return List;
+
+ QmlParser::Value *value = d->value;
+ if (!value && !d->property)
+ return Invalid;
+
+ switch(value->type) {
+ case QmlParser::Value::Unknown:
+ return Invalid;
+ case QmlParser::Value::Literal:
+ return Literal;
+ case QmlParser::Value::PropertyBinding:
+ return PropertyBinding;
+ case QmlParser::Value::ValueSource:
+ return ValueSource;
+ case QmlParser::Value::ValueInterceptor:
+ return ValueInterceptor;
+ case QmlParser::Value::CreatedObject:
+ return Object;
+ case QmlParser::Value::SignalObject:
+ return Invalid;
+ case QmlParser::Value::SignalExpression:
+ return Literal;
+ case QmlParser::Value::Id:
+ return Literal;
+ }
+ return Invalid;
+}
+
+/*!
+ Returns true if this is an invalid value, otherwise false.
+*/
+bool QmlDomValue::isInvalid() const
+{
+ return type() == Invalid;
+}
+
+/*!
+ Returns true if this is a literal value, otherwise false.
+*/
+bool QmlDomValue::isLiteral() const
+{
+ return type() == Literal;
+}
+
+/*!
+ Returns true if this is a property binding value, otherwise false.
+*/
+bool QmlDomValue::isBinding() const
+{
+ return type() == PropertyBinding;
+}
+
+/*!
+ Returns true if this is a value source value, otherwise false.
+*/
+bool QmlDomValue::isValueSource() const
+{
+ return type() == ValueSource;
+}
+
+/*!
+ Returns true if this is a value interceptor value, otherwise false.
+*/
+bool QmlDomValue::isValueInterceptor() const
+{
+ return type() == ValueInterceptor;
+}
+
+/*!
+ Returns true if this is an object value, otherwise false.
+*/
+bool QmlDomValue::isObject() const
+{
+ return type() == Object;
+}
+
+/*!
+ Returns true if this is a list value, otherwise false.
+*/
+bool QmlDomValue::isList() const
+{
+ return type() == List;
+}
+
+/*!
+ Returns a QmlDomValueLiteral if this value is a literal type, otherwise
+ returns an invalid QmlDomValueLiteral.
+
+ \sa QmlDomValue::type()
+*/
+QmlDomValueLiteral QmlDomValue::toLiteral() const
+{
+ QmlDomValueLiteral rv;
+ if (type() == Literal) {
+ rv.d->value = d->value;
+ rv.d->value->addref();
+ }
+ return rv;
+}
+
+/*!
+ Returns a QmlDomValueBinding if this value is a property binding type,
+ otherwise returns an invalid QmlDomValueBinding.
+
+ \sa QmlDomValue::type()
+*/
+QmlDomValueBinding QmlDomValue::toBinding() const
+{
+ QmlDomValueBinding rv;
+ if (type() == PropertyBinding) {
+ rv.d->value = d->value;
+ rv.d->value->addref();
+ }
+ return rv;
+}
+
+/*!
+ Returns a QmlDomValueValueSource if this value is a property value source
+ type, otherwise returns an invalid QmlDomValueValueSource.
+
+ \sa QmlDomValue::type()
+*/
+QmlDomValueValueSource QmlDomValue::toValueSource() const
+{
+ QmlDomValueValueSource rv;
+ if (type() == ValueSource) {
+ rv.d->value = d->value;
+ rv.d->value->addref();
+ }
+ return rv;
+}
+
+/*!
+ Returns a QmlDomValueValueInterceptor if this value is a property value interceptor
+ type, otherwise returns an invalid QmlDomValueValueInterceptor.
+
+ \sa QmlDomValue::type()
+*/
+QmlDomValueValueInterceptor QmlDomValue::toValueInterceptor() const
+{
+ QmlDomValueValueInterceptor rv;
+ if (type() == ValueInterceptor) {
+ rv.d->value = d->value;
+ rv.d->value->addref();
+ }
+ return rv;
+}
+
+/*!
+ Returns a QmlDomObject if this value is an object assignment type, otherwise
+ returns an invalid QmlDomObject.
+
+ \sa QmlDomValue::type()
+*/
+QmlDomObject QmlDomValue::toObject() const
+{
+ QmlDomObject rv;
+ if (type() == Object) {
+ rv.d->object = d->value->object;
+ rv.d->object->addref();
+ }
+ return rv;
+}
+
+/*!
+ Returns a QmlDomList if this value is a list type, otherwise returns an
+ invalid QmlDomList.
+
+ \sa QmlDomValue::type()
+*/
+QmlDomList QmlDomValue::toList() const
+{
+ QmlDomList rv;
+ if (type() == List) {
+ rv.d = d;
+ }
+ return rv;
+}
+
+/*!
+ Returns the position in the input data where the property value startd, or -1
+ if the value is invalid.
+*/
+int QmlDomValue::position() const
+{
+ if (type() == Invalid)
+ return -1;
+ else
+ return d->value->location.range.offset;
+}
+
+/*!
+ Returns the length in the input data from where the property value started u
+pto the end of it, or -1 if the value is invalid.
+*/
+int QmlDomValue::length() const
+{
+ if (type() == Invalid)
+ return -1;
+ else
+ return d->value->location.range.length;
+}
+
+/*!
+ \class QmlDomList
+ \internal
+ \brief The QmlDomList class represents a list of values assigned to a QML property.
+
+ Lists of values can be assigned to properties. For example, the following
+ example assigns multiple objects to Item's "children" property
+ \qml
+Item {
+ children: [
+ Text { },
+ Rectangle { }
+ ]
+}
+ \endqml
+
+ Lists can also be implicitly created by assigning multiple
+ \l {QmlDomValueValueSource}{value sources} or constants to a property.
+ \qml
+Item {
+ x: 10
+ x: NumberAnimation {
+ running: false
+ from: 0
+ to: 100
+ }
+}
+ \endqml
+*/
+
+/*!
+ Construct an empty QmlDomList.
+*/
+QmlDomList::QmlDomList()
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomList.
+*/
+QmlDomList::QmlDomList(const QmlDomList &other)
+: d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomList.
+*/
+QmlDomList::~QmlDomList()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomList.
+*/
+QmlDomList &QmlDomList::operator=(const QmlDomList &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ Returns the list of QmlDomValue's.
+*/
+QList<QmlDomValue> QmlDomList::values() const
+{
+ QList<QmlDomValue> rv;
+ if (!d->property)
+ return rv;
+
+ for (int ii = 0; ii < d->property->values.count(); ++ii) {
+ QmlDomValue v;
+ v.d->value = d->property->values.at(ii);
+ v.d->value->addref();
+ rv << v;
+ }
+
+ return rv;
+}
+
+/*!
+ Returns the position in the input data where the list started, or -1 if
+ the property is invalid.
+*/
+int QmlDomList::position() const
+{
+ if (d && d->property) {
+ return d->property->listValueRange.offset;
+ } else
+ return -1;
+}
+
+/*!
+ Returns the length in the input data from where the list started upto
+ the end of it, or 0 if the property is invalid.
+*/
+int QmlDomList::length() const
+{
+ if (d && d->property)
+ return d->property->listValueRange.length;
+ else
+ return -1;
+}
+
+/*!
+ Returns a list of positions of the commas in the QML file.
+*/
+QList<int> QmlDomList:: commaPositions() const
+{
+ if (d && d->property)
+ return d->property->listCommaPositions;
+ else
+ return QList<int>();
+}
+
+/*!
+ \class QmlDomComponent
+ \internal
+ \brief The QmlDomComponent class represents sub-component within a QML document.
+
+ Sub-components are QmlComponents defined within a QML document. The
+ following example shows the definition of a sub-component with the id
+ "listDelegate".
+
+ \qml
+Item {
+ Component {
+ id: listDelegate
+ Text {
+ text: modelData.text
+ }
+ }
+}
+ \endqml
+
+ Like QmlDomDocument's, components contain a single root object.
+*/
+
+/*!
+ Construct an empty QmlDomComponent.
+*/
+QmlDomComponent::QmlDomComponent()
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomComponent.
+*/
+QmlDomComponent::QmlDomComponent(const QmlDomComponent &other)
+: QmlDomObject(other)
+{
+}
+
+/*!
+ Destroy the QmlDomComponent.
+*/
+QmlDomComponent::~QmlDomComponent()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomComponent.
+*/
+QmlDomComponent &QmlDomComponent::operator=(const QmlDomComponent &other)
+{
+ static_cast<QmlDomObject &>(*this) = other;
+ return *this;
+}
+
+/*!
+ Returns the component's root object.
+
+ In the example below, the root object is the "Text" object.
+ \qml
+Item {
+ Component {
+ id: listDelegate
+ Text {
+ text: modelData.text
+ }
+ }
+}
+ \endqml
+*/
+QmlDomObject QmlDomComponent::componentRoot() const
+{
+ QmlDomObject rv;
+ if (d->object) {
+ QmlParser::Object *obj = 0;
+ if (d->object->defaultProperty &&
+ d->object->defaultProperty->values.count() == 1 &&
+ d->object->defaultProperty->values.at(0)->object)
+ obj = d->object->defaultProperty->values.at(0)->object;
+
+ if (obj) {
+ rv.d->object = obj;
+ rv.d->object->addref();
+ }
+ }
+
+ return rv;
+}
+
+QmlDomImportPrivate::QmlDomImportPrivate()
+: type(File)
+{
+}
+
+QmlDomImportPrivate::~QmlDomImportPrivate()
+{
+}
+
+/*!
+ \class QmlDomImport
+ \internal
+ \brief The QmlDomImport class represents an import statement.
+*/
+
+/*!
+ Construct an empty QmlDomImport.
+*/
+QmlDomImport::QmlDomImport()
+: d(new QmlDomImportPrivate)
+{
+}
+
+/*!
+ Create a copy of \a other QmlDomImport.
+*/
+QmlDomImport::QmlDomImport(const QmlDomImport &other)
+: d(other.d)
+{
+}
+
+/*!
+ Destroy the QmlDomImport.
+*/
+QmlDomImport::~QmlDomImport()
+{
+}
+
+/*!
+ Assign \a other to this QmlDomImport.
+*/
+QmlDomImport &QmlDomImport::operator=(const QmlDomImport &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ Returns the type of the import.
+ */
+QmlDomImport::Type QmlDomImport::type() const
+{
+ return static_cast<QmlDomImport::Type>(d->type);
+}
+
+/*!
+ Returns the URI of the import (e.g. 'subdir' or 'com.nokia.Qt')
+ */
+QString QmlDomImport::uri() const
+{
+ return d->uri;
+}
+
+/*!
+ Returns the version specified by the import. An empty string if no version was specified.
+ */
+QString QmlDomImport::version() const
+{
+ return d->version;
+}
+
+/*!
+ Returns the (optional) qualifier string (the token following the 'as' keyword) of the import.
+ */
+QString QmlDomImport::qualifier() const
+{
+ return d->qualifier;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmldom.h b/src/declarative/qml/qmldom.h
new file mode 100644
index 0000000..8442f49
--- /dev/null
+++ b/src/declarative/qml/qmldom.h
@@ -0,0 +1,349 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLDOM_H
+#define QMLDOM_H
+
+#include "qmlerror.h"
+
+#include <QtCore/qlist.h>
+#include <QtCore/qshareddata.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QString;
+class QByteArray;
+class QmlDomObject;
+class QmlDomList;
+class QmlDomValue;
+class QmlEngine;
+class QmlDomComponent;
+class QmlDomImport;
+class QIODevice;
+
+class QmlDomDocumentPrivate;
+
+class Q_DECLARATIVE_EXPORT QmlDomDocument
+{
+public:
+ QmlDomDocument();
+ QmlDomDocument(const QmlDomDocument &);
+ ~QmlDomDocument();
+ QmlDomDocument &operator=(const QmlDomDocument &);
+
+ QList<QmlDomImport> imports() const;
+
+ QList<QmlError> errors() const;
+ bool load(QmlEngine *, const QByteArray &, const QUrl & = QUrl());
+
+ QmlDomObject rootObject() const;
+
+private:
+ QSharedDataPointer<QmlDomDocumentPrivate> d;
+};
+
+class QmlDomPropertyPrivate;
+class Q_DECLARATIVE_EXPORT QmlDomProperty
+{
+public:
+ QmlDomProperty();
+ QmlDomProperty(const QmlDomProperty &);
+ ~QmlDomProperty();
+ QmlDomProperty &operator=(const QmlDomProperty &);
+
+ bool isValid() const;
+
+ QByteArray propertyName() const;
+ QList<QByteArray> propertyNameParts() const;
+
+ bool isDefaultProperty() const;
+
+ QmlDomValue value() const;
+
+ int position() const;
+ int length() const;
+
+private:
+ friend class QmlDomObject;
+ friend class QmlDomDynamicProperty;
+ QSharedDataPointer<QmlDomPropertyPrivate> d;
+};
+
+class QmlDomDynamicPropertyPrivate;
+class Q_DECLARATIVE_EXPORT QmlDomDynamicProperty
+{
+public:
+ QmlDomDynamicProperty();
+ QmlDomDynamicProperty(const QmlDomDynamicProperty &);
+ ~QmlDomDynamicProperty();
+ QmlDomDynamicProperty &operator=(const QmlDomDynamicProperty &);
+
+ bool isValid() const;
+
+ QByteArray propertyName() const;
+ int propertyType() const;
+ QByteArray propertyTypeName() const;
+
+ bool isDefaultProperty() const;
+ QmlDomProperty defaultValue() const;
+
+ bool isAlias() const;
+
+ int position() const;
+ int length() const;
+
+private:
+ friend class QmlDomObject;
+ QSharedDataPointer<QmlDomDynamicPropertyPrivate> d;
+};
+
+class QmlDomObjectPrivate;
+class Q_DECLARATIVE_EXPORT QmlDomObject
+{
+public:
+ QmlDomObject();
+ QmlDomObject(const QmlDomObject &);
+ ~QmlDomObject();
+ QmlDomObject &operator=(const QmlDomObject &);
+
+ bool isValid() const;
+
+ QByteArray objectType() const;
+ QByteArray objectClassName() const;
+
+ int objectTypeMajorVersion() const;
+ int objectTypeMinorVersion() const;
+
+ QString objectId() const;
+
+ QList<QmlDomProperty> properties() const;
+ QmlDomProperty property(const QByteArray &) const;
+
+ QList<QmlDomDynamicProperty> dynamicProperties() const;
+ QmlDomDynamicProperty dynamicProperty(const QByteArray &) const;
+
+ bool isCustomType() const;
+ QByteArray customTypeData() const;
+
+ bool isComponent() const;
+ QmlDomComponent toComponent() const;
+
+ int position() const;
+ int length() const;
+
+ QUrl url() const;
+private:
+ friend class QmlDomDocument;
+ friend class QmlDomComponent;
+ friend class QmlDomValue;
+ friend class QmlDomValueValueSource;
+ friend class QmlDomValueValueInterceptor;
+ QSharedDataPointer<QmlDomObjectPrivate> d;
+};
+
+class QmlDomValuePrivate;
+class QmlDomBasicValuePrivate;
+class Q_DECLARATIVE_EXPORT QmlDomValueLiteral
+{
+public:
+ QmlDomValueLiteral();
+ QmlDomValueLiteral(const QmlDomValueLiteral &);
+ ~QmlDomValueLiteral();
+ QmlDomValueLiteral &operator=(const QmlDomValueLiteral &);
+
+ QString literal() const;
+
+private:
+ friend class QmlDomValue;
+ QSharedDataPointer<QmlDomBasicValuePrivate> d;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDomValueBinding
+{
+public:
+ QmlDomValueBinding();
+ QmlDomValueBinding(const QmlDomValueBinding &);
+ ~QmlDomValueBinding();
+ QmlDomValueBinding &operator=(const QmlDomValueBinding &);
+
+ QString binding() const;
+
+private:
+ friend class QmlDomValue;
+ QSharedDataPointer<QmlDomBasicValuePrivate> d;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDomValueValueSource
+{
+public:
+ QmlDomValueValueSource();
+ QmlDomValueValueSource(const QmlDomValueValueSource &);
+ ~QmlDomValueValueSource();
+ QmlDomValueValueSource &operator=(const QmlDomValueValueSource &);
+
+ QmlDomObject object() const;
+
+private:
+ friend class QmlDomValue;
+ QSharedDataPointer<QmlDomBasicValuePrivate> d;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDomValueValueInterceptor
+{
+public:
+ QmlDomValueValueInterceptor();
+ QmlDomValueValueInterceptor(const QmlDomValueValueInterceptor &);
+ ~QmlDomValueValueInterceptor();
+ QmlDomValueValueInterceptor &operator=(const QmlDomValueValueInterceptor &);
+
+ QmlDomObject object() const;
+
+private:
+ friend class QmlDomValue;
+ QSharedDataPointer<QmlDomBasicValuePrivate> d;
+};
+
+
+class Q_DECLARATIVE_EXPORT QmlDomComponent : public QmlDomObject
+{
+public:
+ QmlDomComponent();
+ QmlDomComponent(const QmlDomComponent &);
+ ~QmlDomComponent();
+ QmlDomComponent &operator=(const QmlDomComponent &);
+
+ QmlDomObject componentRoot() const;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDomValue
+{
+public:
+ enum Type {
+ Invalid,
+ Literal,
+ PropertyBinding,
+ ValueSource,
+ ValueInterceptor,
+ Object,
+ List
+ };
+
+ QmlDomValue();
+ QmlDomValue(const QmlDomValue &);
+ ~QmlDomValue();
+ QmlDomValue &operator=(const QmlDomValue &);
+
+ Type type() const;
+
+ bool isInvalid() const;
+ bool isLiteral() const;
+ bool isBinding() const;
+ bool isValueSource() const;
+ bool isValueInterceptor() const;
+ bool isObject() const;
+ bool isList() const;
+
+ QmlDomValueLiteral toLiteral() const;
+ QmlDomValueBinding toBinding() const;
+ QmlDomValueValueSource toValueSource() const;
+ QmlDomValueValueInterceptor toValueInterceptor() const;
+ QmlDomObject toObject() const;
+ QmlDomList toList() const;
+
+ int position() const;
+ int length() const;
+
+private:
+ friend class QmlDomProperty;
+ friend class QmlDomList;
+ QSharedDataPointer<QmlDomValuePrivate> d;
+};
+
+class Q_DECLARATIVE_EXPORT QmlDomList
+{
+public:
+ QmlDomList();
+ QmlDomList(const QmlDomList &);
+ ~QmlDomList();
+ QmlDomList &operator=(const QmlDomList &);
+
+ QList<QmlDomValue> values() const;
+
+ int position() const;
+ int length() const;
+
+ QList<int> commaPositions() const;
+
+private:
+ friend class QmlDomValue;
+ QSharedDataPointer<QmlDomValuePrivate> d;
+};
+
+class QmlDomImportPrivate;
+class Q_DECLARATIVE_EXPORT QmlDomImport
+{
+public:
+ enum Type { Library, File };
+
+ QmlDomImport();
+ QmlDomImport(const QmlDomImport &);
+ ~QmlDomImport();
+ QmlDomImport &operator=(const QmlDomImport &);
+
+ Type type() const;
+ QString uri() const;
+ QString version() const;
+ QString qualifier() const;
+
+private:
+ friend class QmlDomDocument;
+ QSharedDataPointer<QmlDomImportPrivate> d;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLDOM_H
diff --git a/src/declarative/qml/qmldom_p.h b/src/declarative/qml/qmldom_p.h
new file mode 100644
index 0000000..df6a980
--- /dev/null
+++ b/src/declarative/qml/qmldom_p.h
@@ -0,0 +1,157 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLDOM_P_H
+#define QMLDOM_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 "qmlparser_p.h"
+
+#include <QtCore/QtGlobal>
+
+QT_BEGIN_NAMESPACE
+
+class QmlDomDocumentPrivate : public QSharedData
+{
+public:
+ QmlDomDocumentPrivate();
+ QmlDomDocumentPrivate(const QmlDomDocumentPrivate &o)
+ : QSharedData(o) { qFatal("Not impl"); }
+ ~QmlDomDocumentPrivate();
+
+ QList<QmlError> errors;
+ QList<QmlDomImport> imports;
+ QmlParser::Object *root;
+ QList<int> automaticSemicolonOffsets;
+};
+
+class QmlDomObjectPrivate : public QSharedData
+{
+public:
+ QmlDomObjectPrivate();
+ QmlDomObjectPrivate(const QmlDomObjectPrivate &o)
+ : QSharedData(o) { qFatal("Not impl"); }
+ ~QmlDomObjectPrivate();
+
+ typedef QList<QPair<QmlParser::Property *, QByteArray> > Properties;
+ Properties properties() const;
+ Properties properties(QmlParser::Property *) const;
+
+ QmlParser::Object *object;
+};
+
+class QmlDomPropertyPrivate : public QSharedData
+{
+public:
+ QmlDomPropertyPrivate();
+ QmlDomPropertyPrivate(const QmlDomPropertyPrivate &o)
+ : QSharedData(o) { qFatal("Not impl"); }
+ ~QmlDomPropertyPrivate();
+
+ QByteArray propertyName;
+ QmlParser::Property *property;
+};
+
+class QmlDomDynamicPropertyPrivate : public QSharedData
+{
+public:
+ QmlDomDynamicPropertyPrivate();
+ QmlDomDynamicPropertyPrivate(const QmlDomDynamicPropertyPrivate &o)
+ : QSharedData(o) { qFatal("Not impl"); }
+ ~QmlDomDynamicPropertyPrivate();
+
+ bool valid;
+ QmlParser::Object::DynamicProperty property;
+};
+
+class QmlDomValuePrivate : public QSharedData
+{
+public:
+ QmlDomValuePrivate();
+ QmlDomValuePrivate(const QmlDomValuePrivate &o)
+ : QSharedData(o) { qFatal("Not impl"); }
+ ~QmlDomValuePrivate();
+
+ QmlParser::Property *property;
+ QmlParser::Value *value;
+};
+
+class QmlDomBasicValuePrivate : public QSharedData
+{
+public:
+ QmlDomBasicValuePrivate();
+ QmlDomBasicValuePrivate(const QmlDomBasicValuePrivate &o)
+ : QSharedData(o) { qFatal("Not impl"); }
+ ~QmlDomBasicValuePrivate();
+
+ QmlParser::Value *value;
+};
+
+class QmlDomImportPrivate : public QSharedData
+{
+public:
+ QmlDomImportPrivate();
+ QmlDomImportPrivate(const QmlDomImportPrivate &o)
+ : QSharedData(o) { qFatal("Not impl"); }
+ ~QmlDomImportPrivate();
+
+ enum Type { Library, File };
+
+ Type type;
+ QString uri;
+ QString version;
+ QString qualifier;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLDOM_P_H
+
diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp
new file mode 100644
index 0000000..cdbe5f3
--- /dev/null
+++ b/src/declarative/qml/qmlengine.cpp
@@ -0,0 +1,1659 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlengine_p.h"
+#include "qmlengine.h"
+
+#include "qmlcontext_p.h"
+#include "qmlcompiler_p.h"
+#include "qmlglobalscriptclass_p.h"
+#include "qml.h"
+#include "qmlcontext.h"
+#include "qmlexpression.h"
+#include "qmlcomponent.h"
+#include "qmlmetaproperty_p.h"
+#include "qmlmoduleplugin.h"
+#include "qmlbinding_p.h"
+#include "qmlvme_p.h"
+#include "qmlenginedebug_p.h"
+#include "qmlstringconverters_p.h"
+#include "qmlxmlhttprequest_p.h"
+#include "qmlsqldatabase_p.h"
+#include "qmltypenamescriptclass_p.h"
+#include "qmllistscriptclass_p.h"
+#include "qmlscriptstring.h"
+#include "qmlglobal_p.h"
+#include "qmlworkerscript_p.h"
+#include "qmlcomponent_p.h"
+#include "qmlscriptclass_p.h"
+#include "qmlnetworkaccessmanagerfactory.h"
+
+#include <qfxperf_p_p.h>
+
+#include <QtCore/qmetaobject.h>
+#include <QScriptClass>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+#include <QNetworkAccessManager>
+#include <QDesktopServices>
+#include <QTimer>
+#include <QList>
+#include <QPair>
+#include <QDebug>
+#include <QMetaObject>
+#include <QStack>
+#include <QtCore/qlibraryinfo.h>
+#include <QtCore/qthreadstorage.h>
+#include <QtCore/qthread.h>
+#include <QtCore/qcoreapplication.h>
+#include <QtCore/qdir.h>
+#include <QtGui/qcolor.h>
+#include <QtGui/qvector3d.h>
+#include <QtGui/qsound.h>
+#include <QGraphicsObject>
+#include <QtCore/qcryptographichash.h>
+
+#include <private/qfactoryloader_p.h>
+#include <private/qobject_p.h>
+#include <private/qscriptdeclarativeclass_p.h>
+
+#ifdef Q_OS_WIN // for %APPDATA%
+#include <qt_windows.h>
+#include <qlibrary.h>
+
+#define CSIDL_APPDATA 0x001a // <username>\Application Data
+#endif
+
+Q_DECLARE_METATYPE(QmlMetaProperty)
+Q_DECLARE_METATYPE(QList<QObject *>);
+
+QT_BEGIN_NAMESPACE
+
+DEFINE_BOOL_CONFIG_OPTION(qmlImportTrace, QML_IMPORT_TRACE)
+
+QML_DEFINE_TYPE(Qt,4,6,QtObject,QObject)
+/*!
+ \qmlclass QtObject QObject
+ \brief The QtObject element is the most basic element in QML
+
+ The QtObject element is a non-visual element which contains only
+ the objectName property. It is useful for when you need an extremely
+ lightweight element to place your own custom properties in.
+
+ It can also be useful for C++ integration, as it is just a plain QObject. See
+ the QObject documentation for further details.
+*/
+/*!
+ \qmlproperty string QtObject::objectName
+ This property allows you to give a name to this specific object instance.
+
+ See \l{scripting.html#accessing-child-qobjects}{Accessing Child QObjects}
+ in the scripting documentation for details how objectName can be used from
+ scripts.
+*/
+
+struct StaticQtMetaObject : public QObject
+{
+ static const QMetaObject *get()
+ { return &static_cast<StaticQtMetaObject*> (0)->staticQtMetaObject; }
+};
+
+QmlEnginePrivate::QmlEnginePrivate(QmlEngine *e)
+: captureProperties(false), rootContext(0), currentExpression(0), isDebugging(false),
+ contextClass(0), sharedContext(0), sharedScope(0), objectClass(0), valueTypeClass(0),
+ globalClass(0), cleanup(0), erroredBindings(0), inProgressCreations(0),
+ scriptEngine(this), workerScriptEngine(0), componentAttacheds(0), inBeginCreate(false),
+ networkAccessManager(0), networkAccessManagerFactory(0),
+ typeManager(e), uniqueId(1)
+{
+ globalClass = new QmlGlobalScriptClass(&scriptEngine);
+ fileImportPath.append(QLibraryInfo::location(QLibraryInfo::DataPath)+QDir::separator()+QLatin1String("qml"));
+}
+
+QUrl QmlScriptEngine::resolvedUrl(QScriptContext *context, const QUrl& url)
+{
+ if (p) {
+ QmlContext *ctxt = QmlEnginePrivate::get(this)->getContext(context);
+ Q_ASSERT(ctxt);
+ return ctxt->resolvedUrl(url);
+ }
+ return baseUrl.resolved(url);
+}
+
+QmlScriptEngine::QmlScriptEngine(QmlEnginePrivate *priv)
+: p(priv), sqlQueryClass(0), namedNodeMapClass(0), nodeListClass(0)
+{
+ // Note that all documentation for stuff put on the global object goes in
+ // doc/src/declarative/globalobject.qdoc
+
+ bool mainthread = priv != 0;
+
+ QScriptValue qtObject =
+ newQMetaObject(StaticQtMetaObject::get());
+ globalObject().setProperty(QLatin1String("Qt"), qtObject);
+
+ offlineStoragePath = QDesktopServices::storageLocation(QDesktopServices::DataLocation).replace(QLatin1Char('/'), QDir::separator())
+ + QDir::separator() + QLatin1String("QML")
+ + QDir::separator() + QLatin1String("OfflineStorage");
+
+
+ qt_add_qmlxmlhttprequest(this);
+ qt_add_qmlsqldatabase(this);
+ // XXX A Multimedia "Qt.Sound" class also needs to be made available,
+ // XXX but we don't want a dependency in that cirection.
+ // XXX When the above a done some better way, that way should also be
+ // XXX used to add Qt.Sound class.
+
+
+ //types
+ qtObject.setProperty(QLatin1String("rgba"), newFunction(QmlEnginePrivate::rgba, 4));
+ qtObject.setProperty(QLatin1String("hsla"), newFunction(QmlEnginePrivate::hsla, 4));
+ qtObject.setProperty(QLatin1String("rect"), newFunction(QmlEnginePrivate::rect, 4));
+ qtObject.setProperty(QLatin1String("point"), newFunction(QmlEnginePrivate::point, 2));
+ qtObject.setProperty(QLatin1String("size"), newFunction(QmlEnginePrivate::size, 2));
+ qtObject.setProperty(QLatin1String("vector3d"), newFunction(QmlEnginePrivate::vector, 3));
+
+ if (mainthread) {
+ //color helpers
+ qtObject.setProperty(QLatin1String("lighter"), newFunction(QmlEnginePrivate::lighter, 1));
+ qtObject.setProperty(QLatin1String("darker"), newFunction(QmlEnginePrivate::darker, 1));
+ qtObject.setProperty(QLatin1String("tint"), newFunction(QmlEnginePrivate::tint, 2));
+ }
+
+ //misc methods
+ qtObject.setProperty(QLatin1String("closestAngle"), newFunction(QmlEnginePrivate::closestAngle, 2));
+ qtObject.setProperty(QLatin1String("playSound"), newFunction(QmlEnginePrivate::playSound, 1));
+ qtObject.setProperty(QLatin1String("openUrlExternally"),newFunction(QmlEnginePrivate::desktopOpenUrl, 1));
+ qtObject.setProperty(QLatin1String("md5"),newFunction(QmlEnginePrivate::md5, 1));
+ qtObject.setProperty(QLatin1String("btoa"),newFunction(QmlEnginePrivate::btoa, 1));
+ qtObject.setProperty(QLatin1String("atob"),newFunction(QmlEnginePrivate::atob, 1));
+ qtObject.setProperty(QLatin1String("quit"), newFunction(QmlEnginePrivate::quit, 0));
+ qtObject.setProperty(QLatin1String("resolvedUrl"),newFunction(QmlScriptEngine::resolvedUrl, 1));
+
+ //firebug/webkit compat
+ QScriptValue consoleObject = newObject();
+ consoleObject.setProperty(QLatin1String("log"),newFunction(QmlEnginePrivate::consoleLog, 1));
+ consoleObject.setProperty(QLatin1String("debug"),newFunction(QmlEnginePrivate::consoleLog, 1));
+ globalObject().setProperty(QLatin1String("console"), consoleObject);
+
+ if (mainthread) {
+ globalObject().setProperty(QLatin1String("createQmlObject"),
+ newFunction(QmlEnginePrivate::createQmlObject, 1));
+ globalObject().setProperty(QLatin1String("createComponent"),
+ newFunction(QmlEnginePrivate::createComponent, 1));
+ }
+
+ // translation functions need to be installed
+ // before the global script class is constructed (QTBUG-6437)
+ installTranslatorFunctions();
+}
+
+QmlScriptEngine::~QmlScriptEngine()
+{
+ delete sqlQueryClass;
+ delete nodeListClass;
+ delete namedNodeMapClass;
+}
+
+QScriptValue QmlScriptEngine::resolvedUrl(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ QString arg = ctxt->argument(0).toString();
+ QUrl r = QmlScriptEngine::get(engine)->resolvedUrl(ctxt,QUrl(arg));
+ return QScriptValue(r.toString());
+}
+
+QNetworkAccessManager *QmlScriptEngine::networkAccessManager()
+{
+ return p->getNetworkAccessManager();
+}
+
+QmlEnginePrivate::~QmlEnginePrivate()
+{
+ while (cleanup) {
+ QmlCleanup *c = cleanup;
+ cleanup = c->next;
+ if (cleanup) cleanup->prev = &cleanup;
+ c->next = 0;
+ c->prev = 0;
+ c->clear();
+ }
+
+ delete rootContext;
+ rootContext = 0;
+ delete contextClass;
+ contextClass = 0;
+ delete objectClass;
+ objectClass = 0;
+ delete valueTypeClass;
+ valueTypeClass = 0;
+ delete typeNameClass;
+ typeNameClass = 0;
+ delete listClass;
+ listClass = 0;
+ delete globalClass;
+ globalClass = 0;
+
+ for(int ii = 0; ii < bindValues.count(); ++ii)
+ clear(bindValues[ii]);
+ for(int ii = 0; ii < parserStatus.count(); ++ii)
+ clear(parserStatus[ii]);
+ for(QHash<int, QmlCompiledData*>::ConstIterator iter = m_compositeTypes.constBegin(); iter != m_compositeTypes.constEnd(); ++iter)
+ (*iter)->release();
+ for(QHash<const QMetaObject *, QmlPropertyCache *>::Iterator iter = propertyCache.begin(); iter != propertyCache.end(); ++iter)
+ (*iter)->release();
+
+}
+
+void QmlEnginePrivate::clear(SimpleList<QmlAbstractBinding> &bvs)
+{
+ bvs.clear();
+}
+
+void QmlEnginePrivate::clear(SimpleList<QmlParserStatus> &pss)
+{
+ for (int ii = 0; ii < pss.count; ++ii) {
+ QmlParserStatus *ps = pss.at(ii);
+ if(ps)
+ ps->d = 0;
+ }
+ pss.clear();
+}
+
+Q_GLOBAL_STATIC(QmlEngineDebugServer, qmlEngineDebugServer);
+
+void QmlEnginePrivate::init()
+{
+ Q_Q(QmlEngine);
+ qRegisterMetaType<QVariant>("QVariant");
+ qRegisterMetaType<QmlScriptString>("QmlScriptString");
+ qRegisterMetaType<QScriptValue>("QScriptValue");
+
+ contextClass = new QmlContextScriptClass(q);
+ objectClass = new QmlObjectScriptClass(q);
+ valueTypeClass = new QmlValueTypeScriptClass(q);
+ typeNameClass = new QmlTypeNameScriptClass(q);
+ listClass = new QmlListScriptClass(q);
+ rootContext = new QmlContext(q,true);
+
+ if (QCoreApplication::instance()->thread() == q->thread() &&
+ QmlEngineDebugServer::isDebuggingEnabled()) {
+ qmlEngineDebugServer();
+ isDebugging = true;
+ QmlEngineDebugServer::addEngine(q);
+
+ qmlEngineDebugServer()->waitForClients();
+ }
+}
+
+QmlWorkerScriptEngine *QmlEnginePrivate::getWorkerScriptEngine()
+{
+ Q_Q(QmlEngine);
+ if (!workerScriptEngine)
+ workerScriptEngine = new QmlWorkerScriptEngine(q);
+ return workerScriptEngine;
+}
+
+/*!
+ \class QmlEngine
+ \brief The QmlEngine class provides an environment for instantiating QML components.
+ \mainclass
+
+ Each QML component is instantiated in a QmlContext. QmlContext's are
+ essential for passing data to QML components. In QML, contexts are arranged
+ hierarchically and this hierarchy is managed by the QmlEngine.
+
+ Prior to creating any QML components, an application must have created a
+ QmlEngine to gain access to a QML context. The following example shows how
+ to create a simple Text item.
+
+ \code
+ QmlEngine engine;
+ QmlComponent component(&engine);
+ component.setData("import Qt 4.6\nText { text: \"Hello world!\" }", QUrl());
+ QmlGraphicsItem *item = qobject_cast<QmlGraphicsItem *>(component.create());
+
+ //add item to view, etc
+ ...
+ \endcode
+
+ In this case, the Text item will be created in the engine's
+ \l {QmlEngine::rootContext()}{root context}.
+
+ \sa QmlComponent QmlContext
+*/
+
+/*!
+ Create a new QmlEngine with the given \a parent.
+*/
+QmlEngine::QmlEngine(QObject *parent)
+: QObject(*new QmlEnginePrivate(this), parent)
+{
+ Q_D(QmlEngine);
+ d->init();
+}
+
+/*!
+ Destroys the QmlEngine.
+
+ Any QmlContext's created on this engine will be invalidated, but not
+ destroyed (unless they are parented to the QmlEngine object).
+*/
+QmlEngine::~QmlEngine()
+{
+ Q_D(QmlEngine);
+ if (d->isDebugging)
+ QmlEngineDebugServer::remEngine(this);
+}
+
+/*!
+ Clears the engine's internal component cache.
+
+ Normally the QmlEngine caches components loaded from qml files. This method
+ clears this cache and forces the component to be reloaded.
+ */
+void QmlEngine::clearComponentCache()
+{
+ Q_D(QmlEngine);
+ d->typeManager.clearCache();
+}
+
+/*!
+ Returns the engine's root context.
+
+ The root context is automatically created by the QmlEngine. Data that
+ should be available to all QML component instances instantiated by the
+ engine should be put in the root context.
+
+ Additional data that should only be available to a subset of component
+ instances should be added to sub-contexts parented to the root context.
+*/
+QmlContext *QmlEngine::rootContext()
+{
+ Q_D(QmlEngine);
+ return d->rootContext;
+}
+
+/*!
+ Sets the \a factory to use for creating QNetworkAccessManager(s).
+
+ QNetworkAccessManager is used for all network access by QML.
+ By implementing a factory it is possible to create custom
+ QNetworkAccessManager with specialized caching, proxy and
+ cookie support.
+
+ The factory must be set before exceuting the engine.
+*/
+void QmlEngine::setNetworkAccessManagerFactory(QmlNetworkAccessManagerFactory *factory)
+{
+ Q_D(QmlEngine);
+ d->networkAccessManagerFactory = factory;
+}
+
+/*!
+ Returns the current QmlNetworkAccessManagerFactory.
+
+ \sa setNetworkAccessManagerFactory()
+*/
+QmlNetworkAccessManagerFactory *QmlEngine::networkAccessManagerFactory() const
+{
+ Q_D(const QmlEngine);
+ return d->networkAccessManagerFactory;
+}
+
+QNetworkAccessManager *QmlEnginePrivate::getNetworkAccessManager() const
+{
+ Q_Q(const QmlEngine);
+
+ if (!networkAccessManager) {
+ if (networkAccessManagerFactory) {
+ networkAccessManager = networkAccessManagerFactory->create(const_cast<QmlEngine*>(q));
+ } else {
+ networkAccessManager = new QNetworkAccessManager(const_cast<QmlEngine*>(q));
+ }
+ }
+ return networkAccessManager;
+}
+
+/*!
+ Returns a common QNetworkAccessManager which can be used by any QML element
+ instantiated by this engine.
+
+ If a QmlNetworkAccessManagerFactory has been set and a QNetworkAccessManager
+ has not yet been created, the QmlNetworkAccessManagerFactory will be used
+ to create the QNetworkAccessManager; otherwise the returned QNetworkAccessManager
+ will have no proxy or cache set.
+
+ \sa setNetworkAccessManagerFactory()
+*/
+QNetworkAccessManager *QmlEngine::networkAccessManager() const
+{
+ Q_D(const QmlEngine);
+ return d->getNetworkAccessManager();
+}
+
+/*!
+ Return the base URL for this engine. The base URL is only used to resolve
+ components when a relative URL is passed to the QmlComponent constructor.
+
+ If a base URL has not been explicitly set, this method returns the
+ application's current working directory.
+
+ \sa setBaseUrl()
+*/
+QUrl QmlEngine::baseUrl() const
+{
+ Q_D(const QmlEngine);
+ if (d->baseUrl.isEmpty()) {
+ return QUrl::fromLocalFile(QDir::currentPath() + QDir::separator());
+ } else {
+ return d->baseUrl;
+ }
+}
+
+/*!
+ Set the base URL for this engine to \a url.
+
+ \sa baseUrl()
+*/
+void QmlEngine::setBaseUrl(const QUrl &url)
+{
+ Q_D(QmlEngine);
+ d->baseUrl = url;
+}
+
+/*!
+ Returns the QmlContext for the \a object, or 0 if no context has been set.
+
+ When the QmlEngine instantiates a QObject, the context is set automatically.
+ */
+QmlContext *QmlEngine::contextForObject(const QObject *object)
+{
+ if(!object)
+ return 0;
+
+ QObjectPrivate *priv = QObjectPrivate::get(const_cast<QObject *>(object));
+
+ QmlDeclarativeData *data =
+ static_cast<QmlDeclarativeData *>(priv->declarativeData);
+
+ if (!data)
+ return 0;
+ else if (data->outerContext)
+ return data->outerContext;
+ else
+ return data->context;
+}
+
+/*!
+ Sets the QmlContext for the \a object to \a context.
+ If the \a object already has a context, a warning is
+ output, but the context is not changed.
+
+ When the QmlEngine instantiates a QObject, the context is set automatically.
+ */
+void QmlEngine::setContextForObject(QObject *object, QmlContext *context)
+{
+ if (!object || !context)
+ return;
+
+ QmlDeclarativeData *data = QmlDeclarativeData::get(object, true);
+ if (data->context) {
+ qWarning("QmlEngine::setContextForObject(): Object already has a QmlContext");
+ return;
+ }
+
+ data->context = context;
+ data->nextContextObject = context->d_func()->contextObjects;
+ if (data->nextContextObject)
+ data->nextContextObject->prevContextObject = &data->nextContextObject;
+ data->prevContextObject = &context->d_func()->contextObjects;
+ context->d_func()->contextObjects = data;
+}
+
+void qmlExecuteDeferred(QObject *object)
+{
+ QmlDeclarativeData *data = QmlDeclarativeData::get(object);
+
+ if (data && data->deferredComponent) {
+
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(data->context->engine());
+
+ QmlComponentPrivate::ConstructionState state;
+ QmlComponentPrivate::beginDeferred(data->context, ep, object, &state);
+
+ data->deferredComponent->release();
+ data->deferredComponent = 0;
+
+ QmlComponentPrivate::complete(ep, &state);
+
+ if (!state.errors.isEmpty())
+ qWarning() << state.errors;
+
+ }
+}
+
+QmlContext *qmlContext(const QObject *obj)
+{
+ return QmlEngine::contextForObject(obj);
+}
+
+QmlEngine *qmlEngine(const QObject *obj)
+{
+ QmlContext *context = QmlEngine::contextForObject(obj);
+ return context?context->engine():0;
+}
+
+QObject *qmlAttachedPropertiesObjectById(int id, const QObject *object, bool create)
+{
+ QmlDeclarativeData *data = QmlDeclarativeData::get(object);
+ if (!data)
+ return 0; // Attached properties are only on objects created by QML
+
+ QObject *rv = data->attachedProperties?data->attachedProperties->value(id):0;
+ if (rv || !create)
+ return rv;
+
+ QmlAttachedPropertiesFunc pf = QmlMetaType::attachedPropertiesFuncById(id);
+ if (!pf)
+ return 0;
+
+ rv = pf(const_cast<QObject *>(object));
+
+ if (rv) {
+ if (!data->attachedProperties)
+ data->attachedProperties = new QHash<int, QObject *>();
+ data->attachedProperties->insert(id, rv);
+ }
+
+ return rv;
+}
+
+void QmlDeclarativeData::destroyed(QObject *object)
+{
+ if (deferredComponent)
+ deferredComponent->release();
+ if (attachedProperties)
+ delete attachedProperties;
+
+ if (nextContextObject)
+ nextContextObject->prevContextObject = prevContextObject;
+ if (prevContextObject)
+ *prevContextObject = nextContextObject;
+
+ QmlAbstractBinding *binding = bindings;
+ while (binding) {
+ QmlAbstractBinding *next = binding->m_nextBinding;
+ binding->m_prevBinding = 0;
+ binding->m_nextBinding = 0;
+ binding->destroy();
+ binding = next;
+ }
+
+ if (bindingBits)
+ free(bindingBits);
+
+ if (propertyCache)
+ propertyCache->release();
+
+ QmlGuard<QObject> *guard = guards;
+ while (guard) {
+ QmlGuard<QObject> *g = guard;
+ guard = guard->next;
+ g->o = 0;
+ g->prev = 0;
+ g->next = 0;
+ g->objectDestroyed(object);
+ }
+
+ delete this;
+}
+
+bool QmlDeclarativeData::hasBindingBit(int bit) const
+{
+ if (bindingBitsSize > bit)
+ return bindingBits[bit / 32] & (1 << (bit % 32));
+ else
+ return false;
+}
+
+void QmlDeclarativeData::clearBindingBit(int bit)
+{
+ if (bindingBitsSize > bit)
+ bindingBits[bit / 32] &= ~(1 << (bit % 32));
+}
+
+void QmlDeclarativeData::setBindingBit(QObject *obj, int bit)
+{
+ if (bindingBitsSize <= bit) {
+ int props = obj->metaObject()->propertyCount();
+ Q_ASSERT(bit < props);
+
+ int arraySize = (props + 31) / 32;
+ int oldArraySize = bindingBitsSize / 32;
+
+ bindingBits = (quint32 *)realloc(bindingBits,
+ arraySize * sizeof(quint32));
+
+ memset(bindingBits + oldArraySize,
+ 0x00,
+ sizeof(quint32) * (arraySize - oldArraySize));
+
+ bindingBitsSize = arraySize * 32;
+ }
+
+ bindingBits[bit / 32] |= (1 << (bit % 32));
+}
+
+/*!
+ Creates a QScriptValue allowing you to use \a object in QML script.
+ \a engine is the QmlEngine it is to be created in.
+
+ The QScriptValue returned is a QtScript Object, not a QtScript QObject, due
+ to the special needs of QML requiring more functionality than a standard
+ QtScript QObject.
+*/
+QScriptValue QmlEnginePrivate::qmlScriptObject(QObject* object,
+ QmlEngine* engine)
+{
+ QmlEnginePrivate *enginePriv = QmlEnginePrivate::get(engine);
+ return enginePriv->objectClass->newQObject(object);
+}
+
+/*!
+ Returns the QmlContext for the executing QScript \a ctxt.
+*/
+QmlContext *QmlEnginePrivate::getContext(QScriptContext *ctxt)
+{
+ QScriptValue scopeNode = QScriptDeclarativeClass::scopeChainValue(ctxt, -3);
+ Q_ASSERT(scopeNode.isValid());
+ Q_ASSERT(QScriptDeclarativeClass::scriptClass(scopeNode) == contextClass);
+ return contextClass->contextFromValue(scopeNode);
+}
+
+QScriptValue QmlEnginePrivate::createComponent(QScriptContext *ctxt,
+ QScriptEngine *engine)
+{
+ QmlEnginePrivate *activeEnginePriv =
+ static_cast<QmlScriptEngine*>(engine)->p;
+ QmlEngine* activeEngine = activeEnginePriv->q_func();
+
+ QmlContext* context = activeEnginePriv->getContext(ctxt);
+ Q_ASSERT(context);
+ if(ctxt->argumentCount() != 1) {
+ return engine->nullValue();
+ }else{
+ QString arg = ctxt->argument(0).toString();
+ if (arg.isEmpty())
+ return engine->nullValue();
+ QUrl url = QUrl(context->resolvedUrl(QUrl(arg)));
+ QmlComponent *c = new QmlComponent(activeEngine, url, activeEngine);
+ c->setCreationContext(context);
+ return activeEnginePriv->objectClass->newQObject(c, qMetaTypeId<QmlComponent*>());
+ }
+}
+
+QScriptValue QmlEnginePrivate::createQmlObject(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ QmlEnginePrivate *activeEnginePriv =
+ static_cast<QmlScriptEngine*>(engine)->p;
+ QmlEngine* activeEngine = activeEnginePriv->q_func();
+
+ if(ctxt->argumentCount() < 2 || ctxt->argumentCount() > 3)
+ return engine->nullValue();
+
+ QmlContext* context = activeEnginePriv->getContext(ctxt);
+ Q_ASSERT(context);
+
+ QString qml = ctxt->argument(0).toString();
+ if (qml.isEmpty())
+ return engine->nullValue();
+
+ QUrl url;
+ if(ctxt->argumentCount() > 2)
+ url = QUrl(ctxt->argument(2).toString());
+ else
+ url = QUrl(QLatin1String("inline"));
+
+ if (url.isValid() && url.isRelative())
+ url = context->resolvedUrl(url);
+
+ QObject *parentArg = activeEnginePriv->objectClass->toQObject(ctxt->argument(1));
+ if(!parentArg)
+ return engine->nullValue();
+
+ QmlComponent component(activeEngine);
+ component.setData(qml.toUtf8(), url);
+
+ if(component.isError()) {
+ QList<QmlError> errors = component.errors();
+ qWarning().nospace() << "QmlEngine::createQmlObject():";
+ foreach (const QmlError &error, errors)
+ qWarning().nospace() << " " << error;
+
+ return engine->nullValue();
+ }
+
+ if (!component.isReady()) {
+ qWarning().nospace() << "QmlEngine::createQmlObject(): Component is not ready";
+
+ return engine->nullValue();
+ }
+
+ QObject *obj = component.create(context);
+
+ if(component.isError()) {
+ QList<QmlError> errors = component.errors();
+ qWarning().nospace() << "QmlEngine::createQmlObject():";
+ foreach (const QmlError &error, errors)
+ qWarning().nospace() << " " << error;
+
+ return engine->nullValue();
+ }
+
+ Q_ASSERT(obj);
+
+ obj->setParent(parentArg);
+ QGraphicsObject* gobj = qobject_cast<QGraphicsObject*>(obj);
+ QGraphicsObject* gparent = qobject_cast<QGraphicsObject*>(parentArg);
+ if(gobj && gparent)
+ gobj->setParentItem(gparent);
+
+ return qmlScriptObject(obj, activeEngine);
+}
+
+QScriptValue QmlEnginePrivate::vector(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ if(ctxt->argumentCount() != 3)
+ return engine->nullValue();
+ qsreal x = ctxt->argument(0).toNumber();
+ qsreal y = ctxt->argument(1).toNumber();
+ qsreal z = ctxt->argument(2).toNumber();
+ return engine->newVariant(qVariantFromValue(QVector3D(x, y, z)));
+}
+
+QScriptValue QmlEnginePrivate::rgba(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ int argCount = ctxt->argumentCount();
+ if(argCount < 3 || argCount > 4)
+ return engine->nullValue();
+ qsreal r = ctxt->argument(0).toNumber();
+ qsreal g = ctxt->argument(1).toNumber();
+ qsreal b = ctxt->argument(2).toNumber();
+ qsreal a = (argCount == 4) ? ctxt->argument(3).toNumber() : 1;
+
+ if (r < 0 || r > 1 || g < 0 || g > 1 || b < 0 || b > 1 || a < 0 || a > 1)
+ return engine->nullValue();
+
+ return qScriptValueFromValue(engine, qVariantFromValue(QColor::fromRgbF(r, g, b, a)));
+}
+
+QScriptValue QmlEnginePrivate::hsla(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ int argCount = ctxt->argumentCount();
+ if(argCount < 3 || argCount > 4)
+ return engine->nullValue();
+ qsreal h = ctxt->argument(0).toNumber();
+ qsreal s = ctxt->argument(1).toNumber();
+ qsreal l = ctxt->argument(2).toNumber();
+ qsreal a = (argCount == 4) ? ctxt->argument(3).toNumber() : 1;
+
+ if (h < 0 || h > 1 || s < 0 || s > 1 || l < 0 || l > 1 || a < 0 || a > 1)
+ return engine->nullValue();
+
+ return qScriptValueFromValue(engine, qVariantFromValue(QColor::fromHslF(h, s, l, a)));
+}
+
+QScriptValue QmlEnginePrivate::rect(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ if(ctxt->argumentCount() != 4)
+ return engine->nullValue();
+
+ qsreal x = ctxt->argument(0).toNumber();
+ qsreal y = ctxt->argument(1).toNumber();
+ qsreal w = ctxt->argument(2).toNumber();
+ qsreal h = ctxt->argument(3).toNumber();
+
+ if (w < 0 || h < 0)
+ return engine->nullValue();
+
+ return qScriptValueFromValue(engine, qVariantFromValue(QRectF(x, y, w, h)));
+}
+
+QScriptValue QmlEnginePrivate::point(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ if(ctxt->argumentCount() != 2)
+ return engine->nullValue();
+ qsreal x = ctxt->argument(0).toNumber();
+ qsreal y = ctxt->argument(1).toNumber();
+ return qScriptValueFromValue(engine, qVariantFromValue(QPointF(x, y)));
+}
+
+QScriptValue QmlEnginePrivate::size(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ if(ctxt->argumentCount() != 2)
+ return engine->nullValue();
+ qsreal w = ctxt->argument(0).toNumber();
+ qsreal h = ctxt->argument(1).toNumber();
+ return qScriptValueFromValue(engine, qVariantFromValue(QSizeF(w, h)));
+}
+
+QScriptValue QmlEnginePrivate::lighter(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ if(ctxt->argumentCount() != 1)
+ return engine->nullValue();
+ QVariant v = ctxt->argument(0).toVariant();
+ QColor color;
+ if (v.userType() == QVariant::Color)
+ color = v.value<QColor>();
+ else if (v.userType() == QVariant::String) {
+ bool ok;
+ color = QmlStringConverters::colorFromString(v.toString(), &ok);
+ if (!ok)
+ return engine->nullValue();
+ } else
+ return engine->nullValue();
+ color = color.lighter();
+ return qScriptValueFromValue(engine, qVariantFromValue(color));
+}
+
+QScriptValue QmlEnginePrivate::darker(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ if(ctxt->argumentCount() != 1)
+ return engine->nullValue();
+ QVariant v = ctxt->argument(0).toVariant();
+ QColor color;
+ if (v.userType() == QVariant::Color)
+ color = v.value<QColor>();
+ else if (v.userType() == QVariant::String) {
+ bool ok;
+ color = QmlStringConverters::colorFromString(v.toString(), &ok);
+ if (!ok)
+ return engine->nullValue();
+ } else
+ return engine->nullValue();
+ color = color.darker();
+ return qScriptValueFromValue(engine, qVariantFromValue(color));
+}
+
+QScriptValue QmlEnginePrivate::playSound(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ if (ctxt->argumentCount() != 1)
+ return engine->undefinedValue();
+
+ QUrl url(ctxt->argument(0).toString());
+
+ QmlEnginePrivate *enginePriv = QmlEnginePrivate::get(engine);
+ if (url.isRelative()) {
+ QmlContext *context = enginePriv->getContext(ctxt);
+ if (!context)
+ return engine->undefinedValue();
+
+ url = context->resolvedUrl(url);
+ }
+
+ if (url.scheme() == QLatin1String("file")) {
+
+ QSound::play(url.toLocalFile());
+
+ }
+ return engine->undefinedValue();
+}
+
+QScriptValue QmlEnginePrivate::desktopOpenUrl(QScriptContext *ctxt, QScriptEngine *e)
+{
+ if(ctxt->argumentCount() < 1)
+ return e->newVariant(QVariant(false));
+ bool ret = QDesktopServices::openUrl(QUrl(ctxt->argument(0).toString()));
+ return e->newVariant(QVariant(ret));
+}
+
+QScriptValue QmlEnginePrivate::md5(QScriptContext *ctxt, QScriptEngine *)
+{
+ QByteArray data;
+
+ if (ctxt->argumentCount() >= 1)
+ data = ctxt->argument(0).toString().toUtf8();
+
+ QByteArray result = QCryptographicHash::hash(data, QCryptographicHash::Md5);
+
+ return QScriptValue(QLatin1String(result.toHex()));
+}
+
+QScriptValue QmlEnginePrivate::btoa(QScriptContext *ctxt, QScriptEngine *)
+{
+ QByteArray data;
+
+ if (ctxt->argumentCount() >= 1)
+ data = ctxt->argument(0).toString().toUtf8();
+
+ return QScriptValue(QLatin1String(data.toBase64()));
+}
+
+QScriptValue QmlEnginePrivate::atob(QScriptContext *ctxt, QScriptEngine *)
+{
+ QByteArray data;
+
+ if (ctxt->argumentCount() >= 1)
+ data = ctxt->argument(0).toString().toUtf8();
+
+ return QScriptValue(QLatin1String(QByteArray::fromBase64(data)));
+}
+
+QScriptValue QmlEnginePrivate::consoleLog(QScriptContext *ctxt, QScriptEngine *e)
+{
+ if(ctxt->argumentCount() < 1)
+ return e->newVariant(QVariant(false));
+
+ QByteArray msg;
+
+ for (int i=0; i<ctxt->argumentCount(); ++i) {
+ if (!msg.isEmpty()) msg += ' ';
+ msg += ctxt->argument(i).toString().toLocal8Bit();
+ // does not support firebug "%[a-z]" formatting, since firebug really
+ // does just ignore the format letter, which makes it pointless.
+ }
+
+ qDebug("%s",msg.constData());
+
+ return e->newVariant(QVariant(true));
+}
+
+void QmlEnginePrivate::sendQuit ()
+{
+ Q_Q(QmlEngine);
+ emit q->quit ();
+}
+
+QScriptValue QmlEnginePrivate::quit(QScriptContext * /*ctxt*/, QScriptEngine *e)
+{
+ QmlEnginePrivate *qe = get (e);
+ qe->sendQuit ();
+ return QScriptValue();
+}
+
+QScriptValue QmlEnginePrivate::closestAngle(QScriptContext *ctxt, QScriptEngine *e)
+{
+ if(ctxt->argumentCount() < 2)
+ return e->newVariant(QVariant(0.0));
+ qreal a = ctxt->argument(0).toNumber();
+ qreal b = ctxt->argument(1).toNumber();
+ qreal ret = b;
+ qreal diff = b-a;
+ while(diff > 180.0){
+ ret -= 360.0;
+ diff -= 360.0;
+ }
+ while(diff < -180.0){
+ ret += 360.0;
+ diff += 360.0;
+ }
+ return e->newVariant(QVariant(ret));
+}
+
+QScriptValue QmlEnginePrivate::tint(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ if(ctxt->argumentCount() != 2)
+ return engine->nullValue();
+ //get color
+ QVariant v = ctxt->argument(0).toVariant();
+ QColor color;
+ if (v.userType() == QVariant::Color)
+ color = v.value<QColor>();
+ else if (v.userType() == QVariant::String) {
+ bool ok;
+ color = QmlStringConverters::colorFromString(v.toString(), &ok);
+ if (!ok)
+ return engine->nullValue();
+ } else
+ return engine->nullValue();
+
+ //get tint color
+ v = ctxt->argument(1).toVariant();
+ QColor tintColor;
+ if (v.userType() == QVariant::Color)
+ tintColor = v.value<QColor>();
+ else if (v.userType() == QVariant::String) {
+ bool ok;
+ tintColor = QmlStringConverters::colorFromString(v.toString(), &ok);
+ if (!ok)
+ return engine->nullValue();
+ } else
+ return engine->nullValue();
+
+ //tint
+ QColor finalColor;
+ int a = tintColor.alpha();
+ if (a == 0xFF)
+ finalColor = tintColor;
+ else if (a == 0x00)
+ finalColor = color;
+ else {
+ uint src = tintColor.rgba();
+ uint dest = color.rgba();
+
+ uint res = (((a * (src & 0xFF00FF)) +
+ ((0xFF - a) * (dest & 0xFF00FF))) >> 8) & 0xFF00FF;
+ res |= (((a * ((src >> 8) & 0xFF00FF)) +
+ ((0xFF - a) * ((dest >> 8) & 0xFF00FF)))) & 0xFF00FF00;
+ if ((src & 0xFF000000) == 0xFF000000)
+ res |= 0xFF000000;
+
+ finalColor = QColor::fromRgba(res);
+ }
+
+ return qScriptValueFromValue(engine, qVariantFromValue(finalColor));
+}
+
+
+QScriptValue QmlEnginePrivate::scriptValueFromVariant(const QVariant &val)
+{
+ bool objOk;
+ QObject *obj = QmlMetaType::toQObject(val, &objOk);
+ if (objOk) {
+ return objectClass->newQObject(obj);
+ } else {
+ return qScriptValueFromValue(&scriptEngine, val);
+ }
+}
+
+QVariant QmlEnginePrivate::scriptValueToVariant(const QScriptValue &val)
+{
+ QScriptDeclarativeClass *dc = QScriptDeclarativeClass::scriptClass(val);
+ if (dc == objectClass)
+ return QVariant::fromValue(objectClass->toQObject(val));
+ else if (dc == contextClass)
+ return QVariant();
+
+ QScriptDeclarativeClass *sc = QScriptDeclarativeClass::scriptClass(val);
+ if (!sc) {
+ return val.toVariant();
+ } else if (sc == valueTypeClass) {
+ return valueTypeClass->toVariant(val);
+ } else {
+ return QVariant();
+ }
+}
+
+QmlScriptClass::QmlScriptClass(QScriptEngine *engine)
+: QScriptDeclarativeClass(engine)
+{
+}
+
+QVariant QmlScriptClass::toVariant(QmlEngine *engine, const QScriptValue &val)
+{
+ QmlEnginePrivate *ep =
+ static_cast<QmlEnginePrivate *>(QObjectPrivate::get(engine));
+
+ return ep->scriptValueToVariant(val);
+}
+
+// XXX this beyonds in QUrl::toLocalFile()
+static QString toLocalFileOrQrc(const QUrl& url)
+{
+ QString r = url.toLocalFile();
+ if (r.isEmpty() && url.scheme() == QLatin1String("qrc"))
+ r = QLatin1Char(':') + url.path();
+ return r;
+}
+
+/////////////////////////////////////////////////////////////
+struct QmlEnginePrivate::ImportedNamespace {
+ QStringList uris;
+ QStringList urls;
+ QList<int> majversions;
+ QList<int> minversions;
+ QList<bool> isLibrary;
+ QList<bool> isBuiltin; // Types provided by C++ code (including plugins)
+ QList<QString> qmlDirContent;
+
+ bool find(const QByteArray& type, int *vmajor, int *vminor, QmlType** type_return, QUrl* url_return) const
+ {
+ for (int i=0; i<urls.count(); ++i) {
+ int vmaj = majversions.at(i);
+ int vmin = minversions.at(i);
+
+ if (isBuiltin.at(i)) {
+ QByteArray qt = uris.at(i).toUtf8();
+ qt += '/';
+ qt += type;
+ if (qmlImportTrace())
+ qDebug() << "Look in" << qt;
+ QmlType *t = QmlMetaType::qmlType(qt,vmaj,vmin);
+ if (vmajor) *vmajor = vmaj;
+ if (vminor) *vminor = vmin;
+ if (t) {
+ if (qmlImportTrace())
+ qDebug() << "Found" << qt;
+ if (type_return)
+ *type_return = t;
+ return true;
+ }
+ }
+ QUrl url = QUrl(urls.at(i) + QLatin1Char('/') + QString::fromUtf8(type) + QLatin1String(".qml"));
+ QString qmldircontent = qmlDirContent.at(i);
+ if (vmaj>=0 || !qmldircontent.isEmpty()) {
+ // Check version file - XXX cache these in QmlEngine!
+ if (qmldircontent.isEmpty()) {
+ QFile qmldir(toLocalFileOrQrc(QUrl(urls.at(i)+QLatin1String("/qmldir"))));
+ if (qmldir.open(QIODevice::ReadOnly)) {
+ qmldircontent = QString::fromUtf8(qmldir.readAll());
+ }
+ }
+ QString typespace = QString::fromUtf8(type)+QLatin1Char(' ');
+ QStringList lines = qmldircontent.split(QLatin1Char('\n'));
+ foreach (QString line, lines) {
+ if (line.isEmpty() || line.at(0) == QLatin1Char('#'))
+ continue;
+ if (line.startsWith(typespace)) {
+ int space1 = line.indexOf(QLatin1Char(' '));
+ int space2 = space1 >=0 ? line.indexOf(QLatin1Char(' '),space1+1) : -1;
+ QString mapversions = line.mid(space1+1,space2<0?line.length()-space1-1:space2-space1-1);
+ int dot = mapversions.indexOf(QLatin1Char('.'));
+ int mapvmaj = mapversions.left(dot).toInt();
+ if (mapvmaj<=vmaj) {
+ if (mapvmaj<vmaj || vmin >= mapversions.mid(dot+1).toInt()) {
+ QStringRef mapfile = space2<0 ? QStringRef() : line.midRef(space2+1,line.length()-space2-1);
+ if (url_return)
+ *url_return = url.resolved(QUrl(mapfile.toString()));
+ return true;
+ }
+ }
+ }
+ }
+ } else {
+ // XXX search non-files too! (eg. zip files, see QT-524)
+ QFileInfo f(toLocalFileOrQrc(url));
+ if (f.exists()) {
+ if (url_return)
+ *url_return = url;
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+};
+
+Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
+ (QmlModuleFactoryInterface_iid, QLatin1String("/qmlmodules")))
+
+class QmlImportsPrivate {
+public:
+ QmlImportsPrivate() : ref(1)
+ {
+ }
+
+ ~QmlImportsPrivate()
+ {
+ foreach (QmlEnginePrivate::ImportedNamespace* s, set.values())
+ delete s;
+ }
+
+ bool add(const QUrl& base, const QString& qmldircontent, const QString& uri, const QString& prefix, int vmaj, int vmin, QmlScriptParser::Import::Type importType, const QStringList& importPath)
+ {
+ QmlEnginePrivate::ImportedNamespace *s;
+ if (prefix.isEmpty()) {
+ s = &unqualifiedset;
+ } else {
+ s = set.value(prefix);
+ if (!s)
+ set.insert(prefix,(s=new QmlEnginePrivate::ImportedNamespace));
+ }
+ QString url = uri;
+ bool isbuiltin = false;
+ if (importType == QmlScriptParser::Import::Library) {
+ url.replace(QLatin1Char('.'),QLatin1Char('/'));
+ bool found = false;
+ foreach (QString p, importPath) {
+ QString dir = p+QLatin1Char('/')+url;
+ QFileInfo fi(dir+QLatin1String("/qmldir"));
+ if (fi.isFile()) {
+ url = QUrl::fromLocalFile(fi.absolutePath()).toString();
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ // XXX assume it is a built-in type qualifier
+ isbuiltin = true;
+ }
+ QFactoryLoader *l = loader();
+ QmlModuleFactoryInterface *factory =
+ qobject_cast<QmlModuleFactoryInterface*>(l->instance(uri));
+ if (factory) {
+ factory->defineModuleOnce(uri);
+ isbuiltin = true;
+ }
+ } else {
+ url = base.resolved(QUrl(url)).toString();
+ }
+ s->uris.prepend(uri);
+ s->urls.prepend(url);
+ s->majversions.prepend(vmaj);
+ s->minversions.prepend(vmin);
+ s->isLibrary.prepend(importType == QmlScriptParser::Import::Library);
+ s->isBuiltin.prepend(isbuiltin);
+ s->qmlDirContent.prepend(qmldircontent);
+ return true;
+ }
+
+ bool find(const QByteArray& type, int *vmajor, int *vminor, QmlType** type_return, QUrl* url_return)
+ {
+ QmlEnginePrivate::ImportedNamespace *s = 0;
+ int slash = type.indexOf('/');
+ if (slash >= 0) {
+ s = set.value(QString::fromUtf8(type.left(slash)));
+ if (!s)
+ return false; // qualifier must be a namespace
+ int nslash = type.indexOf('/',slash+1);
+ if (nslash > 0)
+ return false; // only single qualification allowed
+ } else {
+ s = &unqualifiedset;
+ }
+ QByteArray unqualifiedtype = slash < 0 ? type : type.mid(slash+1); // common-case opt (QString::mid works fine, but slower)
+ if (s) {
+ if (s->find(unqualifiedtype,vmajor,vminor,type_return,url_return))
+ return true;
+ if (s->urls.count() == 1 && !s->isBuiltin[0] && !s->isLibrary[0] && url_return) {
+ *url_return = QUrl(s->urls[0]+QLatin1Char('/')).resolved(QUrl(QString::fromUtf8(unqualifiedtype) + QLatin1String(".qml")));
+ return true;
+ }
+ }
+ if (url_return) {
+ *url_return = base.resolved(QUrl(QString::fromUtf8(type + ".qml")));
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ QmlEnginePrivate::ImportedNamespace *findNamespace(const QString& type)
+ {
+ return set.value(type);
+ }
+
+ QUrl base;
+ int ref;
+
+private:
+ friend struct QmlEnginePrivate::Imports;
+ QmlEnginePrivate::ImportedNamespace unqualifiedset;
+ QHash<QString,QmlEnginePrivate::ImportedNamespace* > set;
+};
+
+QmlEnginePrivate::Imports::Imports(const Imports &copy) :
+ d(copy.d)
+{
+ ++d->ref;
+}
+
+QmlEnginePrivate::Imports &QmlEnginePrivate::Imports::operator =(const Imports &copy)
+{
+ ++copy.d->ref;
+ if (--d->ref == 0)
+ delete d;
+ d = copy.d;
+ return *this;
+}
+
+QmlEnginePrivate::Imports::Imports() :
+ d(new QmlImportsPrivate)
+{
+}
+
+QmlEnginePrivate::Imports::~Imports()
+{
+ if (--d->ref == 0)
+ delete d;
+}
+
+#include "qmlmetatype.h"
+#include "qmltypenamecache_p.h"
+
+static QmlTypeNameCache *cacheForNamespace(QmlEngine *engine, const QmlEnginePrivate::ImportedNamespace &set, QmlTypeNameCache *cache)
+{
+ if (!cache)
+ cache = new QmlTypeNameCache(engine);
+
+ QList<QmlType *> types = QmlMetaType::qmlTypes();
+
+ for (int ii = 0; ii < set.uris.count(); ++ii) {
+ if (!set.isBuiltin.at(ii))
+ continue;
+
+ QByteArray base = set.uris.at(ii).toUtf8() + '/';
+ int major = set.majversions.at(ii);
+ int minor = set.minversions.at(ii);
+
+ foreach (QmlType *type, types) {
+ if (type->qmlTypeName().startsWith(base) &&
+ type->qmlTypeName().lastIndexOf('/') == (base.length() - 1) &&
+ type->availableInVersion(major,minor))
+ {
+ QString name = QString::fromUtf8(type->qmlTypeName().mid(base.length()));
+
+ cache->add(name, type);
+ }
+ }
+ }
+
+ return cache;
+}
+
+QmlTypeNameCache *QmlEnginePrivate::Imports::cache(QmlEngine *engine) const
+{
+ const QmlEnginePrivate::ImportedNamespace &set = d->unqualifiedset;
+
+ QmlTypeNameCache *cache = new QmlTypeNameCache(engine);
+
+ for (QHash<QString,QmlEnginePrivate::ImportedNamespace* >::ConstIterator iter = d->set.begin();
+ iter != d->set.end(); ++iter) {
+
+ QmlTypeNameCache::Data *d = cache->data(iter.key());
+ if (d) {
+ if (!d->typeNamespace)
+ cacheForNamespace(engine, *(*iter), d->typeNamespace);
+ } else {
+ QmlTypeNameCache *nc = cacheForNamespace(engine, *(*iter), 0);
+ cache->add(iter.key(), nc);
+ nc->release();
+ }
+ }
+
+ cacheForNamespace(engine, set, cache);
+
+ return cache;
+}
+
+/*
+QStringList QmlEnginePrivate::Imports::unqualifiedSet() const
+{
+ QStringList rv;
+
+ const QmlEnginePrivate::ImportedNamespace &set = d->unqualifiedset;
+
+ for (int ii = 0; ii < set.urls.count(); ++ii) {
+ if (set.isBuiltin.at(ii))
+ rv << set.urls.at(ii);
+ }
+
+ return rv;
+}
+*/
+
+/*!
+ Sets the base URL to be used for all relative file imports added.
+*/
+void QmlEnginePrivate::Imports::setBaseUrl(const QUrl& url)
+{
+ d->base = url;
+}
+
+/*!
+ Returns the base URL to be used for all relative file imports added.
+*/
+QUrl QmlEnginePrivate::Imports::baseUrl() const
+{
+ return d->base;
+}
+
+/*!
+ Adds \a path as a directory where installed QML components are
+ defined in a URL-based directory structure.
+
+ For example, if you add \c /opt/MyApp/lib/qml and then load QML
+ that imports \c com.mycompany.Feature, then QmlEngine will look
+ in \c /opt/MyApp/lib/qml/com/mycompany/Feature/ for the components
+ provided by that module (and in the case of versioned imports,
+ for the \c qmldir file definiting the type version mapping.
+
+ By default, only the "qml" subdirectory of QLibraryInfo::location(QLibraryInfo::DataPath)
+ is included on the import path.
+*/
+void QmlEngine::addImportPath(const QString& path)
+{
+ if (qmlImportTrace())
+ qDebug() << "QmlEngine::addImportPath" << path;
+ Q_D(QmlEngine);
+ d->fileImportPath.prepend(path);
+}
+
+/*!
+ \property QmlEngine::offlineStoragePath
+ \brief the directory for storing offline user data
+
+ Returns the directory where SQL and other offline
+ storage is placed.
+
+ QmlGraphicsWebView and the SQL databases created with openDatabase()
+ are stored here.
+
+ The default is QML/OfflineStorage in the platform-standard
+ user application data directory.
+
+ Note that the path may not currently exist on the filesystem, so
+ callers wanting to \e create new files at this location should create
+ it first - see QDir::mkpath().
+*/
+void QmlEngine::setOfflineStoragePath(const QString& dir)
+{
+ Q_D(QmlEngine);
+ d->scriptEngine.offlineStoragePath = dir;
+}
+
+QString QmlEngine::offlineStoragePath() const
+{
+ Q_D(const QmlEngine);
+ return d->scriptEngine.offlineStoragePath;
+}
+
+
+/*!
+ \internal
+
+ Adds information to \a imports such that subsequent calls to resolveType()
+ will resolve types qualified by \a prefix by considering types found at the given \a uri.
+
+ The uri is either a directory (if importType is FileImport), or a URI resolved using paths
+ added via addImportPath() (if importType is LibraryImport).
+
+ The \a prefix may be empty, in which case the import location is considered for
+ unqualified types.
+
+ The base URL must already have been set with Import::setBaseUrl().
+*/
+bool QmlEnginePrivate::addToImport(Imports* imports, const QString& qmldircontent, const QString& uri, const QString& prefix, int vmaj, int vmin, QmlScriptParser::Import::Type importType) const
+{
+ bool ok = imports->d->add(imports->d->base,qmldircontent,uri,prefix,vmaj,vmin,importType,fileImportPath);
+ if (qmlImportTrace())
+ qDebug() << "QmlEngine::addToImport(" << imports << uri << prefix << vmaj << '.' << vmin << (importType==QmlScriptParser::Import::Library? "Library" : "File") << ": " << ok;
+ return ok;
+}
+
+/*!
+ \internal
+
+ Using the given \a imports, the given (namespace qualified) \a type is resolved to either
+ an ImportedNamespace stored at \a ns_return,
+ a QmlType stored at \a type_return, or
+ a component located at \a url_return.
+
+ If any return pointer is 0, the corresponding search is not done.
+
+ \sa addToImport()
+*/
+bool QmlEnginePrivate::resolveType(const Imports& imports, const QByteArray& type, QmlType** type_return, QUrl* url_return, int *vmaj, int *vmin, ImportedNamespace** ns_return) const
+{
+ ImportedNamespace* ns = imports.d->findNamespace(QString::fromUtf8(type));
+ if (ns) {
+ if (qmlImportTrace())
+ qDebug() << "QmlEngine::resolveType" << type << "is namespace for" << ns->urls;
+ if (ns_return)
+ *ns_return = ns;
+ return true;
+ }
+ if (type_return || url_return) {
+ if (imports.d->find(type,vmaj,vmin,type_return,url_return)) {
+ if (qmlImportTrace()) {
+ if (type_return && *type_return)
+ qDebug() << "QmlEngine::resolveType" << type << '=' << (*type_return)->typeName();
+ if (url_return)
+ qDebug() << "QmlEngine::resolveType" << type << '=' << *url_return;
+ }
+ return true;
+ }
+ if (qmlImportTrace())
+ qDebug() << "QmlEngine::resolveType" << type << "not found";
+ }
+ return false;
+}
+
+/*!
+ \internal
+
+ Searching \e only in the namespace \a ns (previously returned in a call to
+ resolveType(), \a type is found and returned to either
+ a QmlType stored at \a type_return, or
+ a component located at \a url_return.
+
+ If either return pointer is 0, the corresponding search is not done.
+*/
+void QmlEnginePrivate::resolveTypeInNamespace(ImportedNamespace* ns, const QByteArray& type, QmlType** type_return, QUrl* url_return, int *vmaj, int *vmin ) const
+{
+ ns->find(type,vmaj,vmin,type_return,url_return);
+}
+
+static void voidptr_destructor(void *v)
+{
+ void **ptr = (void **)v;
+ delete ptr;
+}
+
+static void *voidptr_constructor(const void *v)
+{
+ if (!v) {
+ return new void*;
+ } else {
+ return new void*(*(void **)v);
+ }
+}
+
+void QmlEnginePrivate::registerCompositeType(QmlCompiledData *data)
+{
+ QByteArray name = data->root->className();
+
+ QByteArray ptr = name + '*';
+ QByteArray lst = "QmlList<" + ptr + ">*";
+
+ int ptr_type = QMetaType::registerType(ptr.constData(), voidptr_destructor,
+ voidptr_constructor);
+ int lst_type = QMetaType::registerType(lst.constData(), voidptr_destructor,
+ voidptr_constructor);
+
+ m_qmlLists.insert(lst_type, ptr_type);
+ m_compositeTypes.insert(ptr_type, data);
+ data->addref();
+}
+
+bool QmlEnginePrivate::isQmlList(int t) const
+{
+ return m_qmlLists.contains(t) || QmlMetaType::isQmlList(t);
+}
+
+bool QmlEnginePrivate::isQObject(int t)
+{
+ return m_compositeTypes.contains(t) || QmlMetaType::isQObject(t);
+}
+
+QObject *QmlEnginePrivate::toQObject(const QVariant &v, bool *ok) const
+{
+ int t = v.userType();
+ if (m_compositeTypes.contains(t)) {
+ if (ok) *ok = true;
+ return *(QObject **)(v.constData());
+ } else {
+ return QmlMetaType::toQObject(v, ok);
+ }
+}
+
+int QmlEnginePrivate::qmlListType(int t) const
+{
+ QHash<int, int>::ConstIterator iter = m_qmlLists.find(t);
+ if (iter != m_qmlLists.end())
+ return *iter;
+ else
+ return QmlMetaType::qmlListType(t);
+}
+
+QmlMetaType::TypeCategory QmlEnginePrivate::typeCategory(int t) const
+{
+ if (m_compositeTypes.contains(t))
+ return QmlMetaType::Object;
+ else if (m_qmlLists.contains(t))
+ return QmlMetaType::QmlList;
+ else
+ return QmlMetaType::typeCategory(t);
+}
+
+const QMetaObject *QmlEnginePrivate::rawMetaObjectForType(int t) const
+{
+ QHash<int, QmlCompiledData*>::ConstIterator iter = m_compositeTypes.find(t);
+ if (iter != m_compositeTypes.end()) {
+ return (*iter)->root;
+ } else {
+ QmlType *type = QmlMetaType::qmlType(t);
+ return type?type->baseMetaObject():0;
+ }
+}
+
+const QMetaObject *QmlEnginePrivate::metaObjectForType(int t) const
+{
+ QHash<int, QmlCompiledData*>::ConstIterator iter = m_compositeTypes.find(t);
+ if (iter != m_compositeTypes.end()) {
+ return (*iter)->root;
+ } else {
+ QmlType *type = QmlMetaType::qmlType(t);
+ return type?type->metaObject():0;
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlengine.h b/src/declarative/qml/qmlengine.h
new file mode 100644
index 0000000..7ee014a
--- /dev/null
+++ b/src/declarative/qml/qmlengine.h
@@ -0,0 +1,106 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLENGINE_H
+#define QMLENGINE_H
+
+#include <QtCore/qurl.h>
+#include <QtCore/qobject.h>
+#include <QtCore/qmap.h>
+#include <QtScript/qscriptvalue.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlComponent;
+class QmlEnginePrivate;
+class QmlImportsPrivate;
+class QmlExpression;
+class QmlContext;
+class QmlType;
+class QUrl;
+class QScriptEngine;
+class QScriptContext;
+class QNetworkAccessManager;
+class QmlNetworkAccessManagerFactory;
+class Q_DECLARATIVE_EXPORT QmlEngine : public QObject
+{
+ Q_PROPERTY(QString offlineStoragePath READ offlineStoragePath WRITE setOfflineStoragePath)
+ Q_OBJECT
+public:
+ QmlEngine(QObject *p = 0);
+ virtual ~QmlEngine();
+
+ QmlContext *rootContext();
+
+ void clearComponentCache();
+
+ void addImportPath(const QString& dir);
+
+ void setNetworkAccessManagerFactory(QmlNetworkAccessManagerFactory *);
+ QmlNetworkAccessManagerFactory *networkAccessManagerFactory() const;
+
+ QNetworkAccessManager *networkAccessManager() const;
+
+ void setOfflineStoragePath(const QString& dir);
+ QString offlineStoragePath() const;
+
+ QUrl baseUrl() const;
+ void setBaseUrl(const QUrl &);
+
+ static QmlContext *contextForObject(const QObject *);
+ static void setContextForObject(QObject *, QmlContext *);
+
+Q_SIGNALS:
+ void quit ();
+
+private:
+ Q_DECLARE_PRIVATE(QmlEngine)
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLENGINE_H
diff --git a/src/declarative/qml/qmlengine_p.h b/src/declarative/qml/qmlengine_p.h
new file mode 100644
index 0000000..13ed5ef
--- /dev/null
+++ b/src/declarative/qml/qmlengine_p.h
@@ -0,0 +1,320 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLENGINE_P_H
+#define QMLENGINE_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 "qmlengine.h"
+
+#include "qmlclassfactory_p.h"
+#include "qmlcompositetypemanager_p.h"
+#include "qpodvector_p.h"
+#include "qml.h"
+#include "qmlvaluetype_p.h"
+#include "qmlcontext.h"
+#include "qmlexpression.h"
+#include "qmlmetaproperty_p.h"
+#include "qmlpropertycache_p.h"
+#include "qmlobjectscriptclass_p.h"
+#include "qmlcontextscriptclass_p.h"
+#include "qmlvaluetypescriptclass_p.h"
+
+#include <QtScript/QScriptClass>
+#include <QtScript/QScriptValue>
+#include <QtScript/QScriptString>
+#include <QtCore/qstring.h>
+#include <QtCore/qlist.h>
+#include <QtCore/qpair.h>
+#include <QtCore/qstack.h>
+#include <QtScript/qscriptengine.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlContext;
+class QmlEngine;
+class QmlContextPrivate;
+class QmlExpression;
+class QmlContextScriptClass;
+class QmlObjectScriptClass;
+class QmlTypeNameScriptClass;
+class QmlValueTypeScriptClass;
+class QScriptEngineDebugger;
+class QNetworkReply;
+class QNetworkAccessManager;
+class QmlNetworkAccessManagerFactory;
+class QmlAbstractBinding;
+class QScriptDeclarativeClass;
+class QmlTypeNameScriptClass;
+class QmlTypeNameCache;
+class QmlComponentAttached;
+class QmlListScriptClass;
+class QmlCleanup;
+class QmlDelayedError;
+class QmlWorkerScriptEngine;
+class QmlGlobalScriptClass;
+
+class QmlScriptEngine : public QScriptEngine
+{
+public:
+ QmlScriptEngine(QmlEnginePrivate *priv);
+ virtual ~QmlScriptEngine();
+
+ QUrl resolvedUrl(QScriptContext *context, const QUrl& url); // resolved against p's context, or baseUrl if no p
+ static QScriptValue resolvedUrl(QScriptContext *ctxt, QScriptEngine *engine);
+
+ static QmlScriptEngine *get(QScriptEngine* e) { return static_cast<QmlScriptEngine*>(e); }
+
+ QmlEnginePrivate *p;
+
+ // User by SQL API
+ QScriptClass *sqlQueryClass;
+ QString offlineStoragePath;
+
+ // Used by DOM Core 3 API
+ QScriptClass *namedNodeMapClass;
+ QScriptClass *nodeListClass;
+
+ QUrl baseUrl;
+
+ virtual QNetworkAccessManager *networkAccessManager();
+};
+
+class Q_AUTOTEST_EXPORT QmlEnginePrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlEngine)
+public:
+ QmlEnginePrivate(QmlEngine *);
+ ~QmlEnginePrivate();
+
+ void init();
+
+ struct CapturedProperty {
+ CapturedProperty(QObject *o, int c, int n)
+ : object(o), coreIndex(c), notifyIndex(n) {}
+
+ QObject *object;
+ int coreIndex;
+ int notifyIndex;
+ };
+ bool captureProperties;
+ QPODVector<CapturedProperty> capturedProperties;
+
+ QmlContext *rootContext;
+ QmlExpression *currentExpression;
+ bool isDebugging;
+
+ struct ImportedNamespace;
+ QmlContextScriptClass *contextClass;
+ QmlContext *sharedContext;
+ QObject *sharedScope;
+ QmlObjectScriptClass *objectClass;
+ QmlValueTypeScriptClass *valueTypeClass;
+ QmlTypeNameScriptClass *typeNameClass;
+ QmlListScriptClass *listClass;
+ // Global script class
+ QmlGlobalScriptClass *globalClass;
+
+ // Registered cleanup handlers
+ QmlCleanup *cleanup;
+
+ // Bindings that have had errors during startup
+ QmlDelayedError *erroredBindings;
+ int inProgressCreations;
+
+ QmlScriptEngine scriptEngine;
+
+ QmlWorkerScriptEngine *getWorkerScriptEngine();
+ QmlWorkerScriptEngine *workerScriptEngine;
+
+ QUrl baseUrl;
+
+ template<class T>
+ struct SimpleList {
+ SimpleList()
+ : count(0), values(0) {}
+ SimpleList(int r)
+ : count(0), values(new T*[r]) {}
+
+ int count;
+ T **values;
+
+ void append(T *v) {
+ values[count++] = v;
+ }
+
+ T *at(int idx) const {
+ return values[idx];
+ }
+
+ void clear() {
+ delete [] values;
+ }
+ };
+
+ static void clear(SimpleList<QmlAbstractBinding> &);
+ static void clear(SimpleList<QmlParserStatus> &);
+
+ QList<SimpleList<QmlAbstractBinding> > bindValues;
+ QList<SimpleList<QmlParserStatus> > parserStatus;
+ QmlComponentAttached *componentAttacheds;
+
+ bool inBeginCreate;
+
+ QNetworkAccessManager *getNetworkAccessManager() const;
+ mutable QNetworkAccessManager *networkAccessManager;
+ mutable QmlNetworkAccessManagerFactory *networkAccessManagerFactory;
+
+ QmlCompositeTypeManager typeManager;
+ QStringList fileImportPath;
+ QString offlineStoragePath;
+
+ mutable quint32 uniqueId;
+ quint32 getUniqueId() const {
+ return uniqueId++;
+ }
+
+ QmlValueTypeFactory valueTypes;
+
+ QHash<const QMetaObject *, QmlPropertyCache *> propertyCache;
+ QmlPropertyCache *cache(QObject *obj) {
+ Q_Q(QmlEngine);
+ if (!obj || QObjectPrivate::get(obj)->metaObject) return 0;
+ const QMetaObject *mo = obj->metaObject();
+ QmlPropertyCache *rv = propertyCache.value(mo);
+ if (!rv) {
+ rv = QmlPropertyCache::create(q, mo);
+ propertyCache.insert(mo, rv);
+ }
+ return rv;
+ }
+
+ // ### This whole class is embarrassing
+ struct Imports {
+ Imports();
+ ~Imports();
+ Imports(const Imports &copy);
+ Imports &operator =(const Imports &copy);
+
+ void setBaseUrl(const QUrl& url);
+ QUrl baseUrl() const;
+
+ QmlTypeNameCache *cache(QmlEngine *) const;
+
+ private:
+ friend class QmlEnginePrivate;
+ QmlImportsPrivate *d;
+ };
+
+ bool addToImport(Imports*, const QString& qmlDirContent,const QString& uri, const QString& prefix, int vmaj, int vmin, QmlScriptParser::Import::Type importType) const;
+ bool resolveType(const Imports&, const QByteArray& type,
+ QmlType** type_return, QUrl* url_return,
+ int *version_major, int *version_minor,
+ ImportedNamespace** ns_return) const;
+ void resolveTypeInNamespace(ImportedNamespace*, const QByteArray& type,
+ QmlType** type_return, QUrl* url_return,
+ int *version_major, int *version_minor ) const;
+
+
+ void registerCompositeType(QmlCompiledData *);
+ bool isQmlList(int) const;
+ bool isQObject(int);
+ QObject *toQObject(const QVariant &, bool *ok = 0) const;
+ int qmlListType(int) const;
+ QmlMetaType::TypeCategory typeCategory(int) const;
+ const QMetaObject *rawMetaObjectForType(int) const;
+ const QMetaObject *metaObjectForType(int) const;
+ QHash<int, int> m_qmlLists;
+ QHash<int, QmlCompiledData *> m_compositeTypes;
+
+ QScriptValue scriptValueFromVariant(const QVariant &);
+ QVariant scriptValueToVariant(const QScriptValue &);
+
+ void sendQuit ();
+
+ static QScriptValue qmlScriptObject(QObject*, QmlEngine*);
+
+ static QScriptValue createComponent(QScriptContext*, QScriptEngine*);
+ static QScriptValue createQmlObject(QScriptContext*, QScriptEngine*);
+ static QScriptValue vector(QScriptContext*, QScriptEngine*);
+ static QScriptValue rgba(QScriptContext*, QScriptEngine*);
+ static QScriptValue hsla(QScriptContext*, QScriptEngine*);
+ static QScriptValue point(QScriptContext*, QScriptEngine*);
+ static QScriptValue size(QScriptContext*, QScriptEngine*);
+ static QScriptValue rect(QScriptContext*, QScriptEngine*);
+
+ static QScriptValue lighter(QScriptContext*, QScriptEngine*);
+ static QScriptValue darker(QScriptContext*, QScriptEngine*);
+ static QScriptValue tint(QScriptContext*, QScriptEngine*);
+
+ static QScriptValue closestAngle(QScriptContext*, QScriptEngine*);
+ static QScriptValue playSound(QScriptContext*, QScriptEngine*);
+ static QScriptValue desktopOpenUrl(QScriptContext*, QScriptEngine*);
+ static QScriptValue md5(QScriptContext*, QScriptEngine*);
+ static QScriptValue btoa(QScriptContext*, QScriptEngine*);
+ static QScriptValue atob(QScriptContext*, QScriptEngine*);
+ static QScriptValue consoleLog(QScriptContext*, QScriptEngine*);
+ static QScriptValue quit(QScriptContext*, QScriptEngine*);
+
+ static QScriptEngine *getScriptEngine(QmlEngine *e) { return &e->d_func()->scriptEngine; }
+ static QmlEngine *getEngine(QScriptEngine *e) { return static_cast<QmlScriptEngine*>(e)->p->q_func(); }
+ static QmlEnginePrivate *get(QmlEngine *e) { return e->d_func(); }
+ static QmlEnginePrivate *get(QScriptEngine *e) { return static_cast<QmlScriptEngine*>(e)->p; }
+ static QmlEngine *get(QmlEnginePrivate *p) { return p->q_func(); }
+ QmlContext *getContext(QScriptContext *);
+};
+
+
+QT_END_NAMESPACE
+
+#endif // QMLENGINE_P_H
diff --git a/src/declarative/qml/qmlenginedebug.cpp b/src/declarative/qml/qmlenginedebug.cpp
new file mode 100644
index 0000000..b0c1ec9
--- /dev/null
+++ b/src/declarative/qml/qmlenginedebug.cpp
@@ -0,0 +1,457 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlenginedebug_p.h"
+
+#include "qmlboundsignal_p.h"
+#include "qmlengine.h"
+#include "qmlmetatype.h"
+#include "qmlmetaproperty.h"
+#include "qmlbinding.h"
+#include "qmlcontext_p.h"
+#include "qmlwatcher_p.h"
+
+#include <QtCore/qdebug.h>
+#include <QtCore/qmetaobject.h>
+
+QT_BEGIN_NAMESPACE
+
+QList<QmlEngine *> QmlEngineDebugServer::m_engines;
+QmlEngineDebugServer::QmlEngineDebugServer(QObject *parent)
+: QmlDebugService(QLatin1String("QmlEngine"), parent),
+ m_watch(new QmlWatcher(this))
+{
+ QObject::connect(m_watch, SIGNAL(propertyChanged(int,int,QMetaProperty,QVariant)),
+ this, SLOT(propertyChanged(int,int,QMetaProperty,QVariant)));
+}
+
+QDataStream &operator<<(QDataStream &ds,
+ const QmlEngineDebugServer::QmlObjectData &data)
+{
+ ds << data.url << data.lineNumber << data.columnNumber << data.objectName
+ << data.objectType << data.objectId << data.contextId;
+ return ds;
+}
+
+QDataStream &operator>>(QDataStream &ds,
+ QmlEngineDebugServer::QmlObjectData &data)
+{
+ ds >> data.url >> data.lineNumber >> data.columnNumber >> data.objectName
+ >> data.objectType >> data.objectId >> data.contextId;
+ return ds;
+}
+
+QDataStream &operator<<(QDataStream &ds,
+ const QmlEngineDebugServer::QmlObjectProperty &data)
+{
+ ds << (int)data.type << data.name << data.value << data.valueTypeName
+ << data.binding << data.hasNotifySignal;
+ return ds;
+}
+
+QDataStream &operator>>(QDataStream &ds,
+ QmlEngineDebugServer::QmlObjectProperty &data)
+{
+ int type;
+ ds >> type >> data.name >> data.value >> data.valueTypeName
+ >> data.binding >> data.hasNotifySignal;
+ data.type = (QmlEngineDebugServer::QmlObjectProperty::Type)type;
+ return ds;
+}
+
+QmlEngineDebugServer::QmlObjectProperty
+QmlEngineDebugServer::propertyData(QObject *obj, int propIdx)
+{
+ QmlObjectProperty rv;
+
+ QMetaProperty prop = obj->metaObject()->property(propIdx);
+
+ rv.type = QmlObjectProperty::Unknown;
+ rv.valueTypeName = QString::fromUtf8(prop.typeName());
+ rv.name = QString::fromUtf8(prop.name());
+ rv.hasNotifySignal = prop.hasNotifySignal();
+ QmlAbstractBinding *binding = QmlMetaProperty(obj, rv.name).binding();
+ if (binding)
+ rv.binding = binding->expression();
+
+ QVariant value = prop.read(obj);
+ rv.value = valueContents(value);
+
+ if (QVariant::Type(prop.userType()) < QVariant::UserType) {
+ rv.type = QmlObjectProperty::Basic;
+ } else if (QmlMetaType::isQObject(prop.userType())) {
+ rv.type = QmlObjectProperty::Object;
+ } else if (QmlMetaType::isList(prop.userType()) ||
+ QmlMetaType::isQmlList(prop.userType())) {
+ rv.type = QmlObjectProperty::List;
+ }
+
+ return rv;
+}
+
+QVariant QmlEngineDebugServer::valueContents(const QVariant &value) const
+{
+ int userType = value.userType();
+ if (QVariant::Type(userType) < QVariant::UserType)
+ return value;
+
+
+ if (QmlMetaType::isList(userType) || QmlMetaType::isQmlList(userType)) {
+ int count = QmlMetaType::listCount(value);
+ QVariantList contents;
+ for (int i=0; i<count; i++)
+ contents << valueContents(QmlMetaType::listAt(value, i));
+ return contents;
+ } else if (QmlMetaType::isQObject(userType)) {
+ QObject *o = QmlMetaType::toQObject(value);
+ if (o) {
+ QString name = o->objectName();
+ if (name.isEmpty())
+ name = QLatin1String("<unnamed object>");
+ return name;
+ }
+ }
+
+ return QLatin1String("<unknown value>");
+}
+
+void QmlEngineDebugServer::buildObjectDump(QDataStream &message,
+ QObject *object, bool recur)
+{
+ message << objectData(object);
+
+ // Some children aren't added to an object until particular properties are read
+ // - e.g. child state objects aren't added until the 'states' property is read -
+ // but this should only affect internal objects that aren't shown by the
+ // debugger anyway.
+
+ QObjectList children = object->children();
+
+ int childrenCount = children.count();
+ for (int ii = 0; ii < children.count(); ++ii) {
+ if (qobject_cast<QmlContext*>(children[ii]) || QmlBoundSignal::cast(children[ii]))
+ --childrenCount;
+ }
+
+ message << childrenCount << recur;
+
+ QList<QmlObjectProperty> fakeProperties;
+
+ for (int ii = 0; ii < children.count(); ++ii) {
+ QObject *child = children.at(ii);
+ if (qobject_cast<QmlContext*>(child))
+ continue;
+ QmlBoundSignal *signal = QmlBoundSignal::cast(child);
+ if (signal) {
+ QmlObjectProperty prop;
+ prop.type = QmlObjectProperty::SignalProperty;
+ prop.hasNotifySignal = false;
+ QmlExpression *expr = signal->expression();
+ if (expr) {
+ prop.value = expr->expression();
+ QObject *scope = expr->scopeObject();
+ if (scope) {
+ QString sig = QLatin1String(scope->metaObject()->method(signal->index()).signature());
+ int lparen = sig.indexOf(QLatin1Char('('));
+ if (lparen >= 0) {
+ QString methodName = sig.mid(0, lparen);
+ prop.name = QLatin1String("on") + methodName[0].toUpper()
+ + methodName.mid(1);
+ }
+ }
+ }
+ fakeProperties << prop;
+ } else {
+ if (recur)
+ buildObjectDump(message, child, recur);
+ else
+ message << objectData(child);
+ }
+ }
+
+ message << (object->metaObject()->propertyCount() + fakeProperties.count());
+
+ for (int ii = 0; ii < object->metaObject()->propertyCount(); ++ii)
+ message << propertyData(object, ii);
+
+ for (int ii = 0; ii < fakeProperties.count(); ++ii)
+ message << fakeProperties[ii];
+}
+
+void QmlEngineDebugServer::buildObjectList(QDataStream &message,
+ QmlContext *ctxt)
+{
+ QmlContextPrivate *p = (QmlContextPrivate *)QObjectPrivate::get(ctxt);
+
+ QString ctxtName = ctxt->objectName();
+ int ctxtId = QmlDebugService::idForObject(ctxt);
+
+ message << ctxtName << ctxtId;
+
+ int count = 0;
+
+ for (QSet<QmlContext *>::ConstIterator iter = p->childContexts.begin();
+ iter != p->childContexts.end(); ++iter) {
+ QmlContextPrivate *p = (QmlContextPrivate *)QObjectPrivate::get(*iter);
+ if (p->isInternal)
+ continue;
+ ++count;
+ }
+
+ message << count;
+
+ for (QSet<QmlContext *>::ConstIterator iter = p->childContexts.begin();
+ iter != p->childContexts.end(); ++iter) {
+ QmlContextPrivate *p = (QmlContextPrivate *)QObjectPrivate::get(*iter);
+ if (p->isInternal)
+ continue;
+ buildObjectList(message, *iter);
+ }
+
+ // Clean deleted objects
+ for (int ii = 0; ii < p->instances.count(); ++ii) {
+ if (!p->instances.at(ii)) {
+ p->instances.removeAt(ii);
+ --ii;
+ }
+ }
+
+ message << p->instances.count();
+ for (int ii = 0; ii < p->instances.count(); ++ii) {
+ message << objectData(p->instances.at(ii));
+ }
+}
+
+QmlEngineDebugServer::QmlObjectData
+QmlEngineDebugServer::objectData(QObject *object)
+{
+ QmlDeclarativeData *ddata = QmlDeclarativeData::get(object);
+ QmlObjectData rv;
+ if (ddata) {
+ rv.url = ddata->outerContext->baseUrl();
+ rv.lineNumber = ddata->lineNumber;
+ rv.columnNumber = ddata->columnNumber;
+ } else {
+ rv.lineNumber = -1;
+ rv.columnNumber = -1;
+ }
+
+ rv.objectName = object->objectName();
+ rv.objectId = QmlDebugService::idForObject(object);
+ rv.contextId = QmlDebugService::idForObject(qmlContext(object));
+
+ QmlType *type = QmlMetaType::qmlType(object->metaObject());
+ if (type) {
+ QString typeName = QLatin1String(type->qmlTypeName());
+ int lastSlash = typeName.lastIndexOf(QLatin1Char('/'));
+ rv.objectType = lastSlash < 0 ? typeName : typeName.mid(lastSlash+1);
+ } else {
+ rv.objectType = QString::fromUtf8(object->metaObject()->className());
+ int marker = rv.objectType.indexOf(QLatin1String("_QMLTYPE_"));
+ if (marker != -1)
+ rv.objectType = rv.objectType.left(marker);
+ }
+
+ return rv;
+}
+
+void QmlEngineDebugServer::messageReceived(const QByteArray &message)
+{
+ QDataStream ds(message);
+
+ QByteArray type;
+ ds >> type;
+
+ //qDebug() << "QmlEngineDebugServer::messageReceived()" << type;
+
+ if (type == "LIST_ENGINES") {
+ int queryId;
+ ds >> queryId;
+
+ QByteArray reply;
+ QDataStream rs(&reply, QIODevice::WriteOnly);
+ rs << QByteArray("LIST_ENGINES_R");
+ rs << queryId << m_engines.count();
+
+ for (int ii = 0; ii < m_engines.count(); ++ii) {
+ QmlEngine *engine = m_engines.at(ii);
+
+ QString engineName = engine->objectName();
+ int engineId = QmlDebugService::idForObject(engine);
+
+ rs << engineName << engineId;
+ }
+
+ sendMessage(reply);
+ } else if (type == "LIST_OBJECTS") {
+ int queryId;
+ int engineId = -1;
+ ds >> queryId >> engineId;
+
+ QmlEngine *engine =
+ qobject_cast<QmlEngine *>(QmlDebugService::objectForId(engineId));
+
+ QByteArray reply;
+ QDataStream rs(&reply, QIODevice::WriteOnly);
+ rs << QByteArray("LIST_OBJECTS_R") << queryId;
+
+ if (engine)
+ buildObjectList(rs, engine->rootContext());
+
+ sendMessage(reply);
+ } else if (type == "FETCH_OBJECT") {
+ int queryId;
+ int objectId;
+ bool recurse;
+
+ ds >> queryId >> objectId >> recurse;
+
+ QObject *object = QmlDebugService::objectForId(objectId);
+
+ QByteArray reply;
+ QDataStream rs(&reply, QIODevice::WriteOnly);
+ rs << QByteArray("FETCH_OBJECT_R") << queryId;
+
+ if (object)
+ buildObjectDump(rs, object, recurse);
+
+ sendMessage(reply);
+ } else if (type == "WATCH_OBJECT") {
+ int queryId;
+ int objectId;
+
+ ds >> queryId >> objectId;
+ bool ok = m_watch->addWatch(queryId, objectId);
+
+ QByteArray reply;
+ QDataStream rs(&reply, QIODevice::WriteOnly);
+ rs << QByteArray("WATCH_OBJECT_R") << queryId << ok;
+
+ sendMessage(reply);
+ } else if (type == "WATCH_PROPERTY") {
+ int queryId;
+ int objectId;
+ QByteArray property;
+
+ ds >> queryId >> objectId >> property;
+ bool ok = m_watch->addWatch(queryId, objectId, property);
+
+ QByteArray reply;
+ QDataStream rs(&reply, QIODevice::WriteOnly);
+ rs << QByteArray("WATCH_PROPERTY_R") << queryId << ok;
+
+ sendMessage(reply);
+ } else if (type == "WATCH_EXPR_OBJECT") {
+ int queryId;
+ int debugId;
+ QString expr;
+
+ ds >> queryId >> debugId >> expr;
+ bool ok = m_watch->addWatch(queryId, debugId, expr);
+
+ QByteArray reply;
+ QDataStream rs(&reply, QIODevice::WriteOnly);
+ rs << QByteArray("WATCH_EXPR_OBJECT_R") << queryId << ok;
+
+ sendMessage(reply);
+ } else if (type == "NO_WATCH") {
+ int queryId;
+
+ ds >> queryId;
+ m_watch->removeWatch(queryId);
+ } else if (type == "EVAL_EXPRESSION") {
+ int queryId;
+ int objectId;
+ QString expr;
+
+ ds >> queryId >> objectId >> expr;
+
+ QObject *object = QmlDebugService::objectForId(objectId);
+ QmlContext *context = qmlContext(object);
+ QVariant result;
+ if (object && context) {
+ QmlExpression *exprObj = new QmlExpression(context, expr, object);
+ bool undefined = false;
+ QVariant value = exprObj->value(&undefined);
+ if (undefined)
+ result = QLatin1String("<undefined>");
+ else
+ result = valueContents(value);
+ delete exprObj;
+ } else {
+ result = QLatin1String("<unknown context>");
+ }
+
+ QByteArray reply;
+ QDataStream rs(&reply, QIODevice::WriteOnly);
+ rs << QByteArray("EVAL_EXPRESSION_R") << queryId << result;
+
+ sendMessage(reply);
+ }
+}
+
+void QmlEngineDebugServer::propertyChanged(int id, int objectId, const QMetaProperty &property, const QVariant &value)
+{
+ QByteArray reply;
+ QDataStream rs(&reply, QIODevice::WriteOnly);
+
+ rs << QByteArray("UPDATE_WATCH") << id << objectId << QByteArray(property.name()) << valueContents(value);
+
+ sendMessage(reply);
+}
+
+void QmlEngineDebugServer::addEngine(QmlEngine *engine)
+{
+ Q_ASSERT(engine);
+ Q_ASSERT(!m_engines.contains(engine));
+
+ m_engines.append(engine);
+}
+
+void QmlEngineDebugServer::remEngine(QmlEngine *engine)
+{
+ Q_ASSERT(engine);
+ Q_ASSERT(m_engines.contains(engine));
+
+ m_engines.removeAll(engine);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlenginedebug_p.h b/src/declarative/qml/qmlenginedebug_p.h
new file mode 100644
index 0000000..7c48b8b
--- /dev/null
+++ b/src/declarative/qml/qmlenginedebug_p.h
@@ -0,0 +1,121 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLENGINEDEBUG_P_H
+#define QMLENGINEDEBUG_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 "../debugger/qmldebugservice_p.h"
+
+#include <QtCore/qurl.h>
+#include <QtCore/qvariant.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlEngine;
+class QmlContext;
+class QmlWatcher;
+class QDataStream;
+
+class QmlEngineDebugServer : public QmlDebugService
+{
+ Q_OBJECT
+public:
+ QmlEngineDebugServer(QObject * = 0);
+
+ struct QmlObjectData {
+ QUrl url;
+ int lineNumber;
+ int columnNumber;
+ QString objectName;
+ QString objectType;
+ int objectId;
+ int contextId;
+ };
+
+ struct QmlObjectProperty {
+ enum Type { Unknown, Basic, Object, List, SignalProperty };
+ Type type;
+ QString name;
+ QVariant value;
+ QString valueTypeName;
+ QString binding;
+ bool hasNotifySignal;
+ };
+
+ static void addEngine(QmlEngine *);
+ static void remEngine(QmlEngine *);
+
+protected:
+ virtual void messageReceived(const QByteArray &);
+
+private Q_SLOTS:
+ void propertyChanged(int id, int objectId, const QMetaProperty &property, const QVariant &value);
+
+private:
+ void buildObjectList(QDataStream &, QmlContext *);
+ void buildObjectDump(QDataStream &, QObject *, bool);
+ QmlObjectData objectData(QObject *);
+ QmlObjectProperty propertyData(QObject *, int);
+ QVariant valueContents(const QVariant &defaultValue) const;
+
+ static QList<QmlEngine *> m_engines;
+ QmlWatcher *m_watch;
+};
+Q_DECLARATIVE_EXPORT QDataStream &operator<<(QDataStream &, const QmlEngineDebugServer::QmlObjectData &);
+Q_DECLARATIVE_EXPORT QDataStream &operator>>(QDataStream &, QmlEngineDebugServer::QmlObjectData &);
+Q_DECLARATIVE_EXPORT QDataStream &operator<<(QDataStream &, const QmlEngineDebugServer::QmlObjectProperty &);
+Q_DECLARATIVE_EXPORT QDataStream &operator>>(QDataStream &, QmlEngineDebugServer::QmlObjectProperty &);
+
+QT_END_NAMESPACE
+
+#endif // QMLENGINEDEBUG_P_H
+
diff --git a/src/declarative/qml/qmlerror.cpp b/src/declarative/qml/qmlerror.cpp
new file mode 100644
index 0000000..d9ca20d
--- /dev/null
+++ b/src/declarative/qml/qmlerror.cpp
@@ -0,0 +1,257 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlerror.h"
+
+#include <QtCore/qdebug.h>
+#include <QtCore/qfile.h>
+#include <QtCore/qstringlist.h>
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QmlError
+ \brief The QmlError class encapsulates a QML error
+*/
+class QmlErrorPrivate
+{
+public:
+ QmlErrorPrivate();
+
+ QUrl url;
+ QString description;
+ int line;
+ int column;
+};
+
+QmlErrorPrivate::QmlErrorPrivate()
+: line(-1), column(-1)
+{
+}
+
+/*!
+ Create an empty error object.
+*/
+QmlError::QmlError()
+: d(0)
+{
+}
+
+/*!
+ Create a copy of \a other.
+*/
+QmlError::QmlError(const QmlError &other)
+: d(0)
+{
+ *this = other;
+}
+
+/*!
+ Assign \a other to this error object.
+*/
+QmlError &QmlError::operator=(const QmlError &other)
+{
+ if (!other.d) {
+ delete d;
+ d = 0;
+ } else {
+ if (!d) d = new QmlErrorPrivate;
+ d->url = other.d->url;
+ d->description = other.d->description;
+ d->line = other.d->line;
+ d->column = other.d->column;
+ }
+ return *this;
+}
+
+/*!
+ \internal
+*/
+QmlError::~QmlError()
+{
+ delete d; d = 0;
+}
+
+/*!
+ Return true if this error is valid, otherwise false.
+*/
+bool QmlError::isValid() const
+{
+ return d != 0;
+}
+
+/*!
+ Return the url for the file that caused this error.
+*/
+QUrl QmlError::url() const
+{
+ if (d) return d->url;
+ else return QUrl();
+}
+
+/*!
+ Set the \a url for the file that caused this error.
+*/
+void QmlError::setUrl(const QUrl &url)
+{
+ if (!d) d = new QmlErrorPrivate;
+ d->url = url;
+}
+
+/*!
+ Return the error description.
+*/
+QString QmlError::description() const
+{
+ if (d) return d->description;
+ else return QString();
+}
+
+/*!
+ Set the error \a description.
+*/
+void QmlError::setDescription(const QString &description)
+{
+ if (!d) d = new QmlErrorPrivate;
+ d->description = description;
+}
+
+/*!
+ Return the error line number.
+*/
+int QmlError::line() const
+{
+ if (d) return d->line;
+ else return -1;
+}
+
+/*!
+ Set the error \a line number.
+*/
+void QmlError::setLine(int line)
+{
+ if (!d) d = new QmlErrorPrivate;
+ d->line = line;
+}
+
+/*!
+ Return the error column number.
+*/
+int QmlError::column() const
+{
+ if (d) return d->column;
+ else return -1;
+}
+
+/*!
+ Set the error \a column number.
+*/
+void QmlError::setColumn(int column)
+{
+ if (!d) d = new QmlErrorPrivate;
+ d->column = column;
+}
+
+/*!
+ Return the error as a human readable string.
+*/
+QString QmlError::toString() const
+{
+ QString rv;
+ rv = url().toString() + QLatin1Char(':') + QString::number(line());
+ if(column() != -1)
+ rv += QLatin1Char(':') + QString::number(column());
+
+ rv += QLatin1String(": ") + description();
+
+ return rv;
+}
+
+/*!
+ \relates QmlError
+ \fn QDebug operator<<(QDebug debug, const QmlError &error)
+
+ Output a human readable version of \a error to \a debug.
+*/
+
+QDebug operator<<(QDebug debug, const QmlError &error)
+{
+ debug << qPrintable(error.toString());
+
+ QUrl url = error.url();
+
+ if (error.line() > 0 && url.scheme() == QLatin1String("file")) {
+ QString file = url.toLocalFile();
+ QFile f(file);
+ if (f.open(QIODevice::ReadOnly)) {
+ QByteArray data = f.readAll();
+ QTextStream stream(data, QIODevice::ReadOnly);
+ stream.setCodec("UTF-8");
+ const QString code = stream.readAll();
+ const QStringList lines = code.split(QLatin1Char('\n'));
+
+ if (lines.count() >= error.line()) {
+ const QString &line = lines.at(error.line() - 1);
+ debug << "\n " << qPrintable(line);
+
+ if(error.column() > 0) {
+ int column = qMax(0, error.column() - 1);
+ column = qMin(column, line.length());
+
+ QByteArray ind;
+ ind.reserve(column);
+ for (int i = 0; i < column; ++i) {
+ const QChar ch = line.at(i);
+ if (ch.isSpace())
+ ind.append(ch.unicode());
+ else
+ ind.append(' ');
+ }
+ ind.append('^');
+ debug << "\n " << ind.constData();
+ }
+ }
+ }
+ }
+ return debug;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlerror.h b/src/declarative/qml/qmlerror.h
new file mode 100644
index 0000000..c54f932
--- /dev/null
+++ b/src/declarative/qml/qmlerror.h
@@ -0,0 +1,86 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLERROR_H
+#define QMLERROR_H
+
+#include <QtCore/qurl.h>
+#include <QtCore/qstring.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QDebug;
+class QmlErrorPrivate;
+class Q_DECLARATIVE_EXPORT QmlError
+{
+public:
+ QmlError();
+ QmlError(const QmlError &);
+ QmlError &operator=(const QmlError &);
+ ~QmlError();
+
+ bool isValid() const;
+
+ QUrl url() const;
+ void setUrl(const QUrl &);
+ QString description() const;
+ void setDescription(const QString &);
+ int line() const;
+ void setLine(int);
+ int column() const;
+ void setColumn(int);
+
+ QString toString() const;
+private:
+ QmlErrorPrivate *d;
+};
+
+QDebug Q_DECLARATIVE_EXPORT operator<<(QDebug debug, const QmlError &error);
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLERROR_H
diff --git a/src/declarative/qml/qmlexpression.cpp b/src/declarative/qml/qmlexpression.cpp
new file mode 100644
index 0000000..6f32ef4
--- /dev/null
+++ b/src/declarative/qml/qmlexpression.cpp
@@ -0,0 +1,831 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlexpression.h"
+#include "qmlexpression_p.h"
+
+#include "qmlengine_p.h"
+#include "qmlcontext_p.h"
+#include "qmlrewrite_p.h"
+#include "qmlcompiler_p.h"
+
+#include <QtCore/qdebug.h>
+#include <QtScript/qscriptprogram.h>
+
+#include <private/qscriptdeclarativeclass_p.h>
+
+Q_DECLARE_METATYPE(QList<QObject *>);
+
+QT_BEGIN_NAMESPACE
+
+bool QmlDelayedError::addError(QmlEnginePrivate *e)
+{
+ if (!e || prevError) return false;
+
+ if (e->inProgressCreations == 0) return false; // Not in construction
+
+ prevError = &e->erroredBindings;
+ nextError = e->erroredBindings;
+ e->erroredBindings = this;
+ if (nextError) nextError->prevError = &nextError;
+
+ return true;
+}
+
+QmlExpressionData::QmlExpressionData()
+: q(0), dataRef(0), expressionFunctionValid(false), expressionRewritten(false), me(0),
+ trackChange(true), isShared(false), line(-1), guardList(0), guardListLength(0)
+{
+}
+
+QmlExpressionData::~QmlExpressionData()
+{
+ if (guardList) { delete [] guardList; guardList = 0; }
+ if (dataRef) dataRef->release();
+}
+
+QmlExpressionPrivate::QmlExpressionPrivate()
+: data(new QmlExpressionData)
+{
+ data->q = this;
+}
+
+QmlExpressionPrivate::QmlExpressionPrivate(QmlExpressionData *d)
+: data(d)
+{
+ data->q = this;
+}
+
+QmlExpressionPrivate::~QmlExpressionPrivate()
+{
+ if (data) { data->q = 0; data->release(); data = 0; }
+}
+
+void QmlExpressionPrivate::init(QmlContext *ctxt, const QString &expr,
+ QObject *me)
+{
+ data->expression = expr;
+
+ data->QmlAbstractExpression::setContext(ctxt);
+ data->me = me;
+}
+
+void QmlExpressionPrivate::init(QmlContext *ctxt, void *expr, QmlRefCount *rc,
+ QObject *me, const QString &url, int lineNumber)
+{
+ data->url = url;
+ data->line = lineNumber;
+
+ if (data->dataRef) data->dataRef->release();
+ data->dataRef = rc;
+ if (data->dataRef) data->dataRef->addref();
+
+ quint32 *exprData = (quint32 *)expr;
+ QmlCompiledData *dd = (QmlCompiledData *)rc;
+
+ data->expressionRewritten = true;
+ data->expression = QString::fromRawData((QChar *)(exprData + 2), exprData[1]);
+
+ int progIdx = *(exprData);
+ bool isShared = progIdx & 0x80000000;
+ progIdx &= 0x7FFFFFFF;
+
+ QmlEngine *engine = ctxt->engine();
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ if (isShared) {
+
+ if (!dd->cachedClosures.at(progIdx)) {
+ QScriptContext *scriptContext = QScriptDeclarativeClass::pushCleanContext(scriptEngine);
+ scriptContext->pushScope(ep->contextClass->newSharedContext());
+ dd->cachedClosures[progIdx] = new QScriptValue(scriptEngine->evaluate(data->expression, data->url, data->line));
+ scriptEngine->popContext();
+ }
+
+ data->expressionFunction = *dd->cachedClosures.at(progIdx);
+ data->isShared = true;
+ data->expressionFunctionValid = true;
+
+ } else {
+
+#if !defined(Q_OS_SYMBIAN) //XXX Why doesn't this work?
+ if (!dd->cachedPrograms.at(progIdx)) {
+ dd->cachedPrograms[progIdx] =
+ new QScriptProgram(data->expression, data->url, data->line);
+ }
+
+ data->expressionFunction = evalInObjectScope(ctxt, me, *dd->cachedPrograms.at(progIdx));
+#else
+ data->expressionFunction = evalInObjectScope(ctxt, me, data->expression);
+#endif
+
+ data->expressionFunctionValid = true;
+ }
+
+ data->QmlAbstractExpression::setContext(ctxt);
+ data->me = me;
+}
+
+QScriptValue QmlExpressionPrivate::evalInObjectScope(QmlContext *context, QObject *object,
+ const QString &program)
+{
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(context->engine());
+ QScriptContext *scriptContext = QScriptDeclarativeClass::pushCleanContext(&ep->scriptEngine);
+ scriptContext->pushScope(ep->contextClass->newContext(context, object));
+ QScriptValue rv = ep->scriptEngine.evaluate(program);
+ ep->scriptEngine.popContext();
+ return rv;
+}
+
+QScriptValue QmlExpressionPrivate::evalInObjectScope(QmlContext *context, QObject *object,
+ const QScriptProgram &program)
+{
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(context->engine());
+ QScriptContext *scriptContext = QScriptDeclarativeClass::pushCleanContext(&ep->scriptEngine);
+ scriptContext->pushScope(ep->contextClass->newContext(context, object));
+ QScriptValue rv = ep->scriptEngine.evaluate(program);
+ ep->scriptEngine.popContext();
+ return rv;
+}
+
+/*!
+ \class QmlExpression
+ \brief The QmlExpression class evaluates JavaScript in a QML context.
+*/
+
+/*!
+ Create an invalid QmlExpression.
+
+ As the expression will not have an associated QmlContext, this will be a
+ null expression object and its value will always be an invalid QVariant.
+ */
+QmlExpression::QmlExpression()
+: QObject(*new QmlExpressionPrivate, 0)
+{
+}
+
+/*! \internal */
+QmlExpression::QmlExpression(QmlContext *ctxt, void *expr,
+ QmlRefCount *rc, QObject *me,
+ const QString &url, int lineNumber,
+ QmlExpressionPrivate &dd)
+: QObject(dd, 0)
+{
+ Q_D(QmlExpression);
+ d->init(ctxt, expr, rc, me, url, lineNumber);
+}
+
+/*!
+ Create a QmlExpression object.
+
+ The \a expression JavaScript will be executed in the \a ctxt QmlContext.
+ If specified, the \a scope object's properties will also be in scope during
+ the expression's execution.
+*/
+QmlExpression::QmlExpression(QmlContext *ctxt, const QString &expression,
+ QObject *scope)
+: QObject(*new QmlExpressionPrivate, 0)
+{
+ Q_D(QmlExpression);
+ d->init(ctxt, expression, scope);
+}
+
+/*! \internal */
+QmlExpression::QmlExpression(QmlContext *ctxt, const QString &expression,
+ QObject *scope, QmlExpressionPrivate &dd)
+: QObject(dd, 0)
+{
+ Q_D(QmlExpression);
+ d->init(ctxt, expression, scope);
+}
+
+/*!
+ Destroy the QmlExpression instance.
+*/
+QmlExpression::~QmlExpression()
+{
+}
+
+/*!
+ Returns the QmlEngine this expression is associated with, or 0 if there
+ is no association or the QmlEngine has been destroyed.
+*/
+QmlEngine *QmlExpression::engine() const
+{
+ Q_D(const QmlExpression);
+ return d->data->context()?d->data->context()->engine():0;
+}
+
+/*!
+ Returns the QmlContext this expression is associated with, or 0 if there
+ is no association or the QmlContext has been destroyed.
+*/
+QmlContext *QmlExpression::context() const
+{
+ Q_D(const QmlExpression);
+ return d->data->context();
+}
+
+/*!
+ Returns the expression string.
+*/
+QString QmlExpression::expression() const
+{
+ Q_D(const QmlExpression);
+ return d->data->expression;
+}
+
+/*!
+ Clear the expression.
+*/
+void QmlExpression::clearExpression()
+{
+ setExpression(QString());
+}
+
+/*!
+ Set the expression to \a expression.
+*/
+void QmlExpression::setExpression(const QString &expression)
+{
+ Q_D(QmlExpression);
+
+ d->clearGuards();
+
+ d->data->expression = expression;
+ d->data->expressionFunctionValid = false;
+ d->data->expressionRewritten = false;
+ d->data->expressionFunction = QScriptValue();
+}
+
+void QmlExpressionPrivate::exceptionToError(QScriptEngine *scriptEngine,
+ QmlError &error)
+{
+ if (scriptEngine->hasUncaughtException() &&
+ scriptEngine->uncaughtException().isError()) {
+
+ QString fileName;
+ int lineNumber = scriptEngine->uncaughtExceptionLineNumber();
+
+ QScriptValue exception = scriptEngine->uncaughtException();
+ QLatin1String fileNameProp("fileName");
+
+ if (!exception.property(fileNameProp).toString().isEmpty()){
+ fileName = exception.property(fileNameProp).toString();
+ } else {
+ fileName = QLatin1String("<Unknown File>");
+ }
+
+ error.setUrl(QUrl(fileName));
+ error.setLine(lineNumber);
+ error.setColumn(-1);
+ error.setDescription(exception.toString());
+ } else {
+ error = QmlError();
+ }
+}
+
+QVariant QmlExpressionPrivate::evalQtScript(QObject *secondaryScope, bool *isUndefined)
+{
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::BindValueQt> perfqt;
+#endif
+
+ QmlExpressionData *data = this->data;
+ QmlContextPrivate *ctxtPriv = data->context()->d_func();
+ QmlEngine *engine = data->context()->engine();
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+
+ if (secondaryScope)
+ ctxtPriv->defaultObjects.append(secondaryScope);
+
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ if (!data->expressionFunctionValid) {
+
+ QScriptContext *scriptContext = QScriptDeclarativeClass::pushCleanContext(scriptEngine);
+ scriptContext->pushScope(ep->contextClass->newContext(data->context(), data->me));
+
+ if (data->expressionRewritten) {
+ data->expressionFunction = scriptEngine->evaluate(data->expression,
+ data->url, data->line);
+ } else {
+ QmlRewrite::RewriteBinding rewriteBinding;
+
+ bool ok = true;
+ const QString code = rewriteBinding(data->expression, &ok);
+ if (!ok) {
+ scriptEngine->popContext();
+ return QVariant();
+ }
+ data->expressionFunction = scriptEngine->evaluate(code, data->url, data->line);
+ }
+
+ scriptEngine->popContext();
+ data->expressionFunctionValid = true;
+ }
+
+ QmlContext *oldSharedContext = 0;
+ QObject *oldSharedScope = 0;
+ if (data->isShared) {
+ oldSharedContext = ep->sharedContext;
+ oldSharedScope = ep->sharedScope;
+ ep->sharedContext = data->context();
+ ep->sharedScope = data->me;
+ }
+
+ QScriptValue svalue = data->expressionFunction.call();
+
+ if (data->isShared) {
+ ep->sharedContext = oldSharedContext;
+ ep->sharedScope = oldSharedScope;
+ }
+
+ if (isUndefined)
+ *isUndefined = svalue.isUndefined() || scriptEngine->hasUncaughtException();
+
+ // Handle exception
+ if (scriptEngine->hasUncaughtException()) {
+ exceptionToError(scriptEngine, data->error);
+ scriptEngine->clearExceptions();
+ return QVariant();
+ } else {
+ data->error = QmlError();
+ }
+
+ if (secondaryScope) {
+ QObject *last = ctxtPriv->defaultObjects.takeLast();
+ Q_ASSERT(last == secondaryScope);
+ Q_UNUSED(last);
+ }
+
+ QVariant rv;
+
+ if (svalue.isArray()) {
+ int length = svalue.property(QLatin1String("length")).toInt32();
+ if (length && svalue.property(0).isObject()) {
+ QList<QObject *> list;
+ for (int ii = 0; ii < length; ++ii) {
+ QScriptValue arrayItem = svalue.property(ii);
+ QObject *d = arrayItem.toQObject();
+ list << d;
+ }
+ rv = QVariant::fromValue(list);
+ }
+ } else if (svalue.isObject() &&
+ ep->objectClass->scriptClass(svalue) == ep->objectClass) {
+ QObject *o = svalue.toQObject();
+ int type = QMetaType::QObjectStar;
+ // If the object is null, we extract the predicted type. While this isn't
+ // 100% reliable, in many cases it gives us better error messages if we
+ // assign this null-object to an incompatible property
+ if (!o) type = ep->objectClass->objectType(svalue);
+
+ return QVariant(type, &o);
+ }
+
+ if (rv.isNull())
+ rv = svalue.toVariant();
+
+ return rv;
+}
+
+QVariant QmlExpressionPrivate::value(QObject *secondaryScope, bool *isUndefined)
+{
+ Q_Q(QmlExpression);
+
+ QVariant rv;
+ if (!q->engine()) {
+ qWarning("QmlExpression: Attempted to evaluate an expression in an invalid context");
+ return rv;
+ }
+
+ if (data->expression.isEmpty())
+ return rv;
+
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::BindValue> perf;
+#endif
+
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(q->engine());
+
+ QmlExpression *lastCurrentExpression = ep->currentExpression;
+ bool lastCaptureProperties = ep->captureProperties;
+ QPODVector<QmlEnginePrivate::CapturedProperty> lastCapturedProperties;
+ ep->capturedProperties.copyAndClear(lastCapturedProperties);
+
+ ep->currentExpression = q;
+ ep->captureProperties = data->trackChange;
+
+ // This object might be deleted during the eval
+ QmlExpressionData *localData = data;
+ localData->addref();
+
+ rv = evalQtScript(secondaryScope, isUndefined);
+
+ ep->currentExpression = lastCurrentExpression;
+ ep->captureProperties = lastCaptureProperties;
+
+ // Check if we were deleted
+ if (localData->q) {
+ if ((!data->trackChange || !ep->capturedProperties.count()) && data->guardList) {
+ clearGuards();
+ } else if(data->trackChange) {
+ updateGuards(ep->capturedProperties);
+ }
+ }
+
+ localData->release();
+
+ lastCapturedProperties.copyAndClear(ep->capturedProperties);
+
+ return rv;
+}
+
+/*!
+ Returns the value of the expression, or an invalid QVariant if the
+ expression is invalid or has an error.
+
+ \a isUndefined is set to true if the expression resulted in an
+ undefined value.
+
+ \sa hasError(), error()
+*/
+QVariant QmlExpression::value(bool *isUndefined)
+{
+ Q_D(QmlExpression);
+ return d->value(0, isUndefined);
+}
+
+/*!
+ Returns true if the expression results in a constant value.
+ QmlExpression::value() must have been invoked at least once before the
+ return from this method is valid.
+ */
+bool QmlExpression::isConstant() const
+{
+ Q_D(const QmlExpression);
+ return !d->data->guardList;
+}
+
+/*!
+ Returns true if the changes are tracked in the expression's value.
+*/
+bool QmlExpression::trackChange() const
+{
+ Q_D(const QmlExpression);
+ return d->data->trackChange;
+}
+
+/*!
+ Set whether changes are tracked in the expression's value to \a trackChange.
+
+ If true, the QmlExpression will monitor properties involved in the
+ expression's evaluation, and call QmlExpression::valueChanged() if they have
+ changed. This allows an application to ensure that any value associated
+ with the result of the expression remains up to date.
+
+ If false, the QmlExpression will not montitor properties involved in the
+ expression's evaluation, and QmlExpression::valueChanged() will never be
+ called. This is more efficient if an application wants a "one off"
+ evaluation of the expression.
+
+ By default, trackChange is true.
+*/
+void QmlExpression::setTrackChange(bool trackChange)
+{
+ Q_D(QmlExpression);
+ d->data->trackChange = trackChange;
+}
+
+/*!
+ Returns the source file URL for this expression. The source location must
+ have been previously set by calling setSourceLocation().
+*/
+QString QmlExpression::sourceFile() const
+{
+ Q_D(const QmlExpression);
+ return d->data->url;
+}
+
+/*!
+ Returns the source file line number for this expression. The source location
+ must have been previously set by calling setSourceLocation().
+*/
+int QmlExpression::lineNumber() const
+{
+ Q_D(const QmlExpression);
+ return d->data->line;
+}
+
+/*!
+ Set the location of this expression to \a line of \a url. This information
+ is used by the script engine.
+*/
+void QmlExpression::setSourceLocation(const QString &url, int line)
+{
+ Q_D(QmlExpression);
+ d->data->url = url;
+ d->data->line = line;
+}
+
+/*!
+ Returns the expression's scope object, if provided, otherwise 0.
+
+ In addition to data provided by the expression's QmlContext, the scope
+ object's properties are also in scope during the expression's evaluation.
+*/
+QObject *QmlExpression::scopeObject() const
+{
+ Q_D(const QmlExpression);
+ return d->data->me;
+}
+
+/*!
+ Returns true if the last call to value() resulted in an error,
+ otherwise false.
+
+ \sa error(), clearError()
+*/
+bool QmlExpression::hasError() const
+{
+ Q_D(const QmlExpression);
+ return d->data->error.isValid();
+}
+
+/*!
+ Clear any expression errors. Calls to hasError() following this will
+ return false.
+
+ \sa hasError(), error()
+*/
+void QmlExpression::clearError()
+{
+ Q_D(QmlExpression);
+ d->data->error = QmlError();
+}
+
+/*!
+ Return any error from the last call to value(). If there was no error,
+ this returns an invalid QmlError instance.
+
+ \sa hasError(), clearError()
+*/
+
+QmlError QmlExpression::error() const
+{
+ Q_D(const QmlExpression);
+ return d->data->error;
+}
+
+/*! \internal */
+void QmlExpression::__q_notify()
+{
+ emitValueChanged();
+}
+
+void QmlExpressionPrivate::clearGuards()
+{
+ Q_Q(QmlExpression);
+
+ static int notifyIdx = -1;
+ if (notifyIdx == -1)
+ notifyIdx =
+ QmlExpression::staticMetaObject.indexOfMethod("__q_notify()");
+
+ for (int ii = 0; ii < data->guardListLength; ++ii) {
+ if (data->guardList[ii].data()) {
+#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 2))
+ QMetaObject::disconnectOne(data->guardList[ii].data(),
+ data->guardList[ii].notifyIndex,
+ q, notifyIdx);
+#else
+ // QTBUG-6781
+ QMetaObject::disconnect(data->guardList[ii].data(),
+ data->guardList[ii].notifyIndex,
+ q, notifyIdx);
+#endif
+ }
+ }
+
+ delete [] data->guardList; data->guardList = 0;
+ data->guardListLength = 0;
+}
+
+void QmlExpressionPrivate::updateGuards(const QPODVector<QmlEnginePrivate::CapturedProperty> &properties)
+{
+ //clearGuards();
+ Q_Q(QmlExpression);
+
+ static int notifyIdx = -1;
+ if (notifyIdx == -1)
+ notifyIdx =
+ QmlExpression::staticMetaObject.indexOfMethod("__q_notify()");
+
+ QmlExpressionData::SignalGuard *newGuardList = 0;
+
+ if (properties.count() != data->guardListLength)
+ newGuardList = new QmlExpressionData::SignalGuard[properties.count()];
+
+ bool outputWarningHeader = false;
+ int hit = 0;
+ for (int ii = 0; ii < properties.count(); ++ii) {
+ const QmlEnginePrivate::CapturedProperty &property = properties.at(ii);
+
+ bool needGuard = true;
+ if (ii >= data->guardListLength) {
+ // New guard
+ } else if(data->guardList[ii].data() == property.object &&
+ data->guardList[ii].notifyIndex == property.notifyIndex) {
+ // Cache hit
+ if (!data->guardList[ii].isDuplicate ||
+ (data->guardList[ii].isDuplicate && hit == ii)) {
+ needGuard = false;
+ ++hit;
+ }
+ } else if(data->guardList[ii].data() && !data->guardList[ii].isDuplicate) {
+ // Cache miss
+#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 2))
+ QMetaObject::disconnectOne(data->guardList[ii].data(),
+ data->guardList[ii].notifyIndex,
+ q, notifyIdx);
+#else
+ // QTBUG-6781
+ QMetaObject::disconnect(data->guardList[ii].data(),
+ data->guardList[ii].notifyIndex,
+ q, notifyIdx);
+#endif
+ }
+ /* else {
+ // Cache miss, but nothing to do
+ } */
+
+ if (needGuard) {
+ if (!newGuardList) {
+ newGuardList = new QmlExpressionData::SignalGuard[properties.count()];
+ for (int jj = 0; jj < ii; ++jj)
+ newGuardList[jj] = data->guardList[jj];
+ }
+
+ if (property.notifyIndex != -1) {
+ bool existing = false;
+ for (int jj = 0; !existing && jj < ii; ++jj)
+ existing = newGuardList[jj].data() == property.object &&
+ newGuardList[jj].notifyIndex == property.notifyIndex;
+
+ newGuardList[ii] = property.object;
+ newGuardList[ii].notifyIndex = property.notifyIndex;
+ if (existing)
+ newGuardList[ii].isDuplicate = true;
+ else
+ QMetaObject::connect(property.object, property.notifyIndex,
+ q, notifyIdx);
+ } else {
+ if (!outputWarningHeader) {
+ outputWarningHeader = true;
+ qWarning() << "QmlExpression: Expression" << q->expression()
+ << "depends on non-NOTIFYable properties:";
+ }
+
+ const QMetaObject *metaObj = property.object->metaObject();
+ QMetaProperty metaProp = metaObj->property(property.coreIndex);
+
+ qWarning().nospace() << " " << metaObj->className()
+ << "::" << metaProp.name();
+ }
+ } else if (newGuardList) {
+ newGuardList[ii] = data->guardList[ii];
+ }
+ }
+
+ for (int ii = properties.count(); ii < data->guardListLength; ++ii) {
+ if (data->guardList[ii].data() && !data->guardList[ii].isDuplicate) {
+#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 2))
+ QMetaObject::disconnectOne(data->guardList[ii].data(),
+ data->guardList[ii].notifyIndex,
+ q, notifyIdx);
+#else
+ // QTBUG-6781
+ QMetaObject::disconnect(data->guardList[ii].data(),
+ data->guardList[ii].notifyIndex,
+ q, notifyIdx);
+#endif
+ }
+ }
+
+ if (newGuardList) {
+ if (data->guardList) delete [] data->guardList;
+ data->guardList = newGuardList;
+ data->guardListLength = properties.count();
+ }
+}
+
+/*!
+ \fn void QmlExpression::valueChanged()
+
+ Emitted each time the expression value changes from the last time it was
+ evaluated. The expression must have been evaluated at least once (by
+ calling QmlExpression::value()) before this signal will be emitted.
+*/
+
+/*!
+ Subclasses can capture the emission of the valueChanged() signal by overriding
+ this function. They can choose whether to then call valueChanged().
+*/
+void QmlExpression::emitValueChanged()
+{
+ emit valueChanged();
+}
+
+QmlAbstractExpression::QmlAbstractExpression()
+: m_context(0), m_prevExpression(0), m_nextExpression(0)
+{
+}
+
+QmlAbstractExpression::~QmlAbstractExpression()
+{
+ if (m_prevExpression) {
+ *m_prevExpression = m_nextExpression;
+ if (m_nextExpression)
+ m_nextExpression->m_prevExpression = m_prevExpression;
+ }
+}
+
+QmlContext *QmlAbstractExpression::context() const
+{
+ return m_context;
+}
+
+void QmlAbstractExpression::setContext(QmlContext *context)
+{
+ if (m_prevExpression) {
+ *m_prevExpression = m_nextExpression;
+ if (m_nextExpression)
+ m_nextExpression->m_prevExpression = m_prevExpression;
+ m_prevExpression = 0;
+ m_nextExpression = 0;
+ }
+
+ m_context = context;
+
+ if (m_context) {
+ QmlContextPrivate *cp =
+ static_cast<QmlContextPrivate *>(QObjectPrivate::get(m_context));
+ m_nextExpression = cp->expressions;
+ if (m_nextExpression)
+ m_nextExpression->m_prevExpression = &m_nextExpression;
+ m_prevExpression = &cp->expressions;
+ cp->expressions = this;
+ }
+}
+
+void QmlAbstractExpression::refresh()
+{
+}
+
+bool QmlAbstractExpression::isValid() const
+{
+ return m_context != 0;
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/qml/qmlexpression.h b/src/declarative/qml/qmlexpression.h
new file mode 100644
index 0000000..4df7641
--- /dev/null
+++ b/src/declarative/qml/qmlexpression.h
@@ -0,0 +1,118 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLEXPRESSION_H
+#define QMLEXPRESSION_H
+
+#include "qmlerror.h"
+
+#include <QtCore/qobject.h>
+#include <QtCore/qvariant.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QString;
+class QmlRefCount;
+class QmlEngine;
+class QmlContext;
+class QmlExpressionPrivate;
+class Q_DECLARATIVE_EXPORT QmlExpression : public QObject
+{
+ Q_OBJECT
+public:
+ QmlExpression();
+ QmlExpression(QmlContext *, const QString &, QObject *);
+ virtual ~QmlExpression();
+
+ QmlEngine *engine() const;
+ QmlContext *context() const;
+
+ QString expression() const;
+ void clearExpression();
+ virtual void setExpression(const QString &);
+ bool isConstant() const;
+
+ bool trackChange() const;
+ void setTrackChange(bool);
+
+ QString sourceFile() const;
+ int lineNumber() const;
+ void setSourceLocation(const QString &fileName, int line);
+
+ QObject *scopeObject() const;
+
+ bool hasError() const;
+ void clearError();
+ QmlError error() const;
+
+public Q_SLOTS:
+ QVariant value(bool *isUndefined = 0);
+
+Q_SIGNALS:
+ void valueChanged();
+
+protected:
+ virtual void emitValueChanged();
+
+ QmlExpression(QmlContext *, const QString &, QObject *,
+ QmlExpressionPrivate &dd);
+ QmlExpression(QmlContext *, void *, QmlRefCount *rc, QObject *me, const QString &,
+ int, QmlExpressionPrivate &dd);
+
+private Q_SLOTS:
+ void __q_notify();
+
+private:
+ Q_DECLARE_PRIVATE(QmlExpression)
+ friend class QmlDebugger;
+ friend class QmlContext;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLEXPRESSION_H
+
diff --git a/src/declarative/qml/qmlexpression_p.h b/src/declarative/qml/qmlexpression_p.h
new file mode 100644
index 0000000..b19c60c
--- /dev/null
+++ b/src/declarative/qml/qmlexpression_p.h
@@ -0,0 +1,187 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLEXPRESSION_P_H
+#define QMLEXPRESSION_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 "qmlexpression.h"
+
+#include "qmlengine_p.h"
+#include "qmlguard_p.h"
+
+#include <QtScript/qscriptvalue.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlAbstractExpression
+{
+public:
+ QmlAbstractExpression();
+ virtual ~QmlAbstractExpression();
+
+ bool isValid() const;
+
+ QmlContext *context() const;
+ void setContext(QmlContext *);
+
+ virtual void refresh();
+
+private:
+ friend class QmlContext;
+ friend class QmlContextPrivate;
+ QmlContext *m_context;
+ QmlAbstractExpression **m_prevExpression;
+ QmlAbstractExpression *m_nextExpression;
+};
+
+class QmlDelayedError
+{
+public:
+ inline QmlDelayedError() : nextError(0), prevError(0) {}
+ inline ~QmlDelayedError() { removeError(); }
+
+ QmlError error;
+
+ bool addError(QmlEnginePrivate *);
+
+ inline void removeError() {
+ if (!prevError) return;
+ if (nextError) nextError->prevError = prevError;
+ *prevError = nextError;
+ nextError = 0;
+ prevError = 0;
+ }
+
+private:
+ QmlDelayedError *nextError;
+ QmlDelayedError **prevError;
+};
+
+class QmlExpressionData : public QmlAbstractExpression, public QmlDelayedError, public QmlRefCount
+{
+public:
+ QmlExpressionData();
+ virtual ~QmlExpressionData();
+
+ QmlExpressionPrivate *q;
+
+ QmlRefCount *dataRef;
+ QString expression;
+ bool expressionFunctionValid:1;
+ bool expressionRewritten:1;
+ QScriptValue expressionFunction;
+
+ QObject *me;
+ bool trackChange;
+
+ bool isShared;
+
+ QString url; // This is a QString for a reason. QUrls are slooooooow...
+ int line;
+
+ struct SignalGuard : public QmlGuard<QObject> {
+ SignalGuard() : isDuplicate(false), notifyIndex(-1) {}
+
+ SignalGuard &operator=(QObject *obj) {
+ QmlGuard<QObject>::operator=(obj);
+ return *this;
+ }
+ SignalGuard &operator=(const SignalGuard &o) {
+ QmlGuard<QObject>::operator=(o);
+ isDuplicate = o.isDuplicate;
+ notifyIndex = o.notifyIndex;
+ return *this;
+ }
+
+ bool isDuplicate:1;
+ int notifyIndex:31;
+ };
+ SignalGuard *guardList;
+ int guardListLength;
+};
+
+class QmlExpression;
+class QString;
+class QmlExpressionPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlExpression)
+public:
+ QmlExpressionPrivate();
+ QmlExpressionPrivate(QmlExpressionData *);
+ ~QmlExpressionPrivate();
+
+ void init(QmlContext *, const QString &, QObject *);
+ void init(QmlContext *, void *, QmlRefCount *, QObject *, const QString &, int);
+
+ QmlExpressionData *data;
+
+ QVariant value(QObject *secondaryScope = 0, bool *isUndefined = 0);
+ QVariant evalQtScript(QObject *secondaryScope, bool *isUndefined = 0);
+
+ void updateGuards(const QPODVector<QmlEnginePrivate::CapturedProperty> &properties);
+ void clearGuards();
+
+ static QmlExpressionPrivate *get(QmlExpression *expr) {
+ return static_cast<QmlExpressionPrivate *>(QObjectPrivate::get(expr));
+ }
+ static QmlExpression *get(QmlExpressionPrivate *expr) {
+ return expr->q_func();
+ }
+
+ static void exceptionToError(QScriptEngine *, QmlError &);
+ static QScriptValue evalInObjectScope(QmlContext *, QObject *, const QString &);
+ static QScriptValue evalInObjectScope(QmlContext *, QObject *, const QScriptProgram &);
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLEXPRESSION_P_H
diff --git a/src/declarative/qml/qmlglobal_p.h b/src/declarative/qml/qmlglobal_p.h
new file mode 100644
index 0000000..dc282bc
--- /dev/null
+++ b/src/declarative/qml/qmlglobal_p.h
@@ -0,0 +1,91 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGLOBAL_H
+#define QMLGLOBAL_H
+
+#include <QtCore/qglobal.h>
+#include <QtCore/QObject>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+#define DEFINE_BOOL_CONFIG_OPTION(name, var) \
+ static bool name() \
+ { \
+ static enum { Yes, No, Unknown } status = Unknown; \
+ if (status == Unknown) { \
+ QByteArray v = qgetenv(#var); \
+ bool value = !v.isEmpty() && v != "0" && v != "false"; \
+ if (value) status = Yes; \
+ else status = No; \
+ } \
+ return status == Yes; \
+ }
+
+struct QmlGraphics_DerivedObject : public QObject
+{
+ void setParent_noEvent(QObject *parent) {
+ bool sce = d_ptr->sendChildEvents;
+ d_ptr->sendChildEvents = false;
+ setParent(parent);
+ d_ptr->sendChildEvents = sce;
+ }
+};
+
+/*!
+ Makes the \a object a child of \a parent. Note that when using this method,
+ neither \a parent nor the object's previous parent (if it had one) will
+ receive ChildRemoved or ChildAdded events.
+*/
+inline void QmlGraphics_setParent_noEvent(QObject *object, QObject *parent)
+{
+ static_cast<QmlGraphics_DerivedObject *>(object)->setParent_noEvent(parent);
+}
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLGLOBAL_H
diff --git a/src/declarative/qml/qmlglobalscriptclass.cpp b/src/declarative/qml/qmlglobalscriptclass.cpp
new file mode 100644
index 0000000..13c1017
--- /dev/null
+++ b/src/declarative/qml/qmlglobalscriptclass.cpp
@@ -0,0 +1,121 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlglobalscriptclass_p.h"
+
+#include <QtScript/qscriptstring.h>
+#include <QtScript/qscriptengine.h>
+#include <QtScript/qscriptvalueiterator.h>
+
+QT_BEGIN_NAMESPACE
+
+/*
+ Used to prevent any writes to the global object.
+*/
+QmlGlobalScriptClass::QmlGlobalScriptClass(QScriptEngine *engine)
+: QScriptClass(engine)
+{
+ QScriptValue v = engine->newObject();
+ globalObject = engine->globalObject();
+
+ QScriptValueIterator iter(globalObject);
+ while (iter.hasNext()) {
+ iter.next();
+ v.setProperty(iter.scriptName(), iter.value());
+ }
+
+ v.setScriptClass(this);
+ engine->setGlobalObject(v);
+}
+
+QScriptClass::QueryFlags
+QmlGlobalScriptClass::queryProperty(const QScriptValue &object,
+ const QScriptString &name,
+ QueryFlags flags, uint *id)
+{
+ Q_UNUSED(object);
+ Q_UNUSED(name);
+ Q_UNUSED(flags);
+ Q_UNUSED(id);
+ return HandlesReadAccess | HandlesWriteAccess;
+}
+
+QScriptValue
+QmlGlobalScriptClass::property(const QScriptValue &object,
+ const QScriptString &name,
+ uint id)
+{
+ Q_UNUSED(object);
+ Q_UNUSED(name);
+ Q_UNUSED(id);
+ return engine()->undefinedValue();
+}
+
+void QmlGlobalScriptClass::setProperty(QScriptValue &object,
+ const QScriptString &name,
+ uint id, const QScriptValue &value)
+{
+ Q_UNUSED(object);
+ Q_UNUSED(id);
+ Q_UNUSED(value);
+ QString error = QLatin1String("Invalid write to global property \"") +
+ name.toString() + QLatin1Char('\"');
+ engine()->currentContext()->throwError(error);
+}
+
+void QmlGlobalScriptClass::explicitSetProperty(const QString &name, const QScriptValue &value)
+{
+ QScriptValue v = engine()->newObject();
+ globalObject = engine()->globalObject();
+
+ QScriptValueIterator iter(globalObject);
+ while (iter.hasNext()) {
+ iter.next();
+ v.setProperty(iter.scriptName(), iter.value());
+ }
+
+ v.setProperty(name, value);
+ v.setScriptClass(this);
+ engine()->setGlobalObject(v);
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/qml/qmlglobalscriptclass_p.h b/src/declarative/qml/qmlglobalscriptclass_p.h
new file mode 100644
index 0000000..56c91fe
--- /dev/null
+++ b/src/declarative/qml/qmlglobalscriptclass_p.h
@@ -0,0 +1,83 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGLOBALSCRIPTCLASS_P_H
+#define QMLGLOBALSCRIPTCLASS_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 <QtScript/qscriptclass.h>
+
+QT_BEGIN_NAMESPACE
+
+class Q_AUTOTEST_EXPORT QmlGlobalScriptClass : public QScriptClass
+{
+public:
+ QmlGlobalScriptClass(QScriptEngine *);
+
+ virtual QueryFlags queryProperty(const QScriptValue &object,
+ const QScriptString &name,
+ QueryFlags flags, uint *id);
+
+ virtual QScriptValue property(const QScriptValue &object,
+ const QScriptString &name, uint id);
+
+ virtual void setProperty(QScriptValue &object, const QScriptString &name,
+ uint id, const QScriptValue &value);
+
+ void explicitSetProperty(const QString &, const QScriptValue &);
+
+private:
+ QScriptValue globalObject;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLGLOBALSCRIPTCLASS_P_H
diff --git a/src/declarative/qml/qmlguard_p.h b/src/declarative/qml/qmlguard_p.h
new file mode 100644
index 0000000..1e55bcb
--- /dev/null
+++ b/src/declarative/qml/qmlguard_p.h
@@ -0,0 +1,156 @@
+/****************************************************************************
+**
+** 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 QtCore module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLGUARD_P_H
+#define QMLGUARD_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of qapplication_*.cpp, qwidget*.cpp and qfiledialog.cpp. 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 QObject;
+template<class T>
+class QmlGuard
+{
+ QObject *o;
+ QmlGuard<QObject> *next;
+ QmlGuard<QObject> **prev;
+ friend class QmlDeclarativeData;
+public:
+ inline QmlGuard();
+ inline QmlGuard(T *);
+ inline QmlGuard(const QmlGuard<T> &);
+ inline virtual ~QmlGuard();
+
+ inline QmlGuard<T> &operator=(const QmlGuard<T> &o);
+ inline QmlGuard<T> &operator=(T *);
+
+ inline bool isNull() const
+ { return !o; }
+
+ inline T* operator->() const
+ { return static_cast<T*>(const_cast<QObject*>(o)); }
+ inline T& operator*() const
+ { return *static_cast<T*>(const_cast<QObject*>(o)); }
+ inline operator T*() const
+ { return static_cast<T*>(const_cast<QObject*>(o)); }
+ inline T* data() const
+ { return static_cast<T*>(const_cast<QObject*>(o)); }
+
+protected:
+ virtual void objectDestroyed(T *) {}
+
+private:
+ inline void addGuard();
+ inline void remGuard();
+};
+
+Q_DECLARE_METATYPE(QmlGuard<QObject>);
+
+QT_END_NAMESPACE
+
+#include "qmldeclarativedata_p.h"
+
+QT_BEGIN_NAMESPACE
+
+template<class T>
+QmlGuard<T>::QmlGuard()
+: o(0), next(0), prev(0)
+{
+}
+
+template<class T>
+QmlGuard<T>::QmlGuard(T *g)
+: o(g), next(0), prev(0)
+{
+ if (o) addGuard();
+}
+
+template<class T>
+QmlGuard<T>::QmlGuard(const QmlGuard<T> &g)
+: o(g.o), next(0), prev(0)
+{
+ if (o) addGuard();
+}
+
+template<class T>
+QmlGuard<T>::~QmlGuard()
+{
+ if (prev) remGuard();
+ o = 0;
+}
+
+template<class T>
+QmlGuard<T> &QmlGuard<T>::operator=(const QmlGuard<T> &g)
+{
+ if (g.o != o) {
+ if (prev) remGuard();
+ o = g.o;
+ if (o) addGuard();
+ }
+ return *this;
+}
+
+template<class T>
+QmlGuard<T> &QmlGuard<T>::operator=(T *g)
+{
+ if (g != o) {
+ if (prev) remGuard();
+ o = g;
+ if (o) addGuard();
+ }
+ return *this;
+}
+
+QT_END_NAMESPACE
+
+#endif // QMLGUARD_P_H
diff --git a/src/declarative/qml/qmlinfo.cpp b/src/declarative/qml/qmlinfo.cpp
new file mode 100644
index 0000000..dabf944
--- /dev/null
+++ b/src/declarative/qml/qmlinfo.cpp
@@ -0,0 +1,127 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlinfo.h"
+
+#include "qmldeclarativedata_p.h"
+#include "qmlcontext.h"
+#include "qmlmetatype.h"
+
+#include <QCoreApplication>
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \fn QmlInfo qmlInfo(const QObject *object)
+
+ \brief Prints warnings messages that include the file and line number for QML types.
+
+ When QML types display warning messages, it improves traceability
+ if they include the QML file and line number on which the
+ particular instance was instantiated.
+
+ To include the file and line number, an object must be passed. If
+ the file and line number is not available for that instance
+ (either it was not instantiated by the QML engine or location
+ information is disabled), "unknown location" will be used instead.
+
+ For example,
+
+ \code
+ qmlInfo(object) << tr("component property is a write-once property");
+ \endcode
+
+ prints
+
+ \code
+ QML MyCustomType (unknown location): component property is a write-once property
+ \endcode
+*/
+
+QmlInfo::QmlInfo(const QObject *object)
+: QDebug(QtWarningMsg)
+{
+ QString pos = QLatin1String("QML");
+ if (object) {
+ pos += QLatin1Char(' ');
+
+ QString typeName;
+ QmlType *type = QmlMetaType::qmlType(object->metaObject());
+ if (type) {
+ typeName = QLatin1String(type->qmlTypeName());
+ int lastSlash = typeName.lastIndexOf(QLatin1Char('/'));
+ if (lastSlash != -1)
+ typeName = typeName.mid(lastSlash+1);
+ } else {
+ typeName = QString::fromUtf8(object->metaObject()->className());
+ int marker = typeName.indexOf(QLatin1String("_QMLTYPE_"));
+ if (marker != -1)
+ typeName = typeName.left(marker);
+ }
+
+ pos += typeName;
+ }
+ QmlDeclarativeData *ddata = object?QmlDeclarativeData::get(object):0;
+ pos += QLatin1String(" (");
+ if (ddata) {
+ if (ddata->outerContext) {
+ pos += ddata->outerContext->baseUrl().toString();
+ pos += QLatin1Char(':');
+ pos += QString::number(ddata->lineNumber);
+ pos += QLatin1Char(':');
+ pos += QString::number(ddata->columnNumber);
+ } else {
+ pos += QCoreApplication::translate("QmlInfo","unknown location");
+ }
+ } else {
+ pos += QCoreApplication::translate("QmlInfo","unknown location");
+ }
+ pos += QLatin1Char(')');
+ *this << pos;
+ nospace();
+}
+
+QmlInfo::~QmlInfo()
+{
+}
+
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlinfo.h b/src/declarative/qml/qmlinfo.h
new file mode 100644
index 0000000..fd56118
--- /dev/null
+++ b/src/declarative/qml/qmlinfo.h
@@ -0,0 +1,92 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLINFO_H
+#define QMLINFO_H
+
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class Q_DECLARATIVE_EXPORT QmlInfo : public QDebug
+{
+public:
+ QmlInfo(const QObject *);
+ ~QmlInfo();
+
+ inline QmlInfo &operator<<(QChar t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(QBool t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(bool t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(char t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(signed short t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(unsigned short t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(signed int t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(unsigned int t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(signed long t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(unsigned long t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(qint64 t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(quint64 t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(float t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(double t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(const char* t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(const QString & t) { QDebug::operator<<(t.toLocal8Bit().constData()); return *this; }
+ inline QmlInfo &operator<<(const QStringRef & t) { return operator<<(t.toString()); }
+ inline QmlInfo &operator<<(const QLatin1String &t) { QDebug::operator<<(t.latin1()); return *this; }
+ inline QmlInfo &operator<<(const QByteArray & t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(const void * t) { QDebug::operator<<(t); return *this; }
+ inline QmlInfo &operator<<(QTextStreamFunction f) { QDebug::operator<<(f); return *this; }
+ inline QmlInfo &operator<<(QTextStreamManipulator m) { QDebug::operator<<(m); return *this; }
+};
+
+Q_DECLARATIVE_EXPORT inline QmlInfo qmlInfo(const QObject *me)
+{
+ return QmlInfo(me);
+}
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLINFO_H
diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp
new file mode 100644
index 0000000..d99bf65
--- /dev/null
+++ b/src/declarative/qml/qmlinstruction.cpp
@@ -0,0 +1,216 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlinstruction_p.h"
+
+#include "qmlcompiler_p.h"
+
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+void QmlCompiledData::dump(QmlInstruction *instr, int idx)
+{
+ QByteArray lineNumber = QByteArray::number(instr->line);
+ if (instr->line == (unsigned short)-1)
+ lineNumber = "NA";
+ const char *line = lineNumber.constData();
+
+ switch(instr->type) {
+ case QmlInstruction::Init:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "INIT\t\t\t" << instr->init.bindingsSize << "\t" << instr->init.parserStatusSize << "\t" << instr->init.contextCache << "\t" << instr->init.compiledBinding;
+ break;
+ case QmlInstruction::CreateObject:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "CREATE\t\t\t" << instr->create.type << "\t\t\t" << types.at(instr->create.type).className;
+ break;
+ case QmlInstruction::SetId:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "SETID\t\t\t" << instr->setId.value << "\t\t\t" << primitives.at(instr->setId.value);
+ break;
+ case QmlInstruction::SetDefault:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "SET_DEFAULT";
+ break;
+ case QmlInstruction::CreateComponent:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "CREATE_COMPONENT\t" << instr->createComponent.count;
+ break;
+ case QmlInstruction::StoreMetaObject:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_META\t\t" << instr->storeMeta.data;
+ break;
+
+ case QmlInstruction::StoreFloat:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_FLOAT\t\t" << instr->storeFloat.propertyIndex << "\t" << instr->storeFloat.value;
+ break;
+ case QmlInstruction::StoreDouble:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_DOUBLE\t\t" << instr->storeDouble.propertyIndex << "\t" << instr->storeDouble.value;
+ break;
+ case QmlInstruction::StoreInteger:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_INTEGER\t\t" << instr->storeInteger.propertyIndex << "\t" << instr->storeInteger.value;
+ break;
+ case QmlInstruction::StoreBool:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_BOOL\t\t" << instr->storeBool.propertyIndex << "\t" << instr->storeBool.value;
+ break;
+ case QmlInstruction::StoreString:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_STRING\t\t" << instr->storeString.propertyIndex << "\t" << instr->storeString.value << "\t\t" << primitives.at(instr->storeString.value);
+ break;
+ case QmlInstruction::StoreUrl:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_URL\t\t" << instr->storeUrl.propertyIndex << "\t" << instr->storeUrl.value << "\t\t" << primitives.at(instr->storeUrl.value);
+ break;
+ case QmlInstruction::StoreColor:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_COLOR\t\t" << instr->storeColor.propertyIndex << "\t\t\t" << QString::number(instr->storeColor.value, 16);
+ break;
+ case QmlInstruction::StoreDate:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_DATE\t\t" << instr->storeDate.propertyIndex << "\t" << instr->storeDate.value;
+ break;
+ case QmlInstruction::StoreTime:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_TIME\t\t" << instr->storeTime.propertyIndex << "\t" << instr->storeTime.valueIndex;
+ break;
+ case QmlInstruction::StoreDateTime:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_DATETIME\t\t" << instr->storeDateTime.propertyIndex << "\t" << instr->storeDateTime.valueIndex;
+ break;
+ case QmlInstruction::StorePoint:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_POINT\t\t" << instr->storeRealPair.propertyIndex << "\t" << instr->storeRealPair.valueIndex;
+ break;
+ case QmlInstruction::StorePointF:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_POINTF\t\t" << instr->storeRealPair.propertyIndex << "\t" << instr->storeRealPair.valueIndex;
+ break;
+ case QmlInstruction::StoreSize:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_SIZE\t\t" << instr->storeRealPair.propertyIndex << "\t" << instr->storeRealPair.valueIndex;
+ break;
+ case QmlInstruction::StoreSizeF:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_SIZEF\t\t" << instr->storeRealPair.propertyIndex << "\t" << instr->storeRealPair.valueIndex;
+ break;
+ case QmlInstruction::StoreRect:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_RECT\t\t" << instr->storeRect.propertyIndex << "\t" << instr->storeRect.valueIndex;
+ break;
+ case QmlInstruction::StoreRectF:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_RECTF\t\t" << instr->storeRect.propertyIndex << "\t" << instr->storeRect.valueIndex;
+ break;
+ case QmlInstruction::StoreVector3D:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_VECTOR3D\t\t" << instr->storeVector3D.propertyIndex << "\t" << instr->storeVector3D.valueIndex;
+ break;
+ case QmlInstruction::StoreVariant:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_VARIANT\t\t" << instr->storeString.propertyIndex << "\t" << instr->storeString.value << "\t\t" << primitives.at(instr->storeString.value);
+ break;
+ case QmlInstruction::StoreObject:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_OBJECT\t\t" << instr->storeObject.propertyIndex;
+ break;
+ case QmlInstruction::StoreVariantObject:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_VARIANT_OBJECT\t" << instr->storeObject.propertyIndex;
+ break;
+ case QmlInstruction::StoreInterface:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_INTERFACE\t\t" << instr->storeObject.propertyIndex;
+ break;
+
+ case QmlInstruction::StoreSignal:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_SIGNAL\t\t" << instr->storeSignal.signalIndex << "\t" << instr->storeSignal.value << "\t\t" << primitives.at(instr->storeSignal.value);
+ break;
+ case QmlInstruction::StoreScript:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_SCRIPT\t\t" << instr->storeScript.value;
+ break;
+ case QmlInstruction::StoreScriptString:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_SCRIPT_STRING\t" << instr->storeScriptString.propertyIndex << "\t" << instr->storeScriptString.value << "\t" << instr->storeScriptString.scope;
+ break;
+
+ case QmlInstruction::AssignSignalObject:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "ASSIGN_SIGNAL_OBJECT\t" << instr->assignSignalObject.signal << "\t\t\t" << datas.at(instr->assignSignalObject.signal);
+ break;
+ case QmlInstruction::AssignCustomType:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "ASSIGN_CUSTOMTYPE\t" << instr->assignCustomType.propertyIndex << "\t" << instr->assignCustomType.valueIndex;
+ break;
+
+ case QmlInstruction::StoreBinding:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_BINDING\t" << instr->assignBinding.property << "\t" << instr->assignBinding.value << "\t" << instr->assignBinding.context;
+ break;
+ case QmlInstruction::StoreCompiledBinding:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_COMPILED_BINDING\t" << instr->assignBinding.property << "\t" << instr->assignBinding.value << "\t" << instr->assignBinding.context;
+ break;
+ case QmlInstruction::StoreValueSource:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_VALUE_SOURCE\t" << instr->assignValueSource.property << "\t" << instr->assignValueSource.castValue;
+ break;
+ case QmlInstruction::StoreValueInterceptor:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_VALUE_INTERCEPTOR\t" << instr->assignValueInterceptor.property << "\t" << instr->assignValueInterceptor.castValue;
+ break;
+
+ case QmlInstruction::BeginObject:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "BEGIN\t\t\t" << instr->begin.castValue;
+ break;
+ case QmlInstruction::StoreObjectQmlList:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_OBJECT_QMLLIST";
+ break;
+ case QmlInstruction::StoreObjectQList:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "STORE_OBJECT_QLIST";
+ break;
+ case QmlInstruction::AssignObjectList:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "ASSIGN_OBJECT_LIST";
+ break;
+ case QmlInstruction::FetchAttached:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "FETCH_ATTACHED\t\t" << instr->fetchAttached.id;
+ break;
+ case QmlInstruction::FetchQmlList:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "FETCH_QMLLIST\t\t" << instr->fetchQmlList.property << "\t" << instr->fetchQmlList.type;
+ break;
+ case QmlInstruction::FetchQList:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "FETCH_QLIST\t\t" << instr->fetch.property;
+ break;
+ case QmlInstruction::FetchObject:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "FETCH\t\t\t" << instr->fetch.property;
+ break;
+ case QmlInstruction::FetchValueType:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "FETCH_VALUE\t\t" << instr->fetchValue.property << "\t" << instr->fetchValue.type;
+ break;
+ case QmlInstruction::PopFetchedObject:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "POP";
+ break;
+ case QmlInstruction::PopQList:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "POP_QLIST";
+ break;
+ case QmlInstruction::PopValueType:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "POP_VALUE\t\t" << instr->fetchValue.property << "\t" << instr->fetchValue.type;
+ break;
+ case QmlInstruction::Defer:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "DEFER" << "\t\t\t" << instr->defer.deferCount;
+ break;
+ default:
+ qWarning().nospace() << idx << "\t\t" << line << "\t" << "XXX UNKOWN INSTRUCTION" << "\t" << instr->type;
+ break;
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h
new file mode 100644
index 0000000..0639397
--- /dev/null
+++ b/src/declarative/qml/qmlinstruction_p.h
@@ -0,0 +1,321 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLINSTRUCTION_P_H
+#define QMLINSTRUCTION_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 QmlCompiledData;
+class Q_DECLARATIVE_EXPORT QmlInstruction
+{
+public:
+ enum Type {
+ //
+ // Object Creation
+ //
+ // CreateObject - Create a new object instance and push it on the
+ // object stack
+ // SetId - Set the id of the object on the top of the object stack
+ // SetDefault - Sets the instance on the top of the object stack to
+ // be the context's default object.
+ // StoreMetaObject - Assign the dynamic metaobject to object on the
+ // top of the stack.
+ Init, /* init */
+ CreateObject, /* create */
+ SetId, /* setId */
+ SetDefault,
+ CreateComponent, /* createComponent */
+ StoreMetaObject, /* storeMeta */
+
+ //
+ // Precomputed single assignment
+ //
+ // StoreFloat - Store a float in a core property
+ // StoreDouble - Store a double in a core property
+ // StoreInteger - Store a int or uint in a core property
+ // StoreBool - Store a bool in a core property
+ // StoreString - Store a QString in a core property
+ // StoreUrl - Store a QUrl in a core property
+ // StoreColor - Store a QColor in a core property
+ // StoreDate - Store a QDate in a core property
+ // StoreTime - Store a QTime in a core property
+ // StoreDateTime - Store a QDateTime in a core property
+ // StoreVariant - Store a QVariant in a core property
+ // StoreObject - Pop the object on the top of the object stack and
+ // store it in a core property
+ StoreFloat, /* storeFloat */
+ StoreDouble, /* storeDouble */
+ StoreInteger, /* storeInteger */
+ StoreBool, /* storeBool */
+ StoreString, /* storeString */
+ StoreUrl, /* storeUrl */
+ StoreColor, /* storeColor */
+ StoreDate, /* storeDate */
+ StoreTime, /* storeTime */
+ StoreDateTime, /* storeDateTime */
+ StorePoint, /* storeRealPair */
+ StorePointF, /* storeRealPair */
+ StoreSize, /* storeRealPair */
+ StoreSizeF, /* storeRealPair */
+ StoreRect, /* storeRect */
+ StoreRectF, /* storeRect */
+ StoreVector3D, /* storeVector3D */
+ StoreVariant, /* storeString */
+ StoreObject, /* storeObject */
+ StoreVariantObject, /* storeObject */
+ StoreInterface, /* storeObject */
+
+ StoreSignal, /* storeSignal */
+ StoreScript, /* storeScript */
+ StoreScriptString, /* storeScriptString */
+
+ //
+ // Unresolved single assignment
+ //
+ AssignSignalObject, /* assignSignalObject */
+ AssignCustomType, /* assignCustomType */
+
+ StoreBinding, /* assignBinding */
+ StoreCompiledBinding, /* assignBinding */
+ StoreValueSource, /* assignValueSource */
+ StoreValueInterceptor, /* assignValueInterceptor */
+
+ BeginObject, /* begin */
+
+ StoreObjectQmlList, /* NA */
+ StoreObjectQList, /* NA */
+ AssignObjectList, /* NA */
+
+ FetchAttached, /* fetchAttached */
+ FetchQmlList, /* fetchQmlList */
+ FetchQList, /* fetch */
+ FetchObject, /* fetch */
+ FetchValueType, /* fetchValue */
+
+ //
+ // Stack manipulation
+ //
+ // PopFetchedObject - Remove an object from the object stack
+ // PopQList - Remove a list from the list stack
+ PopFetchedObject,
+ PopQList,
+ PopValueType, /* fetchValue */
+
+ //
+ // Deferred creation
+ //
+ Defer, /* defer */
+ };
+ QmlInstruction()
+ : line(0) {}
+
+ Type type;
+ unsigned short line;
+ union {
+ struct {
+ int bindingsSize;
+ int parserStatusSize;
+ int contextCache;
+ int compiledBinding;
+ } init;
+ struct {
+ int type;
+ int data;
+ int bindingBits;
+ ushort column;
+ } create;
+ struct {
+ int data;
+ int aliasData;
+ int propertyCache;
+ } storeMeta;
+ struct {
+ int value;
+ int index;
+ } setId;
+ struct {
+ int property;
+ int owner;
+ int castValue;
+ } assignValueSource;
+ struct {
+ int property;
+ int owner;
+ int castValue;
+ } assignValueInterceptor;
+ struct {
+ unsigned int property;
+ int value;
+ short context;
+ short owner;
+ } assignBinding;
+ struct {
+ int property;
+ int id;
+ } assignIdOptBinding;
+ struct {
+ int property;
+ int contextIdx;
+ short context;
+ short notifyIdx;
+ } assignObjPropBinding;
+ struct {
+ int property;
+ } fetch;
+ struct {
+ int property;
+ int type;
+ } fetchValue;
+ struct {
+ int property;
+ int type;
+ } fetchQmlList;
+ struct {
+ int castValue;
+ } begin;
+ struct {
+ int propertyIndex;
+ float value;
+ } storeFloat;
+ struct {
+ int propertyIndex;
+ double value;
+ } storeDouble;
+ struct {
+ int propertyIndex;
+ int value;
+ } storeInteger;
+ struct {
+ int propertyIndex;
+ bool value;
+ } storeBool;
+ struct {
+ int propertyIndex;
+ int value;
+ } storeString;
+ struct {
+ int propertyIndex;
+ int value;
+ int scope;
+ } storeScriptString;
+ struct {
+ int value;
+ } storeScript;
+ struct {
+ int propertyIndex;
+ int value;
+ } storeUrl;
+ struct {
+ int propertyIndex;
+ unsigned int value;
+ } storeColor;
+ struct {
+ int propertyIndex;
+ int value;
+ } storeDate;
+ struct {
+ int propertyIndex;
+ int valueIndex;
+ } storeTime;
+ struct {
+ int propertyIndex;
+ int valueIndex;
+ } storeDateTime;
+ struct {
+ int propertyIndex;
+ int valueIndex;
+ } storeRealPair;
+ struct {
+ int propertyIndex;
+ int valueIndex;
+ } storeRect;
+ struct {
+ int propertyIndex;
+ int valueIndex;
+ } storeVector3D;
+ struct {
+ int propertyIndex;
+ } storeObject;
+ struct {
+ int propertyIndex;
+ int valueIndex;
+ } assignCustomType;
+ struct {
+ int signalIndex;
+ int value;
+ } storeSignal;
+ struct {
+ int signal;
+ } assignSignalObject;
+ struct {
+ int count;
+ ushort column;
+ int endLine;
+ int metaObject;
+ } createComponent;
+ struct {
+ int id;
+ } fetchAttached;
+ struct {
+ int deferCount;
+ } defer;
+ };
+
+ void dump(QmlCompiledData *);
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLINSTRUCTION_P_H
diff --git a/src/declarative/qml/qmlintegercache.cpp b/src/declarative/qml/qmlintegercache.cpp
new file mode 100644
index 0000000..1968873
--- /dev/null
+++ b/src/declarative/qml/qmlintegercache.cpp
@@ -0,0 +1,86 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlintegercache_p.h"
+
+#include "qmlengine_p.h"
+#include "qmlmetatype.h"
+
+QT_BEGIN_NAMESPACE
+
+QmlIntegerCache::QmlIntegerCache(QmlEngine *e)
+: QmlCleanup(e), engine(e)
+{
+}
+
+QmlIntegerCache::~QmlIntegerCache()
+{
+ clear();
+}
+
+void QmlIntegerCache::clear()
+{
+ qDeleteAll(stringCache);
+ stringCache.clear();
+ identifierCache.clear();
+ engine = 0;
+}
+
+void QmlIntegerCache::add(const QString &id, int value)
+{
+ Q_ASSERT(!stringCache.contains(id));
+
+ QmlEnginePrivate *enginePriv = QmlEnginePrivate::get(engine);
+
+ // ### use contextClass
+ Data *d = new Data(enginePriv->objectClass->createPersistentIdentifier(id), value);
+
+ stringCache.insert(id, d);
+ identifierCache.insert(d->identifier, d);
+}
+
+int QmlIntegerCache::value(const QString &id)
+{
+ Data *d = stringCache.value(id);
+ return d?d->value:-1;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlintegercache_p.h b/src/declarative/qml/qmlintegercache_p.h
new file mode 100644
index 0000000..d9df52a
--- /dev/null
+++ b/src/declarative/qml/qmlintegercache_p.h
@@ -0,0 +1,111 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLINTEGERCACHE_P_H
+#define QMLINTEGERCACHE_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 "qmlrefcount_p.h"
+#include "qmlcleanup_p.h"
+
+#include <QtCore/qhash.h>
+
+#include <private/qscriptdeclarativeclass_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlType;
+class QmlEngine;
+class QmlIntegerCache : public QmlRefCount, public QmlCleanup
+{
+public:
+ QmlIntegerCache(QmlEngine *);
+ virtual ~QmlIntegerCache();
+
+ inline int count() const;
+ void add(const QString &, int);
+ int value(const QString &);
+ inline int value(const QScriptDeclarativeClass::Identifier &id) const;
+
+protected:
+ virtual void clear();
+
+private:
+ struct Data : public QScriptDeclarativeClass::PersistentIdentifier {
+ Data(const QScriptDeclarativeClass::PersistentIdentifier &i, int v)
+ : QScriptDeclarativeClass::PersistentIdentifier(i), value(v) {}
+
+ int value;
+ };
+
+ typedef QHash<QString, Data *> StringCache;
+ typedef QHash<QScriptDeclarativeClass::Identifier, Data *> IdentifierCache;
+
+ StringCache stringCache;
+ IdentifierCache identifierCache;
+ QmlEngine *engine;
+};
+
+int QmlIntegerCache::value(const QScriptDeclarativeClass::Identifier &id) const
+{
+ Data *d = identifierCache.value(id);
+ return d?d->value:-1;
+}
+
+int QmlIntegerCache::count() const
+{
+ return stringCache.count();
+}
+
+QT_END_NAMESPACE
+
+#endif // QMLINTEGERCACHE_P_H
+
diff --git a/src/declarative/qml/qmllist.h b/src/declarative/qml/qmllist.h
new file mode 100644
index 0000000..ad2d874
--- /dev/null
+++ b/src/declarative/qml/qmllist.h
@@ -0,0 +1,126 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLLIST_H
+#define QMLLIST_H
+
+#include "qmlprivate.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+template<typename T>
+class QmlList : private QmlPrivate::ListInterface
+{
+public:
+ virtual void append(T) = 0;
+ virtual void insert(int, T) = 0;
+ virtual void removeAt(int) = 0;
+ virtual T at(int) const = 0;
+ virtual int count() const = 0;
+ virtual void clear() = 0;
+ QmlList<T> &operator<<(T t) { append(t); return *this; }
+
+protected:
+ virtual int type() const { return qMetaTypeId<T>(); }
+ virtual void append(void *d) { const T &v = *(T *)d; append(v); }
+ virtual void insert(int i, void *d) { const T &v = *(T *)d; insert(i, v); }
+ virtual void at(int i, void *p) const { const T &v = at(i); *((T*)p) = v; }
+};
+
+template<typename T>
+class QmlConcreteList : public QList<T>, public QmlList<T>
+{
+public:
+ virtual void append(T v) { QList<T>::append(v); }
+ virtual void insert(int i, T v) { QList<T>::insert(i, v); }
+ virtual void clear() { QList<T>::clear(); }
+ virtual T at(int i) const { return QList<T>::at(i); }
+ virtual void removeAt(int i) { QList<T>::removeAt(i); }
+ virtual int count() const { return QList<T>::count(); }
+};
+
+#define QML_DECLARE_LIST_PROXY(ClassName, ListType, ListName) \
+class Qml_ProxyList_ ##ListName : public QmlList<ListType> \
+{ \
+ public: \
+ virtual void removeAt(int idx) \
+ { \
+ ClassName *p = (ClassName *)((char *)this + ((char *)(ClassName *)(0x10000000) - (char *)&((ClassName *)(0x10000000))->ListName)); \
+ p->ListName ## _removeAt(idx); \
+ } \
+ virtual int count() const \
+ { \
+ ClassName *p = (ClassName *)((char *)this + ((char *)(ClassName *)(0x10000000) - (char *)&((ClassName *)(0x10000000))->ListName)); \
+ return p->ListName ## _count(); \
+ } \
+ virtual void append(ListType v) \
+ { \
+ ClassName *p = (ClassName *)((char *)this + ((char *)(ClassName *)(0x10000000) - (char *)&((ClassName *)(0x10000000))->ListName)); \
+ p->ListName ## _append(v); \
+ } \
+ virtual void insert(int idx, ListType v) \
+ { \
+ ClassName *p = (ClassName *)((char *)this + ((char *)(ClassName *)(0x10000000) - (char *)&((ClassName *)(0x10000000))->ListName)); \
+ p->ListName ## _insert(idx, v); \
+ } \
+ virtual ListType at(int idx) const \
+ { \
+ ClassName *p = (ClassName *)((char *)this + ((char *)(ClassName *)(0x10000000) - (char *)&((ClassName *)(0x10000000))->ListName)); \
+ return p->ListName ## _at(idx); \
+ } \
+ virtual void clear() \
+ { \
+ ClassName *p = (ClassName *)((char *)this + ((char *)(ClassName *)(0x10000000) - (char *)&((ClassName *)(0x10000000))->ListName)); \
+ p->ListName ## _clear(); \
+ } \
+}; \
+friend class Qml_ProxyList_ ##ListName ; \
+Qml_ProxyList_##ListName ListName;
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLLIST_H
diff --git a/src/declarative/qml/qmllistscriptclass.cpp b/src/declarative/qml/qmllistscriptclass.cpp
new file mode 100644
index 0000000..d4cdc6e
--- /dev/null
+++ b/src/declarative/qml/qmllistscriptclass.cpp
@@ -0,0 +1,173 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmllistscriptclass_p.h"
+
+#include "qmlengine_p.h"
+#include "qmlguard_p.h"
+
+QT_BEGIN_NAMESPACE
+
+struct ListData : public QScriptDeclarativeClass::Object {
+ QmlGuard<QObject> object;
+ int propertyIdx;
+ QmlListScriptClass::ListCategory type;
+ int propertyType;
+};
+
+QmlListScriptClass::QmlListScriptClass(QmlEngine *e)
+: QmlScriptClass(QmlEnginePrivate::getScriptEngine(e)), engine(e)
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+ Q_UNUSED(scriptEngine);
+
+ m_lengthId = createPersistentIdentifier(QLatin1String("length"));
+}
+
+QmlListScriptClass::~QmlListScriptClass()
+{
+}
+
+QScriptValue QmlListScriptClass::newList(QObject *object, int propId, ListCategory type, int propType)
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ if (!object || propId == -1)
+ return scriptEngine->nullValue();
+
+ ListData *data = new ListData;
+ data->object = object;
+ data->propertyIdx = propId;
+ data->type = type;
+ data->propertyType = propType;
+
+ return newObject(scriptEngine, this, data);
+}
+
+QScriptClass::QueryFlags
+QmlListScriptClass::queryProperty(Object *object, const Identifier &name,
+ QScriptClass::QueryFlags flags)
+{
+ Q_UNUSED(object);
+ Q_UNUSED(flags);
+ if (name == m_lengthId.identifier)
+ return QScriptClass::HandlesReadAccess;
+
+ bool ok = false;
+ quint32 idx = toArrayIndex(name, &ok);
+
+ if (ok) {
+ lastIndex = idx;
+ return QScriptClass::HandlesReadAccess;
+ } else {
+ return 0;
+ }
+}
+
+QmlListScriptClass::ScriptValue QmlListScriptClass::property(Object *obj, const Identifier &name)
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+ QmlEnginePrivate *enginePriv = QmlEnginePrivate::get(engine);
+
+ ListData *data = (ListData *)obj;
+ if (!data->object)
+ return Value();
+
+ void *list = 0;
+ void *args[] = { &list, 0 };
+ QMetaObject::metacall(data->object, QMetaObject::ReadProperty,
+ data->propertyIdx, args);
+
+ if (!list)
+ return Value();
+
+ if (data->type == QListPtr) {
+ const QList<QObject *> &qlist = *((QList<QObject *>*)list);
+
+ quint32 count = qlist.count();
+
+ if (name == m_lengthId.identifier)
+ return Value(scriptEngine, count);
+ else if (lastIndex < count)
+ return Value(scriptEngine, enginePriv->objectClass->newQObject(qlist.at(lastIndex)));
+ else
+ return Value();
+
+ } else {
+ Q_ASSERT(data->type == QmlListPtr);
+ const QmlList<QObject *> &qmllist = *((QmlList<QObject *>*)list);
+
+ quint32 count = qmllist.count();
+
+ if (name == m_lengthId.identifier)
+ return Value(scriptEngine, count);
+ else if (lastIndex < count)
+ return Value(scriptEngine, enginePriv->objectClass->newQObject(qmllist.at(lastIndex)));
+ else
+ return Value();
+ }
+}
+
+QVariant QmlListScriptClass::toVariant(Object *obj, bool *ok)
+{
+ ListData *data = (ListData *)obj;
+
+ if (!data->object) {
+ if (ok) *ok = false;
+ return QVariant();
+ }
+
+ void *list = 0;
+ void *args[] = { &list, 0 };
+ QMetaObject::metacall(data->object, QMetaObject::ReadProperty,
+ data->propertyIdx, args);
+
+ if (!list) {
+ if (ok) *ok = false;
+ return QVariant();
+ }
+
+ if (ok) *ok = true;
+ return QVariant(data->propertyType, &list);
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/qml/qmllistscriptclass_p.h b/src/declarative/qml/qmllistscriptclass_p.h
new file mode 100644
index 0000000..e484b34
--- /dev/null
+++ b/src/declarative/qml/qmllistscriptclass_p.h
@@ -0,0 +1,86 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLLISTSCRIPTCLASS_P_H
+#define QMLLISTSCRIPTCLASS_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 <private/qmlscriptclass_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlEngine;
+class QmlListScriptClass : public QmlScriptClass
+{
+public:
+ QmlListScriptClass(QmlEngine *);
+ ~QmlListScriptClass();
+
+ enum ListCategory { QListPtr, QmlListPtr };
+ QScriptValue newList(QObject *, int, ListCategory, int);
+
+protected:
+ virtual QScriptClass::QueryFlags queryProperty(Object *, const Identifier &,
+ QScriptClass::QueryFlags flags);
+ virtual ScriptValue property(Object *, const Identifier &);
+ virtual QVariant toVariant(Object *, bool *ok);
+
+private:
+ PersistentIdentifier m_lengthId;
+ QmlEngine *engine;
+
+ quint32 lastIndex;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLLISTSCRIPTCLASS_P_H
+
diff --git a/src/declarative/qml/qmlmetaproperty.cpp b/src/declarative/qml/qmlmetaproperty.cpp
new file mode 100644
index 0000000..f23a50a
--- /dev/null
+++ b/src/declarative/qml/qmlmetaproperty.cpp
@@ -0,0 +1,1245 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlmetaproperty.h"
+#include "qmlmetaproperty_p.h"
+
+#include "qmlcompositetypedata_p.h"
+#include "qml.h"
+#include "qmlbinding.h"
+#include "qmlcontext.h"
+#include "qmlcontext_p.h"
+#include "qmlboundsignal_p.h"
+#include "qmlengine.h"
+#include "qmlengine_p.h"
+#include "qmldeclarativedata_p.h"
+#include "qmlstringconverters_p.h"
+
+#include <qfxperf_p_p.h>
+
+#include <QStringList>
+#include <QtCore/qdebug.h>
+
+#include <math.h>
+
+Q_DECLARE_METATYPE(QList<QObject *>);
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QmlMetaProperty
+ \brief The QmlMetaProperty class abstracts accessing QML properties.
+ \internal
+ */
+
+/*!
+ Create an invalid QmlMetaProperty.
+*/
+QmlMetaProperty::QmlMetaProperty()
+: d(new QmlMetaPropertyPrivate)
+{
+ d->q = this;
+}
+
+/*! \internal */
+QmlMetaProperty::~QmlMetaProperty()
+{
+ delete d; d = 0;
+}
+
+/*!
+ Creates a QmlMetaProperty for the default property of \a obj. If there is no
+ default property, an invalid QmlMetaProperty will be created.
+ */
+QmlMetaProperty::QmlMetaProperty(QObject *obj)
+: d(new QmlMetaPropertyPrivate)
+{
+ d->q = this;
+ d->initDefault(obj);
+}
+
+/*!
+ \internal
+ Creates a QmlMetaProperty for the default property of \a obj. If there is no
+ default property, an invalid QmlMetaProperty will be created.
+ */
+QmlMetaProperty::QmlMetaProperty(QObject *obj, QmlContext *ctxt)
+: d(new QmlMetaPropertyPrivate)
+{
+ d->q = this;
+ d->context = ctxt;
+ d->initDefault(obj);
+}
+
+/*!
+ Initialize from the default property of \a obj
+*/
+void QmlMetaPropertyPrivate::initDefault(QObject *obj)
+{
+ if (!obj)
+ return;
+
+ QMetaProperty p = QmlMetaType::defaultProperty(obj);
+ core.load(p);
+ if (core.isValid()) {
+ isDefaultProperty = true;
+ object = obj;
+ }
+}
+
+/*!
+ Creates a QmlMetaProperty for the property \a name of \a obj.
+ */
+QmlMetaProperty::QmlMetaProperty(QObject *obj, const QString &name)
+: d(new QmlMetaPropertyPrivate)
+{
+ d->q = this;
+ d->initProperty(obj, name);
+ if (!isValid()) d->object = 0;
+}
+
+/*!
+ \internal
+ Creates a QmlMetaProperty for the property \a name of \a obj.
+ */
+QmlMetaProperty::QmlMetaProperty(QObject *obj, const QString &name, QmlContext *ctxt)
+: d(new QmlMetaPropertyPrivate)
+{
+ d->q = this;
+ d->context = ctxt;
+ d->initProperty(obj, name);
+ if (!isValid()) { d->object = 0; d->context = 0; }
+}
+
+void QmlMetaPropertyPrivate::initProperty(QObject *obj, const QString &name)
+{
+ QmlEnginePrivate *enginePrivate = 0;
+ if (context && context->engine())
+ enginePrivate = QmlEnginePrivate::get(context->engine());
+
+ object = obj;
+
+ if (name.isEmpty() || !obj)
+ return;
+
+ if (enginePrivate && name.at(0).isUpper()) {
+ // Attached property
+ // ### What about qualified types?
+ QmlTypeNameCache *tnCache = QmlContextPrivate::get(context)->imports;
+ if (tnCache) {
+ QmlTypeNameCache::Data *d = tnCache->data(name);
+ if (d && d->type && d->type->attachedPropertiesFunction()) {
+ attachedFunc = d->type->index();
+ }
+ }
+ return;
+
+ } else if (name.count() >= 3 &&
+ name.at(0) == QChar(QLatin1Char('o')) &&
+ name.at(1) == QChar(QLatin1Char('n')) &&
+ name.at(2).isUpper()) {
+ // Signal
+ QString signalName = name.mid(2);
+ signalName[0] = signalName.at(0).toLower();
+
+ QMetaMethod method = findSignal(obj, signalName);
+ if (method.signature()) {
+ core.load(method);
+ return;
+ }
+ }
+
+ // Property
+ QmlPropertyCache::Data local;
+ QmlPropertyCache::Data *property =
+ QmlPropertyCache::property(context?context->engine():0, obj, name, local);
+ if (property && !(property->flags & QmlPropertyCache::Data::IsFunction))
+ core = *property;
+}
+
+/*!
+ Create a copy of \a other.
+*/
+QmlMetaProperty::QmlMetaProperty(const QmlMetaProperty &other)
+: d(new QmlMetaPropertyPrivate(*other.d))
+{
+ d->q = this;
+}
+
+/*!
+ \enum QmlMetaProperty::PropertyCategory
+
+ This enum specifies a category of QML property.
+
+ \value Unknown The category is unknown. This will never be returned from propertyCategory()
+ \value InvalidProperty The property is invalid.
+ \value Bindable The property is a QmlBinding.
+ \value List The property is a QList pointer
+ \value QmlList The property is a QmlList pointer
+ \value Object The property is a QObject derived type pointer
+ \value Normal The property is none of the above.
+ */
+
+/*!
+ \enum QmlMetaProperty::Type
+
+ This enum specifies a type of QML property.
+
+ \value Invalid The property is invalid.
+ \value Property The property is a regular Qt property.
+ \value SignalProperty The property is a signal property.
+ \value Default The property is the default property.
+ \value Attached The property is an attached property.
+*/
+
+/*!
+ Returns the property category.
+*/
+QmlMetaProperty::PropertyCategory QmlMetaProperty::propertyCategory() const
+{
+ return d->propertyCategory();
+}
+
+QmlMetaProperty::PropertyCategory
+QmlMetaPropertyPrivate::propertyCategory() const
+{
+ uint type = q->type();
+
+ if (type & QmlMetaProperty::ValueTypeProperty) {
+ return QmlMetaProperty::Normal;
+ } else if (type & QmlMetaProperty::Attached) {
+ return QmlMetaProperty::Object;
+ } else if (type & QmlMetaProperty::Property) {
+ int type = propertyType();
+ if (type == QVariant::Invalid)
+ return QmlMetaProperty::InvalidProperty;
+ else if ((uint)type < QVariant::UserType)
+ return QmlMetaProperty::Normal;
+ else if (type == qMetaTypeId<QmlBinding *>())
+ return QmlMetaProperty::Bindable;
+ else if (core.flags & QmlPropertyCache::Data::IsQObjectDerived)
+ return QmlMetaProperty::Object;
+ else if (core.flags & QmlPropertyCache::Data::IsQmlList)
+ return QmlMetaProperty::QmlList;
+ else if (core.flags & QmlPropertyCache::Data::IsQList)
+ return QmlMetaProperty::List;
+ else
+ return QmlMetaProperty::Normal;
+ } else {
+ return QmlMetaProperty::InvalidProperty;
+ }
+}
+
+/*!
+ Returns the type name of the property, or 0 if the property has no type
+ name.
+*/
+const char *QmlMetaProperty::propertyTypeName() const
+{
+ if (type() & ValueTypeProperty) {
+
+ QmlEnginePrivate *ep = d->context?QmlEnginePrivate::get(d->context->engine()):0;
+ QmlValueType *valueType = 0;
+ if (ep) valueType = ep->valueTypes[d->core.propType];
+ else valueType = QmlValueTypeFactory::valueType(d->core.propType);
+ Q_ASSERT(valueType);
+
+ const char *rv = valueType->metaObject()->property(d->valueType.valueTypeCoreIdx).typeName();
+
+ if (!ep) delete valueType;
+
+ return rv;
+ } else if (d->object && type() & Property && d->core.isValid()) {
+ return d->object->metaObject()->property(d->core.coreIndex).typeName();
+ } else {
+ return 0;
+ }
+}
+
+/*!
+ Returns true if \a other and this QmlMetaProperty represent the same
+ property.
+*/
+bool QmlMetaProperty::operator==(const QmlMetaProperty &other) const
+{
+ // category is intentially omitted here as it is generated
+ // from the other members
+ return d->object == other.d->object &&
+ d->core == other.d->core &&
+ d->valueType == other.d->valueType &&
+ d->attachedFunc == other.d->attachedFunc;
+}
+
+/*!
+ Returns the QVariant type of the property, or QVariant::Invalid if the
+ property has no QVariant type.
+*/
+int QmlMetaProperty::propertyType() const
+{
+ return d->propertyType();
+}
+
+int QmlMetaPropertyPrivate::propertyType() const
+{
+ uint type = q->type();
+ if (type & QmlMetaProperty::ValueTypeProperty) {
+ return valueType.valueTypePropType;
+ } else if (type & QmlMetaProperty::Attached) {
+ return qMetaTypeId<QObject *>();
+ } else if (type & QmlMetaProperty::Property) {
+ if (core.propType == (int)QVariant::LastType)
+ return qMetaTypeId<QVariant>();
+ else
+ return core.propType;
+ } else {
+ return QVariant::Invalid;
+ }
+}
+
+/*!
+ Returns the type of the property.
+*/
+QmlMetaProperty::Type QmlMetaProperty::type() const
+{
+ if (d->core.flags & QmlPropertyCache::Data::IsFunction)
+ return SignalProperty;
+ else if (d->attachedFunc != -1)
+ return Attached;
+ else if (d->valueType.valueTypeCoreIdx != -1)
+ return (Type)(Property | ValueTypeProperty);
+ else if (d->core.isValid())
+ return (Type)(Property | ((d->isDefaultProperty)?Default:0));
+ else
+ return Invalid;
+}
+
+/*!
+ Returns true if this QmlMetaProperty represents a regular Qt property.
+*/
+bool QmlMetaProperty::isProperty() const
+{
+ return type() & Property;
+}
+
+/*!
+ Returns true if this QmlMetaProperty represents a default property.
+*/
+bool QmlMetaProperty::isDefault() const
+{
+ return type() & Default;
+}
+
+/*!
+ Returns the QmlMetaProperty's QObject.
+*/
+QObject *QmlMetaProperty::object() const
+{
+ return d->object;
+}
+
+/*!
+ Assign \a other to this QmlMetaProperty.
+*/
+QmlMetaProperty &QmlMetaProperty::operator=(const QmlMetaProperty &other)
+{
+ d->context = other.d->context;
+ d->object = other.d->object;
+
+ d->isDefaultProperty = other.d->isDefaultProperty;
+ d->core = other.d->core;
+
+ d->valueType = other.d->valueType;
+
+ d->attachedFunc = other.d->attachedFunc;
+ return *this;
+}
+
+/*!
+ Returns true if the property is writable, otherwise false.
+*/
+bool QmlMetaProperty::isWritable() const
+{
+ QmlMetaProperty::PropertyCategory category = propertyCategory();
+
+ if (!d->object)
+ return false;
+ if (category == List || category == QmlList)
+ return true;
+ else if (type() & SignalProperty)
+ return false;
+ else if (d->core.isValid() && d->object)
+ return d->core.flags & QmlPropertyCache::Data::IsWritable;
+ else
+ return false;
+}
+
+/*!
+ Returns true if the property is designable, otherwise false.
+*/
+bool QmlMetaProperty::isDesignable() const
+{
+ if (type() & Property && d->core.isValid() && d->object)
+ return d->object->metaObject()->property(d->core.coreIndex).isDesignable();
+ else
+ return false;
+}
+
+/*!
+ Returns true if the property is resettable, otherwise false.
+*/
+bool QmlMetaProperty::isResettable() const
+{
+ if (type() & Property && d->core.isValid() && d->object)
+ return d->core.flags & QmlPropertyCache::Data::IsResettable;
+ else
+ return false;
+}
+
+/*!
+ Returns true if the QmlMetaProperty refers to a valid property, otherwise
+ false.
+*/
+bool QmlMetaProperty::isValid() const
+{
+ return type() != Invalid;
+}
+
+/*!
+ Return the name of this QML property.
+*/
+QString QmlMetaProperty::name() const
+{
+ if (!d->isNameCached) {
+ // ###
+ if (!d->object) {
+ } else if (type() & ValueTypeProperty) {
+ QString rv = d->core.name(d->object) + QLatin1Char('.');
+
+ QmlEnginePrivate *ep = d->context?QmlEnginePrivate::get(d->context->engine()):0;
+ QmlValueType *valueType = 0;
+ if (ep) valueType = ep->valueTypes[d->core.propType];
+ else valueType = QmlValueTypeFactory::valueType(d->core.propType);
+ Q_ASSERT(valueType);
+
+ rv += QString::fromUtf8(valueType->metaObject()->property(d->valueType.valueTypeCoreIdx).name());
+
+ if (!ep) delete valueType;
+
+ d->nameCache = rv;
+ } else if (type() & SignalProperty) {
+ QString name = QLatin1String("on") + d->core.name(d->object);
+ name[2] = name.at(2).toUpper();
+ d->nameCache = name;
+ } else {
+ d->nameCache = d->core.name(d->object);
+ }
+ d->isNameCached = true;
+ }
+
+ return d->nameCache;
+}
+
+/*!
+ Returns the \l{QMetaProperty} {Qt property} associated with
+ this QML property.
+ */
+QMetaProperty QmlMetaProperty::property() const
+{
+ if (type() & Property && d->core.isValid() && d->object)
+ return d->object->metaObject()->property(d->core.coreIndex);
+ else
+ return QMetaProperty();
+}
+
+/*!
+ Return the QMetaMethod for this property if it is a SignalProperty,
+ otherwise returns an invalid QMetaMethod.
+*/
+QMetaMethod QmlMetaProperty::method() const
+{
+ if (type() & SignalProperty && d->object)
+ return d->object->metaObject()->method(d->core.coreIndex);
+ else
+ return QMetaMethod();
+}
+
+
+/*!
+ Returns the binding associated with this property, or 0 if no binding
+ exists.
+*/
+QmlAbstractBinding *QmlMetaProperty::binding() const
+{
+ if (!isProperty() || (type() & Attached) || !d->object)
+ return 0;
+
+ QmlDeclarativeData *data = QmlDeclarativeData::get(d->object);
+ if (!data)
+ return 0;
+
+ if (!data->hasBindingBit(d->core.coreIndex))
+ return 0;
+
+ QmlAbstractBinding *binding = data->bindings;
+ while (binding) {
+ // ### This wont work for value types
+ if (binding->propertyIndex() == d->core.coreIndex)
+ return binding;
+ binding = binding->m_nextBinding;
+ }
+ return 0;
+}
+
+/*!
+ Set the binding associated with this property to \a newBinding. Returns
+ the existing binding (if any), otherwise 0.
+
+ \a newBinding will be enabled, and the returned binding (if any) will be
+ disabled.
+
+ Ownership of \a newBinding transfers to QML. Ownership of the return value
+ is assumed by the caller.
+
+ \a flags is passed through to the binding and is used for the initial update (when
+ the binding sets the intial value, it will use these flags for the write).
+*/
+QmlAbstractBinding *
+QmlMetaProperty::setBinding(QmlAbstractBinding *newBinding, QmlMetaProperty::WriteFlags flags) const
+{
+ if (!isProperty() || (type() & Attached) || !d->object) {
+ if (newBinding)
+ newBinding->destroy();
+ return 0;
+ }
+
+ return d->setBinding(d->object, d->core, newBinding, flags);
+}
+
+QmlAbstractBinding *
+QmlMetaPropertyPrivate::setBinding(QObject *object, const QmlPropertyCache::Data &core,
+ QmlAbstractBinding *newBinding, QmlMetaProperty::WriteFlags flags)
+{
+ QmlDeclarativeData *data = QmlDeclarativeData::get(object, 0 != newBinding);
+
+ if (data && data->hasBindingBit(core.coreIndex)) {
+ QmlAbstractBinding *binding = data->bindings;
+ while (binding) {
+ // ### This wont work for value types
+ if (binding->propertyIndex() == core.coreIndex) {
+ binding->setEnabled(false);
+
+ if (newBinding)
+ newBinding->setEnabled(true, flags);
+
+ return binding; // ### QmlAbstractBinding;
+ }
+
+ binding = binding->m_nextBinding;
+ }
+ }
+
+ if (newBinding)
+ newBinding->setEnabled(true, flags);
+
+ return 0;
+}
+/*!
+ Returns the expression associated with this signal property, or 0 if no
+ signal expression exists.
+*/
+QmlExpression *QmlMetaProperty::signalExpression() const
+{
+ if (!(type() & SignalProperty))
+ return 0;
+
+ const QObjectList &children = d->object->children();
+
+ for (int ii = 0; ii < children.count(); ++ii) {
+ QObject *child = children.at(ii);
+
+ QmlBoundSignal *signal = QmlBoundSignal::cast(child);
+ if (signal && signal->index() == coreIndex())
+ return signal->expression();
+ }
+
+ return 0;
+}
+
+/*!
+ Set the signal expression associated with this signal property to \a expr.
+ Returns the existing signal expression (if any), otherwise 0.
+
+ Ownership of \a expr transfers to QML. Ownership of the return value is
+ assumed by the caller.
+*/
+QmlExpression *QmlMetaProperty::setSignalExpression(QmlExpression *expr) const
+{
+ if (!(type() & SignalProperty)) {
+ delete expr;
+ return 0;
+ }
+
+ const QObjectList &children = d->object->children();
+
+ for (int ii = 0; ii < children.count(); ++ii) {
+ QObject *child = children.at(ii);
+
+ QmlBoundSignal *signal = QmlBoundSignal::cast(child);
+ if (signal && signal->index() == coreIndex())
+ return signal->setExpression(expr);
+ }
+
+ if (expr) {
+ QmlBoundSignal *signal = new QmlBoundSignal(d->object, method(), d->object);
+ return signal->setExpression(expr);
+ } else {
+ return 0;
+ }
+}
+
+QMetaMethod QmlMetaPropertyPrivate::findSignal(QObject *obj, const QString &name)
+{
+ const QMetaObject *mo = obj->metaObject();
+
+ int methods = mo->methodCount();
+ for (int ii = methods - 1; ii >= 0; --ii) {
+ QMetaMethod method = mo->method(ii);
+ QString methodName = QString::fromUtf8(method.signature());
+ int idx = methodName.indexOf(QLatin1Char('('));
+ methodName = methodName.left(idx);
+
+ if (methodName == name)
+ return method;
+ }
+ return QMetaMethod();
+}
+
+QObject *QmlMetaPropertyPrivate::attachedObject() const
+{
+ if (attachedFunc == -1)
+ return 0;
+ else
+ return qmlAttachedPropertiesObjectById(attachedFunc, object);
+}
+
+/*!
+ Returns the property value.
+*/
+QVariant QmlMetaProperty::read() const
+{
+ if (!d->object)
+ return QVariant();
+
+ if (type() & SignalProperty) {
+
+ return QVariant();
+
+ } else if (type() & Property || type() & Attached) {
+
+ return d->readValueProperty();
+
+ }
+ return QVariant();
+}
+
+QVariant QmlMetaPropertyPrivate::readValueProperty()
+{
+ uint type = q->type();
+ if (type & QmlMetaProperty::Attached) {
+
+ return QVariant::fromValue(attachedObject());
+
+ } else if(type & QmlMetaProperty::ValueTypeProperty) {
+
+ QmlEnginePrivate *ep = context?QmlEnginePrivate::get(context->engine()):0;
+ QmlValueType *valueType = 0;
+ if (ep) valueType = ep->valueTypes[core.propType];
+ else valueType = QmlValueTypeFactory::valueType(core.propType);
+ Q_ASSERT(valueType);
+
+ valueType->read(object, core.coreIndex);
+
+ QVariant rv =
+ valueType->metaObject()->property(this->valueType.valueTypeCoreIdx).read(valueType);
+
+ if (!ep) delete valueType;
+ return rv;
+
+ } else {
+
+ return object->metaObject()->property(core.coreIndex).read(object.data());
+
+ }
+}
+
+//###
+//writeEnumProperty MIRRORS the relelvant bit of QMetaProperty::write AND MUST BE KEPT IN SYNC!
+//###
+bool QmlMetaPropertyPrivate::writeEnumProperty(const QMetaProperty &prop, int idx, QObject *object, const QVariant &value, int flags)
+{
+ if (!object || !prop.isWritable())
+ return false;
+
+ QVariant v = value;
+ if (prop.isEnumType()) {
+ QMetaEnum menum = prop.enumerator();
+ if (v.userType() == QVariant::String
+#ifdef QT3_SUPPORT
+ || v.userType() == QVariant::CString
+#endif
+ ) {
+ if (prop.isFlagType())
+ v = QVariant(menum.keysToValue(value.toByteArray()));
+ else
+ v = QVariant(menum.keyToValue(value.toByteArray()));
+ } else if (v.userType() != QVariant::Int && v.userType() != QVariant::UInt) {
+ int enumMetaTypeId = QMetaType::type(QByteArray(menum.scope()) + "::" + menum.name());
+ if ((enumMetaTypeId == 0) || (v.userType() != enumMetaTypeId) || !v.constData())
+ return false;
+ v = QVariant(*reinterpret_cast<const int *>(v.constData()));
+ }
+ v.convert(QVariant::Int);
+ }
+
+ // the status variable is changed by qt_metacall to indicate what it did
+ // this feature is currently only used by QtDBus and should not be depended
+ // upon. Don't change it without looking into QDBusAbstractInterface first
+ // -1 (unchanged): normal qt_metacall, result stored in argv[0]
+ // changed: result stored directly in value, return the value of status
+ int status = -1;
+ void *argv[] = { v.data(), &v, &status, &flags };
+ QMetaObject::metacall(object, QMetaObject::WriteProperty, idx, argv);
+ return status;
+}
+
+bool QmlMetaPropertyPrivate::writeValueProperty(const QVariant &value,
+ QmlMetaProperty::WriteFlags flags)
+{
+ // Remove any existing bindings on this property
+ if (!(flags & QmlMetaProperty::DontRemoveBinding))
+ delete q->setBinding(0);
+
+ bool rv = false;
+ uint type = q->type();
+ if (type & QmlMetaProperty::ValueTypeProperty) {
+ QmlEnginePrivate *ep =
+ context?static_cast<QmlEnginePrivate *>(QObjectPrivate::get(context->engine())):0;
+
+ QmlValueType *writeBack = 0;
+ if (ep) {
+ writeBack = ep->valueTypes[core.propType];
+ } else {
+ writeBack = QmlValueTypeFactory::valueType(core.propType);
+ }
+
+ writeBack->read(object, core.coreIndex);
+
+ QmlPropertyCache::Data data = core;
+ data.coreIndex = valueType.valueTypeCoreIdx;
+ data.propType = valueType.valueTypePropType;
+ rv = write(writeBack, data, value, context, flags);
+
+ writeBack->write(object, core.coreIndex, flags);
+ if (!ep) delete writeBack;
+
+ } else {
+
+ rv = write(object, core, value, context, flags);
+
+ }
+
+ return rv;
+}
+
+bool QmlMetaPropertyPrivate::write(QObject *object, const QmlPropertyCache::Data &property,
+ const QVariant &value, QmlContext *context,
+ QmlMetaProperty::WriteFlags flags)
+{
+ int coreIdx = property.coreIndex;
+ int status = -1; //for dbus
+
+ if (property.flags & QmlPropertyCache::Data::IsEnumType) {
+ QMetaProperty prop = object->metaObject()->property(property.coreIndex);
+ QVariant v = value;
+ // Enum values come through the script engine as doubles
+ if (value.userType() == QVariant::Double) {
+ double integral;
+ double fractional = modf(value.toDouble(), &integral);
+ if (qFuzzyIsNull(fractional))
+ v.convert(QVariant::Int);
+ }
+ return writeEnumProperty(prop, coreIdx, object, v, flags);
+ }
+
+ int t = property.propType;
+ int vt = value.userType();
+
+ QmlEnginePrivate *enginePriv = 0;
+ if (context && context->engine())
+ enginePriv = QmlEnginePrivate::get(context->engine());
+
+ if (t == QVariant::Url) {
+
+ QUrl u;
+ bool found = false;
+ if (vt == QVariant::Url) {
+ u = value.toUrl();
+ found = true;
+ } else if (vt == QVariant::ByteArray) {
+ u = QUrl(QString::fromUtf8(value.toByteArray()));
+ found = true;
+ } else if (vt == QVariant::String) {
+ u = QUrl(value.toString());
+ found = true;
+ }
+
+ if (!found)
+ return false;
+
+ if (context && u.isRelative() && !u.isEmpty())
+ u = context->resolvedUrl(u);
+ int status = -1;
+ void *argv[] = { &u, 0, &status, &flags };
+ QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx, argv);
+
+ } else if (vt == t) {
+
+ void *a[] = { (void *)value.constData(), 0, &status, &flags };
+ QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx, a);
+
+ } else if (qMetaTypeId<QVariant>() == t) {
+
+ void *a[] = { (void *)&value, 0, &status, &flags };
+ QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx, a);
+
+ } else if (property.flags & QmlPropertyCache::Data::IsQObjectDerived) {
+
+ const QMetaObject *valMo = rawMetaObjectForType(enginePriv, value.userType());
+
+ if (!valMo)
+ return false;
+
+ QObject *o = *(QObject **)value.constData();
+ const QMetaObject *propMo = rawMetaObjectForType(enginePriv, t);
+
+ if (o) valMo = o->metaObject();
+
+ if (canConvert(valMo, propMo)) {
+ void *args[] = { &o, 0, &status, &flags };
+ QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx,
+ args);
+ } else if (!o && canConvert(propMo, valMo)) {
+ // In the case of a null QObject, we assign the null if there is
+ // any change that the null variant type could be up or down cast to
+ // the property type.
+ void *args[] = { &o, 0, &status, &flags };
+ QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx,
+ args);
+ } else {
+ return false;
+ }
+
+ } else if (property.flags & QmlPropertyCache::Data::IsQList) {
+
+ int listType = QmlMetaType::listType(t);
+ QMetaProperty prop = object->metaObject()->property(property.coreIndex);
+
+ if (value.userType() == qMetaTypeId<QList<QObject *> >()) {
+ const QList<QObject *> &list =
+ qvariant_cast<QList<QObject *> >(value);
+ QVariant listVar = prop.read(object);
+ QmlMetaType::clear(listVar);
+ for (int ii = 0; ii < list.count(); ++ii) {
+ QVariant v = QmlMetaType::qmlType(listType)->fromObject(list.at(ii));
+ QmlMetaType::append(listVar, v);
+ }
+
+ } else if (vt == listType ||
+ value.userType() == listType) {
+ QVariant listVar = prop.read(object);
+ QmlMetaType::append(listVar, value);
+ }
+
+ } else if (property.flags & QmlPropertyCache::Data::IsQmlList) {
+
+ // XXX - optimize!
+ QMetaProperty prop = object->metaObject()->property(property.coreIndex);
+ QVariant list = prop.read(object);
+ QmlPrivate::ListInterface *li =
+ *(QmlPrivate::ListInterface **)list.constData();
+
+ int type = li->type();
+
+ if (QObject *obj = QmlMetaType::toQObject(value)) {
+ const QMetaObject *mo = rawMetaObjectForType(enginePriv, type);
+
+ const QMetaObject *objMo = obj->metaObject();
+ bool found = false;
+ while(!found && objMo) {
+ if (equal(objMo, mo))
+ found = true;
+ else
+ objMo = objMo->superClass();
+ }
+
+ if (!found)
+ return false;
+
+ // NOTE: This assumes a cast to QObject does not alter
+ // the object pointer
+ void *d = (void *)&obj;
+ li->append(d);
+ }
+ } else {
+ Q_ASSERT(vt != t);
+
+ QVariant v = value;
+ if (v.convert((QVariant::Type)t)) {
+ void *a[] = { (void *)v.constData(), 0, &status, &flags};
+ QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx, a);
+ } else if ((uint)t >= QVariant::UserType && vt == QVariant::String) {
+ QmlMetaType::StringConverter con = QmlMetaType::customStringConverter(t);
+ if (!con)
+ return false;
+
+ QVariant v = con(value.toString());
+ if (v.userType() == t) {
+ void *a[] = { (void *)v.constData(), 0, &status, &flags};
+ QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx, a);
+ }
+ } else if (vt == QVariant::String) {
+ bool ok = false;
+ QVariant v = QmlStringConverters::variantFromString(value.toString(), t, &ok);
+ if (!ok)
+ return false;
+
+ void *a[] = { (void *)v.constData(), 0, &status, &flags};
+ QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx, a);
+ } else {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+const QMetaObject *QmlMetaPropertyPrivate::rawMetaObjectForType(QmlEnginePrivate *engine, int userType)
+{
+ if (engine) {
+ return engine->rawMetaObjectForType(userType);
+ } else {
+ QmlType *type = QmlMetaType::qmlType(userType);
+ return type?type->baseMetaObject():0;
+ }
+}
+
+/*!
+ Set the property value to \a value.
+*/
+bool QmlMetaProperty::write(const QVariant &value) const
+{
+ return write(value, 0);
+}
+
+/*!
+ Resets the property value.
+*/
+bool QmlMetaProperty::reset() const
+{
+ if (isResettable()) {
+ void *args[] = { 0 };
+ QMetaObject::metacall(d->object, QMetaObject::ResetProperty, d->core.coreIndex, args);
+ return true;
+ } else {
+ return false;
+ }
+}
+
+bool QmlMetaProperty::write(const QVariant &value, QmlMetaProperty::WriteFlags flags) const
+{
+ if (d->object && type() & Property && d->core.isValid() && isWritable())
+ return d->writeValueProperty(value, flags);
+ else
+ return false;
+}
+
+/*!
+ Returns true if the property has a change notifier signal, otherwise false.
+*/
+bool QmlMetaProperty::hasChangedNotifier() const
+{
+ if (type() & Property && !(type() & Attached) && d->object) {
+ return d->object->metaObject()->property(d->core.coreIndex).hasNotifySignal();
+ }
+ return false;
+}
+
+/*!
+ Returns true if the property needs a change notifier signal for bindings
+ to remain upto date, false otherwise.
+
+ Some properties, such as attached properties or those whose value never
+ changes, do not require a change notifier.
+*/
+bool QmlMetaProperty::needsChangedNotifier() const
+{
+ return type() & Property && !(type() & Attached) &&
+ !property().isConstant();
+}
+
+/*!
+ Connects the property's change notifier signal to the
+ specified \a method of the \a dest object and returns
+ true. Returns false if this metaproperty does not
+ represent a regular Qt property or if it has no
+ change notifier signal, or if the \a dest object does
+ not have the specified \a method.
+*/
+bool QmlMetaProperty::connectNotifier(QObject *dest, int method) const
+{
+ if (!(type() & Property) || (type() & Attached) || !d->object)
+ return false;
+
+ QMetaProperty prop = d->object->metaObject()->property(d->core.coreIndex);
+ if (prop.hasNotifySignal()) {
+ return QMetaObject::connect(d->object, prop.notifySignalIndex(), dest, method, Qt::DirectConnection);
+ } else {
+ return false;
+ }
+}
+
+/*!
+ Connects the property's change notifier signal to the
+ specified \a slot of the \a dest object and returns
+ true. Returns false if this metaproperty does not
+ represent a regular Qt property or if it has no
+ change notifier signal, or if the \a dest object does
+ not have the specified \a slot.
+*/
+bool QmlMetaProperty::connectNotifier(QObject *dest, const char *slot) const
+{
+ if (!(type() & Property) || (type() & Attached) || !d->object)
+ return false;
+
+ QMetaProperty prop = d->object->metaObject()->property(d->core.coreIndex);
+ if (prop.hasNotifySignal()) {
+ QByteArray signal(QByteArray("2") + prop.notifySignal().signature());
+ return QObject::connect(d->object, signal.constData(), dest, slot);
+ } else {
+ return false;
+ }
+}
+
+/*!
+ Return the Qt metaobject index of the property.
+*/
+int QmlMetaProperty::coreIndex() const
+{
+ return d->core.coreIndex;
+}
+
+/*! \internal */
+int QmlMetaProperty::valueTypeCoreIndex() const
+{
+ return d->valueType.valueTypeCoreIdx;
+}
+
+Q_GLOBAL_STATIC(QmlValueTypeFactory, qmlValueTypes);
+
+
+struct SerializedData {
+ QmlMetaProperty::Type type;
+ QmlPropertyCache::Data core;
+};
+
+struct ValueTypeSerializedData : public SerializedData {
+ QmlPropertyCache::ValueTypeData valueType;
+};
+
+QByteArray QmlMetaPropertyPrivate::saveValueType(const QMetaObject *metaObject, int index,
+ int subIndex, int subType)
+{
+ ValueTypeSerializedData sd;
+ sd.type = QmlMetaProperty::ValueTypeProperty;
+ sd.core.load(metaObject->property(index));
+ sd.valueType.valueTypeCoreIdx = subIndex;
+ sd.valueType.valueTypePropType = subType;
+
+ QByteArray rv((const char *)&sd, sizeof(sd));
+ return rv;
+}
+
+QByteArray QmlMetaPropertyPrivate::saveProperty(const QMetaObject *metaObject, int index)
+{
+ SerializedData sd;
+ sd.type = QmlMetaProperty::Property;
+ sd.core.load(metaObject->property(index));
+
+ QByteArray rv((const char *)&sd, sizeof(sd));
+ return rv;
+}
+
+QmlMetaProperty
+QmlMetaPropertyPrivate::restore(const QByteArray &data, QObject *object, QmlContext *ctxt)
+{
+ QmlMetaProperty prop;
+
+ if (data.isEmpty())
+ return prop;
+
+ prop.d->object = object;
+ prop.d->context = ctxt;
+
+ const SerializedData *sd = (const SerializedData *)data.constData();
+ if (sd->type == QmlMetaProperty::Property) {
+ prop.d->core = sd->core;
+ } else if(sd->type == QmlMetaProperty::ValueTypeProperty) {
+ const ValueTypeSerializedData *vt = (const ValueTypeSerializedData *)sd;
+ prop.d->core = vt->core;
+ prop.d->valueType = vt->valueType;
+ }
+
+ return prop;
+}
+
+/*!
+ \internal
+
+ Creates a QmlMetaProperty for the property \a name of \a obj. Unlike
+ the QmlMetaProperty(QObject*, QString, QmlContext*) constructor, this static function
+ will correctly handle dot properties, including value types and attached properties.
+*/
+QmlMetaProperty QmlMetaProperty::createProperty(QObject *obj,
+ const QString &name,
+ QmlContext *context)
+{
+ QmlTypeNameCache *typeNameCache = context?QmlContextPrivate::get(context)->imports:0;
+
+ QStringList path = name.split(QLatin1Char('.'));
+ QObject *object = obj;
+
+ for (int jj = 0; jj < path.count() - 1; ++jj) {
+ const QString &pathName = path.at(jj);
+
+ if (QmlTypeNameCache::Data *data = typeNameCache?typeNameCache->data(pathName):0) {
+ if (data->type) {
+ QmlAttachedPropertiesFunc func = data->type->attachedPropertiesFunction();
+ if (!func)
+ return QmlMetaProperty();
+ object = qmlAttachedPropertiesObjectById(data->type->index(), object);
+ if (!object)
+ return QmlMetaProperty();
+ continue;
+ } else {
+ Q_ASSERT(data->typeNamespace);
+ ++jj;
+ data = data->typeNamespace->data(path.at(jj));
+ if (!data || !data->type)
+ return QmlMetaProperty();
+ QmlAttachedPropertiesFunc func = data->type->attachedPropertiesFunction();
+ if (!func)
+ return QmlMetaProperty();
+ object = qmlAttachedPropertiesObjectById(data->type->index(), object);
+ if (!object)
+ return QmlMetaProperty();
+ continue;
+ }
+ }
+
+ QmlMetaProperty prop(object, pathName, context);
+
+ if (jj == path.count() - 2 && prop.propertyType() < (int)QVariant::UserType &&
+ qmlValueTypes()->valueTypes[prop.propertyType()]) {
+ // We're now at a value type property. We can use a global valuetypes array as we
+ // never actually use the objects, just look up their properties.
+ QObject *typeObject =
+ qmlValueTypes()->valueTypes[prop.propertyType()];
+ int idx = typeObject->metaObject()->indexOfProperty(path.last().toUtf8().constData());
+ if (idx == -1)
+ return QmlMetaProperty();
+ QMetaProperty vtProp = typeObject->metaObject()->property(idx);
+
+ QmlMetaProperty p = prop;
+ p.d->valueType.valueTypeCoreIdx = idx;
+ p.d->valueType.valueTypePropType = vtProp.userType();
+ return p;
+ }
+
+ QObject *objVal = QmlMetaType::toQObject(prop.read());
+ if (!objVal)
+ return QmlMetaProperty();
+ object = objVal;
+ }
+
+ const QString &propName = path.last();
+ QmlMetaProperty prop(object, propName, context);
+ if (!prop.isValid())
+ return QmlMetaProperty();
+ else
+ return prop;
+}
+
+/*!
+ Returns true if lhs and rhs refer to the same metaobject data
+*/
+bool QmlMetaPropertyPrivate::equal(const QMetaObject *lhs, const QMetaObject *rhs)
+{
+ return lhs == rhs || (1 && lhs && rhs && lhs->d.stringdata == rhs->d.stringdata);
+}
+
+/*!
+ Returns true if from inherits to.
+*/
+bool QmlMetaPropertyPrivate::canConvert(const QMetaObject *from, const QMetaObject *to)
+{
+ if (from && to == &QObject::staticMetaObject)
+ return true;
+
+ while (from) {
+ if (equal(from, to))
+ return true;
+ from = from->superClass();
+ }
+
+ return false;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlmetaproperty.h b/src/declarative/qml/qmlmetaproperty.h
new file mode 100644
index 0000000..240f5a2
--- /dev/null
+++ b/src/declarative/qml/qmlmetaproperty.h
@@ -0,0 +1,148 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLMETAPROPERTY_H
+#define QMLMETAPROPERTY_H
+
+#include <QtCore/qmetaobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QObject;
+class QmlAbstractBinding;
+class QmlExpression;
+class QStringList;
+class QVariant;
+struct QMetaObject;
+class QmlContext;
+class QmlEngine;
+
+class QmlMetaPropertyPrivate;
+class Q_DECLARATIVE_EXPORT QmlMetaProperty
+{
+public:
+ enum PropertyCategory {
+ Unknown,
+ InvalidProperty,
+ Bindable,
+ List,
+ QmlList, //XXX
+ Object,
+ Normal
+ };
+ QmlMetaProperty();
+ QmlMetaProperty(QObject *);
+ QmlMetaProperty(QObject *, const QString &);
+ QmlMetaProperty(QObject *, QmlContext *);
+ QmlMetaProperty(QObject *, const QString &, QmlContext *);
+ QmlMetaProperty(const QmlMetaProperty &);
+ QmlMetaProperty &operator=(const QmlMetaProperty &);
+ ~QmlMetaProperty();
+
+ QString name() const;
+
+ QVariant read() const;
+ bool write(const QVariant &) const;
+ enum WriteFlag { BypassInterceptor = 0x01, DontRemoveBinding = 0x02 };
+ Q_DECLARE_FLAGS(WriteFlags, WriteFlag)
+ bool write(const QVariant &, QmlMetaProperty::WriteFlags) const;
+ bool reset() const;
+
+ bool hasChangedNotifier() const;
+ bool needsChangedNotifier() const;
+ bool connectNotifier(QObject *dest, const char *slot) const;
+ bool connectNotifier(QObject *dest, int method) const;
+
+ QMetaMethod method() const;
+
+ enum Type { Invalid = 0x00,
+ Property = 0x01,
+ SignalProperty = 0x02,
+ Default = 0x08,
+ Attached = 0x10,
+ ValueTypeProperty = 0x20 };
+
+ Type type() const;
+ bool isProperty() const;
+ bool isDefault() const;
+ bool isWritable() const;
+ bool isDesignable() const;
+ bool isResettable() const;
+ bool isValid() const;
+ QObject *object() const;
+
+ PropertyCategory propertyCategory() const;
+
+ int propertyType() const;
+ const char *propertyTypeName() const;
+
+ bool operator==(const QmlMetaProperty &) const;
+
+ QMetaProperty property() const;
+
+ QmlAbstractBinding *binding() const;
+ QmlAbstractBinding *setBinding(QmlAbstractBinding *,
+ QmlMetaProperty::WriteFlags flags = QmlMetaProperty::DontRemoveBinding) const;
+
+ QmlExpression *signalExpression() const;
+ QmlExpression *setSignalExpression(QmlExpression *) const;
+
+ static QmlMetaProperty createProperty(QObject *, const QString &, QmlContext *context=0);
+
+ int coreIndex() const;
+ int valueTypeCoreIndex() const;
+private:
+ friend class QmlEnginePrivate;
+ friend class QmlMetaPropertyPrivate;
+ QmlMetaPropertyPrivate *d;
+};
+typedef QList<QmlMetaProperty> QmlMetaProperties;
+ Q_DECLARE_OPERATORS_FOR_FLAGS(QmlMetaProperty::WriteFlags)
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLMETAPROPERTY_H
diff --git a/src/declarative/qml/qmlmetaproperty_p.h b/src/declarative/qml/qmlmetaproperty_p.h
new file mode 100644
index 0000000..90b443e
--- /dev/null
+++ b/src/declarative/qml/qmlmetaproperty_p.h
@@ -0,0 +1,124 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLMETAPROPERTY_P_H
+#define QMLMETAPROPERTY_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 "qmlmetaproperty.h"
+
+#include "qmlpropertycache_p.h"
+#include "qmlguard_p.h"
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlContext;
+class QmlEnginePrivate;
+class QmlMetaPropertyPrivate
+{
+public:
+ QmlMetaPropertyPrivate()
+ : q(0), context(0), object(0), isDefaultProperty(false), isNameCached(false),
+ attachedFunc(-1) {}
+
+ QmlMetaPropertyPrivate(const QmlMetaPropertyPrivate &other)
+ : q(0), context(other.context), object(other.object),
+ isDefaultProperty(other.isDefaultProperty), isNameCached(other.isNameCached),
+ core(other.core), nameCache(other.nameCache),
+ valueType(other.valueType), attachedFunc(other.attachedFunc) {}
+
+ QmlMetaProperty *q;
+ QmlContext *context;
+ QmlGuard<QObject> object;
+
+ bool isDefaultProperty:1;
+ bool isNameCached:1;
+ QmlPropertyCache::Data core;
+ QString nameCache;
+
+ // Describes the "virtual" value-type sub-property.
+ QmlPropertyCache::ValueTypeData valueType;
+
+ // The attached property accessor
+ int attachedFunc;
+
+ void initProperty(QObject *obj, const QString &name);
+ void initDefault(QObject *obj);
+
+ QObject *attachedObject() const;
+ QMetaMethod findSignal(QObject *, const QString &);
+
+ int propertyType() const;
+ QmlMetaProperty::PropertyCategory propertyCategory() const;
+
+ QVariant readValueProperty();
+ bool writeValueProperty(const QVariant &, QmlMetaProperty::WriteFlags);
+
+ static const QMetaObject *rawMetaObjectForType(QmlEnginePrivate *, int);
+ static bool writeEnumProperty(const QMetaProperty &prop, int idx, QObject *object, const QVariant &value, int flags);
+ static bool write(QObject *, const QmlPropertyCache::Data &, const QVariant &, QmlContext *,
+ QmlMetaProperty::WriteFlags flags = 0);
+ static QmlAbstractBinding *setBinding(QObject *, const QmlPropertyCache::Data &, QmlAbstractBinding *,
+ QmlMetaProperty::WriteFlags flags = QmlMetaProperty::DontRemoveBinding);
+
+ static QByteArray saveValueType(const QMetaObject *, int, int, int);
+ static QByteArray saveProperty(const QMetaObject *, int);
+ static QmlMetaProperty restore(const QByteArray &, QObject *, QmlContext * = 0);
+
+ static bool equal(const QMetaObject *, const QMetaObject *);
+ static bool canConvert(const QMetaObject *from, const QMetaObject *to);
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLMETAPROPERTY_P_H
diff --git a/src/declarative/qml/qmlmetatype.cpp b/src/declarative/qml/qmlmetatype.cpp
new file mode 100644
index 0000000..e66f600
--- /dev/null
+++ b/src/declarative/qml/qmlmetatype.cpp
@@ -0,0 +1,1301 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlmetatype.h"
+
+#include "qmlproxymetaobject_p.h"
+#include "qmlcustomparser_p.h"
+#include "qmlguard_p.h"
+
+#include <QtCore/qdebug.h>
+#include <QtCore/qstringlist.h>
+#include <QtCore/qmetaobject.h>
+#include <QtCore/qbitarray.h>
+#include <QtCore/qreadwritelock.h>
+#include <qmetatype.h>
+#include <qobjectdefs.h>
+#include <qdatetime.h>
+#include <qbytearray.h>
+#include <qreadwritelock.h>
+#include <qstring.h>
+#include <qstringlist.h>
+#include <qvector.h>
+#include <qlocale.h>
+#include <QtCore/qcryptographichash.h>
+#include <QtScript/qscriptvalue.h>
+
+#include <ctype.h>
+
+#ifdef QT_BOOTSTRAPPED
+# ifndef QT_NO_GEOM_VARIANT
+# define QT_NO_GEOM_VARIANT
+# endif
+#else
+# include <qbitarray.h>
+# include <qurl.h>
+# include <qvariant.h>
+#endif
+
+#ifndef QT_NO_GEOM_VARIANT
+# include <qsize.h>
+# include <qpoint.h>
+# include <qrect.h>
+# include <qline.h>
+# include <qvector3d.h>
+#endif
+#define NS(x) QT_PREPEND_NAMESPACE(x)
+
+QT_BEGIN_NAMESPACE
+
+struct QmlMetaTypeData
+{
+ ~QmlMetaTypeData();
+ QList<QmlType *> types;
+ typedef QHash<int, QmlType *> Ids;
+ Ids idToType;
+ typedef QHash<QByteArray, QmlType *> Names;
+ Names nameToType;
+ typedef QHash<const QMetaObject *, QmlType *> MetaObjects;
+ MetaObjects metaObjectToType;
+ typedef QHash<int, QmlMetaType::StringConverter> StringConverters;
+ StringConverters stringConverters;
+
+ QBitArray objects;
+ QBitArray interfaces;
+ QBitArray qmllists;
+ QBitArray lists;
+};
+Q_GLOBAL_STATIC(QmlMetaTypeData, metaTypeData)
+Q_GLOBAL_STATIC(QReadWriteLock, metaTypeDataLock)
+
+QmlMetaTypeData::~QmlMetaTypeData()
+{
+ for (int i = 0; i < types.count(); ++i)
+ delete types.at(i);
+}
+
+class QmlTypePrivate
+{
+public:
+ QmlTypePrivate();
+
+ void init() const;
+
+ bool m_isInterface : 1;
+ const char *m_iid;
+ QByteArray m_name;
+ int m_version_maj;
+ int m_version_min;
+ int m_typeId; int m_listId; int m_qmlListId;
+ QmlPrivate::Func m_opFunc;
+ const QMetaObject *m_baseMetaObject;
+ QmlAttachedPropertiesFunc m_attachedPropertiesFunc;
+ const QMetaObject *m_attachedPropertiesType;
+ int m_parserStatusCast;
+ int m_propertyValueSourceCast;
+ int m_propertyValueInterceptorCast;
+ QmlPrivate::CreateFunc m_extFunc;
+ const QMetaObject *m_extMetaObject;
+ int m_index;
+ QmlCustomParser *m_customParser;
+ mutable volatile bool m_isSetup:1;
+ mutable QList<QmlProxyMetaObject::ProxyData> m_metaObjects;
+};
+
+QmlTypePrivate::QmlTypePrivate()
+: m_isInterface(false), m_iid(0), m_typeId(0), m_listId(0), m_qmlListId(0),
+ m_opFunc(0), m_baseMetaObject(0), m_attachedPropertiesFunc(0), m_attachedPropertiesType(0),
+ m_parserStatusCast(-1), m_propertyValueSourceCast(-1), m_propertyValueInterceptorCast(-1),
+ m_extFunc(0), m_extMetaObject(0), m_index(-1), m_customParser(0), m_isSetup(false)
+{
+}
+
+
+QmlType::QmlType(int type, int listType, int qmlListType,
+ QmlPrivate::Func opFunc, const char *iid, int index)
+: d(new QmlTypePrivate)
+{
+ d->m_isInterface = true;
+ d->m_iid = iid;
+ d->m_typeId = type;
+ d->m_listId = listType;
+ d->m_qmlListId = qmlListType;
+ d->m_opFunc = opFunc;
+ d->m_index = index;
+ d->m_isSetup = true;
+ d->m_version_maj = 0;
+ d->m_version_min = 0;
+}
+
+QmlType::QmlType(int type, int listType, int qmlListType,
+ QmlPrivate::Func opFunc, const char *qmlName,
+ int version_maj, int version_min,
+ const QMetaObject *metaObject,
+ QmlAttachedPropertiesFunc attachedPropertiesFunc,
+ const QMetaObject *attachedType,
+ int parserStatusCast, int propertyValueSourceCast, int propertyValueInterceptorCast,
+ QmlPrivate::CreateFunc extFunc,
+ const QMetaObject *extMetaObject, int index,
+ QmlCustomParser *customParser)
+: d(new QmlTypePrivate)
+{
+ d->m_name = qmlName;
+ d->m_version_maj = version_maj;
+ d->m_version_min = version_min;
+ d->m_typeId = type;
+ d->m_listId = listType;
+ d->m_qmlListId = qmlListType;
+ d->m_opFunc = opFunc;
+ d->m_baseMetaObject = metaObject;
+ d->m_attachedPropertiesFunc = attachedPropertiesFunc;
+ d->m_attachedPropertiesType = attachedType;
+ d->m_parserStatusCast = parserStatusCast;
+ d->m_propertyValueSourceCast = propertyValueSourceCast;
+ d->m_propertyValueInterceptorCast = propertyValueInterceptorCast;
+ d->m_extFunc = extFunc;
+ d->m_index = index;
+ d->m_customParser = customParser;
+
+ if (extMetaObject)
+ d->m_extMetaObject = extMetaObject;
+}
+
+QmlType::~QmlType()
+{
+ delete d->m_customParser;
+ delete d;
+}
+
+int QmlType::majorVersion() const
+{
+ return d->m_version_maj;
+}
+
+int QmlType::minorVersion() const
+{
+ return d->m_version_min;
+}
+
+bool QmlType::availableInVersion(int vmajor, int vminor) const
+{
+ return vmajor > d->m_version_maj || (vmajor == d->m_version_maj && vminor >= d->m_version_min);
+}
+
+void QmlTypePrivate::init() const
+{
+ if (m_isSetup) return;
+
+ QWriteLocker lock(metaTypeDataLock());
+ if (m_isSetup)
+ return;
+
+ // Setup extended meta object
+ // XXX - very inefficient
+ const QMetaObject *mo = m_baseMetaObject;
+ if (m_extFunc) {
+ QMetaObject *mmo = new QMetaObject;
+ *mmo = *m_extMetaObject;
+ mmo->d.superdata = mo;
+ QmlProxyMetaObject::ProxyData data = { mmo, m_extFunc, 0, 0 };
+ m_metaObjects << data;
+ }
+
+ mo = mo->d.superdata;
+ while(mo) {
+ QmlType *t = metaTypeData()->metaObjectToType.value(mo);
+ if (t) {
+ if (t->d->m_extFunc) {
+ QMetaObject *mmo = new QMetaObject;
+ *mmo = *t->d->m_extMetaObject;
+ mmo->d.superdata = m_baseMetaObject;
+ if (!m_metaObjects.isEmpty())
+ m_metaObjects.last().metaObject->d.superdata = mmo;
+ QmlProxyMetaObject::ProxyData data = { mmo, t->d->m_extFunc, 0, 0 };
+ m_metaObjects << data;
+ }
+ }
+ mo = mo->d.superdata;
+ }
+
+ for (int ii = 0; ii < m_metaObjects.count(); ++ii) {
+ m_metaObjects[ii].propertyOffset =
+ m_metaObjects.at(ii).metaObject->propertyOffset();
+ m_metaObjects[ii].methodOffset =
+ m_metaObjects.at(ii).metaObject->methodOffset();
+ }
+
+ m_isSetup = true;
+ lock.unlock();
+}
+
+QByteArray QmlType::typeName() const
+{
+ if (d->m_baseMetaObject)
+ return d->m_baseMetaObject->className();
+ else
+ return QByteArray();
+}
+
+QByteArray QmlType::qmlTypeName() const
+{
+ return d->m_name;
+}
+
+QObject *QmlType::create() const
+{
+ d->init();
+
+ QVariant v;
+ QObject *rv = 0;
+ d->m_opFunc(QmlPrivate::Create, 0, v, v, (void **)&rv);
+
+ if (rv && !d->m_metaObjects.isEmpty())
+ (void *)new QmlProxyMetaObject(rv, &d->m_metaObjects);
+
+ return rv;
+}
+
+QmlCustomParser *QmlType::customParser() const
+{
+ return d->m_customParser;
+}
+
+bool QmlType::isInterface() const
+{
+ return d->m_isInterface;
+}
+
+int QmlType::typeId() const
+{
+ return d->m_typeId;
+}
+
+int QmlType::qListTypeId() const
+{
+ return d->m_listId;
+}
+
+int QmlType::qmlListTypeId() const
+{
+ return d->m_qmlListId;
+}
+
+void QmlType::listClear(const QVariant &list)
+{
+ Q_ASSERT(list.userType() == qListTypeId());
+ QVariant arg;
+ d->m_opFunc(QmlPrivate::Clear, 0, list, arg, 0);
+}
+
+void QmlType::listAppend(const QVariant &list, const QVariant &item)
+{
+ Q_ASSERT(list.userType() == qListTypeId());
+ d->m_opFunc(QmlPrivate::Append, 0, list, item, 0);
+}
+
+QVariant QmlType::listAt(const QVariant &list, int idx)
+{
+ Q_ASSERT(list.userType() == qListTypeId());
+ QVariant rv;
+ void *ptr = (void *)&rv;
+ d->m_opFunc(QmlPrivate::Value, idx, list, QVariant(), &ptr);
+ return rv;
+}
+
+int QmlType::listCount(const QVariant &list)
+{
+ Q_ASSERT(list.userType() == qListTypeId());
+ return d->m_opFunc(QmlPrivate::Length, 0, list, QVariant(), 0);
+}
+
+const QMetaObject *QmlType::metaObject() const
+{
+ d->init();
+
+ if (d->m_metaObjects.isEmpty())
+ return d->m_baseMetaObject;
+ else
+ return d->m_metaObjects.first().metaObject;
+
+}
+
+const QMetaObject *QmlType::baseMetaObject() const
+{
+ return d->m_baseMetaObject;
+}
+
+QmlAttachedPropertiesFunc QmlType::attachedPropertiesFunction() const
+{
+ return d->m_attachedPropertiesFunc;
+}
+
+const QMetaObject *QmlType::attachedPropertiesType() const
+{
+ return d->m_attachedPropertiesType;
+}
+
+int QmlType::parserStatusCast() const
+{
+ return d->m_parserStatusCast;
+}
+
+int QmlType::propertyValueSourceCast() const
+{
+ return d->m_propertyValueSourceCast;
+}
+
+int QmlType::propertyValueInterceptorCast() const
+{
+ return d->m_propertyValueInterceptorCast;
+}
+
+QVariant QmlType::fromObject(QObject *obj) const
+{
+ QVariant rv;
+ QVariant *v_ptr = &rv;
+ QVariant vobj = QVariant::fromValue(obj);
+ d->m_opFunc(QmlPrivate::FromObject, 0, QVariant(), vobj, (void **)&v_ptr);
+ return rv;
+}
+
+const char *QmlType::interfaceIId() const
+{
+ return d->m_iid;
+}
+
+int QmlType::index() const
+{
+ return d->m_index;
+}
+
+int QmlMetaType::registerInterface(const QmlPrivate::MetaTypeIds &id,
+ QmlPrivate::Func listFunction,
+ const char *iid)
+{
+ QWriteLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+
+ int index = data->types.count();
+
+ QmlType *type = new QmlType(id.typeId, id.listId, id.qmlListId,
+ listFunction, iid, index);
+
+ data->types.append(type);
+ data->idToType.insert(type->typeId(), type);
+ data->idToType.insert(type->qListTypeId(), type);
+ data->idToType.insert(type->qmlListTypeId(), type);
+ // XXX No insertMulti, so no multi-version interfaces?
+ if (!type->qmlTypeName().isEmpty())
+ data->nameToType.insert(type->qmlTypeName(), type);
+
+ if (data->interfaces.size() < id.typeId)
+ data->interfaces.resize(id.typeId + 16);
+ if (data->qmllists.size() < id.qmlListId)
+ data->qmllists.resize(id.qmlListId + 16);
+ if (data->lists.size() < id.listId)
+ data->lists.resize(id.listId + 16);
+ data->interfaces.setBit(id.typeId, true);
+ data->qmllists.setBit(id.qmlListId, true);
+ data->lists.setBit(id.listId, true);
+
+ return index;
+}
+
+int QmlMetaType::registerType(const QmlPrivate::MetaTypeIds &id, QmlPrivate::Func func,
+ const char *uri, int version_maj, int version_min, const char *cname,
+ const QMetaObject *mo, QmlAttachedPropertiesFunc attach, const QMetaObject *attachMo,
+ int pStatus, int object, int valueSource, int valueInterceptor, QmlPrivate::CreateFunc extFunc, const QMetaObject *extmo, QmlCustomParser *parser)
+{
+ Q_UNUSED(object);
+
+ if (cname) {
+ for (int ii = 0; cname[ii]; ++ii) {
+ if (!isalnum(cname[ii])) {
+ qWarning("QmlMetaType: Invalid QML name %s", cname);
+ return -1;
+ }
+ }
+ }
+
+ QWriteLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ int index = data->types.count();
+
+ QByteArray name = uri;
+ if (uri)
+ name += '/';
+ name += cname;
+
+ QmlType *type = new QmlType(id.typeId, id.listId, id.qmlListId,
+ func, name, version_maj, version_min, mo, attach, attachMo, pStatus,
+ valueSource, valueInterceptor, extFunc, extmo, index, parser);
+
+ data->types.append(type);
+ data->idToType.insert(type->typeId(), type);
+ data->idToType.insert(type->qListTypeId(), type);
+ data->idToType.insert(type->qmlListTypeId(), type);
+
+ if (!type->qmlTypeName().isEmpty())
+ data->nameToType.insertMulti(type->qmlTypeName(), type);
+
+ data->metaObjectToType.insert(type->baseMetaObject(), type);
+
+ if (data->objects.size() <= id.typeId)
+ data->objects.resize(id.typeId + 16);
+ if (data->qmllists.size() <= id.qmlListId)
+ data->qmllists.resize(id.qmlListId + 16);
+ if (data->lists.size() <= id.listId)
+ data->lists.resize(id.listId + 16);
+ data->objects.setBit(id.typeId, true);
+ data->qmllists.setBit(id.qmlListId, true);
+ data->lists.setBit(id.listId, true);
+
+ return index;
+}
+
+QObject *QmlMetaType::toQObject(const QVariant &v, bool *ok)
+{
+ if (!isQObject(v.userType())) {
+ if (ok) *ok = false;
+ return 0;
+ }
+
+ if (ok) *ok = true;
+
+ return *(QObject **)v.constData();
+}
+
+bool QmlMetaType::isQObject(int userType)
+{
+ if (userType == QMetaType::QObjectStar)
+ return true;
+
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ return userType >= 0 && userType < data->objects.size() && data->objects.testBit(userType);
+}
+
+/*
+ Returns the item type for a list of type \a id.
+ */
+int QmlMetaType::listType(int id)
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ QmlType *type = data->idToType.value(id);
+ if (type && type->qListTypeId() == id)
+ return type->typeId();
+ else
+ return 0;
+}
+
+/*
+ Returns the item type for a qml list of type \a id.
+ */
+int QmlMetaType::qmlListType(int id)
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ QmlType *type = data->idToType.value(id);
+ if (type && type->qmlListTypeId() == id)
+ return type->typeId();
+ else
+ return 0;
+}
+
+bool QmlMetaType::clear(const QVariant &list)
+{
+ int userType = list.userType();
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ QmlType *type = data->idToType.value(userType);
+ lock.unlock();
+ if (type && type->qListTypeId() == userType) {
+ type->listClear(list);
+ return true;
+ } else {
+ return false;
+ }
+}
+
+bool QmlMetaType::append(const QVariant &list, const QVariant &item)
+{
+ int userType = list.userType();
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ QmlType *type = data->idToType.value(userType);
+ lock.unlock();
+ if (type && type->qListTypeId() == userType &&
+ item.userType() == type->typeId()) {
+ type->listAppend(list, item);
+ return true;
+ } else {
+ return false;
+ }
+}
+
+int QmlMetaType::attachedPropertiesFuncId(const QMetaObject *mo)
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+
+ QmlType *type = data->metaObjectToType.value(mo);
+ if (type && type->attachedPropertiesFunction())
+ return type->index();
+ else
+ return -1;
+}
+
+QmlAttachedPropertiesFunc QmlMetaType::attachedPropertiesFuncById(int id)
+{
+ if (id < 0)
+ return 0;
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ return data->types.at(id)->attachedPropertiesFunction();
+}
+
+QMetaProperty QmlMetaType::defaultProperty(const QMetaObject *metaObject)
+{
+ int idx = metaObject->indexOfClassInfo("DefaultProperty");
+ if (-1 == idx)
+ return QMetaProperty();
+
+ QMetaClassInfo info = metaObject->classInfo(idx);
+ if (!info.value())
+ return QMetaProperty();
+
+ idx = metaObject->indexOfProperty(info.value());
+ if (-1 == idx)
+ return QMetaProperty();
+
+ return metaObject->property(idx);
+}
+
+QMetaProperty QmlMetaType::defaultProperty(QObject *obj)
+{
+ if (!obj)
+ return QMetaProperty();
+
+ const QMetaObject *metaObject = obj->metaObject();
+ return defaultProperty(metaObject);
+}
+
+QMetaMethod QmlMetaType::defaultMethod(const QMetaObject *metaObject)
+{
+ int idx = metaObject->indexOfClassInfo("DefaultMethod");
+ if (-1 == idx)
+ return QMetaMethod();
+
+ QMetaClassInfo info = metaObject->classInfo(idx);
+ if (!info.value())
+ return QMetaMethod();
+
+ idx = metaObject->indexOfMethod(info.value());
+ if (-1 == idx)
+ return QMetaMethod();
+
+ return metaObject->method(idx);
+}
+
+QMetaMethod QmlMetaType::defaultMethod(QObject *obj)
+{
+ if (!obj)
+ return QMetaMethod();
+
+ const QMetaObject *metaObject = obj->metaObject();
+ return defaultMethod(metaObject);
+}
+
+QmlMetaType::TypeCategory QmlMetaType::typeCategory(int userType)
+{
+ if (userType < 0)
+ return Unknown;
+ if (userType == QMetaType::QObjectStar)
+ return Object;
+
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ if (userType < data->objects.size() && data->objects.testBit(userType))
+ return Object;
+ else if (userType < data->qmllists.size() && data->qmllists.testBit(userType))
+ return QmlList;
+ else if (userType < data->lists.size() && data->lists.testBit(userType))
+ return List;
+ else
+ return Unknown;
+}
+
+bool QmlMetaType::isInterface(int userType)
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ return userType >= 0 && userType < data->interfaces.size() && data->interfaces.testBit(userType);
+}
+
+const char *QmlMetaType::interfaceIId(int userType)
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ QmlType *type = data->idToType.value(userType);
+ lock.unlock();
+ if (type && type->isInterface() && type->typeId() == userType)
+ return type->interfaceIId();
+ else
+ return 0;
+}
+
+bool QmlMetaType::isQmlList(int userType)
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ return userType >= 0 && userType < data->qmllists.size() && data->qmllists.testBit(userType);
+}
+
+bool QmlMetaType::isList(int userType)
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ return userType >= 0 && userType < data->lists.size() && data->lists.testBit(userType);
+}
+
+bool QmlMetaType::isList(const QVariant &v)
+{
+ return (v.type() == QVariant::UserType && isList(v.userType()));
+}
+
+int QmlMetaType::listCount(const QVariant &v)
+{
+ int userType = v.userType();
+
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ QmlType *type = data->idToType.value(userType);
+ lock.unlock();
+
+ if (type && type->qListTypeId() == userType)
+ return type->listCount(v);
+ else
+ return 0;
+}
+
+QVariant QmlMetaType::listAt(const QVariant &v, int idx)
+{
+ if (idx < 0)
+ return QVariant();
+
+ int userType = v.userType();
+
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+ QmlType *type = data->idToType.value(userType);
+ lock.unlock();
+
+ if (type && type->qListTypeId() == userType)
+ return type->listAt(v, idx);
+ else
+ return QVariant();
+}
+
+/*!
+ A custom string convertor allows you to specify a function pointer that
+ returns a variant of \a type. For example, if you have written your own icon
+ class that you want to support as an object property assignable in QML:
+
+ \code
+ int type = qRegisterMetaType<SuperIcon>("SuperIcon");
+ QML::addCustomStringConvertor(type, &SuperIcon::pixmapFromString);
+ \endcode
+
+ The function pointer must be of the form:
+ \code
+ QVariant (*StringConverter)(const QString &);
+ \endcode
+ */
+void QmlMetaType::registerCustomStringConverter(int type, StringConverter converter)
+{
+ QWriteLocker lock(metaTypeDataLock());
+
+ QmlMetaTypeData *data = metaTypeData();
+ if (data->stringConverters.contains(type))
+ return;
+ data->stringConverters.insert(type, converter);
+}
+
+/*!
+ Return the custom string converter for \a type, previously installed through
+ registerCustomStringConverter()
+ */
+QmlMetaType::StringConverter QmlMetaType::customStringConverter(int type)
+{
+ QReadLocker lock(metaTypeDataLock());
+
+ QmlMetaTypeData *data = metaTypeData();
+ return data->stringConverters.value(type);
+}
+
+/*!
+ Returns the type (if any) of URI-qualified named \a name in version specified
+ by \a version_major and \a version_minor.
+*/
+QmlType *QmlMetaType::qmlType(const QByteArray &name, int version_major, int version_minor)
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+
+ QList<QmlType*> types = data->nameToType.values(name);
+ foreach (QmlType *t, types) {
+ // XXX version_major<0 just a kludge for QmlMetaPropertyPrivate::initProperty
+ if (version_major<0 || t->availableInVersion(version_major,version_minor))
+ return t;
+ }
+ return 0;
+}
+
+/*!
+ Returns the type (if any) that corresponds to the \a metaObject. Returns null if no
+ type is registered.
+*/
+QmlType *QmlMetaType::qmlType(const QMetaObject *metaObject)
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+
+ return data->metaObjectToType.value(metaObject);
+}
+
+/*!
+ Returns the type (if any) that corresponds to the QVariant::Type \a userType.
+ Returns null if no type is registered.
+*/
+QmlType *QmlMetaType::qmlType(int userType)
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+
+ QmlType *type = data->idToType.value(userType);
+ if (type && type->typeId() == userType)
+ return type;
+ else
+ return 0;
+}
+
+/*!
+ Returns the list of registered QML type names.
+*/
+QList<QByteArray> QmlMetaType::qmlTypeNames()
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+
+ return data->nameToType.keys();
+}
+
+/*!
+ Returns the list of registered QML types.
+*/
+QList<QmlType*> QmlMetaType::qmlTypes()
+{
+ QReadLocker lock(metaTypeDataLock());
+ QmlMetaTypeData *data = metaTypeData();
+
+ return data->nameToType.values();
+}
+
+#include <QtGui/qfont.h>
+#include <QtGui/qpixmap.h>
+#include <QtGui/qbrush.h>
+#include <QtGui/qcolor.h>
+#include <QtGui/qpalette.h>
+#include <QtGui/qicon.h>
+#include <QtGui/qimage.h>
+#include <QtGui/qpolygon.h>
+#include <QtGui/qregion.h>
+#include <QtGui/qbitmap.h>
+#include <QtGui/qcursor.h>
+#include <QtGui/qsizepolicy.h>
+#include <QtGui/qkeysequence.h>
+#include <QtGui/qpen.h>
+
+//#include <QtGui/qtextlength.h>
+#include <QtGui/qtextformat.h>
+#include <QtGui/qmatrix.h>
+#include <QtGui/qtransform.h>
+#include <QtGui/qmatrix4x4.h>
+#include <QtGui/qvector2d.h>
+#include <QtGui/qvector3d.h>
+#include <QtGui/qvector4d.h>
+#include <QtGui/qquaternion.h>
+
+Q_DECLARE_METATYPE(QScriptValue);
+
+/*!
+ Copies \a copy into \a data, assuming they both are of type \a type. If
+ \a copy is zero, a default type is copied. Returns true if the copy was
+ successful and false if not.
+
+ \note This should move into QMetaType once complete
+
+*/
+bool QmlMetaType::copy(int type, void *data, const void *copy)
+{
+ if (copy) {
+ switch(type) {
+ case QMetaType::VoidStar:
+ case QMetaType::QObjectStar:
+ case QMetaType::QWidgetStar:
+ *static_cast<void **>(data) = *static_cast<void* const *>(copy);
+ return true;
+ case QMetaType::Long:
+ *static_cast<long *>(data) = *static_cast<const long*>(copy);
+ return true;
+ case QMetaType::Int:
+ *static_cast<int *>(data) = *static_cast<const int*>(copy);
+ return true;
+ case QMetaType::Short:
+ *static_cast<short *>(data) = *static_cast<const short*>(copy);
+ return true;
+ case QMetaType::Char:
+ *static_cast<char *>(data) = *static_cast<const char*>(copy);
+ return true;
+ case QMetaType::ULong:
+ *static_cast<ulong *>(data) = *static_cast<const ulong*>(copy);
+ return true;
+ case QMetaType::UInt:
+ *static_cast<uint *>(data) = *static_cast<const uint*>(copy);
+ return true;
+ case QMetaType::LongLong:
+ *static_cast<qlonglong *>(data) = *static_cast<const qlonglong*>(copy);
+ return true;
+ case QMetaType::ULongLong:
+ *static_cast<qulonglong *>(data) = *static_cast<const qulonglong*>(copy);
+ return true;
+ case QMetaType::UShort:
+ *static_cast<ushort *>(data) = *static_cast<const ushort*>(copy);
+ return true;
+ case QMetaType::UChar:
+ *static_cast<uchar *>(data) = *static_cast<const uchar*>(copy);
+ return true;
+ case QMetaType::Bool:
+ *static_cast<bool *>(data) = *static_cast<const bool*>(copy);
+ return true;
+ case QMetaType::Float:
+ *static_cast<float *>(data) = *static_cast<const float*>(copy);
+ return true;
+ case QMetaType::Double:
+ *static_cast<double *>(data) = *static_cast<const double*>(copy);
+ return true;
+ case QMetaType::QChar:
+ *static_cast<NS(QChar) *>(data) = *static_cast<const NS(QChar)*>(copy);
+ return true;
+ case QMetaType::QVariantMap:
+ *static_cast<NS(QVariantMap) *>(data) = *static_cast<const NS(QVariantMap)*>(copy);
+ return true;
+ case QMetaType::QVariantHash:
+ *static_cast<NS(QVariantHash) *>(data) = *static_cast<const NS(QVariantHash)*>(copy);
+ return true;
+ case QMetaType::QVariantList:
+ *static_cast<NS(QVariantList) *>(data) = *static_cast<const NS(QVariantList)*>(copy);
+ return true;
+ case QMetaType::QByteArray:
+ *static_cast<NS(QByteArray) *>(data) = *static_cast<const NS(QByteArray)*>(copy);
+ return true;
+ case QMetaType::QString:
+ *static_cast<NS(QString) *>(data) = *static_cast<const NS(QString)*>(copy);
+ return true;
+ case QMetaType::QStringList:
+ *static_cast<NS(QStringList) *>(data) = *static_cast<const NS(QStringList)*>(copy);
+ return true;
+ case QMetaType::QBitArray:
+ *static_cast<NS(QBitArray) *>(data) = *static_cast<const NS(QBitArray)*>(copy);
+ return true;
+ case QMetaType::QDate:
+ *static_cast<NS(QDate) *>(data) = *static_cast<const NS(QDate)*>(copy);
+ return true;
+ case QMetaType::QTime:
+ *static_cast<NS(QTime) *>(data) = *static_cast<const NS(QTime)*>(copy);
+ return true;
+ case QMetaType::QDateTime:
+ *static_cast<NS(QDateTime) *>(data) = *static_cast<const NS(QDateTime)*>(copy);
+ return true;
+ case QMetaType::QUrl:
+ *static_cast<NS(QUrl) *>(data) = *static_cast<const NS(QUrl)*>(copy);
+ return true;
+ case QMetaType::QLocale:
+ *static_cast<NS(QLocale) *>(data) = *static_cast<const NS(QLocale)*>(copy);
+ return true;
+ case QMetaType::QRect:
+ *static_cast<NS(QRect) *>(data) = *static_cast<const NS(QRect)*>(copy);
+ return true;
+ case QMetaType::QRectF:
+ *static_cast<NS(QRectF) *>(data) = *static_cast<const NS(QRectF)*>(copy);
+ return true;
+ case QMetaType::QSize:
+ *static_cast<NS(QSize) *>(data) = *static_cast<const NS(QSize)*>(copy);
+ return true;
+ case QMetaType::QSizeF:
+ *static_cast<NS(QSizeF) *>(data) = *static_cast<const NS(QSizeF)*>(copy);
+ return true;
+ case QMetaType::QLine:
+ *static_cast<NS(QLine) *>(data) = *static_cast<const NS(QLine)*>(copy);
+ return true;
+ case QMetaType::QLineF:
+ *static_cast<NS(QLineF) *>(data) = *static_cast<const NS(QLineF)*>(copy);
+ return true;
+ case QMetaType::QPoint:
+ *static_cast<NS(QPoint) *>(data) = *static_cast<const NS(QPoint)*>(copy);
+ return true;
+ case QMetaType::QPointF:
+ *static_cast<NS(QPointF) *>(data) = *static_cast<const NS(QPointF)*>(copy);
+ return true;
+ case QMetaType::QVector3D:
+ *static_cast<NS(QVector3D) *>(data) = *static_cast<const NS(QVector3D)*>(copy);
+ return true;
+#ifndef QT_NO_REGEXP
+ case QMetaType::QRegExp:
+ *static_cast<NS(QRegExp) *>(data) = *static_cast<const NS(QRegExp)*>(copy);
+ return true;
+#endif
+ case QMetaType::Void:
+ return true;
+
+
+#ifdef QT3_SUPPORT
+ case QMetaType::QColorGroup:
+ *static_cast<NS(QColorGroup) *>(data) = *static_cast<const NS(QColorGroup)*>(copy);
+ return true;
+#endif
+
+ case QMetaType::QFont:
+ *static_cast<NS(QFont) *>(data) = *static_cast<const NS(QFont)*>(copy);
+ return true;
+ case QMetaType::QPixmap:
+ *static_cast<NS(QPixmap) *>(data) = *static_cast<const NS(QPixmap)*>(copy);
+ return true;
+ case QMetaType::QBrush:
+ *static_cast<NS(QBrush) *>(data) = *static_cast<const NS(QBrush)*>(copy);
+ return true;
+ case QMetaType::QColor:
+ *static_cast<NS(QColor) *>(data) = *static_cast<const NS(QColor)*>(copy);
+ return true;
+ case QMetaType::QPalette:
+ *static_cast<NS(QPalette) *>(data) = *static_cast<const NS(QPalette)*>(copy);
+ return true;
+ case QMetaType::QIcon:
+ *static_cast<NS(QIcon) *>(data) = *static_cast<const NS(QIcon)*>(copy);
+ return true;
+ case QMetaType::QImage:
+ *static_cast<NS(QImage) *>(data) = *static_cast<const NS(QImage)*>(copy);
+ return true;
+ case QMetaType::QPolygon:
+ *static_cast<NS(QPolygon) *>(data) = *static_cast<const NS(QPolygon)*>(copy);
+ return true;
+ case QMetaType::QRegion:
+ *static_cast<NS(QRegion) *>(data) = *static_cast<const NS(QRegion)*>(copy);
+ return true;
+ case QMetaType::QBitmap:
+ *static_cast<NS(QBitmap) *>(data) = *static_cast<const NS(QBitmap)*>(copy);
+ return true;
+#ifndef QT_NO_CURSOR
+ case QMetaType::QCursor:
+ *static_cast<NS(QCursor) *>(data) = *static_cast<const NS(QCursor)*>(copy);
+ return true;
+#endif
+ case QMetaType::QSizePolicy:
+ *static_cast<NS(QSizePolicy) *>(data) = *static_cast<const NS(QSizePolicy)*>(copy);
+ return true;
+ case QMetaType::QKeySequence:
+ *static_cast<NS(QKeySequence) *>(data) = *static_cast<const NS(QKeySequence)*>(copy);
+ return true;
+ case QMetaType::QPen:
+ *static_cast<NS(QPen) *>(data) = *static_cast<const NS(QPen)*>(copy);
+ return true;
+ case QMetaType::QTextLength:
+ *static_cast<NS(QTextLength) *>(data) = *static_cast<const NS(QTextLength)*>(copy);
+ return true;
+ case QMetaType::QTextFormat:
+ *static_cast<NS(QTextFormat) *>(data) = *static_cast<const NS(QTextFormat)*>(copy);
+ return true;
+ case QMetaType::QMatrix:
+ *static_cast<NS(QMatrix) *>(data) = *static_cast<const NS(QMatrix)*>(copy);
+ return true;
+ case QMetaType::QTransform:
+ *static_cast<NS(QTransform) *>(data) = *static_cast<const NS(QTransform)*>(copy);
+ return true;
+ case QMetaType::QMatrix4x4:
+ *static_cast<NS(QMatrix4x4) *>(data) = *static_cast<const NS(QMatrix4x4)*>(copy);
+ return true;
+ case QMetaType::QVector2D:
+ *static_cast<NS(QVector2D) *>(data) = *static_cast<const NS(QVector2D)*>(copy);
+ return true;
+ case QMetaType::QVector4D:
+ *static_cast<NS(QVector4D) *>(data) = *static_cast<const NS(QVector4D)*>(copy);
+ return true;
+ case QMetaType::QQuaternion:
+ *static_cast<NS(QQuaternion) *>(data) = *static_cast<const NS(QQuaternion)*>(copy);
+ return true;
+
+ default:
+ if (type == qMetaTypeId<QVariant>()) {
+ *static_cast<NS(QVariant) *>(data) = *static_cast<const NS(QVariant)*>(copy);
+ return true;
+ } else if (type == qMetaTypeId<QScriptValue>()) {
+ *static_cast<NS(QScriptValue) *>(data) = *static_cast<const NS(QScriptValue)*>(copy);
+ return true;
+ } else if (typeCategory(type) != Unknown) {
+ *static_cast<void **>(data) = *static_cast<void* const *>(copy);
+ return true;
+ }
+ break;
+ }
+ } else {
+ switch(type) {
+ case QMetaType::VoidStar:
+ case QMetaType::QObjectStar:
+ case QMetaType::QWidgetStar:
+ *static_cast<void **>(data) = 0;
+ return true;
+ case QMetaType::Long:
+ *static_cast<long *>(data) = long(0);
+ return true;
+ case QMetaType::Int:
+ *static_cast<int *>(data) = int(0);
+ return true;
+ case QMetaType::Short:
+ *static_cast<short *>(data) = short(0);
+ return true;
+ case QMetaType::Char:
+ *static_cast<char *>(data) = char(0);
+ return true;
+ case QMetaType::ULong:
+ *static_cast<ulong *>(data) = ulong(0);
+ return true;
+ case QMetaType::UInt:
+ *static_cast<uint *>(data) = uint(0);
+ return true;
+ case QMetaType::LongLong:
+ *static_cast<qlonglong *>(data) = qlonglong(0);
+ return true;
+ case QMetaType::ULongLong:
+ *static_cast<qulonglong *>(data) = qulonglong(0);
+ return true;
+ case QMetaType::UShort:
+ *static_cast<ushort *>(data) = ushort(0);
+ return true;
+ case QMetaType::UChar:
+ *static_cast<uchar *>(data) = uchar(0);
+ return true;
+ case QMetaType::Bool:
+ *static_cast<bool *>(data) = bool(false);
+ return true;
+ case QMetaType::Float:
+ *static_cast<float *>(data) = float(0);
+ return true;
+ case QMetaType::Double:
+ *static_cast<double *>(data) = double();
+ return true;
+ case QMetaType::QChar:
+ *static_cast<NS(QChar) *>(data) = NS(QChar)();
+ return true;
+ case QMetaType::QVariantMap:
+ *static_cast<NS(QVariantMap) *>(data) = NS(QVariantMap)();
+ return true;
+ case QMetaType::QVariantHash:
+ *static_cast<NS(QVariantHash) *>(data) = NS(QVariantHash)();
+ return true;
+ case QMetaType::QVariantList:
+ *static_cast<NS(QVariantList) *>(data) = NS(QVariantList)();
+ return true;
+ case QMetaType::QByteArray:
+ *static_cast<NS(QByteArray) *>(data) = NS(QByteArray)();
+ return true;
+ case QMetaType::QString:
+ *static_cast<NS(QString) *>(data) = NS(QString)();
+ return true;
+ case QMetaType::QStringList:
+ *static_cast<NS(QStringList) *>(data) = NS(QStringList)();
+ return true;
+ case QMetaType::QBitArray:
+ *static_cast<NS(QBitArray) *>(data) = NS(QBitArray)();
+ return true;
+ case QMetaType::QDate:
+ *static_cast<NS(QDate) *>(data) = NS(QDate)();
+ return true;
+ case QMetaType::QTime:
+ *static_cast<NS(QTime) *>(data) = NS(QTime)();
+ return true;
+ case QMetaType::QDateTime:
+ *static_cast<NS(QDateTime) *>(data) = NS(QDateTime)();
+ return true;
+ case QMetaType::QUrl:
+ *static_cast<NS(QUrl) *>(data) = NS(QUrl)();
+ return true;
+ case QMetaType::QLocale:
+ *static_cast<NS(QLocale) *>(data) = NS(QLocale)();
+ return true;
+ case QMetaType::QRect:
+ *static_cast<NS(QRect) *>(data) = NS(QRect)();
+ return true;
+ case QMetaType::QRectF:
+ *static_cast<NS(QRectF) *>(data) = NS(QRectF)();
+ return true;
+ case QMetaType::QSize:
+ *static_cast<NS(QSize) *>(data) = NS(QSize)();
+ return true;
+ case QMetaType::QSizeF:
+ *static_cast<NS(QSizeF) *>(data) = NS(QSizeF)();
+ return true;
+ case QMetaType::QLine:
+ *static_cast<NS(QLine) *>(data) = NS(QLine)();
+ return true;
+ case QMetaType::QLineF:
+ *static_cast<NS(QLineF) *>(data) = NS(QLineF)();
+ return true;
+ case QMetaType::QPoint:
+ *static_cast<NS(QPoint) *>(data) = NS(QPoint)();
+ return true;
+ case QMetaType::QPointF:
+ *static_cast<NS(QPointF) *>(data) = NS(QPointF)();
+ return true;
+ case QMetaType::QVector3D:
+ *static_cast<NS(QVector3D) *>(data) = NS(QVector3D)();
+ return true;
+#ifndef QT_NO_REGEXP
+ case QMetaType::QRegExp:
+ *static_cast<NS(QRegExp) *>(data) = NS(QRegExp)();
+ return true;
+#endif
+ case QMetaType::Void:
+ return true;
+
+#ifdef QT3_SUPPORT
+ case QMetaType::QColorGroup:
+ *static_cast<NS(QColorGroup) *>(data) = NS(QColorGroup)();
+ return true;
+#endif
+
+ case QMetaType::QFont:
+ *static_cast<NS(QFont) *>(data) = NS(QFont)();
+ return true;
+ case QMetaType::QPixmap:
+ *static_cast<NS(QPixmap) *>(data) = NS(QPixmap)();
+ return true;
+ case QMetaType::QBrush:
+ *static_cast<NS(QBrush) *>(data) = NS(QBrush)();
+ return true;
+ case QMetaType::QColor:
+ *static_cast<NS(QColor) *>(data) = NS(QColor)();
+ return true;
+ case QMetaType::QPalette:
+ *static_cast<NS(QPalette) *>(data) = NS(QPalette)();
+ return true;
+ case QMetaType::QIcon:
+ *static_cast<NS(QIcon) *>(data) = NS(QIcon)();
+ return true;
+ case QMetaType::QImage:
+ *static_cast<NS(QImage) *>(data) = NS(QImage)();
+ return true;
+ case QMetaType::QPolygon:
+ *static_cast<NS(QPolygon) *>(data) = NS(QPolygon)();
+ return true;
+ case QMetaType::QRegion:
+ *static_cast<NS(QRegion) *>(data) = NS(QRegion)();
+ return true;
+ case QMetaType::QBitmap:
+ *static_cast<NS(QBitmap) *>(data) = NS(QBitmap)();
+ return true;
+#ifndef QT_NO_CURSOR
+ case QMetaType::QCursor:
+ *static_cast<NS(QCursor) *>(data) = NS(QCursor)();
+ return true;
+#endif
+ case QMetaType::QSizePolicy:
+ *static_cast<NS(QSizePolicy) *>(data) = NS(QSizePolicy)();
+ return true;
+ case QMetaType::QKeySequence:
+ *static_cast<NS(QKeySequence) *>(data) = NS(QKeySequence)();
+ return true;
+ case QMetaType::QPen:
+ *static_cast<NS(QPen) *>(data) = NS(QPen)();
+ return true;
+ case QMetaType::QTextLength:
+ *static_cast<NS(QTextLength) *>(data) = NS(QTextLength)();
+ return true;
+ case QMetaType::QTextFormat:
+ *static_cast<NS(QTextFormat) *>(data) = NS(QTextFormat)();
+ return true;
+ case QMetaType::QMatrix:
+ *static_cast<NS(QMatrix) *>(data) = NS(QMatrix)();
+ return true;
+ case QMetaType::QTransform:
+ *static_cast<NS(QTransform) *>(data) = NS(QTransform)();
+ return true;
+ case QMetaType::QMatrix4x4:
+ *static_cast<NS(QMatrix4x4) *>(data) = NS(QMatrix4x4)();
+ return true;
+ case QMetaType::QVector2D:
+ *static_cast<NS(QVector2D) *>(data) = NS(QVector2D)();
+ return true;
+ case QMetaType::QVector4D:
+ *static_cast<NS(QVector4D) *>(data) = NS(QVector4D)();
+ return true;
+ case QMetaType::QQuaternion:
+ *static_cast<NS(QQuaternion) *>(data) = NS(QQuaternion)();
+ return true;
+ default:
+ if (type == qMetaTypeId<QVariant>()) {
+ *static_cast<NS(QVariant) *>(data) = NS(QVariant)();
+ return true;
+ } else if (type == qMetaTypeId<QScriptValue>()) {
+ *static_cast<NS(QScriptValue) *>(data) = NS(QScriptValue)();
+ return true;
+ } else if (typeCategory(type) != Unknown) {
+ *static_cast<void **>(data) = 0;
+ return true;
+ }
+ break;
+ }
+ }
+
+ return false;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlmetatype.h b/src/declarative/qml/qmlmetatype.h
new file mode 100644
index 0000000..45ec11d
--- /dev/null
+++ b/src/declarative/qml/qmlmetatype.h
@@ -0,0 +1,301 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLMETATYPE_H
+#define QMLMETATYPE_H
+
+#include "qmlprivate.h"
+#include "qmlparserstatus.h"
+#include "qmlpropertyvaluesource.h"
+#include "qmlpropertyvalueinterceptor.h"
+
+#include <QtCore/qglobal.h>
+#include <QtCore/qvariant.h>
+#include <QtCore/qbitarray.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlType;
+class QmlCustomParser;
+class Q_DECLARATIVE_EXPORT QmlMetaType
+{
+public:
+ static int registerType(const QmlPrivate::MetaTypeIds &, QmlPrivate::Func, const char *, int vmaj, int vmin, const char *qmlName, const QMetaObject *, QmlAttachedPropertiesFunc, const QMetaObject *, int pStatus, int object, int valueSource, int valueInterceptor, QmlPrivate::CreateFunc extFunc, const QMetaObject *extmo, QmlCustomParser *);
+ static int registerInterface(const QmlPrivate::MetaTypeIds &, QmlPrivate::Func, const char *);
+
+ static bool copy(int type, void *data, const void *copy = 0);
+
+ static QList<QByteArray> qmlTypeNames();
+ static QList<QmlType*> qmlTypes();
+
+ static QmlType *qmlType(const QByteArray &, int, int);
+ static QmlType *qmlType(const QMetaObject *);
+ static QmlType *qmlType(int);
+
+ static QMetaProperty defaultProperty(const QMetaObject *);
+ static QMetaProperty defaultProperty(QObject *);
+ static QMetaMethod defaultMethod(const QMetaObject *);
+ static QMetaMethod defaultMethod(QObject *);
+
+ static bool isQObject(int);
+ static QObject *toQObject(const QVariant &, bool *ok = 0);
+
+ static int listType(int);
+ static bool clear(const QVariant &);
+ static bool append(const QVariant &, const QVariant &);
+ static int attachedPropertiesFuncId(const QMetaObject *);
+ static QmlAttachedPropertiesFunc attachedPropertiesFuncById(int);
+
+ enum TypeCategory { Unknown, Object, List, QmlList };
+ static TypeCategory typeCategory(int);
+
+ static bool isInterface(int);
+ static const char *interfaceIId(int);
+ static bool isList(int);
+ static bool isList(const QVariant &);
+ static bool isQmlList(int);
+ static int qmlListType(int);
+ static int listCount(const QVariant &);
+ static QVariant listAt(const QVariant &, int);
+
+ typedef QVariant (*StringConverter)(const QString &);
+ static void registerCustomStringConverter(int, StringConverter);
+ static StringConverter customStringConverter(int);
+};
+
+class QmlTypePrivate;
+class Q_DECLARATIVE_EXPORT QmlType
+{
+public:
+ QByteArray typeName() const;
+ QByteArray qmlTypeName() const;
+
+ int majorVersion() const;
+ int minorVersion() const;
+ bool availableInVersion(int vmajor, int vminor) const;
+
+ QObject *create() const;
+
+ QmlCustomParser *customParser() const;
+
+ bool isInterface() const;
+ int typeId() const;
+ int qListTypeId() const;
+ int qmlListTypeId() const;
+
+ void listClear(const QVariant &);
+ void listAppend(const QVariant &, const QVariant &);
+ QVariant listAt(const QVariant &, int);
+ int listCount(const QVariant &);
+
+ const QMetaObject *metaObject() const;
+ const QMetaObject *baseMetaObject() const;
+
+ QmlAttachedPropertiesFunc attachedPropertiesFunction() const;
+ const QMetaObject *attachedPropertiesType() const;
+
+ int parserStatusCast() const;
+ QVariant fromObject(QObject *) const;
+ const char *interfaceIId() const;
+ int propertyValueSourceCast() const;
+ int propertyValueInterceptorCast() const;
+
+ int index() const;
+private:
+ friend class QmlMetaType;
+ friend class QmlTypePrivate;
+ friend struct QmlMetaTypeData;
+ QmlType(int, int, int, QmlPrivate::Func, const char *, int);
+ QmlType(int, int, int, QmlPrivate::Func, const char *, int, int, const QMetaObject *, QmlAttachedPropertiesFunc, const QMetaObject *, int, int, int, QmlPrivate::CreateFunc, const QMetaObject *, int, QmlCustomParser *);
+ ~QmlType();
+
+ QmlTypePrivate *d;
+};
+
+template<typename T>
+int qmlRegisterType(const char *typeName)
+{
+ QByteArray name(typeName);
+ QmlPrivate::MetaTypeIds ids = {
+ qRegisterMetaType<T *>(QByteArray(name + '*').constData()),
+ qRegisterMetaType<T *>(QByteArray("QList<" + name + "*>*").constData()),
+ qRegisterMetaType<T *>(QByteArray("QmlList<" + name + "*>*").constData())
+ };
+
+ return QmlMetaType::registerType(ids, QmlPrivate::list_nocreate_op<T>, 0, 0, 0, 0,
+ &T::staticMetaObject,
+ QmlPrivate::attachedPropertiesFunc<T>(),
+ QmlPrivate::attachedPropertiesMetaObject<T>(),
+ QmlPrivate::StaticCastSelector<T,QmlParserStatus>::cast(),
+ QmlPrivate::StaticCastSelector<T,QObject>::cast(),
+ QmlPrivate::StaticCastSelector<T,QmlPropertyValueSource>::cast(),
+ QmlPrivate::StaticCastSelector<T,QmlPropertyValueInterceptor>::cast(),
+ 0, 0, 0);
+}
+
+template<typename T>
+int qmlRegisterType(const char *uri, int version_maj, int version_min, const char *qmlName, const char *typeName)
+{
+ QByteArray name(typeName);
+ QmlPrivate::MetaTypeIds ids = {
+ qRegisterMetaType<T *>(QByteArray(name + '*').constData()),
+ qRegisterMetaType<T *>(QByteArray("QList<" + name + "*>*").constData()),
+ qRegisterMetaType<T *>(QByteArray("QmlList<" + name + "*>*").constData())
+ };
+
+ return QmlMetaType::registerType(ids, QmlPrivate::list_op<T>,
+ uri, version_maj, version_min, qmlName,
+ &T::staticMetaObject,
+ QmlPrivate::attachedPropertiesFunc<T>(),
+ QmlPrivate::attachedPropertiesMetaObject<T>(),
+ QmlPrivate::StaticCastSelector<T,QmlParserStatus>::cast(),
+ QmlPrivate::StaticCastSelector<T,QObject>::cast(),
+ QmlPrivate::StaticCastSelector<T,QmlPropertyValueSource>::cast(),
+ QmlPrivate::StaticCastSelector<T,QmlPropertyValueInterceptor>::cast(),
+ 0, 0, 0);
+}
+
+template<typename T, typename E>
+int qmlRegisterExtendedType(const char *typeName)
+{
+ QByteArray name(typeName);
+ QmlPrivate::MetaTypeIds ids = {
+ qRegisterMetaType<T *>(QByteArray(name + '*').constData()),
+ qRegisterMetaType<T *>(QByteArray("QList<" + name + "*>*").constData()),
+ qRegisterMetaType<T *>(QByteArray("QmlList<" + name + "*>*").constData())
+ };
+
+ QmlAttachedPropertiesFunc attached =
+ QmlPrivate::attachedPropertiesFunc<E>();
+ const QMetaObject * attachedMo =
+ QmlPrivate::attachedPropertiesMetaObject<E>();
+ if (!attached) {
+ attached = QmlPrivate::attachedPropertiesFunc<T>();
+ attachedMo = QmlPrivate::attachedPropertiesMetaObject<T>();
+ }
+
+ return QmlMetaType::registerType(ids, QmlPrivate::list_nocreate_op<T>, 0, 0, 0, 0,
+ &T::staticMetaObject, attached, attachedMo,
+ QmlPrivate::StaticCastSelector<T,QmlParserStatus>::cast(),
+ QmlPrivate::StaticCastSelector<T,QObject>::cast(),
+ QmlPrivate::StaticCastSelector<T,QmlPropertyValueSource>::cast(),
+ QmlPrivate::StaticCastSelector<T,QmlPropertyValueInterceptor>::cast(),
+ &QmlPrivate::CreateParent<E>::create, &E::staticMetaObject, 0);
+}
+
+template<typename T, typename E>
+int qmlRegisterExtendedType(const char *uri, int version_maj, int version_min, const char *qmlName, const char *typeName)
+{
+ QByteArray name(typeName);
+ QmlPrivate::MetaTypeIds ids = {
+ qRegisterMetaType<T *>(QByteArray(name + '*').constData()),
+ qRegisterMetaType<T *>(QByteArray("QList<" + name + "*>*").constData()),
+ qRegisterMetaType<T *>(QByteArray("QmlList<" + name + "*>*").constData())
+ };
+
+ QmlAttachedPropertiesFunc attached =
+ QmlPrivate::attachedPropertiesFunc<E>();
+ const QMetaObject * attachedMo =
+ QmlPrivate::attachedPropertiesMetaObject<E>();
+ if (!attached) {
+ attached = QmlPrivate::attachedPropertiesFunc<T>();
+ attachedMo = QmlPrivate::attachedPropertiesMetaObject<T>();
+ }
+
+ return QmlMetaType::registerType(ids, QmlPrivate::list_op<T>,
+ uri, version_maj, version_min, qmlName,
+ &T::staticMetaObject,
+ attached, attachedMo,
+ QmlPrivate::StaticCastSelector<T,QmlParserStatus>::cast(),
+ QmlPrivate::StaticCastSelector<T,QObject>::cast(),
+ QmlPrivate::StaticCastSelector<T,QmlPropertyValueSource>::cast(),
+ QmlPrivate::StaticCastSelector<T,QmlPropertyValueInterceptor>::cast(),
+ &QmlPrivate::CreateParent<E>::create,
+ &E::staticMetaObject, 0);
+}
+
+template<typename T>
+int qmlRegisterInterface(const char *typeName)
+{
+ QByteArray name(typeName);
+ QmlPrivate::MetaTypeIds ids = {
+ qRegisterMetaType<T *>(QByteArray(name + '*').constData()),
+ qRegisterMetaType<T *>(QByteArray("QList<" + name + "*>*").constData()),
+ qRegisterMetaType<T *>(QByteArray("QmlList<" + name + "*>*").constData())
+ };
+
+ return QmlMetaType::registerInterface(ids,
+ QmlPrivate::list_interface_op<T>,
+ qobject_interface_iid<T *>());
+}
+
+template<typename T>
+int qmlRegisterCustomType(const char *uri, int version_maj, int version_min, const char *qmlName, const char *typeName, QmlCustomParser *parser)
+{
+ QByteArray name(typeName);
+ QmlPrivate::MetaTypeIds ids = {
+ qRegisterMetaType<T *>(QByteArray(name + '*').constData()),
+ qRegisterMetaType<T *>(QByteArray("QList<" + name + "*>*").constData()),
+ qRegisterMetaType<T *>(QByteArray("QmlList<" + name + "*>*").constData())
+ };
+
+ return QmlMetaType::registerType(ids, QmlPrivate::list_op<T>,
+ uri, version_maj, version_min, qmlName,
+ &T::staticMetaObject,
+ QmlPrivate::attachedPropertiesFunc<T>(),
+ QmlPrivate::attachedPropertiesMetaObject<T>(),
+ QmlPrivate::StaticCastSelector<T,QmlParserStatus>::cast(),
+ QmlPrivate::StaticCastSelector<T,QObject>::cast(),
+ QmlPrivate::StaticCastSelector<T,QmlPropertyValueSource>::cast(),
+ QmlPrivate::StaticCastSelector<T,QmlPropertyValueInterceptor>::cast(),
+ 0, 0, parser);
+}
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLMETATYPE_H
+
diff --git a/src/declarative/qml/qmlmoduleplugin.cpp b/src/declarative/qml/qmlmoduleplugin.cpp
new file mode 100644
index 0000000..2f2cb25
--- /dev/null
+++ b/src/declarative/qml/qmlmoduleplugin.cpp
@@ -0,0 +1,111 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlmoduleplugin.h"
+#include "qstringlist.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QmlModulePlugin
+ \brief The QmlModulePlugin class provides an abstract base for custom QML module plugins.
+ \reentrant
+ \ingroup plugins
+
+ The QML module plugin is a simple plugin interface that makes it
+ easy to add custom QML modules that can be loaded dynamically
+ into applications.
+
+ Writing a QML module plugin is achieved by subclassing this base
+ class, reimplementing the pure virtual function keys(), and
+ exporting the class with the Q_EXPORT_PLUGIN2() macro. See \l{How
+ to Create Qt Plugins} for details.
+
+ The strings returned by keys() should be the list of URIs of modules
+ that the plugin registers.
+
+ The plugin should register QML types with qmlRegisterType() when the
+ defineModule() method is called.
+
+ \sa examples/declarative/plugins
+*/
+
+/*!
+ Constructs a QML module plugin with the given \a parent. This is
+ invoked automatically by the Q_EXPORT_PLUGIN2() macro.
+*/
+QmlModulePlugin::QmlModulePlugin(QObject *parent)
+ : QObject(parent)
+{
+}
+
+/*!
+ Destroys the QML module plugin.
+
+ You never have to call this explicitly. Qt destroys a plugin
+ automatically when it is no longer used.
+*/
+QmlModulePlugin::~QmlModulePlugin()
+{
+}
+
+/*!
+ \fn void QmlModulePlugin::defineModule(const QString& uri)
+
+ Subclasses must override this function to register types
+ of the module \a uri, which will be one of the strings returned by keys().
+
+ The plugin registers QML types with qmlRegisterType():
+
+ \code
+ qmlRegisterType<MyClass>("com.nokia.MyModule", 1, 0, "MyType", "MyClass");
+ \endcode
+*/
+
+void QmlModulePlugin::defineModuleOnce(const QString& uri)
+{
+ if (!defined.contains(uri)) {
+ defined += uri;
+ defineModule(uri);
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlmoduleplugin.h b/src/declarative/qml/qmlmoduleplugin.h
new file mode 100644
index 0000000..384e05e
--- /dev/null
+++ b/src/declarative/qml/qmlmoduleplugin.h
@@ -0,0 +1,86 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLMODULEPLUGIN_H
+#define QMLMODULEPLUGIN_H
+
+#include <QtCore/qplugin.h>
+#include <QtCore/qfactoryinterface.h>
+#include <QtCore/qlist.h>
+#include <QtCore/qset.h>
+#include <QtCore/qbytearray.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+struct Q_DECLARATIVE_EXPORT QmlModuleFactoryInterface : public QFactoryInterface
+{
+ virtual void defineModuleOnce(const QString& uri) = 0;
+};
+
+#define QmlModuleFactoryInterface_iid "com.nokia.Qt.QmlModuleFactoryInterface"
+
+Q_DECLARE_INTERFACE(QmlModuleFactoryInterface, QmlModuleFactoryInterface_iid)
+
+
+class Q_DECLARATIVE_EXPORT QmlModulePlugin : public QObject, public QmlModuleFactoryInterface
+{
+ Q_OBJECT
+ Q_INTERFACES(QmlModuleFactoryInterface:QFactoryInterface)
+public:
+ explicit QmlModulePlugin(QObject *parent = 0);
+ ~QmlModulePlugin();
+
+ virtual void defineModule(const QString& uri) = 0;
+
+private:
+ void defineModuleOnce(const QString& uri);
+ QSet<QString> defined;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLMODULEPLUGIN_H
diff --git a/src/declarative/qml/qmlnetworkaccessmanagerfactory.cpp b/src/declarative/qml/qmlnetworkaccessmanagerfactory.cpp
new file mode 100644
index 0000000..76f20d8
--- /dev/null
+++ b/src/declarative/qml/qmlnetworkaccessmanagerfactory.cpp
@@ -0,0 +1,79 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlnetworkaccessmanagerfactory.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QmlNetworkAccessManagerFactory
+ \brief The QmlNetworkAccessManagerFactory class provides a factory for QNetworkAccessManager
+
+ QNetworkAccessManager is used for all network access by QML.
+ By implementing a factory it is possible to create custom
+ QNetworkAccessManager with specialized caching, proxy and
+ cookie support.
+
+ To implement a factory, subclass QmlNetworkAccessManagerFactory and implement
+ the create() method.
+
+ If the created QNetworkAccessManager becomes invalid, due to a
+ change in proxy settings, for example, call the invalidate() method.
+ This will cause all QNetworkAccessManagers to be recreated.
+
+ Note: the create() method may be called by multiple threads, so ensure the
+ implementation of this method is reentrant.
+*/
+QmlNetworkAccessManagerFactory::~QmlNetworkAccessManagerFactory()
+{
+}
+
+/*!
+ \fn QNetworkAccessManager *QmlNetworkAccessManagerFactory::create(QObject *parent)
+
+ Implement this method to create a QNetworkAccessManager with \a parent.
+ This allows proxies, caching and cookie support to be setup appropriately.
+
+ Note: this method may be called by multiple threads, so ensure the
+ implementation of this method is reentrant.
+*/
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlnetworkaccessmanagerfactory.h b/src/declarative/qml/qmlnetworkaccessmanagerfactory.h
new file mode 100644
index 0000000..ce9860f
--- /dev/null
+++ b/src/declarative/qml/qmlnetworkaccessmanagerfactory.h
@@ -0,0 +1,66 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLNETWORKACCESSMANAGERFACTORY_H
+#define QMLNETWORKACCESSMANAGERFACTORY_H
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QNetworkAccessManager;
+class Q_DECLARATIVE_EXPORT QmlNetworkAccessManagerFactory
+{
+public:
+ virtual ~QmlNetworkAccessManagerFactory();
+ virtual QNetworkAccessManager *create(QObject *parent) = 0;
+
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLNETWORKACCESSMANAGERFACTORY_H
diff --git a/src/declarative/qml/qmlobjectscriptclass.cpp b/src/declarative/qml/qmlobjectscriptclass.cpp
new file mode 100644
index 0000000..1c41d46
--- /dev/null
+++ b/src/declarative/qml/qmlobjectscriptclass.cpp
@@ -0,0 +1,675 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlobjectscriptclass_p.h"
+
+#include "qmlengine_p.h"
+#include "qmlcontext_p.h"
+#include "qmldeclarativedata_p.h"
+#include "qmltypenamescriptclass_p.h"
+#include "qmllistscriptclass_p.h"
+#include "qmlbinding.h"
+#include "qmlguard_p.h"
+#include "qmlvmemetaobject_p.h"
+
+#include <QtCore/qtimer.h>
+#include <QtCore/qvarlengtharray.h>
+
+Q_DECLARE_METATYPE(QScriptValue);
+
+QT_BEGIN_NAMESPACE
+
+struct ObjectData : public QScriptDeclarativeClass::Object {
+ ObjectData(QObject *o, int t) : object(o), type(t) {}
+ QmlGuard<QObject> object;
+ int type;
+};
+
+/*
+ The QmlObjectScriptClass handles property access for QObjects
+ via QtScript. It is also used to provide a more useful API in
+ QtScript for QML.
+ */
+QmlObjectScriptClass::QmlObjectScriptClass(QmlEngine *bindEngine)
+: QmlScriptClass(QmlEnginePrivate::getScriptEngine(bindEngine)),
+#if (QT_VERSION > QT_VERSION_CHECK(4, 6, 2)) || defined(QT_HAVE_QSCRIPTDECLARATIVECLASS_VALUE)
+ methods(bindEngine),
+#endif
+ lastData(0), engine(bindEngine)
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ m_destroy = scriptEngine->newFunction(destroy);
+ m_destroyId = createPersistentIdentifier(QLatin1String("destroy"));
+ m_toString = scriptEngine->newFunction(tostring);
+ m_toStringId = createPersistentIdentifier(QLatin1String("toString"));
+}
+
+QmlObjectScriptClass::~QmlObjectScriptClass()
+{
+}
+
+QScriptValue QmlObjectScriptClass::newQObject(QObject *object, int type)
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ if (!object)
+ return newObject(scriptEngine, this, new ObjectData(object, type));
+
+ QmlDeclarativeData *ddata = QmlDeclarativeData::get(object, true);
+
+ if (!ddata->scriptValue.isValid()) {
+ ddata->scriptValue = newObject(scriptEngine, this, new ObjectData(object, type));
+ return ddata->scriptValue;
+ } else if (ddata->scriptValue.engine() == QmlEnginePrivate::getScriptEngine(engine)) {
+ return ddata->scriptValue;
+ } else {
+ return newObject(scriptEngine, this, new ObjectData(object, type));
+ }
+}
+
+QObject *QmlObjectScriptClass::toQObject(const QScriptValue &value) const
+{
+ return value.toQObject();
+}
+
+int QmlObjectScriptClass::objectType(const QScriptValue &value) const
+{
+ if (scriptClass(value) != this)
+ return QVariant::Invalid;
+
+ Object *o = object(value);
+ return ((ObjectData*)(o))->type;
+}
+
+QScriptClass::QueryFlags
+QmlObjectScriptClass::queryProperty(Object *object, const Identifier &name,
+ QScriptClass::QueryFlags flags)
+{
+ return queryProperty(toQObject(object), name, flags, 0);
+}
+
+QScriptClass::QueryFlags
+QmlObjectScriptClass::queryProperty(QObject *obj, const Identifier &name,
+ QScriptClass::QueryFlags flags, QmlContext *evalContext,
+ QueryHints hints)
+{
+ Q_UNUSED(flags);
+ lastData = 0;
+ lastTNData = 0;
+
+ if (name == m_destroyId.identifier ||
+ name == m_toStringId.identifier)
+ return QScriptClass::HandlesReadAccess;
+
+ if (!obj)
+ return 0;
+
+ QmlEnginePrivate *enginePrivate = QmlEnginePrivate::get(engine);
+ lastData = QmlPropertyCache::property(engine, obj, name, local);
+
+ if (lastData)
+ return QScriptClass::HandlesReadAccess | QScriptClass::HandlesWriteAccess;
+
+ if (!(hints & SkipAttachedProperties)) {
+ if (!evalContext && context()) {
+ // Global object, QScriptContext activation object, QmlContext object
+ QScriptValue scopeNode = scopeChainValue(context(), -3);
+ if (scopeNode.isValid()) {
+ Q_ASSERT(scriptClass(scopeNode) == enginePrivate->contextClass);
+
+ evalContext = enginePrivate->contextClass->contextFromValue(scopeNode);
+ }
+ }
+
+ if (evalContext) {
+ QmlContextPrivate *cp = QmlContextPrivate::get(evalContext);
+
+ if (cp->imports) {
+ QmlTypeNameCache::Data *data = cp->imports->data(name);
+ if (data) {
+ lastTNData = data;
+ return QScriptClass::HandlesReadAccess;
+ }
+ }
+ }
+ }
+
+ if (!(hints & ImplicitObject)) {
+ local.coreIndex = -1;
+ lastData = &local;
+ return QScriptClass::HandlesReadAccess | QScriptClass::HandlesWriteAccess;
+ }
+
+ return 0;
+}
+
+QmlObjectScriptClass::ScriptValue
+QmlObjectScriptClass::property(Object *object, const Identifier &name)
+{
+ return property(toQObject(object), name);
+}
+
+QmlObjectScriptClass::ScriptValue
+QmlObjectScriptClass::property(QObject *obj, const Identifier &name)
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ if (name == m_destroyId.identifier)
+ return Value(scriptEngine, m_destroy);
+ else if (name == m_toStringId.identifier)
+ return Value(scriptEngine, m_toString);
+
+ if (lastData && !lastData->isValid())
+ return Value();
+
+ Q_ASSERT(obj);
+
+ QmlEnginePrivate *enginePriv = QmlEnginePrivate::get(engine);
+
+ if (lastTNData) {
+
+ if (lastTNData->type)
+ return Value(scriptEngine, enginePriv->typeNameClass->newObject(obj, lastTNData->type));
+ else
+ return Value(scriptEngine, enginePriv->typeNameClass->newObject(obj, lastTNData->typeNamespace));
+
+ } else if (lastData->flags & QmlPropertyCache::Data::IsFunction) {
+ if (lastData->flags & QmlPropertyCache::Data::IsVMEFunction) {
+ return Value(scriptEngine, ((QmlVMEMetaObject *)(obj->metaObject()))->vmeMethod(lastData->coreIndex));
+ } else {
+#if (QT_VERSION > QT_VERSION_CHECK(4, 6, 2)) || defined(QT_HAVE_QSCRIPTDECLARATIVECLASS_VALUE)
+ // Uncomment to use QtScript method call logic
+ // QScriptValue sobj = scriptEngine->newQObject(obj);
+ // return Value(scriptEngine, sobj.property(toString(name)));
+ return Value(scriptEngine, methods.newMethod(obj, lastData));
+#else
+ QScriptValue sobj = scriptEngine->newQObject(obj);
+ return Value(scriptEngine, sobj.property(toString(name)));
+#endif
+ }
+ } else {
+ if (enginePriv->captureProperties && !(lastData->flags & QmlPropertyCache::Data::IsConstant)) {
+ enginePriv->capturedProperties <<
+ QmlEnginePrivate::CapturedProperty(obj, lastData->coreIndex, lastData->notifyIndex);
+ }
+
+ if ((uint)lastData->propType < QVariant::UserType) {
+ QmlValueType *valueType = enginePriv->valueTypes[lastData->propType];
+ if (valueType)
+ return Value(scriptEngine, enginePriv->valueTypeClass->newObject(obj, lastData->coreIndex, valueType));
+ }
+
+ if (lastData->flags & QmlPropertyCache::Data::IsQList) {
+ return Value(scriptEngine, enginePriv->listClass->newList(obj, lastData->coreIndex, QmlListScriptClass::QListPtr, lastData->propType));
+ } else if (lastData->flags & QmlPropertyCache::Data::IsQmlList) {
+ return Value(scriptEngine, enginePriv->listClass->newList(obj, lastData->coreIndex, QmlListScriptClass::QmlListPtr, lastData->propType));
+ } else if (lastData->flags & QmlPropertyCache::Data::IsQObjectDerived) {
+ QObject *rv = 0;
+ void *args[] = { &rv, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, lastData->coreIndex, args);
+ return Value(scriptEngine, newQObject(rv, lastData->propType));
+ } else if (lastData->flags & QmlPropertyCache::Data::IsQScriptValue) {
+ QScriptValue rv = scriptEngine->nullValue();
+ void *args[] = { &rv, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, lastData->coreIndex, args);
+ return Value(scriptEngine, rv);
+ } else if (lastData->propType == QMetaType::QReal) {
+ qreal rv = 0;
+ void *args[] = { &rv, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, lastData->coreIndex, args);
+ return Value(scriptEngine, rv);
+ } else if (lastData->propType == QMetaType::Int) {
+ int rv = 0;
+ void *args[] = { &rv, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, lastData->coreIndex, args);
+ return Value(scriptEngine, rv);
+ } else if (lastData->propType == QMetaType::Bool) {
+ bool rv = false;
+ void *args[] = { &rv, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, lastData->coreIndex, args);
+ return Value(scriptEngine, rv);
+ } else if (lastData->propType == QMetaType::QString) {
+ QString rv;
+ void *args[] = { &rv, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, lastData->coreIndex, args);
+ return Value(scriptEngine, rv);
+ } else if (lastData->propType == QMetaType::UInt) {
+ uint rv = 0;
+ void *args[] = { &rv, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, lastData->coreIndex, args);
+ return Value(scriptEngine, rv);
+ } else if (lastData->propType == QMetaType::Float) {
+ float rv = 0;
+ void *args[] = { &rv, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, lastData->coreIndex, args);
+ return Value(scriptEngine, rv);
+ } else if (lastData->propType == QMetaType::Double) {
+ double rv = 0;
+ void *args[] = { &rv, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, lastData->coreIndex, args);
+ return Value(scriptEngine, rv);
+ } else {
+ QVariant var = obj->metaObject()->property(lastData->coreIndex).read(obj);
+ return Value(scriptEngine, enginePriv->scriptValueFromVariant(var));
+ }
+
+ }
+}
+
+void QmlObjectScriptClass::setProperty(Object *object,
+ const Identifier &name,
+ const QScriptValue &value)
+{
+ return setProperty(toQObject(object), name, value);
+}
+
+void QmlObjectScriptClass::setProperty(QObject *obj,
+ const Identifier &name,
+ const QScriptValue &value,
+ QmlContext *evalContext)
+{
+ Q_UNUSED(name);
+
+ Q_ASSERT(obj);
+ Q_ASSERT(lastData);
+
+ if (!lastData->isValid()) {
+ QString error = QLatin1String("Cannot assign to non-existant property \"") +
+ toString(name) + QLatin1Char('\"');
+ if (context())
+ context()->throwError(error);
+ return;
+ }
+
+ if (!(lastData->flags & QmlPropertyCache::Data::IsWritable)) {
+ QString error = QLatin1String("Cannot assign to read-only property \"") +
+ toString(name) + QLatin1Char('\"');
+ if (context())
+ context()->throwError(error);
+ return;
+ }
+
+ QmlEnginePrivate *enginePriv = QmlEnginePrivate::get(engine);
+
+ if (!evalContext && context()) {
+ // Global object, QScriptContext activation object, QmlContext object
+ QScriptValue scopeNode = scopeChainValue(context(), -3);
+ if (scopeNode.isValid()) {
+ Q_ASSERT(scriptClass(scopeNode) == enginePriv->contextClass);
+
+ evalContext = enginePriv->contextClass->contextFromValue(scopeNode);
+ }
+ }
+
+ QmlAbstractBinding *delBinding = QmlMetaPropertyPrivate::setBinding(obj, *lastData, 0);
+ if (delBinding)
+ delBinding->destroy();
+
+ if (value.isUndefined() && lastData->flags & QmlPropertyCache::Data::IsResettable) {
+ void *a[] = { 0 };
+ QMetaObject::metacall(obj, QMetaObject::ResetProperty, lastData->coreIndex, a);
+ } else {
+ // ### Can well known types be optimized?
+ QVariant v = QmlScriptClass::toVariant(engine, value);
+ QmlMetaPropertyPrivate::write(obj, *lastData, v, evalContext);
+ }
+}
+
+bool QmlObjectScriptClass::isQObject() const
+{
+ return true;
+}
+
+QObject *QmlObjectScriptClass::toQObject(Object *object, bool *ok)
+{
+ if (ok) *ok = true;
+
+ ObjectData *data = (ObjectData*)object;
+ return data->object.data();
+}
+
+QScriptValue QmlObjectScriptClass::tostring(QScriptContext *context, QScriptEngine *)
+{
+ QObject* obj = context->thisObject().toQObject();
+
+ QString ret;
+ if(obj){
+ QString objectName = obj->objectName();
+
+ ret += QString::fromUtf8(obj->metaObject()->className());
+ ret += QLatin1String("(0x");
+ ret += QString::number((intptr_t)obj,16);
+
+ if (!objectName.isEmpty()) {
+ ret += QLatin1String(", \"");
+ ret += objectName;
+ ret += QLatin1Char('\"');
+ }
+
+ ret += QLatin1Char(')');
+ }else{
+ ret += QLatin1String("null");
+ }
+ return QScriptValue(ret);
+}
+
+QScriptValue QmlObjectScriptClass::destroy(QScriptContext *context, QScriptEngine *engine)
+{
+ QObject* obj = context->thisObject().toQObject();
+ if(obj){
+ int delay = 0;
+ if(context->argumentCount() > 0)
+ delay = context->argument(0).toInt32();
+ if (delay > 0)
+ QTimer::singleShot(delay, obj, SLOT(deleteLater()));
+ else
+ obj->deleteLater();
+ }
+ return engine->nullValue();
+}
+
+QStringList QmlObjectScriptClass::propertyNames(Object *object)
+{
+ QObject *obj = toQObject(object);
+ if (!obj)
+ return QStringList();
+
+ QmlEnginePrivate *enginePrivate = QmlEnginePrivate::get(engine);
+
+ QmlPropertyCache *cache = 0;
+ QmlDeclarativeData *ddata = QmlDeclarativeData::get(obj);
+ if (ddata)
+ cache = ddata->propertyCache;
+ if (!cache) {
+ cache = enginePrivate->cache(obj);
+ if (cache && ddata) { cache->addref(); ddata->propertyCache = cache; }
+ }
+
+ if (!cache)
+ return QStringList();
+
+ return cache->propertyNames();
+}
+
+#if (QT_VERSION > QT_VERSION_CHECK(4, 6, 2)) || defined(QT_HAVE_QSCRIPTDECLARATIVECLASS_VALUE)
+
+struct MethodData : public QScriptDeclarativeClass::Object {
+ MethodData(QObject *o, const QmlPropertyCache::Data &d) : object(o), data(d) {}
+
+ QmlGuard<QObject> object;
+ QmlPropertyCache::Data data;
+};
+
+QmlObjectMethodScriptClass::QmlObjectMethodScriptClass(QmlEngine *bindEngine)
+: QScriptDeclarativeClass(QmlEnginePrivate::getScriptEngine(bindEngine)),
+ engine(bindEngine)
+{
+ setSupportsCall(true);
+}
+
+QmlObjectMethodScriptClass::~QmlObjectMethodScriptClass()
+{
+}
+
+QScriptValue QmlObjectMethodScriptClass::newMethod(QObject *object, const QmlPropertyCache::Data *method)
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ return newObject(scriptEngine, this, new MethodData(object, *method));
+}
+
+namespace {
+struct MetaCallArgument {
+ inline MetaCallArgument();
+ inline ~MetaCallArgument();
+ inline void *dataPtr();
+
+ inline void initAsType(int type, QmlEngine *);
+ void fromScriptValue(int type, QmlEngine *, const QScriptValue &);
+ inline QScriptDeclarativeClass::Value toValue(QmlEngine *);
+
+private:
+ MetaCallArgument(const MetaCallArgument &);
+
+ inline void cleanup();
+
+ char *data[16];
+ int type;
+};
+}
+
+MetaCallArgument::MetaCallArgument()
+: type(QVariant::Invalid)
+{
+}
+
+MetaCallArgument::~MetaCallArgument()
+{
+ cleanup();
+}
+
+void MetaCallArgument::cleanup()
+{
+ if (type == QMetaType::QString) {
+ ((QString *)data)->~QString();
+ } else if (type == -1 || type == qMetaTypeId<QVariant>()) {
+ ((QVariant *)data)->~QVariant();
+ } else if (type == qMetaTypeId<QScriptValue>()) {
+ ((QScriptValue *)data)->~QScriptValue();
+ }
+}
+
+void *MetaCallArgument::dataPtr()
+{
+ if (type == -1)
+ return ((QVariant *)data)->data();
+ else
+ return (void *)data;
+}
+
+void MetaCallArgument::initAsType(int callType, QmlEngine *e)
+{
+ if (type != 0) { cleanup(); type = 0; }
+ if (callType == 0) return;
+
+ QScriptEngine *engine = QmlEnginePrivate::getScriptEngine(e);
+
+ if (callType == qMetaTypeId<QScriptValue>()) {
+ new (data) QScriptValue(engine->undefinedValue());
+ type = callType;
+ } else if (callType == QMetaType::Int ||
+ callType == QMetaType::UInt ||
+ callType == QMetaType::Bool ||
+ callType == QMetaType::Double ||
+ callType == QMetaType::Float) {
+ type = callType;
+ } else if (callType == QMetaType::QObjectStar) {
+ *((QObject **)data) = 0;
+ type = callType;
+ } else if (callType == QMetaType::QString) {
+ new (data) QString();
+ type = callType;
+ } else if (callType == qMetaTypeId<QVariant>()) {
+ type = qMetaTypeId<QVariant>();
+ new (data) QVariant();
+ } else {
+ type = -1;
+ new (data) QVariant(callType, (void *)0);
+ }
+}
+
+void MetaCallArgument::fromScriptValue(int callType, QmlEngine *engine, const QScriptValue &value)
+{
+ if (type != 0) { cleanup(); type = 0; }
+
+ if (callType == qMetaTypeId<QScriptValue>()) {
+ new (data) QScriptValue(value);
+ type = qMetaTypeId<QScriptValue>();
+ } else if (callType == QMetaType::Int) {
+ *((int *)data) = int(value.toInt32());
+ type = callType;
+ } else if (callType == QMetaType::UInt) {
+ *((uint *)data) = uint(value.toUInt32());
+ type = callType;
+ } else if (callType == QMetaType::Bool) {
+ *((bool *)data) = value.toBool();
+ type = callType;
+ } else if (callType == QMetaType::Double) {
+ *((double *)data) = double(value.toNumber());
+ type = callType;
+ } else if (callType == QMetaType::Float) {
+ *((float *)data) = float(value.toNumber());
+ type = callType;
+ } else if (callType == QMetaType::QString) {
+ if (value.isNull() || value.isUndefined())
+ new (data) QString();
+ else
+ new (data) QString(value.toString());
+ type = callType;
+ } else if (callType == QMetaType::QObjectStar) {
+ *((QObject **)data) = value.toQObject();
+ type = callType;
+ } else if (callType == qMetaTypeId<QVariant>()) {
+ new (data) QVariant(QmlScriptClass::toVariant(engine, value));
+ type = callType;
+ } else {
+ new (data) QVariant();
+ type = -1;
+
+ QVariant v = QmlScriptClass::toVariant(engine, value);
+ if (v.userType() == callType) {
+ *((QVariant *)data) = v;
+ } else if (v.canConvert((QVariant::Type)callType)) {
+ *((QVariant *)data) = v;
+ ((QVariant *)data)->convert((QVariant::Type)callType);
+ } else {
+ *((QVariant *)data) = QVariant(callType, (void *)0);
+ }
+ }
+}
+
+QScriptDeclarativeClass::Value MetaCallArgument::toValue(QmlEngine *e)
+{
+ QScriptEngine *engine = QmlEnginePrivate::getScriptEngine(e);
+
+ if (type == qMetaTypeId<QScriptValue>()) {
+ return QScriptDeclarativeClass::Value(engine, *((QScriptValue *)data));
+ } else if (type == QMetaType::Int) {
+ return QScriptDeclarativeClass::Value(engine, *((int *)data));
+ } else if (type == QMetaType::UInt) {
+ return QScriptDeclarativeClass::Value(engine, *((uint *)data));
+ } else if (type == QMetaType::Bool) {
+ return QScriptDeclarativeClass::Value(engine, *((bool *)data));
+ } else if (type == QMetaType::Double) {
+ return QScriptDeclarativeClass::Value(engine, *((double *)data));
+ } else if (type == QMetaType::Float) {
+ return QScriptDeclarativeClass::Value(engine, *((float *)data));
+ } else if (type == QMetaType::QString) {
+ return QScriptDeclarativeClass::Value(engine, *((QString *)data));
+ } else if (type == QMetaType::QObjectStar) {
+ return QScriptDeclarativeClass::Value(engine, QmlEnginePrivate::get(e)->objectClass->newQObject(*((QObject **)data)));
+ } else if (type == -1 || type == qMetaTypeId<QVariant>()) {
+ return QScriptDeclarativeClass::Value(engine, QmlEnginePrivate::get(e)->scriptValueFromVariant(*((QVariant *)data)));
+ } else {
+ return QScriptDeclarativeClass::Value();
+ }
+}
+
+QmlObjectMethodScriptClass::Value QmlObjectMethodScriptClass::call(Object *o, QScriptContext *ctxt)
+{
+ MethodData *method = static_cast<MethodData *>(o);
+
+ if (method->data.flags & QmlPropertyCache::Data::HasArguments) {
+
+ QMetaMethod m = method->object->metaObject()->method(method->data.coreIndex);
+ QList<QByteArray> argTypeNames = m.parameterTypes();
+ QVarLengthArray<int, 9> argTypes(argTypeNames.count());
+
+ // ### Cache
+ for (int ii = 0; ii < argTypeNames.count(); ++ii) {
+ argTypes[ii] = QMetaType::type(argTypeNames.at(ii));
+ if (argTypes[ii] == QVariant::Invalid)
+ return Value(ctxt, ctxt->throwError(QString(QLatin1String("Unknown method parameter type: %1")).arg(QLatin1String(argTypeNames.at(ii)))));
+ }
+
+ if (argTypes.count() > ctxt->argumentCount())
+ return Value(ctxt, ctxt->throwError("Insufficient arguments"));
+
+ QVarLengthArray<MetaCallArgument, 9> args(argTypes.count() + 1);
+ args[0].initAsType(method->data.propType, engine);
+
+ for (int ii = 0; ii < argTypes.count(); ++ii)
+ args[ii + 1].fromScriptValue(argTypes[ii], engine, ctxt->argument(ii));
+
+ QVarLengthArray<void *, 9> argData(args.count());
+ for (int ii = 0; ii < args.count(); ++ii)
+ argData[ii] = args[ii].dataPtr();
+
+ QMetaObject::metacall(method->object, QMetaObject::InvokeMetaMethod, method->data.coreIndex, argData.data());
+
+ return args[0].toValue(engine);
+
+ } else if (method->data.propType != 0) {
+
+ MetaCallArgument arg;
+ arg.initAsType(method->data.propType, engine);
+
+ void *args[] = { arg.dataPtr() };
+
+ QMetaObject::metacall(method->object, QMetaObject::InvokeMetaMethod, method->data.coreIndex, args);
+
+ return arg.toValue(engine);
+
+ } else {
+
+ void *args[] = { 0 };
+ QMetaObject::metacall(method->object, QMetaObject::InvokeMetaMethod, method->data.coreIndex, args);
+ return Value();
+
+ }
+ return Value();
+}
+
+#endif
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/qml/qmlobjectscriptclass_p.h b/src/declarative/qml/qmlobjectscriptclass_p.h
new file mode 100644
index 0000000..470c555
--- /dev/null
+++ b/src/declarative/qml/qmlobjectscriptclass_p.h
@@ -0,0 +1,144 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLOBJECTSCRIPTCLASS_P_H
+#define QMLOBJECTSCRIPTCLASS_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 "qmlpropertycache_p.h"
+#include "qmltypenamecache_p.h"
+
+#include <private/qmlscriptclass_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlEngine;
+class QScriptContext;
+class QScriptEngine;
+class QmlContext;
+
+#if (QT_VERSION > QT_VERSION_CHECK(4, 6, 2)) || defined(QT_HAVE_QSCRIPTDECLARATIVECLASS_VALUE)
+class Q_AUTOTEST_EXPORT QmlObjectMethodScriptClass : public QScriptDeclarativeClass
+{
+public:
+ QmlObjectMethodScriptClass(QmlEngine *);
+ ~QmlObjectMethodScriptClass();
+
+ QScriptValue newMethod(QObject *, const QmlPropertyCache::Data *);
+protected:
+ virtual Value call(Object *, QScriptContext *);
+
+private:
+ QmlEngine *engine;
+};
+#endif
+
+class Q_AUTOTEST_EXPORT QmlObjectScriptClass : public QmlScriptClass
+{
+public:
+ QmlObjectScriptClass(QmlEngine *);
+ ~QmlObjectScriptClass();
+
+ QScriptValue newQObject(QObject *, int type = QMetaType::QObjectStar);
+ QObject *toQObject(const QScriptValue &) const;
+ int objectType(const QScriptValue &) const;
+
+ enum QueryHint {
+ ImplicitObject = 0x01,
+ SkipAttachedProperties = 0x02
+ };
+ Q_DECLARE_FLAGS(QueryHints, QueryHint)
+
+ QScriptClass::QueryFlags queryProperty(QObject *, const Identifier &,
+ QScriptClass::QueryFlags flags,
+ QmlContext *evalContext,
+ QueryHints hints = 0);
+
+ ScriptValue property(QObject *, const Identifier &);
+
+ void setProperty(QObject *, const Identifier &name, const QScriptValue &,
+ QmlContext *evalContext = 0);
+ virtual QStringList propertyNames(Object *);
+
+protected:
+ virtual QScriptClass::QueryFlags queryProperty(Object *, const Identifier &,
+ QScriptClass::QueryFlags flags);
+
+ virtual ScriptValue property(Object *, const Identifier &);
+ virtual void setProperty(Object *, const Identifier &name, const QScriptValue &);
+ virtual bool isQObject() const;
+ virtual QObject *toQObject(Object *, bool *ok = 0);
+
+private:
+#if (QT_VERSION > QT_VERSION_CHECK(4, 6, 2)) || defined(QT_HAVE_QSCRIPTDECLARATIVECLASS_VALUE)
+ QmlObjectMethodScriptClass methods;
+#endif
+
+ QmlTypeNameCache::Data *lastTNData;
+ QmlPropertyCache::Data *lastData;
+ QmlPropertyCache::Data local;
+
+ PersistentIdentifier m_destroyId;
+ PersistentIdentifier m_toStringId;
+ QScriptValue m_destroy;
+ QScriptValue m_toString;
+
+ static QScriptValue tostring(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue destroy(QScriptContext *context, QScriptEngine *engine);
+
+ QmlEngine *engine;
+};
+Q_DECLARE_OPERATORS_FOR_FLAGS(QmlObjectScriptClass::QueryHints);
+
+QT_END_NAMESPACE
+
+#endif // QMLOBJECTSCRIPTCLASS_P_H
+
diff --git a/src/declarative/qml/qmlparser.cpp b/src/declarative/qml/qmlparser.cpp
new file mode 100644
index 0000000..02a9e70
--- /dev/null
+++ b/src/declarative/qml/qmlparser.cpp
@@ -0,0 +1,387 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlparser_p.h"
+
+#include "qmlpropertyvaluesource.h"
+#include "qmlvme_p.h"
+#include "qml.h"
+#include "qmlcomponent_p.h"
+#include "qmlcomponent.h"
+#include "qmetaobjectbuilder_p.h"
+#include "qmlvmemetaobject_p.h"
+#include "qmlcompiler_p.h"
+#include "parser/qmljsast_p.h"
+#include "parser/qmljsengine_p.h"
+
+#include <qfxperf_p_p.h>
+
+#include <QStack>
+#include <QColor>
+#include <QPointF>
+#include <QSizeF>
+#include <QRectF>
+#include <QtDebug>
+
+QT_BEGIN_NAMESPACE
+
+using namespace QmlJS;
+using namespace QmlParser;
+
+QmlParser::Object::Object()
+: type(-1), majorVersion(-1), minorVersion(-1), idIndex(-1), metatype(0), defaultProperty(0), parserStatusCast(-1)
+{
+}
+
+QmlParser::Object::~Object()
+{
+ if (defaultProperty) defaultProperty->release();
+ foreach(Property *prop, properties)
+ prop->release();
+ foreach(Property *prop, valueProperties)
+ prop->release();
+ foreach(Property *prop, signalProperties)
+ prop->release();
+ foreach(Property *prop, attachedProperties)
+ prop->release();
+ foreach(Property *prop, groupedProperties)
+ prop->release();
+ foreach(Property *prop, valueTypeProperties)
+ prop->release();
+ typedef QPair<Property *, int> PropPair;
+ foreach(const PropPair &prop, scriptStringProperties)
+ prop.first->release();
+ foreach(const DynamicProperty &prop, dynamicProperties)
+ if (prop.defaultValue) prop.defaultValue->release();
+ foreach(Object *obj, scriptBlockObjects)
+ obj->release();
+}
+
+void Object::setBindingBit(int b)
+{
+ while (bindingBitmask.size() < 4 * (1 + b / 32))
+ bindingBitmask.append(char(0));
+
+ quint32 *bits = (quint32 *)bindingBitmask.data();
+ bits[b / 32] |= (1 << (b % 32));
+}
+
+const QMetaObject *Object::metaObject() const
+{
+ if (!metadata.isEmpty() && metatype)
+ return &extObject;
+ else
+ return metatype;
+}
+
+QmlParser::Property *Object::getDefaultProperty()
+{
+ if (!defaultProperty) {
+ defaultProperty = new Property;
+ defaultProperty->parent = this;
+ }
+ return defaultProperty;
+}
+
+void QmlParser::Object::addValueProperty(Property *p)
+{
+ p->addref();
+ valueProperties << p;
+}
+
+void QmlParser::Object::addSignalProperty(Property *p)
+{
+ p->addref();
+ signalProperties << p;
+}
+
+void QmlParser::Object::addAttachedProperty(Property *p)
+{
+ p->addref();
+ attachedProperties << p;
+}
+
+void QmlParser::Object::addGroupedProperty(Property *p)
+{
+ p->addref();
+ groupedProperties << p;
+}
+
+void QmlParser::Object::addValueTypeProperty(Property *p)
+{
+ p->addref();
+ valueTypeProperties << p;
+}
+
+void QmlParser::Object::addScriptStringProperty(Property *p, int stack)
+{
+ p->addref();
+ scriptStringProperties << qMakePair(p, stack);
+}
+
+
+Property *QmlParser::Object::getProperty(const QByteArray &name, bool create)
+{
+ if (!properties.contains(name)) {
+ if (create) {
+ Property *property = new Property(name);
+ property->parent = this;
+ properties.insert(name, property);
+ } else {
+ return 0;
+ }
+ }
+ return properties[name];
+}
+
+QmlParser::Object::DynamicProperty::DynamicProperty()
+: isDefaultProperty(false), type(Variant), defaultValue(0)
+{
+}
+
+QmlParser::Object::DynamicProperty::DynamicProperty(const DynamicProperty &o)
+: isDefaultProperty(o.isDefaultProperty),
+ type(o.type),
+ customType(o.customType),
+ name(o.name),
+ defaultValue(o.defaultValue),
+ location(o.location)
+{
+}
+
+QmlParser::Object::DynamicSignal::DynamicSignal()
+{
+}
+
+QmlParser::Object::DynamicSignal::DynamicSignal(const DynamicSignal &o)
+: name(o.name), parameterTypes(o.parameterTypes),
+ parameterNames(o.parameterNames)
+{
+}
+
+QmlParser::Object::DynamicSlot::DynamicSlot()
+{
+}
+
+QmlParser::Object::DynamicSlot::DynamicSlot(const DynamicSlot &o)
+: name(o.name), body(o.body), parameterNames(o.parameterNames)
+{
+}
+
+QmlParser::Property::Property()
+: parent(0), type(0), index(-1), value(0), isDefault(true), isDeferred(false)
+{
+}
+
+QmlParser::Property::Property(const QByteArray &n)
+: parent(0), type(0), index(-1), value(0), name(n), isDefault(false),
+ isDeferred(false)
+{
+}
+
+QmlParser::Property::~Property()
+{
+ foreach(Value *value, values)
+ value->release();
+ if (value) value->release();
+}
+
+Object *QmlParser::Property::getValue()
+{
+ if (!value) value = new Object;
+ return value;
+}
+
+void QmlParser::Property::addValue(Value *v)
+{
+ values << v;
+}
+
+bool QmlParser::Property::isEmpty() const
+{
+ return !value && values.isEmpty();
+}
+
+QmlParser::Value::Value()
+: type(Unknown), object(0)
+{
+}
+
+QmlParser::Value::~Value()
+{
+ if (object) object->release();
+}
+
+QmlParser::Variant::Variant()
+: t(Invalid) {}
+
+QmlParser::Variant::Variant(const Variant &o)
+: t(o.t), d(o.d), s(o.s)
+{
+}
+
+QmlParser::Variant::Variant(bool v)
+: t(Boolean), b(v)
+{
+}
+
+QmlParser::Variant::Variant(double v, const QString &asWritten)
+: t(Number), d(v), s(asWritten)
+{
+}
+
+QmlParser::Variant::Variant(const QString &v)
+: t(String), s(v)
+{
+}
+
+QmlParser::Variant::Variant(const QString &v, QmlJS::AST::Node *n)
+: t(Script), n(n), s(v)
+{
+}
+
+QmlParser::Variant &QmlParser::Variant::operator=(const Variant &o)
+{
+ t = o.t;
+ d = o.d;
+ s = o.s;
+ return *this;
+}
+
+QmlParser::Variant::Type QmlParser::Variant::type() const
+{
+ return t;
+}
+
+bool QmlParser::Variant::asBoolean() const
+{
+ return b;
+}
+
+QString QmlParser::Variant::asString() const
+{
+ return s;
+}
+
+double QmlParser::Variant::asNumber() const
+{
+ return d;
+}
+
+QString QmlParser::Variant::asScript() const
+{
+ switch(type()) {
+ default:
+ case Invalid:
+ return QString();
+ case Boolean:
+ return b?QLatin1String("true"):QLatin1String("false");
+ case Number:
+ if (s.isEmpty())
+ return QString::number(d);
+ else
+ return s;
+ case String:
+ case Script:
+ return s;
+ }
+}
+
+QmlJS::AST::Node *QmlParser::Variant::asAST() const
+{
+ if (type() == Script)
+ return n;
+ else
+ return 0;
+}
+
+bool QmlParser::Variant::isStringList() const
+{
+ if (isString())
+ return true;
+
+ if (type() != Script || !n)
+ return false;
+
+ AST::ArrayLiteral *array = AST::cast<AST::ArrayLiteral *>(n);
+ if (!array)
+ return false;
+
+ AST::ElementList *elements = array->elements;
+
+ while (elements) {
+
+ if (!AST::cast<AST::StringLiteral *>(elements->expression))
+ return false;
+
+ elements = elements->next;
+ }
+
+ return true;
+}
+
+QStringList QmlParser::Variant::asStringList() const
+{
+ QStringList rv;
+ if (isString()) {
+ rv << asString();
+ return rv;
+ }
+
+ AST::ArrayLiteral *array = AST::cast<AST::ArrayLiteral *>(n);
+ if (!array)
+ return rv;
+
+ AST::ElementList *elements = array->elements;
+ while (elements) {
+
+ AST::StringLiteral *string = AST::cast<AST::StringLiteral *>(elements->expression);
+ if (!string)
+ return QStringList();
+ rv.append(string->value->asString());
+
+ elements = elements->next;
+ }
+
+ return rv;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlparser_p.h b/src/declarative/qml/qmlparser_p.h
new file mode 100644
index 0000000..aa7a762
--- /dev/null
+++ b/src/declarative/qml/qmlparser_p.h
@@ -0,0 +1,357 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPARSER_P_H
+#define QMLPARSER_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 "qml.h"
+#include "qmlrefcount_p.h"
+
+#include <QtCore/QByteArray>
+#include <QtCore/QList>
+#include <QtCore/qstring.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+namespace QmlJS { namespace AST { class Node; } }
+
+/*
+ XXX
+
+ These types are created (and owned) by the QmlXmlParser and consumed by the
+ QmlCompiler. During the compilation phase the compiler will update some of
+ the fields for both its own use and for the use of the upcoming QmlDom API.
+
+ The types are part of the generic sounding "QmlParser" namespace for legacy
+ reasons (there used to be more in this namespace) and will be cleaned up and
+ migrated into a more appropriate location shortly.
+*/
+namespace QmlParser
+{
+ struct Location
+ {
+ Location() : line(-1), column(-1) {}
+ int line;
+ int column;
+ };
+
+ struct LocationRange
+ {
+ LocationRange() : offset(0), length(0) {}
+ quint32 offset;
+ quint32 length;
+ };
+
+ struct LocationSpan
+ {
+ Location start;
+ Location end;
+ LocationRange range;
+ };
+
+ class Property;
+ class Object : public QmlRefCount
+ {
+ public:
+ Object();
+ virtual ~Object();
+
+ // Type of the object. The integer is an index into the
+ // QmlCompiledData::types array, or -1 if the object is a property
+ // group.
+ int type;
+ // The url of this object if it is an external type. Used by the DOM
+ QUrl url;
+
+ // version information if type is defined in library or C++
+ int majorVersion;
+ int minorVersion;
+
+ // The fully-qualified name of this type
+ QByteArray typeName;
+ // The class name
+ QByteArray className;
+ // The id assigned to the object (if any). Set by the QmlCompiler
+ QString id;
+ // The id index assigned to the object (if any). Set by the QmlCompiler
+ int idIndex;
+ // Custom parsed data
+ QByteArray custom;
+ // Bit mask of the properties assigned bindings
+ QByteArray bindingBitmask;
+ void setBindingBit(int);
+ // Returns the metaobject for this type, or 0 if not available.
+ // Internally selectd between the metatype and extObject variables
+ const QMetaObject *metaObject() const;
+
+ // The compile time metaobject for this type
+ const QMetaObject *metatype;
+ // The synthesized metaobject, if QML added signals or properties to
+ // this type. Otherwise null
+ QAbstractDynamicMetaObject extObject;
+ QByteArray metadata; // Generated by compiler
+ QByteArray synthdata; // Generated by compiler
+
+ Property *getDefaultProperty();
+ Property *getProperty(const QByteArray &name, bool create=true);
+
+ Property *defaultProperty;
+ QHash<QByteArray, Property *> properties;
+
+ QList<Object *> scriptBlockObjects;
+
+ // Output of the compilation phase (these properties continue to exist
+ // in either the defaultProperty or properties members too)
+ void addValueProperty(Property *);
+ void addSignalProperty(Property *);
+ void addAttachedProperty(Property *);
+ void addGroupedProperty(Property *);
+ void addValueTypeProperty(Property *);
+ void addScriptStringProperty(Property *, int = 0);
+ QList<Property *> valueProperties;
+ QList<Property *> signalProperties;
+ QList<Property *> attachedProperties;
+ QList<Property *> groupedProperties;
+ QList<Property *> valueTypeProperties;
+ QList<QPair<Property *, int> > scriptStringProperties;
+
+ // Script blocks that were nested under this object
+ struct ScriptBlock {
+ QStringList codes;
+ QStringList files;
+ QList<int> lineNumbers;
+ };
+ QList<ScriptBlock> scripts;
+
+ // The bytes to cast instances by to get to the QmlParserStatus
+ // interface. -1 indicates the type doesn't support this interface.
+ // Set by the QmlCompiler.
+ int parserStatusCast;
+
+ LocationSpan location;
+
+ struct DynamicProperty {
+ DynamicProperty();
+ DynamicProperty(const DynamicProperty &);
+
+ enum Type { Variant, Int, Bool, Real, String, Url, Color, Date, Alias, Custom, CustomList };
+
+ bool isDefaultProperty;
+ Type type;
+ QByteArray customType;
+ QByteArray name;
+ QmlParser::Property *defaultValue;
+ LocationSpan location;
+ };
+ struct DynamicSignal {
+ DynamicSignal();
+ DynamicSignal(const DynamicSignal &);
+
+ QByteArray name;
+ QList<QByteArray> parameterTypes;
+ QList<QByteArray> parameterNames;
+ };
+ struct DynamicSlot {
+ DynamicSlot();
+ DynamicSlot(const DynamicSlot &);
+
+ QByteArray name;
+ QString body;
+ QList<QByteArray> parameterNames;
+ };
+
+ // The list of dynamic properties
+ QList<DynamicProperty> dynamicProperties;
+ // The list of dynamic signals
+ QList<DynamicSignal> dynamicSignals;
+ // The list of dynamic slots
+ QList<DynamicSlot> dynamicSlots;
+ };
+
+ class Variant
+ {
+ public:
+ enum Type {
+ Invalid,
+ Boolean,
+ Number,
+ String,
+ Script
+ };
+
+ Variant();
+ Variant(const Variant &);
+ Variant(bool);
+ Variant(double, const QString &asWritten=QString());
+ Variant(const QString &);
+ Variant(const QString &, QmlJS::AST::Node *);
+ Variant &operator=(const Variant &);
+
+ Type type() const;
+
+ bool isBoolean() const { return type() == Boolean; }
+ bool isNumber() const { return type() == Number; }
+ bool isString() const { return type() == String; }
+ bool isScript() const { return type() == Script; }
+ bool isStringList() const;
+
+ bool asBoolean() const;
+ QString asString() const;
+ double asNumber() const;
+ QString asScript() const;
+ QmlJS::AST::Node *asAST() const;
+ QStringList asStringList() const;
+
+ private:
+ Type t;
+ union {
+ bool b;
+ double d;
+ QmlJS::AST::Node *n;
+ };
+ QString s;
+ };
+
+ class Value : public QmlRefCount
+ {
+ public:
+ Value();
+ virtual ~Value();
+
+ enum Type {
+ // The type of this value assignment is not yet known
+ Unknown,
+ // This is used as a literal property assignment
+ Literal,
+ // This is used as a property binding assignment
+ PropertyBinding,
+ // This is used as a QmlPropertyValueSource assignment
+ ValueSource,
+ // This is used as a QmlPropertyValueInterceptor assignment
+ ValueInterceptor,
+ // This is used as a property QObject assignment
+ CreatedObject,
+ // This is used as a signal object assignment
+ SignalObject,
+ // This is used as a signal expression assignment
+ SignalExpression,
+ // This is used as an id assignment only
+ Id
+ };
+ Type type;
+
+ // ### Temporary
+ QString primitive() const { return value.asScript(); }
+
+ // Primitive value
+ Variant value;
+ // Object value
+ Object *object;
+
+ LocationSpan location;
+ };
+
+ class Property : public QmlRefCount
+ {
+ public:
+ Property();
+ Property(const QByteArray &n);
+ virtual ~Property();
+
+ // The Object to which this property is attached
+ Object *parent;
+
+ Object *getValue();
+ void addValue(Value *v);
+
+ // The QVariant::Type of the property, or 0 (QVariant::Invalid) if
+ // unknown.
+ int type;
+ // The metaobject index of this property, or -1 if unknown.
+ int index;
+
+ // Returns true if this is an empty property - both value and values
+ // are unset.
+ bool isEmpty() const;
+ // The list of values assigned to this property. Content in values
+ // and value are mutually exclusive
+ QList<Value *> values;
+ // The accessed property. This is used to represent dot properties.
+ // Content in value and values are mutually exclusive.
+ Object *value;
+ // The property name
+ QByteArray name;
+ // True if this property was accessed as the default property.
+ bool isDefault;
+ // True if the setting of this property will be deferred. Set by the
+ // QmlCompiler
+ bool isDeferred;
+
+ LocationSpan location;
+ LocationRange listValueRange;
+ QList<int> listCommaPositions;
+ };
+}
+
+QT_END_NAMESPACE
+
+Q_DECLARE_METATYPE(QmlParser::Variant)
+
+QT_END_HEADER
+
+#endif // QMLPARSER_P_H
diff --git a/src/declarative/qml/qmlparserstatus.cpp b/src/declarative/qml/qmlparserstatus.cpp
new file mode 100644
index 0000000..69ccfda
--- /dev/null
+++ b/src/declarative/qml/qmlparserstatus.cpp
@@ -0,0 +1,80 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlparserstatus.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QmlParserStatus
+ \brief The QmlParserStatus class provides updates on the parser state.
+*/
+
+/*! \internal */
+QmlParserStatus::QmlParserStatus()
+: d(0)
+{
+}
+
+/*! \internal */
+QmlParserStatus::~QmlParserStatus()
+{
+ if(d)
+ (*d) = 0;
+}
+
+/*!
+ Invoked after class creation, but before any properties have been set.
+*/
+void QmlParserStatus::classBegin()
+{
+}
+
+/*!
+ Invoked after the root component that caused this instantiation has
+ completed construction. At this point all static values and binding values
+ have been assigned to the class.
+*/
+void QmlParserStatus::componentComplete()
+{
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlparserstatus.h b/src/declarative/qml/qmlparserstatus.h
new file mode 100644
index 0000000..e12c7b5
--- /dev/null
+++ b/src/declarative/qml/qmlparserstatus.h
@@ -0,0 +1,75 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPARSERSTATUS_H
+#define QMLPARSERSTATUS_H
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class Q_DECLARATIVE_EXPORT QmlParserStatus
+{
+public:
+ QmlParserStatus();
+ virtual ~QmlParserStatus();
+
+ virtual void classBegin();
+ virtual void componentComplete();
+
+private:
+ friend class QmlVME;
+ friend class QmlComponent;
+ friend class QmlComponentPrivate;
+ friend class QmlEnginePrivate;
+ QmlParserStatus **d;
+};
+Q_DECLARE_INTERFACE(QmlParserStatus, "com.trolltech.qml.QmlParserStatus")
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLPARSERSTATUS_H
diff --git a/src/declarative/qml/qmlprivate.cpp b/src/declarative/qml/qmlprivate.cpp
new file mode 100644
index 0000000..01353cc
--- /dev/null
+++ b/src/declarative/qml/qmlprivate.cpp
@@ -0,0 +1,48 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlprivate.h"
+
+QT_BEGIN_NAMESPACE
+
+QmlPrivate::InstanceType::InstanceType(int) {}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlprivate.h b/src/declarative/qml/qmlprivate.h
new file mode 100644
index 0000000..dd98110
--- /dev/null
+++ b/src/declarative/qml/qmlprivate.h
@@ -0,0 +1,386 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPRIVATE_H
+#define QMLPRIVATE_H
+
+#include <QtCore/qglobal.h>
+
+#ifndef Q_OS_WIN
+#include <stdint.h>
+#endif
+#include <QtCore/qvariant.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+typedef QObject *(*QmlAttachedPropertiesFunc)(QObject *);
+
+//template<typename T>
+//struct qml_hasAttached { static bool const value = false; };
+
+template <typename TYPE>
+class QmlTypeInfo
+{
+public:
+ enum {
+ hasAttachedProperties = 0
+ };
+};
+
+
+namespace QmlPrivate
+{
+ class ListInterface
+ {
+ public:
+ virtual ~ListInterface() {}
+ virtual int type() const = 0;
+ virtual void append(void *) = 0;
+ virtual void insert(int, void *) = 0;
+ virtual void removeAt(int) = 0;
+ virtual void at(int, void *) const = 0;
+ virtual int count() const = 0;
+ virtual void clear() = 0;
+ };
+
+ enum ListOp { Append, Set, Insert, Prepend, Length, FromObject,
+ Object, Create, Value, Clear };
+
+ template<typename T>
+ int list_op(ListOp op, int val,
+ const QVariant &vlist,
+ const QVariant &value,
+ void **out);
+
+ template<typename T>
+ int list_nocreate_op(ListOp op, int val,
+ const QVariant &vlist,
+ const QVariant &value,
+ void **out);
+
+ template<typename T>
+ int list_interface_op(ListOp op, int val,
+ const QVariant &vlist,
+ const QVariant &value,
+ void **out);
+
+ template<class From, class To, int N>
+ struct StaticCastSelectorClass
+ {
+ static inline int cast() { return -1; }
+ };
+
+ template<class From, class To>
+ struct StaticCastSelectorClass<From, To, sizeof(int)>
+ {
+ static inline int cast() { return (int)((intptr_t)static_cast<To *>((From *)0x10000000)) - 0x10000000; }
+ };
+
+ template<class From, class To>
+ struct StaticCastSelector
+ {
+ typedef int yes_type;
+ typedef char no_type;
+
+ static yes_type check(To *);
+ static no_type check(...);
+
+ static inline int cast()
+ {
+ return StaticCastSelectorClass<From, To, sizeof(check((From *)0))>::cast();
+ }
+ };
+
+ template <typename T>
+ struct has_attachedPropertiesMember
+ {
+ static bool const value = QmlTypeInfo<T>::hasAttachedProperties;
+ };
+
+ template <typename T, bool hasMember>
+ class has_attachedPropertiesMethod
+ {
+ typedef int yes_type;
+ typedef char no_type;
+
+ template<typename ReturnType>
+ static yes_type check(ReturnType *(*)(QObject *));
+ static no_type check(...);
+
+ public:
+ static bool const value = sizeof(check(&T::qmlAttachedProperties)) == sizeof(yes_type);
+ };
+
+ template <typename T>
+ class has_attachedPropertiesMethod<T, false>
+ {
+ public:
+ static bool const value = false;
+ };
+
+ template<typename T, int N>
+ class AttachedPropertySelector
+ {
+ public:
+ static inline QmlAttachedPropertiesFunc func() { return 0; }
+ static inline const QMetaObject *metaObject() { return 0; }
+ };
+ template<typename T>
+ class AttachedPropertySelector<T, 1>
+ {
+ static inline QObject *attachedProperties(QObject *obj) {
+ return T::qmlAttachedProperties(obj);
+ }
+ template<typename ReturnType>
+ static inline const QMetaObject *attachedPropertiesMetaObject(ReturnType *(*)(QObject *)) {
+ return &ReturnType::staticMetaObject;
+ }
+ public:
+ static inline QmlAttachedPropertiesFunc func() {
+ return &attachedProperties;
+ }
+ static inline const QMetaObject *metaObject() {
+ return attachedPropertiesMetaObject(&T::qmlAttachedProperties);
+ }
+ };
+
+ template<typename T>
+ inline QmlAttachedPropertiesFunc attachedPropertiesFunc()
+ {
+ return AttachedPropertySelector<T, has_attachedPropertiesMethod<T, has_attachedPropertiesMember<T>::value>::value>::func();
+ }
+
+ template<typename T>
+ inline const QMetaObject *attachedPropertiesMetaObject()
+ {
+ return AttachedPropertySelector<T, has_attachedPropertiesMethod<T, has_attachedPropertiesMember<T>::value>::value>::metaObject();
+ }
+
+ struct MetaTypeIds {
+ int typeId;
+ int listId;
+ int qmlListId;
+ };
+ typedef int (*Func)(QmlPrivate::ListOp, int, const QVariant &, const QVariant &, void **);
+ typedef QObject *(*CreateFunc)(QObject *);
+
+ template<typename T>
+ struct CreateParent {
+ static QObject *create(QObject *other) {
+ return new T(other);
+ }
+ };
+
+ template<typename T>
+ struct CreateNoParent {
+ static QObject *create() {
+ return new T;
+ }
+ };
+
+ struct Q_DECLARATIVE_EXPORT InstanceType {
+ InstanceType(int);
+ };
+
+ template<typename T, int VMAJ, int VMIN>
+ struct Define {
+ static InstanceType instance;
+ };
+
+ template<typename T>
+ struct ExtCreate {
+ static QObject *create(QObject *other) {
+ return new T(other);
+ }
+ };
+}
+
+template<typename T>
+int QmlPrivate::list_op(QmlPrivate::ListOp op, int val,
+ const QVariant &vlist,
+ const QVariant &value,
+ void **out)
+{
+ if (op == QmlPrivate::Create) {
+ QObject *obj = static_cast<QObject *>(new T);
+ *((QObject **)out) = obj;
+ return 0;
+ }
+ QList<T *> *list = vlist.value<QList<T *> *>();
+ switch(op) {
+ case QmlPrivate::Append:
+ list->append(value.value<T *>());
+ break;
+ case QmlPrivate::Set:
+ (*list)[val] = value.value<T *>();
+ break;
+ case QmlPrivate::Insert:
+ list->insert(val, value.value<T *>());
+ break;
+ case QmlPrivate::Prepend:
+ list->prepend(value.value<T *>());
+ break;
+ case QmlPrivate::Length:
+ return list->count();
+ break;
+ case QmlPrivate::Clear:
+ list->clear();
+ return 0;
+ break;
+ case QmlPrivate::Create:
+ break;
+ case QmlPrivate::Object:
+ *out = static_cast<QObject *>(value.value<T *>());
+ break;
+ case QmlPrivate::FromObject:
+ {
+ QObject *fromObj = value.value<QObject *>();
+ T *me = qobject_cast<T *>(fromObj);
+ if (me) {
+ *((QVariant *)*out) = QVariant::fromValue(me);
+ }
+ }
+ break;
+ case QmlPrivate::Value:
+ if (list->count() <= val) *((QVariant *)*out) = QVariant();
+ else *((QVariant *)*out) = QVariant::fromValue(list->at(val));
+ break;
+ }
+ return 0;
+}
+
+template<typename T>
+int QmlPrivate::list_nocreate_op(QmlPrivate::ListOp op, int val,
+ const QVariant &vlist,
+ const QVariant &value,
+ void **out)
+{
+ QList<T *> *list = vlist.value<QList<T *> *>();
+ switch(op) {
+ case QmlPrivate::Append:
+ list->append(value.value<T *>());
+ break;
+ case QmlPrivate::Set:
+ (*list)[val] = value.value<T *>();
+ break;
+ case QmlPrivate::Insert:
+ list->insert(val, value.value<T *>());
+ break;
+ case QmlPrivate::Prepend:
+ list->prepend(value.value<T *>());
+ break;
+ case QmlPrivate::Length:
+ return list->count();
+ break;
+ case QmlPrivate::Clear:
+ list->clear();
+ return 0;
+ break;
+ case QmlPrivate::Create:
+ break;
+ case QmlPrivate::Object:
+ *out = static_cast<QObject *>(value.value<T *>());
+ break;
+ case QmlPrivate::FromObject:
+ {
+ QObject *fromObj = value.value<QObject *>();
+ T *me = qobject_cast<T *>(fromObj);
+ if (me) {
+ *((QVariant *)*out) = QVariant::fromValue(me);
+ }
+ }
+ break;
+ case QmlPrivate::Value:
+ *((QVariant *)*out) = QVariant::fromValue(list->at(val));
+ break;
+ }
+ return 0;
+}
+
+template<typename T>
+int QmlPrivate::list_interface_op(QmlPrivate::ListOp op, int val,
+ const QVariant &vlist,
+ const QVariant &value,
+ void **out)
+{
+ QList<T *> *list = vlist.value<QList<T *> *>();
+ switch(op) {
+ case QmlPrivate::Append:
+ list->append(value.value<T *>());
+ break;
+ case QmlPrivate::Set:
+ (*list)[val] = value.value<T *>();
+ break;
+ case QmlPrivate::Insert:
+ list->insert(val, value.value<T *>());
+ break;
+ case QmlPrivate::Prepend:
+ list->prepend(value.value<T *>());
+ break;
+ case QmlPrivate::Length:
+ return list->count();
+ break;
+ case QmlPrivate::Clear:
+ list->clear();
+ return 0;
+ break;
+ case QmlPrivate::Create:
+ break;
+ case QmlPrivate::Object:
+ break;
+ case QmlPrivate::FromObject:
+ break;
+ case QmlPrivate::Value:
+ *((QVariant *)*out) = QVariant::fromValue(list->at(val));
+ break;
+ }
+ return 0;
+}
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLPRIVATE_H
diff --git a/src/declarative/qml/qmlpropertycache.cpp b/src/declarative/qml/qmlpropertycache.cpp
new file mode 100644
index 0000000..04cffe1
--- /dev/null
+++ b/src/declarative/qml/qmlpropertycache.cpp
@@ -0,0 +1,415 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlpropertycache_p.h"
+
+#include "qmlengine_p.h"
+#include "qmlbinding.h"
+#include "qdebug.h"
+
+QT_BEGIN_NAMESPACE
+
+Q_DECLARE_METATYPE(QScriptValue);
+
+void QmlPropertyCache::Data::load(const QMetaProperty &p, QmlEngine *engine)
+{
+ propType = p.userType();
+ if (QVariant::Type(propType) == QVariant::LastType)
+ propType = qMetaTypeId<QVariant>();
+ coreIndex = p.propertyIndex();
+ notifyIndex = p.notifySignalIndex();
+
+ if (p.isConstant())
+ flags |= Data::IsConstant;
+ if (p.isWritable())
+ flags |= Data::IsWritable;
+ if (p.isResettable())
+ flags |= Data::IsResettable;
+
+ if (propType == qMetaTypeId<QmlBinding *>()) {
+ flags |= Data::IsQmlBinding;
+ } else if (propType == qMetaTypeId<QScriptValue>()) {
+ flags |= Data::IsQScriptValue;
+ } else if (p.isEnumType()) {
+ flags |= Data::IsEnumType;
+ } else {
+ QmlMetaType::TypeCategory cat = engine ? QmlEnginePrivate::get(engine)->typeCategory(propType)
+ : QmlMetaType::typeCategory(propType);
+ if (cat == QmlMetaType::Object)
+ flags |= Data::IsQObjectDerived;
+ else if (cat == QmlMetaType::List)
+ flags |= Data::IsQList;
+ else if (cat == QmlMetaType::QmlList)
+ flags |= Data::IsQmlList;
+ }
+}
+
+void QmlPropertyCache::Data::load(const QMetaMethod &m)
+{
+ coreIndex = m.methodIndex();
+ flags |= Data::IsFunction;
+ propType = QVariant::Invalid;
+
+ const char *returnType = m.typeName();
+ if (returnType)
+ propType = QMetaType::type(returnType);
+
+ QList<QByteArray> params = m.parameterTypes();
+ if (!params.isEmpty())
+ flags |= Data::HasArguments;
+}
+
+
+QmlPropertyCache::QmlPropertyCache(QmlEngine *e)
+: QmlCleanup(e), engine(e)
+{
+}
+
+QmlPropertyCache::~QmlPropertyCache()
+{
+ clear();
+}
+
+void QmlPropertyCache::clear()
+{
+ for (int ii = 0; ii < indexCache.count(); ++ii)
+ indexCache.at(ii)->release();
+
+ for (StringCache::ConstIterator iter = stringCache.begin();
+ iter != stringCache.end(); ++iter)
+ (*iter)->release();
+
+ for (IdentifierCache::ConstIterator iter = identifierCache.begin();
+ iter != identifierCache.end(); ++iter)
+ (*iter)->release();
+
+ indexCache.clear();
+ stringCache.clear();
+ identifierCache.clear();
+}
+
+QmlPropertyCache::Data QmlPropertyCache::create(const QMetaObject *metaObject,
+ const QString &property)
+{
+ Q_ASSERT(metaObject);
+
+ QmlPropertyCache::Data rv;
+ int idx = metaObject->indexOfProperty(property.toUtf8());
+ if (idx != -1) {
+ rv.load(metaObject->property(idx));
+ return rv;
+ }
+
+ int methodCount = metaObject->methodCount();
+ for (int ii = methodCount - 1; ii >= 0; --ii) {
+ QMetaMethod m = metaObject->method(ii);
+ if (m.access() == QMetaMethod::Private)
+ continue;
+ QString methodName = QString::fromUtf8(m.signature());
+
+ int parenIdx = methodName.indexOf(QLatin1Char('('));
+ Q_ASSERT(parenIdx != -1);
+ methodName = methodName.left(parenIdx);
+
+ if (methodName == property) {
+ rv.load(m);
+ return rv;
+ }
+ }
+
+ return rv;
+}
+
+QmlPropertyCache *QmlPropertyCache::copy() const
+{
+ QmlPropertyCache *cache = new QmlPropertyCache(engine);
+ cache->indexCache = indexCache;
+ cache->stringCache = stringCache;
+ cache->identifierCache = identifierCache;
+
+ for (int ii = 0; ii < indexCache.count(); ++ii)
+ indexCache.at(ii)->addref();
+ for (StringCache::ConstIterator iter = stringCache.begin(); iter != stringCache.end(); ++iter)
+ (*iter)->addref();
+ for (IdentifierCache::ConstIterator iter = identifierCache.begin(); iter != identifierCache.end(); ++iter)
+ (*iter)->addref();
+
+ return cache;
+}
+
+void QmlPropertyCache::append(QmlEngine *engine, const QMetaObject *metaObject,
+ Data::Flag propertyFlags, Data::Flag methodFlags)
+{
+ QmlEnginePrivate *enginePriv = QmlEnginePrivate::get(engine);
+
+ int propCount = metaObject->propertyCount();
+ int propOffset = metaObject->propertyOffset();
+
+ indexCache.resize(propCount);
+ for (int ii = propOffset; ii < propCount; ++ii) {
+ QMetaProperty p = metaObject->property(ii);
+ QString propName = QString::fromUtf8(p.name());
+
+ RData *data = new RData;
+ data->identifier = enginePriv->objectClass->createPersistentIdentifier(propName);
+
+ data->load(p, engine);
+ data->flags |= propertyFlags;
+
+ indexCache[ii] = data;
+
+ if (stringCache.contains(propName)) {
+ stringCache[propName]->release();
+ identifierCache[data->identifier.identifier]->release();
+ }
+
+ stringCache.insert(propName, data);
+ identifierCache.insert(data->identifier.identifier, data);
+ data->addref();
+ data->addref();
+ }
+
+ int methodCount = metaObject->methodCount();
+ int methodOffset = metaObject->methodOffset();
+ for (int ii = methodOffset; ii < methodCount; ++ii) {
+ QMetaMethod m = metaObject->method(ii);
+ if (m.access() == QMetaMethod::Private)
+ continue;
+ QString methodName = QString::fromUtf8(m.signature());
+
+ int parenIdx = methodName.indexOf(QLatin1Char('('));
+ Q_ASSERT(parenIdx != -1);
+ methodName = methodName.left(parenIdx);
+
+ RData *data = new RData;
+ data->identifier = enginePriv->objectClass->createPersistentIdentifier(methodName);
+
+ if (stringCache.contains(methodName)) {
+ stringCache[methodName]->release();
+ identifierCache[data->identifier.identifier]->release();
+ }
+
+ data->load(m);
+ if (m.methodType() == QMetaMethod::Slot || m.methodType() == QMetaMethod::Method)
+ data->flags |= methodFlags;
+
+ stringCache.insert(methodName, data);
+ identifierCache.insert(data->identifier.identifier, data);
+ data->addref();
+ }
+}
+
+// ### Optimize - check engine for the parent meta object etc.
+QmlPropertyCache *QmlPropertyCache::create(QmlEngine *engine, const QMetaObject *metaObject)
+{
+ Q_ASSERT(engine);
+ Q_ASSERT(metaObject);
+
+ QmlPropertyCache *cache = new QmlPropertyCache(engine);
+ cache->update(engine, metaObject);
+ return cache;
+}
+
+void QmlPropertyCache::update(QmlEngine *engine, const QMetaObject *metaObject)
+{
+ Q_ASSERT(engine);
+ Q_ASSERT(metaObject);
+ QmlEnginePrivate *enginePriv = QmlEnginePrivate::get(engine);
+
+ clear();
+
+ // ### The properties/methods should probably be spliced on a per-metaobject basis
+ int propCount = metaObject->propertyCount();
+
+ indexCache.resize(propCount);
+ for (int ii = propCount - 1; ii >= 0; --ii) {
+ QMetaProperty p = metaObject->property(ii);
+ QString propName = QString::fromUtf8(p.name());
+
+ RData *data = new RData;
+ data->identifier = enginePriv->objectClass->createPersistentIdentifier(propName);
+
+ data->load(p, engine);
+
+ indexCache[ii] = data;
+
+ if (stringCache.contains(propName))
+ continue;
+
+ stringCache.insert(propName, data);
+ identifierCache.insert(data->identifier.identifier, data);
+ data->addref();
+ data->addref();
+ }
+
+ int methodCount = metaObject->methodCount();
+ for (int ii = methodCount - 1; ii >= 0; --ii) {
+ QMetaMethod m = metaObject->method(ii);
+ if (m.access() == QMetaMethod::Private)
+ continue;
+ QString methodName = QString::fromUtf8(m.signature());
+
+ int parenIdx = methodName.indexOf(QLatin1Char('('));
+ Q_ASSERT(parenIdx != -1);
+ methodName = methodName.left(parenIdx);
+
+ if (stringCache.contains(methodName))
+ continue;
+
+ RData *data = new RData;
+ data->identifier = enginePriv->objectClass->createPersistentIdentifier(methodName);
+
+ data->load(m);
+
+ stringCache.insert(methodName, data);
+ identifierCache.insert(data->identifier.identifier, data);
+ data->addref();
+ }
+}
+
+QmlPropertyCache::Data *
+QmlPropertyCache::property(int index) const
+{
+ if (index < 0 || index >= indexCache.count())
+ return 0;
+
+ return indexCache.at(index);
+}
+
+QmlPropertyCache::Data *
+QmlPropertyCache::property(const QString &str) const
+{
+ return stringCache.value(str);
+}
+
+QString QmlPropertyCache::Data::name(QObject *object)
+{
+ if (!object)
+ return QString();
+
+ return name(object->metaObject());
+}
+
+QString QmlPropertyCache::Data::name(const QMetaObject *metaObject)
+{
+ if (!metaObject || coreIndex == -1)
+ return QString();
+
+ if (flags & IsFunction) {
+ QMetaMethod m = metaObject->method(coreIndex);
+
+ QString name = QString::fromUtf8(m.signature());
+ int parenIdx = name.indexOf(QLatin1Char('('));
+ if (parenIdx != -1)
+ name = name.left(parenIdx);
+ return name;
+ } else {
+ QMetaProperty p = metaObject->property(coreIndex);
+ return QString::fromUtf8(p.name());
+ }
+}
+
+QStringList QmlPropertyCache::propertyNames() const
+{
+ return stringCache.keys();
+}
+
+QmlPropertyCache::Data *QmlPropertyCache::property(QmlEngine *engine, QObject *obj,
+ const QScriptDeclarativeClass::Identifier &name, Data &local)
+{
+ QmlPropertyCache::Data *rv = 0;
+
+ QmlEnginePrivate *enginePrivate = QmlEnginePrivate::get(engine);
+
+ QmlPropertyCache *cache = 0;
+ QmlDeclarativeData *ddata = QmlDeclarativeData::get(obj);
+ if (ddata && ddata->propertyCache && ddata->propertyCache->qmlEngine() == engine)
+ cache = ddata->propertyCache;
+ if (!cache) {
+ cache = enginePrivate->cache(obj);
+ if (cache && ddata && !ddata->propertyCache) { cache->addref(); ddata->propertyCache = cache; }
+ }
+
+ if (cache) {
+ rv = cache->property(name);
+ } else {
+ local = QmlPropertyCache::create(obj->metaObject(), enginePrivate->objectClass->toString(name));
+ if (local.isValid())
+ rv = &local;
+ }
+
+ return rv;
+}
+
+QmlPropertyCache::Data *QmlPropertyCache::property(QmlEngine *engine, QObject *obj,
+ const QString &name, Data &local)
+{
+ QmlPropertyCache::Data *rv = 0;
+
+ if (!engine) {
+ local = QmlPropertyCache::create(obj->metaObject(), name);
+ if (local.isValid())
+ rv = &local;
+ } else {
+ QmlEnginePrivate *enginePrivate = QmlEnginePrivate::get(engine);
+
+ QmlPropertyCache *cache = 0;
+ QmlDeclarativeData *ddata = QmlDeclarativeData::get(obj);
+ if (ddata && ddata->propertyCache && ddata->propertyCache->qmlEngine() == engine)
+ cache = ddata->propertyCache;
+ if (!cache) {
+ cache = enginePrivate->cache(obj);
+ if (cache && ddata && !ddata->propertyCache) { cache->addref(); ddata->propertyCache = cache; }
+ }
+
+ if (cache) {
+ rv = cache->property(name);
+ } else {
+ local = QmlPropertyCache::create(obj->metaObject(), name);
+ if (local.isValid())
+ rv = &local;
+ }
+ }
+
+ return rv;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlpropertycache_p.h b/src/declarative/qml/qmlpropertycache_p.h
new file mode 100644
index 0000000..efc4643
--- /dev/null
+++ b/src/declarative/qml/qmlpropertycache_p.h
@@ -0,0 +1,194 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPROPERTYCACHE_P_H
+#define QMLPROPERTYCACHE_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 "qmlrefcount_p.h"
+#include "qmlcleanup_p.h"
+
+#include <QtCore/qvector.h>
+
+#include <private/qscriptdeclarativeclass_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlEngine;
+class QMetaProperty;
+class QmlPropertyCache : public QmlRefCount, public QmlCleanup
+{
+public:
+ QmlPropertyCache(QmlEngine *);
+ virtual ~QmlPropertyCache();
+
+ struct Data {
+ inline Data();
+ inline bool operator==(const Data &);
+
+ enum Flag {
+ NoFlags = 0x00000000,
+
+ // Can apply to all properties, except IsFunction
+ IsConstant = 0x00000001,
+ IsWritable = 0x00000002,
+ IsResettable = 0x00000004,
+
+ // These are mutualy exclusive
+ IsFunction = 0x00000008,
+ IsQObjectDerived = 0x00000010,
+ IsEnumType = 0x00000020,
+ IsQmlList = 0x00000040,
+ IsQList = 0x00000080,
+ IsQmlBinding = 0x00000100,
+ IsQScriptValue = 0x00000200,
+
+ // Apply only to IsFunctions
+ IsVMEFunction = 0x00000400,
+ HasArguments = 0x00000800
+
+ };
+ Q_DECLARE_FLAGS(Flags, Flag)
+
+ bool isValid() const { return coreIndex != -1; }
+
+ Flags flags;
+ int propType;
+ int coreIndex;
+ int notifyIndex;
+
+ void load(const QMetaProperty &, QmlEngine *engine = 0);
+ void load(const QMetaMethod &);
+ QString name(QObject *);
+ QString name(const QMetaObject *);
+ };
+
+ struct ValueTypeData {
+ inline ValueTypeData();
+ inline bool operator==(const ValueTypeData &);
+ int valueTypeCoreIdx; // The prop index of the access property on the value type wrapper
+ int valueTypePropType; // The QVariant::Type of access property on the value type wrapper
+ };
+
+ void update(QmlEngine *, const QMetaObject *);
+
+ QmlPropertyCache *copy() const;
+ void append(QmlEngine *, const QMetaObject *, Data::Flag propertyFlags = Data::NoFlags,
+ Data::Flag methodFlags = Data::NoFlags);
+
+ static QmlPropertyCache *create(QmlEngine *, const QMetaObject *);
+ static Data create(const QMetaObject *, const QString &);
+
+ inline Data *property(const QScriptDeclarativeClass::Identifier &id) const;
+ Data *property(const QString &) const;
+ Data *property(int) const;
+ QStringList propertyNames() const;
+
+ inline QmlEngine *qmlEngine() const;
+ static Data *property(QmlEngine *, QObject *, const QScriptDeclarativeClass::Identifier &, Data &);
+ static Data *property(QmlEngine *, QObject *, const QString &, Data &);
+protected:
+ virtual void clear();
+
+private:
+ struct RData : public Data, public QmlRefCount {
+ QScriptDeclarativeClass::PersistentIdentifier identifier;
+ };
+
+ typedef QVector<RData *> IndexCache;
+ typedef QHash<QString, RData *> StringCache;
+ typedef QHash<QScriptDeclarativeClass::Identifier, RData *> IdentifierCache;
+
+ QmlEngine *engine;
+ IndexCache indexCache;
+ StringCache stringCache;
+ IdentifierCache identifierCache;
+};
+Q_DECLARE_OPERATORS_FOR_FLAGS(QmlPropertyCache::Data::Flags);
+
+QmlPropertyCache::Data::Data()
+: flags(0), propType(0), coreIndex(-1), notifyIndex(-1)
+{
+}
+
+bool QmlPropertyCache::Data::operator==(const QmlPropertyCache::Data &other)
+{
+ return flags == other.flags &&
+ propType == other.propType &&
+ coreIndex == other.coreIndex &&
+ notifyIndex == other.notifyIndex;
+}
+
+QmlPropertyCache::Data *
+QmlPropertyCache::property(const QScriptDeclarativeClass::Identifier &id) const
+{
+ return identifierCache.value(id);
+}
+
+QmlPropertyCache::ValueTypeData::ValueTypeData()
+: valueTypeCoreIdx(-1), valueTypePropType(0)
+{
+}
+
+bool QmlPropertyCache::ValueTypeData::operator==(const ValueTypeData &o)
+{
+ return valueTypeCoreIdx == o.valueTypeCoreIdx &&
+ valueTypePropType == o.valueTypePropType;
+}
+
+QmlEngine *QmlPropertyCache::qmlEngine() const
+{
+ return engine;
+}
+
+QT_END_NAMESPACE
+
+#endif // QMLPROPERTYCACHE_P_H
diff --git a/src/declarative/qml/qmlpropertyvalueinterceptor.cpp b/src/declarative/qml/qmlpropertyvalueinterceptor.cpp
new file mode 100644
index 0000000..9d0d7f6
--- /dev/null
+++ b/src/declarative/qml/qmlpropertyvalueinterceptor.cpp
@@ -0,0 +1,79 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlpropertyvalueinterceptor.h"
+
+#include "qml.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QmlPropertyValueInterceptor
+ \brief The QmlPropertyValueInterceptor class is inherited by property interceptors such as Behavior.
+ \internal
+
+ This class intercepts property writes, allowing for custom handling. For example, Behavior uses this
+ interception to provide a default animation for all changes to a property's value.
+ */
+
+/*!
+ Constructs a QmlPropertyValueInterceptor.
+*/
+QmlPropertyValueInterceptor::QmlPropertyValueInterceptor()
+{
+}
+
+QmlPropertyValueInterceptor::~QmlPropertyValueInterceptor()
+{
+}
+
+/*!
+ \fn void QmlPropertyValueInterceptor::setTarget(const QmlMetaProperty &property)
+ Set the target \a property for the value interceptor. This method will
+ be called by the QML engine when assigning a value interceptor.
+*/
+
+/*!
+ \fn void QmlPropertyValueInterceptor::write(const QVariant &value)
+ This method will be called when a new \a value is assigned to the property being intercepted.
+*/
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlpropertyvalueinterceptor.h b/src/declarative/qml/qmlpropertyvalueinterceptor.h
new file mode 100644
index 0000000..71cc6c5
--- /dev/null
+++ b/src/declarative/qml/qmlpropertyvalueinterceptor.h
@@ -0,0 +1,68 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPROPERTYVALUEINTERCEPTOR_H
+#define QMLPROPERTYVALUEINTERCEPTOR_H
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlMetaProperty;
+class Q_DECLARATIVE_EXPORT QmlPropertyValueInterceptor
+{
+public:
+ QmlPropertyValueInterceptor();
+ virtual ~QmlPropertyValueInterceptor();
+ virtual void setTarget(const QmlMetaProperty &property) = 0;
+ virtual void write(const QVariant &value) = 0;
+};
+Q_DECLARE_INTERFACE(QmlPropertyValueInterceptor, "com.trolltech.qml.QmlPropertyValueInterceptor")
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLPROPERTYVALUEINTERCEPTOR_H
diff --git a/src/declarative/qml/qmlpropertyvaluesource.cpp b/src/declarative/qml/qmlpropertyvaluesource.cpp
new file mode 100644
index 0000000..50f2f8c
--- /dev/null
+++ b/src/declarative/qml/qmlpropertyvaluesource.cpp
@@ -0,0 +1,71 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlpropertyvaluesource.h"
+
+#include "qml.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QmlPropertyValueSource
+ \brief The QmlPropertyValueSource class is inherited by property value sources such as animations and bindings.
+ \internal
+ */
+
+/*!
+ Constructs a QmlPropertyValueSource.
+*/
+QmlPropertyValueSource::QmlPropertyValueSource()
+{
+}
+
+QmlPropertyValueSource::~QmlPropertyValueSource()
+{
+}
+
+/*!
+ \fn void QmlPropertyValueSource::setTarget(const QmlMetaProperty &property)
+ Set the target \a property for the value source. This method will
+ be called by the QML engine when assigning a value source.
+*/
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlpropertyvaluesource.h b/src/declarative/qml/qmlpropertyvaluesource.h
new file mode 100644
index 0000000..2017fb2
--- /dev/null
+++ b/src/declarative/qml/qmlpropertyvaluesource.h
@@ -0,0 +1,67 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPROPERTYVALUESOURCE_H
+#define QMLPROPERTYVALUESOURCE_H
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlMetaProperty;
+class Q_DECLARATIVE_EXPORT QmlPropertyValueSource
+{
+public:
+ QmlPropertyValueSource();
+ virtual ~QmlPropertyValueSource();
+ virtual void setTarget(const QmlMetaProperty &) = 0;
+};
+Q_DECLARE_INTERFACE(QmlPropertyValueSource, "com.trolltech.qml.QmlPropertyValueSource")
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLPROPERTYVALUESOURCE_H
diff --git a/src/declarative/qml/qmlproxymetaobject.cpp b/src/declarative/qml/qmlproxymetaobject.cpp
new file mode 100644
index 0000000..983c350
--- /dev/null
+++ b/src/declarative/qml/qmlproxymetaobject.cpp
@@ -0,0 +1,138 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlproxymetaobject_p.h"
+
+#include <QDebug>
+
+QT_BEGIN_NAMESPACE
+
+QmlProxyMetaObject::QmlProxyMetaObject(QObject *obj, QList<ProxyData> *mList)
+: metaObjects(mList), proxies(0), parent(0), object(obj)
+{
+#ifdef QMLPROXYMETAOBJECT_DEBUG
+ qWarning() << "QmlProxyMetaObject" << obj->metaObject()->className();
+#endif
+
+ *static_cast<QMetaObject *>(this) = *metaObjects->first().metaObject;
+
+ QObjectPrivate *op = QObjectPrivate::get(obj);
+ if (op->metaObject)
+ parent = static_cast<QAbstractDynamicMetaObject*>(op->metaObject);
+
+ op->metaObject = this;
+
+#ifdef QMLPROXYMETAOBJECT_DEBUG
+ const QMetaObject *mo = obj->metaObject();
+ while(mo) {
+ qWarning() << " " << mo->className();
+ mo = mo->superClass();
+ }
+#endif
+}
+
+QmlProxyMetaObject::~QmlProxyMetaObject()
+{
+ if (parent)
+ delete parent;
+ parent = 0;
+
+ if (proxies)
+ delete [] proxies;
+ proxies = 0;
+}
+
+int QmlProxyMetaObject::metaCall(QMetaObject::Call c, int id, void **a)
+{
+ if ((c == QMetaObject::ReadProperty ||
+ c == QMetaObject::WriteProperty) &&
+ id >= metaObjects->last().propertyOffset) {
+
+ for (int ii = 0; ii < metaObjects->count(); ++ii) {
+ const ProxyData &data = metaObjects->at(ii);
+ if (id >= data.propertyOffset) {
+ if (!proxies) {
+ proxies = new QObject*[metaObjects->count()];
+ ::memset(proxies, 0,
+ sizeof(QObject *) * metaObjects->count());
+ }
+
+ if (!proxies[ii]) {
+ QObject *proxy = data.createFunc(object);
+ const QMetaObject *metaObject = proxy->metaObject();
+ proxies[ii] = proxy;
+
+ int localOffset = data.metaObject->methodOffset();
+ int methodOffset = metaObject->methodOffset();
+ int methods = metaObject->methodCount() - methodOffset;
+
+ // ### - Can this be done more optimally?
+ for (int jj = 0; jj < methods; ++jj) {
+ QMetaMethod method =
+ metaObject->method(jj + methodOffset);
+ if (method.methodType() == QMetaMethod::Signal)
+ QMetaObject::connect(proxy, methodOffset + jj,
+ object, localOffset + jj);
+ }
+ }
+
+ int proxyOffset = proxies[ii]->metaObject()->propertyOffset();
+ int proxyId = id - data.propertyOffset + proxyOffset;
+
+ return proxies[ii]->qt_metacall(c, proxyId, a);
+ }
+ }
+ } else if (c == QMetaObject::InvokeMetaMethod &&
+ id >= metaObjects->last().methodOffset) {
+ QMetaMethod m = object->metaObject()->method(id);
+ if (m.methodType() == QMetaMethod::Signal) {
+ QMetaObject::activate(object, id, a);
+ return -1;
+ }
+ }
+
+ if (parent)
+ return parent->metaCall(c, id, a);
+ else
+ return object->qt_metacall(c, id, a);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlproxymetaobject_p.h b/src/declarative/qml/qmlproxymetaobject_p.h
new file mode 100644
index 0000000..f983030
--- /dev/null
+++ b/src/declarative/qml/qmlproxymetaobject_p.h
@@ -0,0 +1,100 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPROXYMETAOBJECT_P_H
+#define QMLPROXYMETAOBJECT_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 "qmetaobjectbuilder_p.h"
+#include "qml.h"
+
+#include <QtCore/QMetaObject>
+#include <QtCore/QObject>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlProxyMetaObject : public QAbstractDynamicMetaObject
+{
+public:
+ struct ProxyData {
+ typedef QObject *(*CreateFunc)(QObject *);
+ QMetaObject *metaObject;
+ CreateFunc createFunc;
+ int propertyOffset;
+ int methodOffset;
+ };
+
+ QmlProxyMetaObject(QObject *, QList<ProxyData> *);
+ virtual ~QmlProxyMetaObject();
+
+protected:
+ virtual int metaCall(QMetaObject::Call _c, int _id, void **_a);
+
+private:
+ QList<ProxyData> *metaObjects;
+ QObject **proxies;
+
+ QAbstractDynamicMetaObject *parent;
+ QObject *object;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLPROXYMETAOBJECT_P_H
+
diff --git a/src/declarative/qml/qmlrefcount.cpp b/src/declarative/qml/qmlrefcount.cpp
new file mode 100644
index 0000000..9422625
--- /dev/null
+++ b/src/declarative/qml/qmlrefcount.cpp
@@ -0,0 +1,70 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlrefcount_p.h"
+
+QT_BEGIN_NAMESPACE
+
+QmlRefCount::QmlRefCount()
+: refCount(1)
+{
+}
+
+QmlRefCount::~QmlRefCount()
+{
+}
+
+void QmlRefCount::addref()
+{
+ Q_ASSERT(refCount > 0);
+ ++refCount;
+}
+
+void QmlRefCount::release()
+{
+ Q_ASSERT(refCount > 0);
+ --refCount;
+ if (refCount == 0)
+ delete this;
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/qml/qmlrefcount_p.h b/src/declarative/qml/qmlrefcount_p.h
new file mode 100644
index 0000000..7448042
--- /dev/null
+++ b/src/declarative/qml/qmlrefcount_p.h
@@ -0,0 +1,80 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLREFCOUNT_P_H
+#define QMLREFCOUNT_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_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class Q_AUTOTEST_EXPORT QmlRefCount
+{
+public:
+ QmlRefCount();
+ virtual ~QmlRefCount();
+ void addref();
+ void release();
+
+private:
+ int refCount;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLREFCOUNT_P_H
diff --git a/src/declarative/qml/qmlrewrite.cpp b/src/declarative/qml/qmlrewrite.cpp
new file mode 100644
index 0000000..34bd198
--- /dev/null
+++ b/src/declarative/qml/qmlrewrite.cpp
@@ -0,0 +1,215 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlrewrite_p.h"
+
+#include "qmlglobal_p.h"
+
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+DEFINE_BOOL_CONFIG_OPTION(rewriteDump, QML_REWRITE_DUMP);
+
+namespace QmlRewrite {
+
+bool SharedBindingTester::isSharable(const QString &code)
+{
+ Engine engine;
+ NodePool pool(QString(), &engine);
+ Lexer lexer(&engine);
+ Parser parser(&engine);
+ lexer.setCode(code, 0);
+ parser.parseStatement();
+ if (!parser.statement())
+ return false;
+
+ _sharable = true;
+ AST::Node::acceptChild(parser.statement(), this);
+ return _sharable;
+}
+
+QString RewriteBinding::operator()(const QString &code, bool *ok)
+{
+ Engine engine;
+ NodePool pool(QString(), &engine);
+ Lexer lexer(&engine);
+ Parser parser(&engine);
+ lexer.setCode(code, 0);
+ parser.parseStatement();
+ if (!parser.statement()) {
+ if (ok) *ok = false;
+ return QString();
+ } else {
+ if (ok) *ok = true;
+ }
+ return rewrite(code, 0, parser.statement());
+}
+
+void RewriteBinding::accept(AST::Node *node)
+{
+ AST::Node::acceptChild(node, this);
+}
+
+QString RewriteBinding::rewrite(QString code, unsigned position,
+ AST::Statement *node)
+{
+ TextWriter w;
+ _writer = &w;
+ _position = position;
+ _inLoop = 0;
+
+ accept(node);
+
+ unsigned startOfStatement = node->firstSourceLocation().begin() - _position;
+ unsigned endOfStatement = node->lastSourceLocation().end() - _position;
+
+ _writer->replace(startOfStatement, 0, QLatin1String("(function() { "));
+ _writer->replace(endOfStatement, 0, QLatin1String(" })"));
+
+ if (rewriteDump()) {
+ qWarning() << "=============================================================";
+ qWarning() << "Rewrote:";
+ qWarning() << qPrintable(code);
+ }
+
+ w.write(&code);
+
+ if (rewriteDump()) {
+ qWarning() << "To:";
+ qWarning() << qPrintable(code);
+ qWarning() << "=============================================================";
+ }
+
+ return code;
+}
+
+bool RewriteBinding::visit(AST::Block *ast)
+{
+ for (AST::StatementList *it = ast->statements; it; it = it->next) {
+ if (! it->next) {
+ // we need to rewrite only the last statement of a block.
+ accept(it->statement);
+ }
+ }
+
+ return false;
+}
+
+bool RewriteBinding::visit(AST::ExpressionStatement *ast)
+{
+ if (! _inLoop) {
+ unsigned startOfExpressionStatement = ast->firstSourceLocation().begin() - _position;
+ _writer->replace(startOfExpressionStatement, 0, QLatin1String("return "));
+ }
+
+ return false;
+}
+
+bool RewriteBinding::visit(AST::DoWhileStatement *)
+{
+ ++_inLoop;
+ return true;
+}
+
+void RewriteBinding::endVisit(AST::DoWhileStatement *)
+{
+ --_inLoop;
+}
+
+bool RewriteBinding::visit(AST::WhileStatement *)
+{
+ ++_inLoop;
+ return true;
+}
+
+void RewriteBinding::endVisit(AST::WhileStatement *)
+{
+ --_inLoop;
+}
+
+bool RewriteBinding::visit(AST::ForStatement *)
+{
+ ++_inLoop;
+ return true;
+}
+
+void RewriteBinding::endVisit(AST::ForStatement *)
+{
+ --_inLoop;
+}
+
+bool RewriteBinding::visit(AST::LocalForStatement *)
+{
+ ++_inLoop;
+ return true;
+}
+
+void RewriteBinding::endVisit(AST::LocalForStatement *)
+{
+ --_inLoop;
+}
+
+bool RewriteBinding::visit(AST::ForEachStatement *)
+{
+ ++_inLoop;
+ return true;
+}
+
+void RewriteBinding::endVisit(AST::ForEachStatement *)
+{
+ --_inLoop;
+}
+
+bool RewriteBinding::visit(AST::LocalForEachStatement *)
+{
+ ++_inLoop;
+ return true;
+}
+
+void RewriteBinding::endVisit(AST::LocalForEachStatement *)
+{
+ --_inLoop;
+}
+
+} // namespace QmlRewrite
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlrewrite_p.h b/src/declarative/qml/qmlrewrite_p.h
new file mode 100644
index 0000000..a04a0db
--- /dev/null
+++ b/src/declarative/qml/qmlrewrite_p.h
@@ -0,0 +1,121 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLREWRITE_P_H
+#define QMLREWRITE_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 "rewriter/textwriter_p.h"
+#include "parser/qmljslexer_p.h"
+#include "parser/qmljsparser_p.h"
+#include "parser/qmljsnodepool_p.h"
+
+QT_BEGIN_NAMESPACE
+
+namespace QmlRewrite {
+using namespace QmlJS;
+
+class SharedBindingTester : protected AST::Visitor
+{
+ bool _sharable;
+public:
+ bool isSharable(const QString &code);
+
+ virtual bool visit(AST::FunctionDeclaration *) { _sharable = false; return false; }
+ virtual bool visit(AST::FunctionExpression *) { _sharable = false; return false; }
+ virtual bool visit(AST::CallExpression *) { _sharable = false; return false; }
+};
+
+class RewriteBinding: protected AST::Visitor
+{
+ unsigned _position;
+ TextWriter *_writer;
+
+public:
+ QString operator()(const QString &code, bool *ok = 0);
+
+protected:
+ using AST::Visitor::visit;
+
+ void accept(AST::Node *node);
+ QString rewrite(QString code, unsigned position, AST::Statement *node);
+
+ virtual bool visit(AST::Block *ast);
+ virtual bool visit(AST::ExpressionStatement *ast);
+
+ virtual bool visit(AST::DoWhileStatement *ast);
+ virtual void endVisit(AST::DoWhileStatement *ast);
+
+ virtual bool visit(AST::WhileStatement *ast);
+ virtual void endVisit(AST::WhileStatement *ast);
+
+ virtual bool visit(AST::ForStatement *ast);
+ virtual void endVisit(AST::ForStatement *ast);
+
+ virtual bool visit(AST::LocalForStatement *ast);
+ virtual void endVisit(AST::LocalForStatement *ast);
+
+ virtual bool visit(AST::ForEachStatement *ast);
+ virtual void endVisit(AST::ForEachStatement *ast);
+
+ virtual bool visit(AST::LocalForEachStatement *ast);
+ virtual void endVisit(AST::LocalForEachStatement *ast);
+
+private:
+ int _inLoop;
+};
+
+} // namespace QmlRewrite
+
+QT_END_NAMESPACE
+
+#endif // QMLREWRITE_P_H
+
diff --git a/src/declarative/qml/qmlscript.cpp b/src/declarative/qml/qmlscript.cpp
new file mode 100644
index 0000000..10fc9a6
--- /dev/null
+++ b/src/declarative/qml/qmlscript.cpp
@@ -0,0 +1,87 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+// This is just a dummy file to include the documentation
+
+/*!
+ \qmlclass Script QmlScript
+ \brief The Script element provides a way to add JavaScript code snippets in QML.
+ \ingroup group_utility
+
+ The Script element is used to add convenient JavaScript "glue" methods to
+ your Qt Declarative application or component.
+
+ An example:
+
+ \qml
+ Script {
+ function debugMyComponent() {
+ console.log(text.text);
+ console.log(otherinterestingitem.property);
+ }
+ }
+ MouseRegion { onClicked: debugMyComponent() }
+ \endqml
+
+ \note While it is possible to use any JavaScript code within a Script element,
+ it is recommended that the code be limited to defining functions. The Script
+ element executes JavaScript as soon as it is specified, so
+ when defining a component, this may be done before the execution context is
+ fully specified. As a result, some properties or items may not be
+ accessible. You can avoid this problem by limiting your JavaScript to
+ defining functions that are only executed later once the context is fully
+ defined.
+
+ \sa {JavaScript Blocks}
+*/
+
+/*!
+ \qmlproperty string Script::script
+ \default
+ The JavaScript code to be executed.
+*/
+
+/*!
+ \qmlproperty url Script::source
+
+ Specifies a source file containing JavaScript code. This can be used instead
+ of providing inline JavaScript code in the Script element.
+*/
diff --git a/src/declarative/qml/qmlscriptclass_p.h b/src/declarative/qml/qmlscriptclass_p.h
new file mode 100644
index 0000000..847ee66
--- /dev/null
+++ b/src/declarative/qml/qmlscriptclass_p.h
@@ -0,0 +1,89 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSCRIPTCLASS_P_H
+#define QMLSCRIPTCLASS_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 <QtScript/qscriptclass.h>
+#include <private/qscriptdeclarativeclass_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlEngine;
+class QmlScriptClass : public QScriptDeclarativeClass
+{
+public:
+ QmlScriptClass(QScriptEngine *);
+
+ static QVariant toVariant(QmlEngine *, const QScriptValue &);
+
+#if (QT_VERSION <= QT_VERSION_CHECK(4, 6, 2)) && !defined(QT_HAVE_QSCRIPTDECLARATIVECLASS_VALUE)
+ struct Value : public QScriptValue {
+ Value() : QScriptValue() {}
+ Value(QScriptEngine *engine, int v) : QScriptValue(engine, v) {}
+ Value(QScriptEngine *engine, uint v) : QScriptValue(engine, v) {}
+ Value(QScriptEngine *engine, bool v) : QScriptValue(engine, v) {}
+ Value(QScriptEngine *engine, double v) : QScriptValue(engine, v) {}
+ Value(QScriptEngine *engine, float v) : QScriptValue(engine, v) {}
+ Value(QScriptEngine *engine, const QString &v) : QScriptValue(engine, v) {}
+ Value(QScriptEngine *, const QScriptValue &v) : QScriptValue(v) {}
+ };
+
+ typedef QScriptValue ScriptValue;
+#else
+ typedef Value ScriptValue;
+#endif
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLSCRIPTCLASS_P_H
diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp
new file mode 100644
index 0000000..a24ef51
--- /dev/null
+++ b/src/declarative/qml/qmlscriptparser.cpp
@@ -0,0 +1,952 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlscriptparser_p.h"
+
+#include "qmlparser_p.h"
+#include "parser/qmljsengine_p.h"
+#include "parser/qmljsparser_p.h"
+#include "parser/qmljslexer_p.h"
+#include "parser/qmljsnodepool_p.h"
+#include "parser/qmljsastvisitor_p.h"
+#include "parser/qmljsast_p.h"
+#include "qmlrewrite_p.h"
+
+#include <qfxperf_p_p.h>
+
+#include <QStack>
+#include <QCoreApplication>
+#include <QtDebug>
+
+QT_BEGIN_NAMESPACE
+
+using namespace QmlJS;
+using namespace QmlParser;
+
+namespace {
+
+class ProcessAST: protected AST::Visitor
+{
+ struct State {
+ State() : object(0), property(0) {}
+ State(Object *o) : object(o), property(0) {}
+ State(Object *o, Property *p) : object(o), property(p) {}
+
+ Object *object;
+ Property *property;
+ };
+
+ struct StateStack : public QStack<State>
+ {
+ void pushObject(Object *obj)
+ {
+ push(State(obj));
+ }
+
+ void pushProperty(const QString &name, const LocationSpan &location)
+ {
+ const State &state = top();
+ if (state.property) {
+ State s(state.property->getValue(),
+ state.property->getValue()->getProperty(name.toUtf8()));
+ s.property->location = location;
+ push(s);
+ } else {
+ State s(state.object,
+ state.object->getProperty(name.toUtf8()));
+
+ s.property->location = location;
+ push(s);
+ }
+ }
+ };
+
+public:
+ ProcessAST(QmlScriptParser *parser);
+ virtual ~ProcessAST();
+
+ void operator()(const QString &code, AST::Node *node);
+
+protected:
+ Object *defineObjectBinding(AST::UiQualifiedId *propertyName,
+ AST::UiQualifiedId *objectTypeName,
+ LocationSpan location,
+ AST::UiObjectInitializer *initializer = 0);
+
+ Object *defineObjectBinding_helper(AST::UiQualifiedId *propertyName,
+ const QString &objectType,
+ AST::SourceLocation typeLocation,
+ LocationSpan location,
+ AST::UiObjectInitializer *initializer = 0);
+
+ QmlParser::Variant getVariant(AST::ExpressionNode *expr);
+
+ LocationSpan location(AST::SourceLocation start, AST::SourceLocation end);
+ LocationSpan location(AST::UiQualifiedId *);
+
+ using AST::Visitor::visit;
+ using AST::Visitor::endVisit;
+
+ virtual bool visit(AST::UiProgram *node);
+ virtual bool visit(AST::UiImport *node);
+ virtual bool visit(AST::UiObjectDefinition *node);
+ virtual bool visit(AST::UiPublicMember *node);
+ virtual bool visit(AST::UiObjectBinding *node);
+
+ virtual bool visit(AST::UiScriptBinding *node);
+ virtual bool visit(AST::UiArrayBinding *node);
+ virtual bool visit(AST::UiSourceElement *node);
+
+ void accept(AST::Node *node);
+
+ QString asString(AST::UiQualifiedId *node) const;
+
+ const State state() const;
+ Object *currentObject() const;
+ Property *currentProperty() const;
+
+ QString qualifiedNameId() const;
+
+ QString textAt(const AST::SourceLocation &loc) const
+ { return _contents.mid(loc.offset, loc.length); }
+
+
+ QString textAt(const AST::SourceLocation &first,
+ const AST::SourceLocation &last) const
+ { return _contents.mid(first.offset, last.offset + last.length - first.offset); }
+
+ QString asString(AST::ExpressionNode *expr)
+ {
+ if (! expr)
+ return QString();
+
+ return textAt(expr->firstSourceLocation(), expr->lastSourceLocation());
+ }
+
+ QString asString(AST::Statement *stmt)
+ {
+ if (! stmt)
+ return QString();
+
+ QString s = textAt(stmt->firstSourceLocation(), stmt->lastSourceLocation());
+ s += QLatin1Char('\n');
+ return s;
+ }
+
+private:
+ QmlScriptParser *_parser;
+ StateStack _stateStack;
+ QStringList _scope;
+ QString _contents;
+
+ inline bool isSignalProperty(const QByteArray &propertyName) const {
+ return (propertyName.length() >= 3 && propertyName.startsWith("on") &&
+ ('A' <= propertyName.at(2) && 'Z' >= propertyName.at(2)));
+ }
+
+};
+
+ProcessAST::ProcessAST(QmlScriptParser *parser)
+ : _parser(parser)
+{
+}
+
+ProcessAST::~ProcessAST()
+{
+}
+
+void ProcessAST::operator()(const QString &code, AST::Node *node)
+{
+ _contents = code;
+ accept(node);
+}
+
+void ProcessAST::accept(AST::Node *node)
+{
+ AST::Node::acceptChild(node, this);
+}
+
+const ProcessAST::State ProcessAST::state() const
+{
+ if (_stateStack.isEmpty())
+ return State();
+
+ return _stateStack.back();
+}
+
+Object *ProcessAST::currentObject() const
+{
+ return state().object;
+}
+
+Property *ProcessAST::currentProperty() const
+{
+ return state().property;
+}
+
+QString ProcessAST::qualifiedNameId() const
+{
+ return _scope.join(QLatin1String("/"));
+}
+
+QString ProcessAST::asString(AST::UiQualifiedId *node) const
+{
+ QString s;
+
+ for (AST::UiQualifiedId *it = node; it; it = it->next) {
+ s.append(it->name->asString());
+
+ if (it->next)
+ s.append(QLatin1Char('.'));
+ }
+
+ return s;
+}
+
+Object *
+ProcessAST::defineObjectBinding_helper(AST::UiQualifiedId *propertyName,
+ const QString &objectType,
+ AST::SourceLocation typeLocation,
+ LocationSpan location,
+ AST::UiObjectInitializer *initializer)
+{
+ int lastTypeDot = objectType.lastIndexOf(QLatin1Char('.'));
+ bool isType = !objectType.isEmpty() &&
+ (objectType.at(0).isUpper() ||
+ (lastTypeDot >= 0 && objectType.at(lastTypeDot+1).isUpper()));
+
+ int propertyCount = 0;
+ for (; propertyName; propertyName = propertyName->next){
+ ++propertyCount;
+ _stateStack.pushProperty(propertyName->name->asString(),
+ this->location(propertyName));
+ }
+
+ if (!isType) {
+
+ if(propertyCount || !currentObject()) {
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser","Expected type name"));
+ error.setLine(typeLocation.startLine);
+ error.setColumn(typeLocation.startColumn);
+ _parser->_errors << error;
+ return 0;
+ }
+
+ LocationSpan loc = ProcessAST::location(typeLocation, typeLocation);
+ if (propertyName)
+ loc = ProcessAST::location(propertyName);
+
+ _stateStack.pushProperty(objectType, loc);
+ accept(initializer);
+ _stateStack.pop();
+
+ return 0;
+
+ } else {
+ // Class
+
+ QString resolvableObjectType = objectType;
+ if (lastTypeDot >= 0)
+ resolvableObjectType.replace(QLatin1Char('.'),QLatin1Char('/'));
+
+ bool isScript = resolvableObjectType == QLatin1String("Script");
+
+ if (isScript) {
+ if (_stateStack.isEmpty() || _stateStack.top().property) {
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser","Invalid use of Script block"));
+ error.setLine(typeLocation.startLine);
+ error.setColumn(typeLocation.startColumn);
+ _parser->_errors << error;
+ return 0;
+ }
+ }
+
+ Object *obj = new Object;
+
+ if (!isScript) {
+ QmlScriptParser::TypeReference *typeRef = _parser->findOrCreateType(resolvableObjectType);
+ obj->type = typeRef->id;
+
+ typeRef->refObjects.append(obj);
+ }
+
+ // XXX this doesn't do anything (_scope never builds up)
+ _scope.append(resolvableObjectType);
+ obj->typeName = qualifiedNameId().toUtf8();
+ _scope.removeLast();
+
+ obj->location = location;
+
+ if (isScript) {
+
+ _stateStack.top().object->scriptBlockObjects.append(obj);
+
+ } else if (propertyCount) {
+
+ Property *prop = currentProperty();
+ Value *v = new Value;
+ v->object = obj;
+ v->location = obj->location;
+ prop->addValue(v);
+
+ while (propertyCount--)
+ _stateStack.pop();
+
+ } else {
+
+ if (! _parser->tree()) {
+ _parser->setTree(obj);
+ } else {
+ const State state = _stateStack.top();
+ Value *v = new Value;
+ v->object = obj;
+ v->location = obj->location;
+ if (state.property) {
+ state.property->addValue(v);
+ } else {
+ Property *defaultProp = state.object->getDefaultProperty();
+ if (defaultProp->location.start.line == -1) {
+ defaultProp->location = v->location;
+ defaultProp->location.end = defaultProp->location.start;
+ defaultProp->location.range.length = 0;
+ }
+ defaultProp->addValue(v);
+ }
+ }
+ }
+
+ _stateStack.pushObject(obj);
+ accept(initializer);
+ _stateStack.pop();
+
+ return obj;
+ }
+}
+
+Object *ProcessAST::defineObjectBinding(AST::UiQualifiedId *qualifiedId,
+ AST::UiQualifiedId *objectTypeName,
+ LocationSpan location,
+ AST::UiObjectInitializer *initializer)
+{
+ const QString objectType = asString(objectTypeName);
+ const AST::SourceLocation typeLocation = objectTypeName->identifierToken;
+
+ if (objectType == QLatin1String("Script")) {
+
+ AST::UiObjectMemberList *it = initializer->members;
+ for (; it; it = it->next) {
+ AST::UiScriptBinding *scriptBinding = AST::cast<AST::UiScriptBinding *>(it->member);
+ if (! scriptBinding)
+ continue;
+
+ QString propertyName = asString(scriptBinding->qualifiedId);
+ if (propertyName == QLatin1String("source")) {
+ if (AST::ExpressionStatement *stmt = AST::cast<AST::ExpressionStatement *>(scriptBinding->statement)) {
+ QmlParser::Variant string = getVariant(stmt->expression);
+ if (string.isStringList()) {
+ QStringList urls = string.asStringList();
+ // We need to add this as a resource
+ for (int ii = 0; ii < urls.count(); ++ii)
+ _parser->_refUrls << QUrl(urls.at(ii));
+ }
+ }
+ }
+ }
+
+ }
+
+ return defineObjectBinding_helper(qualifiedId, objectType, typeLocation, location, initializer);
+}
+
+LocationSpan ProcessAST::location(AST::UiQualifiedId *id)
+{
+ return location(id->identifierToken, id->identifierToken);
+}
+
+LocationSpan ProcessAST::location(AST::SourceLocation start, AST::SourceLocation end)
+{
+ LocationSpan rv;
+ rv.start.line = start.startLine;
+ rv.start.column = start.startColumn;
+ rv.end.line = end.startLine;
+ rv.end.column = end.startColumn + end.length - 1;
+ rv.range.offset = start.offset;
+ rv.range.length = end.offset + end.length - start.offset;
+ return rv;
+}
+
+// UiProgram: UiImportListOpt UiObjectMemberList ;
+bool ProcessAST::visit(AST::UiProgram *node)
+{
+ accept(node->imports);
+ accept(node->members->member);
+ return false;
+}
+
+// UiImport: T_IMPORT T_STRING_LITERAL ;
+bool ProcessAST::visit(AST::UiImport *node)
+{
+ QString uri;
+ QmlScriptParser::Import import;
+
+ if (node->fileName) {
+ import.type = QmlScriptParser::Import::File;
+ uri = node->fileName->asString();
+ } else {
+ import.type = QmlScriptParser::Import::Library;
+ uri = asString(node->importUri);
+ }
+
+ AST::SourceLocation startLoc = node->importToken;
+ AST::SourceLocation endLoc = node->semicolonToken;
+
+ if (node->importId) {
+ import.qualifier = node->importId->asString();
+ if (!import.qualifier.at(0).isUpper()) {
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser","Invalid import qualifier ID"));
+ error.setLine(node->importIdToken.startLine);
+ error.setColumn(node->importIdToken.startColumn);
+ _parser->_errors << error;
+ return false;
+ }
+ }
+ if (node->versionToken.isValid())
+ import.version = textAt(node->versionToken);
+ else if (import.type == QmlScriptParser::Import::Library) {
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser","Library import requires a version"));
+ error.setLine(node->importIdToken.startLine);
+ error.setColumn(node->importIdToken.startColumn);
+ _parser->_errors << error;
+ return false;
+ }
+
+ import.location = location(startLoc, endLoc);
+ import.uri = uri;
+
+ _parser->_imports << import;
+
+ return false;
+}
+
+bool ProcessAST::visit(AST::UiPublicMember *node)
+{
+ const struct TypeNameToType {
+ const char *name;
+ Object::DynamicProperty::Type type;
+ const char *qtName;
+ } propTypeNameToTypes[] = {
+ { "int", Object::DynamicProperty::Int, "int" },
+ { "bool", Object::DynamicProperty::Bool, "bool" },
+ { "double", Object::DynamicProperty::Real, "double" },
+ { "real", Object::DynamicProperty::Real, "qreal" },
+ { "string", Object::DynamicProperty::String, "QString" },
+ { "url", Object::DynamicProperty::Url, "QUrl" },
+ { "color", Object::DynamicProperty::Color, "QColor" },
+ { "date", Object::DynamicProperty::Date, "QDate" },
+ { "var", Object::DynamicProperty::Variant, "QVariant" },
+ { "variant", Object::DynamicProperty::Variant, "QVariant" }
+ };
+ const int propTypeNameToTypesCount = sizeof(propTypeNameToTypes) /
+ sizeof(propTypeNameToTypes[0]);
+
+ if(node->type == AST::UiPublicMember::Signal) {
+ const QString name = node->name->asString();
+
+ Object::DynamicSignal signal;
+ signal.name = name.toUtf8();
+
+ AST::UiParameterList *p = node->parameters;
+ while (p) {
+ const QString memberType = p->type->asString();
+ const char *qtType = 0;
+ for(int ii = 0; !qtType && ii < propTypeNameToTypesCount; ++ii) {
+ if(QLatin1String(propTypeNameToTypes[ii].name) == memberType)
+ qtType = propTypeNameToTypes[ii].qtName;
+ }
+
+ if (!qtType) {
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser","Expected parameter type"));
+ error.setLine(node->typeToken.startLine);
+ error.setColumn(node->typeToken.startColumn);
+ _parser->_errors << error;
+ return false;
+ }
+
+ signal.parameterTypes << qtType;
+ signal.parameterNames << p->name->asString().toUtf8();
+ p = p->finish();
+ }
+
+ _stateStack.top().object->dynamicSignals << signal;
+ } else {
+ const QString memberType = node->memberType->asString();
+ const QString name = node->name->asString();
+
+ bool typeFound = false;
+ Object::DynamicProperty::Type type;
+
+ if (memberType == QLatin1String("alias")) {
+ type = Object::DynamicProperty::Alias;
+ typeFound = true;
+ }
+
+ for(int ii = 0; !typeFound && ii < propTypeNameToTypesCount; ++ii) {
+ if(QLatin1String(propTypeNameToTypes[ii].name) == memberType) {
+ type = propTypeNameToTypes[ii].type;
+ typeFound = true;
+ }
+ }
+
+ if (!typeFound && memberType.at(0).isUpper()) {
+ QString typemodifier;
+ if(node->typeModifier)
+ typemodifier = node->typeModifier->asString();
+ if (typemodifier == QString()) {
+ type = Object::DynamicProperty::Custom;
+ } else if(typemodifier == QLatin1String("list")) {
+ type = Object::DynamicProperty::CustomList;
+ } else {
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser","Invalid property type modifier"));
+ error.setLine(node->typeModifierToken.startLine);
+ error.setColumn(node->typeModifierToken.startColumn);
+ _parser->_errors << error;
+ return false;
+ }
+ typeFound = true;
+ } else if (node->typeModifier) {
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser","Unexpected property type modifier"));
+ error.setLine(node->typeModifierToken.startLine);
+ error.setColumn(node->typeModifierToken.startColumn);
+ _parser->_errors << error;
+ return false;
+ }
+
+ if(!typeFound) {
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser","Expected property type"));
+ error.setLine(node->typeToken.startLine);
+ error.setColumn(node->typeToken.startColumn);
+ _parser->_errors << error;
+ return false;
+ }
+
+ if (node->isReadonlyMember) {
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser","Readonly not yet supported"));
+ error.setLine(node->readonlyToken.startLine);
+ error.setColumn(node->readonlyToken.startColumn);
+ _parser->_errors << error;
+ return false;
+
+ }
+ Object::DynamicProperty property;
+ property.isDefaultProperty = node->isDefaultMember;
+ property.type = type;
+ if (type >= Object::DynamicProperty::Custom) {
+ QmlScriptParser::TypeReference *typeRef =
+ _parser->findOrCreateType(memberType);
+ typeRef->refObjects.append(_stateStack.top().object);
+ }
+ property.customType = memberType.toUtf8();
+ property.name = name.toUtf8();
+ property.location = location(node->firstSourceLocation(),
+ node->lastSourceLocation());
+
+ if (node->expression) { // default value
+ property.defaultValue = new Property;
+ property.defaultValue->parent = _stateStack.top().object;
+ property.defaultValue->location =
+ location(node->expression->firstSourceLocation(),
+ node->expression->lastSourceLocation());
+ Value *value = new Value;
+ value->location = location(node->expression->firstSourceLocation(),
+ node->expression->lastSourceLocation());
+ value->value = getVariant(node->expression);
+ property.defaultValue->values << value;
+ }
+
+ _stateStack.top().object->dynamicProperties << property;
+ }
+
+ return true;
+}
+
+
+// UiObjectMember: UiQualifiedId UiObjectInitializer ;
+bool ProcessAST::visit(AST::UiObjectDefinition *node)
+{
+ LocationSpan l = location(node->firstSourceLocation(),
+ node->lastSourceLocation());
+
+ defineObjectBinding(/*propertyName = */ 0,
+ node->qualifiedTypeNameId,
+ l,
+ node->initializer);
+
+ return false;
+}
+
+
+// UiObjectMember: UiQualifiedId T_COLON UiQualifiedId UiObjectInitializer ;
+bool ProcessAST::visit(AST::UiObjectBinding *node)
+{
+ LocationSpan l = location(node->qualifiedTypeNameId->identifierToken,
+ node->initializer->rbraceToken);
+
+ defineObjectBinding(node->qualifiedId,
+ node->qualifiedTypeNameId,
+ l,
+ node->initializer);
+
+ return false;
+}
+
+QmlParser::Variant ProcessAST::getVariant(AST::ExpressionNode *expr)
+{
+ if (AST::StringLiteral *lit = AST::cast<AST::StringLiteral *>(expr)) {
+ return QmlParser::Variant(lit->value->asString());
+ } else if (expr->kind == AST::Node::Kind_TrueLiteral) {
+ return QmlParser::Variant(true);
+ } else if (expr->kind == AST::Node::Kind_FalseLiteral) {
+ return QmlParser::Variant(false);
+ } else if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(expr)) {
+ return QmlParser::Variant(lit->value, asString(expr));
+ } else {
+
+ if (AST::UnaryMinusExpression *unaryMinus = AST::cast<AST::UnaryMinusExpression *>(expr)) {
+ if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(unaryMinus->expression)) {
+ return QmlParser::Variant(-lit->value, asString(expr));
+ }
+ }
+
+ return QmlParser::Variant(asString(expr), expr);
+ }
+}
+
+
+// UiObjectMember: UiQualifiedId T_COLON Statement ;
+bool ProcessAST::visit(AST::UiScriptBinding *node)
+{
+ int propertyCount = 0;
+ AST::UiQualifiedId *propertyName = node->qualifiedId;
+ for (; propertyName; propertyName = propertyName->next){
+ ++propertyCount;
+ _stateStack.pushProperty(propertyName->name->asString(),
+ location(propertyName));
+ }
+
+ Property *prop = currentProperty();
+
+ QmlParser::Variant primitive;
+
+ if (AST::ExpressionStatement *stmt = AST::cast<AST::ExpressionStatement *>(node->statement)) {
+ primitive = getVariant(stmt->expression);
+ } else { // do binding
+ primitive = QmlParser::Variant(asString(node->statement),
+ node->statement);
+ }
+
+ prop->location.range.length = prop->location.range.offset + prop->location.range.length - node->qualifiedId->identifierToken.offset;
+ prop->location.range.offset = node->qualifiedId->identifierToken.offset;
+ Value *v = new Value;
+ v->value = primitive;
+ v->location = location(node->statement->firstSourceLocation(),
+ node->statement->lastSourceLocation());
+
+ prop->addValue(v);
+
+ while (propertyCount--)
+ _stateStack.pop();
+
+ return true;
+}
+
+static QList<int> collectCommas(AST::UiArrayMemberList *members)
+{
+ QList<int> commas;
+
+ if (members) {
+ for (AST::UiArrayMemberList *it = members->next; it; it = it->next) {
+ commas.append(it->commaToken.offset);
+ }
+ }
+
+ return commas;
+}
+
+// UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ;
+bool ProcessAST::visit(AST::UiArrayBinding *node)
+{
+ int propertyCount = 0;
+ AST::UiQualifiedId *propertyName = node->qualifiedId;
+ for (; propertyName; propertyName = propertyName->next){
+ ++propertyCount;
+ _stateStack.pushProperty(propertyName->name->asString(),
+ location(propertyName));
+ }
+
+ accept(node->members);
+
+ // For the DOM, store the position of the T_LBRACKET upto the T_RBRACKET as the range:
+ Property* prop = currentProperty();
+ prop->listValueRange.offset = node->lbracketToken.offset;
+ prop->listValueRange.length = node->rbracketToken.offset + node->rbracketToken.length - node->lbracketToken.offset;
+
+ // Store the positions of the comma token too, again for the DOM to be able to retreive it.
+ prop->listCommaPositions = collectCommas(node->members);
+
+ while (propertyCount--)
+ _stateStack.pop();
+
+ return false;
+}
+
+bool ProcessAST::visit(AST::UiSourceElement *node)
+{
+ QmlParser::Object *obj = currentObject();
+
+ bool isScript = (obj && obj->typeName == "Script");
+
+ if (!isScript) {
+
+ if (AST::FunctionDeclaration *funDecl = AST::cast<AST::FunctionDeclaration *>(node->sourceElement)) {
+
+ Object::DynamicSlot slot;
+
+ AST::FormalParameterList *f = funDecl->formals;
+ while (f) {
+ slot.parameterNames << f->name->asString().toUtf8();
+ f = f->finish();
+ }
+
+ QString body = textAt(funDecl->lbraceToken, funDecl->rbraceToken);
+ slot.name = funDecl->name->asString().toUtf8();
+ slot.body = body;
+ obj->dynamicSlots << slot;
+
+ } else {
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser","QmlJS declaration outside Script element"));
+ error.setLine(node->firstSourceLocation().startLine);
+ error.setColumn(node->firstSourceLocation().startColumn);
+ _parser->_errors << error;
+ }
+ return false;
+
+ } else {
+ QString source;
+
+ int line = 0;
+ if (AST::FunctionDeclaration *funDecl = AST::cast<AST::FunctionDeclaration *>(node->sourceElement)) {
+ line = funDecl->functionToken.startLine;
+ source = asString(funDecl);
+ } else if (AST::VariableStatement *varStmt = AST::cast<AST::VariableStatement *>(node->sourceElement)) {
+ // ignore variable declarations
+ line = varStmt->declarationKindToken.startLine;
+
+ QmlError error;
+ error.setDescription(QCoreApplication::translate("QmlParser", "Variable declarations not allow in inline Script blocks"));
+ error.setLine(node->firstSourceLocation().startLine);
+ error.setColumn(node->firstSourceLocation().startColumn);
+ _parser->_errors << error;
+ return false;
+ }
+
+ Value *value = new Value;
+ value->location = location(node->firstSourceLocation(),
+ node->lastSourceLocation());
+ value->value = QmlParser::Variant(source);
+
+ obj->getDefaultProperty()->addValue(value);
+ }
+
+ return false;
+}
+
+} // end of anonymous namespace
+
+
+QmlScriptParser::QmlScriptParser()
+: root(0), data(0)
+{
+
+}
+
+QmlScriptParser::~QmlScriptParser()
+{
+ clear();
+}
+
+class QmlScriptParserJsASTData
+{
+public:
+ QmlScriptParserJsASTData(const QString &filename)
+ : nodePool(filename, &engine) {}
+
+ Engine engine;
+ NodePool nodePool;
+};
+
+bool QmlScriptParser::parse(const QByteArray &qmldata, const QUrl &url)
+{
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ QmlPerfTimer<QmlPerf::QmlParsing> pt;
+#endif
+ clear();
+
+ const QString fileName = url.toString();
+
+ QTextStream stream(qmldata, QIODevice::ReadOnly);
+ stream.setCodec("UTF-8");
+ const QString code = stream.readAll();
+
+ data = new QmlScriptParserJsASTData(fileName);
+
+ Lexer lexer(&data->engine);
+ lexer.setCode(code, /*line = */ 1);
+
+ Parser parser(&data->engine);
+
+ if (! parser.parse() || !_errors.isEmpty()) {
+
+ // Extract errors from the parser
+ foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
+
+ if (m.isWarning())
+ continue;
+
+ QmlError error;
+ error.setUrl(url);
+ error.setDescription(m.message);
+ error.setLine(m.loc.startLine);
+ error.setColumn(m.loc.startColumn);
+ _errors << error;
+
+ }
+ }
+
+ if (_errors.isEmpty()) {
+ ProcessAST process(this);
+ process(code, parser.ast());
+
+ // Set the url for process errors
+ for(int ii = 0; ii < _errors.count(); ++ii)
+ _errors[ii].setUrl(url);
+ }
+
+ return _errors.isEmpty();
+}
+
+QList<QmlScriptParser::TypeReference*> QmlScriptParser::referencedTypes() const
+{
+ return _refTypes;
+}
+
+QList<QUrl> QmlScriptParser::referencedResources() const
+{
+ return _refUrls;
+}
+
+Object *QmlScriptParser::tree() const
+{
+ return root;
+}
+
+QList<QmlScriptParser::Import> QmlScriptParser::imports() const
+{
+ return _imports;
+}
+
+QList<QmlError> QmlScriptParser::errors() const
+{
+ return _errors;
+}
+
+void QmlScriptParser::clear()
+{
+ if (root) {
+ root->release();
+ root = 0;
+ }
+ _imports.clear();
+ qDeleteAll(_refTypes);
+ _refTypes.clear();
+ _errors.clear();
+
+ if (data) {
+ delete data;
+ data = 0;
+ }
+}
+
+QmlScriptParser::TypeReference *QmlScriptParser::findOrCreateType(const QString &name)
+{
+ TypeReference *type = 0;
+ int i = 0;
+ for (; i < _refTypes.size(); ++i) {
+ if (_refTypes.at(i)->name == name) {
+ type = _refTypes.at(i);
+ break;
+ }
+ }
+ if (!type) {
+ type = new TypeReference(i, name);
+ _refTypes.append(type);
+ }
+
+ return type;
+}
+
+void QmlScriptParser::setTree(Object *tree)
+{
+ Q_ASSERT(! root);
+
+ root = tree;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlscriptparser_p.h b/src/declarative/qml/qmlscriptparser_p.h
new file mode 100644
index 0000000..16888aa
--- /dev/null
+++ b/src/declarative/qml/qmlscriptparser_p.h
@@ -0,0 +1,137 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+#ifndef QMLSCRIPTPARSER_P_H
+#define QMLSCRIPTPARSER_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 "qmlerror.h"
+#include "qmlparser_p.h"
+
+#include <QtCore/QList>
+#include <QtCore/QUrl>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QByteArray;
+
+class QmlScriptParserJsASTData;
+class QmlScriptParser
+{
+public:
+ class Import
+ {
+ public:
+ Import() : type(Library) {}
+
+ enum Type { Library, File };
+ Type type;
+
+ QString uri;
+ QString qualifier;
+ QString version;
+
+ QmlParser::LocationSpan location;
+ };
+
+ class TypeReference
+ {
+ public:
+ TypeReference(int typeId, const QString &typeName) : id(typeId), name(typeName) {}
+
+ int id;
+ // type as it has been referenced in Qml
+ QString name;
+ // objects in parse tree referencing the type
+ QList<QmlParser::Object*> refObjects;
+ };
+
+ QmlScriptParser();
+ ~QmlScriptParser();
+
+ bool parse(const QByteArray &data, const QUrl &url = QUrl());
+
+ QList<TypeReference*> referencedTypes() const;
+ QList<QUrl> referencedResources() const;
+
+ QmlParser::Object *tree() const;
+ QList<Import> imports() const;
+
+ void clear();
+
+ QList<QmlError> errors() const;
+
+// ### private:
+ TypeReference *findOrCreateType(const QString &name);
+ void setTree(QmlParser::Object *tree);
+
+ void setScriptFile(const QString &filename) {_scriptFile = filename; }
+ QString scriptFile() const { return _scriptFile; }
+
+// ### private:
+ QList<QmlError> _errors;
+
+ QmlParser::Object *root;
+ QList<Import> _imports;
+ QList<TypeReference*> _refTypes;
+ QList<QUrl> _refUrls;
+ QString _scriptFile;
+ QmlScriptParserJsASTData *data;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLSCRIPTPARSER_P_H
diff --git a/src/declarative/qml/qmlscriptstring.cpp b/src/declarative/qml/qmlscriptstring.cpp
new file mode 100644
index 0000000..1ccad53
--- /dev/null
+++ b/src/declarative/qml/qmlscriptstring.cpp
@@ -0,0 +1,154 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlscriptstring.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlScriptStringPrivate : public QSharedData
+{
+public:
+ QmlScriptStringPrivate() : context(0), scope(0) {}
+
+ QmlContext *context;
+ QObject *scope;
+ QString script;
+};
+
+/*!
+\class QmlScriptString
+\brief The QmlScriptString class encapsulates a script and its context.
+
+The QmlScriptString is used by properties that want to accept a script "assignment" from QML.
+
+Normally, the following code would result in a binding being established for the \c script
+property. If the property had a type of QmlScriptString, the script - \e {console.log(1921)} - itself
+would be passed to the property and it could choose how to handle it.
+
+\code
+MyType {
+ script: console.log(1921)
+}
+\endcode
+*/
+
+/*!
+Construct an empty instance.
+*/
+QmlScriptString::QmlScriptString()
+: d(new QmlScriptStringPrivate)
+{
+}
+
+/*!
+Copy \a other.
+*/
+QmlScriptString::QmlScriptString(const QmlScriptString &other)
+: d(other.d)
+{
+}
+
+/*!
+\internal
+*/
+QmlScriptString::~QmlScriptString()
+{
+}
+
+/*!
+Assign \a other to this.
+*/
+QmlScriptString &QmlScriptString::operator=(const QmlScriptString &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+Return the context for the script.
+*/
+QmlContext *QmlScriptString::context() const
+{
+ return d->context;
+}
+
+/*!
+Sets the \a context for the script.
+*/
+void QmlScriptString::setContext(QmlContext *context)
+{
+ d->context = context;
+}
+
+/*!
+Returns the scope object for the script.
+*/
+QObject *QmlScriptString::scopeObject() const
+{
+ return d->scope;
+}
+
+/*!
+Sets the scope \a object for the script.
+*/
+void QmlScriptString::setScopeObject(QObject *object)
+{
+ d->scope = object;
+}
+
+/*!
+Returns the script text.
+*/
+QString QmlScriptString::script() const
+{
+ return d->script;
+}
+
+/*!
+Sets the \a script text.
+*/
+void QmlScriptString::setScript(const QString &script)
+{
+ d->script = script;
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/qml/qmlscriptstring.h b/src/declarative/qml/qmlscriptstring.h
new file mode 100644
index 0000000..73a473f
--- /dev/null
+++ b/src/declarative/qml/qmlscriptstring.h
@@ -0,0 +1,87 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSCRIPTSTRING_H
+#define QMLSCRIPTSTRING_H
+
+#include <QtCore/qstring.h>
+#include <QtCore/qshareddata.h>
+#include <QtCore/qmetatype.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QObject;
+class QmlContext;
+class QmlScriptStringPrivate;
+class Q_DECLARATIVE_EXPORT QmlScriptString
+{
+public:
+ QmlScriptString();
+ QmlScriptString(const QmlScriptString &);
+ ~QmlScriptString();
+
+ QmlScriptString &operator=(const QmlScriptString &);
+
+ QmlContext *context() const;
+ void setContext(QmlContext *);
+
+ QObject *scopeObject() const;
+ void setScopeObject(QObject *);
+
+ QString script() const;
+ void setScript(const QString &);
+
+private:
+ QSharedDataPointer<QmlScriptStringPrivate> d;
+};
+
+Q_DECLARE_METATYPE(QmlScriptString);
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLSCRIPTSTRING_H
+
diff --git a/src/declarative/qml/qmlsqldatabase.cpp b/src/declarative/qml/qmlsqldatabase.cpp
new file mode 100644
index 0000000..684caa2
--- /dev/null
+++ b/src/declarative/qml/qmlsqldatabase.cpp
@@ -0,0 +1,425 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlsqldatabase_p.h"
+
+#include "qmlengine.h"
+#include "qmlengine_p.h"
+#include "qmlrefcount_p.h"
+#include "qmlengine_p.h"
+
+#include <QtCore/qobject.h>
+#include <QtScript/qscriptvalue.h>
+#include <QtScript/qscriptvalueiterator.h>
+#include <QtScript/qscriptcontext.h>
+#include <QtScript/qscriptengine.h>
+#include <QtScript/qscriptclasspropertyiterator.h>
+#include <QtSql/qsqldatabase.h>
+#include <QtSql/qsqlquery.h>
+#include <QtSql/qsqlerror.h>
+#include <QtSql/qsqlrecord.h>
+#include <QtCore/qstack.h>
+#include <QtCore/qcryptographichash.h>
+#include <QtCore/qsettings.h>
+#include <QtCore/qdir.h>
+#include <QtCore/qdebug.h>
+
+Q_DECLARE_METATYPE(QSqlDatabase)
+Q_DECLARE_METATYPE(QSqlQuery)
+
+class QmlSqlQueryScriptClass: public QScriptClass {
+public:
+ QmlSqlQueryScriptClass(QScriptEngine *engine) : QScriptClass(engine)
+ {
+ str_length = engine->toStringHandle(QLatin1String("length"));
+ str_forwardOnly = engine->toStringHandle(QLatin1String("forwardOnly")); // not in HTML5 (an optimization)
+ }
+
+ QueryFlags queryProperty(const QScriptValue &,
+ const QScriptString &name,
+ QueryFlags flags, uint *)
+ {
+ if (flags & HandlesReadAccess) {
+ if (name == str_length) {
+ return HandlesReadAccess;
+ } else if (name == str_forwardOnly) {
+ return flags;
+ }
+ }
+ if (flags & HandlesWriteAccess)
+ if (name == str_forwardOnly)
+ return flags;
+ return 0;
+ }
+
+ QScriptValue property(const QScriptValue &object,
+ const QScriptString &name, uint)
+ {
+ QSqlQuery query = qscriptvalue_cast<QSqlQuery>(object.data());
+ if (name == str_length) {
+ int s = query.size();
+ if (s<0) {
+ // Inefficient.
+ if (query.last()) {
+ return query.at()+1;
+ } else {
+ return 0;
+ }
+ } else {
+ return s;
+ }
+ } else if (name == str_forwardOnly) {
+ return query.isForwardOnly();
+ }
+ return engine()->undefinedValue();
+ }
+
+ void setProperty(QScriptValue &object,
+ const QScriptString &name, uint, const QScriptValue & value)
+ {
+ if (name == str_forwardOnly) {
+ QSqlQuery query = qscriptvalue_cast<QSqlQuery>(object.data());
+ query.setForwardOnly(value.toBool());
+ }
+ }
+
+ QScriptValue::PropertyFlags propertyFlags(const QScriptValue &/*object*/, const QScriptString &name, uint /*id*/)
+ {
+ if (name == str_length) {
+ return QScriptValue::Undeletable
+ | QScriptValue::SkipInEnumeration;
+ }
+ return QScriptValue::Undeletable;
+ }
+
+private:
+ QScriptString str_length;
+ QScriptString str_forwardOnly;
+};
+
+// If the spec changes to allow iteration, check git history...
+// class QmlSqlQueryScriptClassPropertyIterator : public QScriptClassPropertyIterator
+
+
+
+enum SqlException {
+ UNKNOWN_ERR,
+ DATABASE_ERR,
+ VERSION_ERR,
+ TOO_LARGE_ERR,
+ QUOTA_ERR,
+ SYNTAX_ERR,
+ CONSTRAINT_ERR,
+ TIMEOUT_ERR
+};
+
+static const char* sqlerror[] = {
+ "UNKNOWN_ERR",
+ "DATABASE_ERR",
+ "VERSION_ERR",
+ "TOO_LARGE_ERR",
+ "QUOTA_ERR",
+ "SYNTAX_ERR",
+ "CONSTRAINT_ERR",
+ "TIMEOUT_ERR",
+ 0
+};
+
+#define THROW_SQL(error, desc) \
+{ \
+ QScriptValue errorValue = context->throwError(desc); \
+ errorValue.setProperty(QLatin1String("code"), error); \
+ return errorValue; \
+}
+
+
+static QString databaseFile(const QString& connectionName, QScriptEngine *engine)
+{
+ QmlScriptEngine *qmlengine = static_cast<QmlScriptEngine*>(engine);
+ QString basename = qmlengine->offlineStoragePath
+ + QDir::separator() + QLatin1String("Databases") + QDir::separator();
+ basename += connectionName;
+ return basename;
+}
+
+
+
+static QScriptValue qmlsqldatabase_item(QScriptContext *context, QScriptEngine *engine)
+{
+ QSqlQuery query = qscriptvalue_cast<QSqlQuery>(context->thisObject().data());
+ int i = context->argument(0).toNumber();
+ if (query.at() == i || query.seek(i)) { // Qt 4.6 doesn't optimize seek(at())
+ QSqlRecord r = query.record();
+ QScriptValue row = engine->newObject();
+ for (int j=0; j<r.count(); ++j) {
+ row.setProperty(r.fieldName(j), QScriptValue(engine,r.value(j).toString()));
+ }
+ return row;
+ }
+ return engine->undefinedValue();
+}
+
+static QScriptValue qmlsqldatabase_executeSql_outsidetransaction(QScriptContext *context, QScriptEngine * /*engine*/)
+{
+ THROW_SQL(DATABASE_ERR,QmlEngine::tr("executeSql called outside transaction()"));
+}
+
+static QScriptValue qmlsqldatabase_executeSql(QScriptContext *context, QScriptEngine *engine)
+{
+ QSqlDatabase db = qscriptvalue_cast<QSqlDatabase>(context->thisObject());
+ QString sql = context->argument(0).toString();
+ QSqlQuery query(db);
+ bool err = false;
+
+ QScriptValue result;
+
+ if (query.prepare(sql)) {
+ if (context->argumentCount() > 1) {
+ QScriptValue values = context->argument(1);
+ if (values.isObject()) {
+ for (QScriptValueIterator it(values); it.hasNext();) {
+ it.next();
+ query.bindValue(it.name(),it.value().toVariant());
+ }
+ } else {
+ query.bindValue(0,values.toVariant());
+ }
+ }
+ if (query.exec()) {
+ result = engine->newObject();
+ QmlScriptEngine *qmlengine = static_cast<QmlScriptEngine*>(engine);
+ if (!qmlengine->sqlQueryClass)
+ qmlengine->sqlQueryClass = new QmlSqlQueryScriptClass(engine);
+ QScriptValue rows = engine->newObject(qmlengine->sqlQueryClass);
+ rows.setData(engine->newVariant(qVariantFromValue(query)));
+ rows.setProperty(QLatin1String("item"), engine->newFunction(qmlsqldatabase_item,1), QScriptValue::SkipInEnumeration);
+ result.setProperty(QLatin1String("rows"),rows);
+ result.setProperty(QLatin1String("rowsAffected"),query.numRowsAffected());
+ result.setProperty(QLatin1String("insertId"),query.lastInsertId().toString());
+ } else {
+ err = true;
+ }
+ } else {
+ err = true;
+ }
+ if (err)
+ THROW_SQL(DATABASE_ERR,query.lastError().text());
+ return result;
+}
+
+static QScriptValue qmlsqldatabase_executeSql_readonly(QScriptContext *context, QScriptEngine *engine)
+{
+ QString sql = context->argument(0).toString();
+ if (sql.startsWith(QLatin1String("SELECT"),Qt::CaseInsensitive)) {
+ return qmlsqldatabase_executeSql(context,engine);
+ } else {
+ THROW_SQL(SYNTAX_ERR,QmlEngine::tr("Read-only Transaction"))
+ }
+}
+
+static QScriptValue qmlsqldatabase_change_version(QScriptContext *context, QScriptEngine *engine)
+{
+ if (context->argumentCount() < 2)
+ return engine->undefinedValue();
+
+ QSqlDatabase db = qscriptvalue_cast<QSqlDatabase>(context->thisObject());
+ QString from_version = context->argument(0).toString();
+ QString to_version = context->argument(1).toString();
+ QScriptValue callback = context->argument(2);
+
+ QScriptValue instance = engine->newObject();
+ instance.setProperty(QLatin1String("executeSql"), engine->newFunction(qmlsqldatabase_executeSql,1));
+ QScriptValue tx = engine->newVariant(instance,qVariantFromValue(db));
+
+ QString foundvers = context->thisObject().property(QLatin1String("version")).toString();
+ if (from_version!=foundvers) {
+ THROW_SQL(2,QmlEngine::tr("Version mismatch: expected %1, found %2").arg(from_version).arg(foundvers));
+ return engine->undefinedValue();
+ }
+
+ bool ok = true;
+ if (callback.isFunction()) {
+ ok = false;
+ db.transaction();
+ callback.call(QScriptValue(), QScriptValueList() << tx);
+ if (engine->hasUncaughtException()) {
+ db.rollback();
+ } else {
+ if (!db.commit()) {
+ db.rollback();
+ THROW_SQL(0,QmlEngine::tr("SQL transaction failed"));
+ } else {
+ ok = true;
+ }
+ }
+ }
+
+ if (ok) {
+ context->thisObject().setProperty(QLatin1String("version"), to_version, QScriptValue::ReadOnly);
+ QSettings ini(databaseFile(db.connectionName(),engine)+QLatin1String(".ini"),QSettings::IniFormat);
+ ini.setValue(QLatin1String("Version"), to_version);
+ }
+
+ return engine->undefinedValue();
+}
+
+static QScriptValue qmlsqldatabase_transaction_shared(QScriptContext *context, QScriptEngine *engine, bool readOnly)
+{
+ QSqlDatabase db = qscriptvalue_cast<QSqlDatabase>(context->thisObject());
+ QScriptValue callback = context->argument(0);
+ if (!callback.isFunction())
+ THROW_SQL(UNKNOWN_ERR,QmlEngine::tr("transaction: missing callback"));
+
+ QScriptValue instance = engine->newObject();
+ instance.setProperty(QLatin1String("executeSql"),
+ engine->newFunction(readOnly ? qmlsqldatabase_executeSql_readonly : qmlsqldatabase_executeSql,1));
+ QScriptValue tx = engine->newVariant(instance,qVariantFromValue(db));
+
+ db.transaction();
+ callback.call(QScriptValue(), QScriptValueList() << tx);
+ instance.setProperty(QLatin1String("executeSql"),
+ engine->newFunction(qmlsqldatabase_executeSql_outsidetransaction));
+ if (engine->hasUncaughtException()) {
+ db.rollback();
+ } else {
+ if (!db.commit())
+ db.rollback();
+ }
+ return engine->undefinedValue();
+}
+
+static QScriptValue qmlsqldatabase_transaction(QScriptContext *context, QScriptEngine *engine)
+{
+ return qmlsqldatabase_transaction_shared(context,engine,false);
+}
+static QScriptValue qmlsqldatabase_read_transaction(QScriptContext *context, QScriptEngine *engine)
+{
+ return qmlsqldatabase_transaction_shared(context,engine,true);
+}
+
+/*
+ Currently documented in doc/src/declarastive/globalobject.qdoc
+*/
+static QScriptValue qmlsqldatabase_open_sync(QScriptContext *context, QScriptEngine *engine)
+{
+ QSqlDatabase database;
+
+ QString dbname = context->argument(0).toString();
+ QString dbversion = context->argument(1).toString();
+ QString dbdescription = context->argument(2).toString();
+ int dbestimatedsize = context->argument(3).toNumber();
+ QScriptValue dbcreationCallback = context->argument(4);
+
+ QCryptographicHash md5(QCryptographicHash::Md5);
+ md5.addData(dbname.toUtf8());
+ QString dbid(QLatin1String(md5.result().toHex()));
+
+ QString basename = databaseFile(dbid,engine);
+ bool created = false;
+ QString version = dbversion;
+
+ {
+ QSettings ini(basename+QLatin1String(".ini"),QSettings::IniFormat);
+
+ if (QSqlDatabase::connectionNames().contains(dbid)) {
+ database = QSqlDatabase::database(dbid);
+ version = ini.value(QLatin1String("Version")).toString();
+ if (version != dbversion && !dbversion.isEmpty() && !version.isEmpty())
+ THROW_SQL(VERSION_ERR,QmlEngine::tr("SQL: database version mismatch"));
+ } else {
+ created = !QFile::exists(basename+QLatin1String(".sqlite"));
+ database = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), dbid);
+ QDir().mkpath(basename);
+ if (created) {
+ ini.setValue(QLatin1String("Name"), dbname);
+ if (dbcreationCallback.isFunction())
+ version = QString();
+ ini.setValue(QLatin1String("Version"), version);
+ ini.setValue(QLatin1String("Description"), dbdescription);
+ ini.setValue(QLatin1String("EstimatedSize"), dbestimatedsize);
+ ini.setValue(QLatin1String("Driver"), QLatin1String("QSQLITE"));
+ } else {
+ if (!dbversion.isEmpty() && ini.value(QLatin1String("Version")) != dbversion) {
+ // Incompatible
+ THROW_SQL(VERSION_ERR,QmlEngine::tr("SQL: database version mismatch"));
+ }
+ version = ini.value(QLatin1String("Version")).toString();
+ }
+ database.setDatabaseName(basename+QLatin1String(".sqlite"));
+ }
+ if (!database.isOpen())
+ database.open();
+ }
+
+ QScriptValue instance = engine->newObject();
+ instance.setProperty(QLatin1String("transaction"), engine->newFunction(qmlsqldatabase_transaction,1));
+ instance.setProperty(QLatin1String("readTransaction"), engine->newFunction(qmlsqldatabase_read_transaction,1));
+ instance.setProperty(QLatin1String("version"), version, QScriptValue::ReadOnly);
+ instance.setProperty(QLatin1String("changeVersion"), engine->newFunction(qmlsqldatabase_change_version,3));
+
+ QScriptValue result = engine->newVariant(instance,qVariantFromValue(database));
+
+ if (created && dbcreationCallback.isFunction()) {
+ dbcreationCallback.call(QScriptValue(), QScriptValueList() << result);
+ }
+
+ return result;
+}
+
+void qt_add_qmlsqldatabase(QScriptEngine *engine)
+{
+ QScriptValue openDatabase = engine->newFunction(qmlsqldatabase_open_sync, 4);
+ engine->globalObject().setProperty(QLatin1String("openDatabaseSync"), openDatabase);
+
+ QScriptValue sqlExceptionPrototype = engine->newObject();
+ for (int i=0; sqlerror[i]; ++i)
+ sqlExceptionPrototype.setProperty(QLatin1String(sqlerror[i]),
+ i,QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+
+ engine->globalObject().setProperty(QLatin1String("SQLException"), sqlExceptionPrototype);
+}
+
+/*
+HTML5 "spec" says "rs.rows[n]", but WebKit only impelments "rs.rows.item(n)". We do both (and property iterator).
+We add a "forwardOnly" property that stops Qt caching results (code promises to only go forward
+through the data.
+*/
+
diff --git a/src/declarative/qml/qmlsqldatabase_p.h b/src/declarative/qml/qmlsqldatabase_p.h
new file mode 100644
index 0000000..5a38bf0
--- /dev/null
+++ b/src/declarative/qml/qmlsqldatabase_p.h
@@ -0,0 +1,60 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSQLDATABASE_P_H
+#define QMLSQLDATABASE_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.
+//
+
+class QScriptEngine;
+void qt_add_qmlsqldatabase(QScriptEngine *engine);
+
+#endif // QMLSQLDATABASE_P_H
+
diff --git a/src/declarative/qml/qmlstringconverters.cpp b/src/declarative/qml/qmlstringconverters.cpp
new file mode 100644
index 0000000..2963ab5
--- /dev/null
+++ b/src/declarative/qml/qmlstringconverters.cpp
@@ -0,0 +1,276 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlstringconverters_p.h"
+
+#include <QtGui/qcolor.h>
+#include <QtGui/qvector3d.h>
+#include <QtCore/qpoint.h>
+#include <QtCore/qrect.h>
+#include <QtCore/qsize.h>
+#include <QtCore/qvariant.h>
+#include <QtCore/qdatetime.h>
+
+QT_BEGIN_NAMESPACE
+
+static uchar fromHex(const uchar c, const uchar c2)
+{
+ uchar rv = 0;
+ if (c >= '0' && c <= '9')
+ rv += (c - '0') * 16;
+ else if (c >= 'A' && c <= 'F')
+ rv += (c - 'A' + 10) * 16;
+ else if (c >= 'a' && c <= 'f')
+ rv += (c - 'a' + 10) * 16;
+
+ if (c2 >= '0' && c2 <= '9')
+ rv += (c2 - '0');
+ else if (c2 >= 'A' && c2 <= 'F')
+ rv += (c2 - 'A' + 10);
+ else if (c2 >= 'a' && c2 <= 'f')
+ rv += (c2 - 'a' + 10);
+
+ return rv;
+}
+
+static uchar fromHex(const QString &s, int idx)
+{
+ uchar c = s.at(idx).toAscii();
+ uchar c2 = s.at(idx + 1).toAscii();
+ return fromHex(c, c2);
+}
+
+QVariant QmlStringConverters::variantFromString(const QString &s)
+{
+ if (s.isEmpty())
+ return QVariant(s);
+ if (s.startsWith(QLatin1Char('\'')) && s.endsWith(QLatin1Char('\''))) {
+ QString data = s.mid(1, s.length() - 2);
+ return QVariant(data);
+ }
+ bool ok = false;
+ QRectF r = rectFFromString(s, &ok);
+ if (ok) return QVariant(r);
+ QColor c = colorFromString(s, &ok);
+ if (ok) return QVariant(c);
+ QPointF p = pointFFromString(s, &ok);
+ if (ok) return QVariant(p);
+ QSizeF sz = sizeFFromString(s, &ok);
+ if (ok) return QVariant(sz);
+ QVector3D v = vector3DFromString(s, &ok);
+ if (ok) return qVariantFromValue(v);
+
+ return QVariant(s);
+}
+
+QVariant QmlStringConverters::variantFromString(const QString &s, int preferredType, bool *ok)
+{
+ switch (preferredType) {
+ case QMetaType::QColor:
+ return QVariant::fromValue(colorFromString(s, ok));
+ case QMetaType::QDate:
+ return QVariant::fromValue(dateFromString(s, ok));
+ case QMetaType::QTime:
+ return QVariant::fromValue(timeFromString(s, ok));
+ case QMetaType::QDateTime:
+ return QVariant::fromValue(dateTimeFromString(s, ok));
+ case QMetaType::QPointF:
+ return QVariant::fromValue(pointFFromString(s, ok));
+ case QMetaType::QPoint:
+ return QVariant::fromValue(pointFFromString(s, ok).toPoint());
+ case QMetaType::QSizeF:
+ return QVariant::fromValue(sizeFFromString(s, ok));
+ case QMetaType::QSize:
+ return QVariant::fromValue(sizeFFromString(s, ok).toSize());
+ case QMetaType::QRectF:
+ return QVariant::fromValue(rectFFromString(s, ok));
+ case QMetaType::QRect:
+ return QVariant::fromValue(rectFFromString(s, ok).toRect());
+ case QMetaType::QVector3D:
+ return QVariant::fromValue(vector3DFromString(s, ok));
+ default:
+ if (ok) *ok = false;
+ return QVariant();
+ }
+}
+
+QColor QmlStringConverters::colorFromString(const QString &s, bool *ok)
+{
+ if (s.startsWith(QLatin1Char('#')) && s.length() == 9) {
+ uchar a = fromHex(s, 1);
+ uchar r = fromHex(s, 3);
+ uchar g = fromHex(s, 5);
+ uchar b = fromHex(s, 7);
+ if (ok) *ok = true;
+ return QColor(r, g, b, a);
+ } else {
+ QColor rv;
+ if (s.startsWith(QLatin1Char('#')) || QColor::colorNames().contains(s.toLower()))
+ rv = QColor(s);
+ if (ok) *ok = rv.isValid();
+ return rv;
+ }
+}
+
+QDate QmlStringConverters::dateFromString(const QString &s, bool *ok)
+{
+ QDate d = QDate::fromString(s, Qt::ISODate);
+ if (ok) *ok = d.isValid();
+ return d;
+}
+
+QTime QmlStringConverters::timeFromString(const QString &s, bool *ok)
+{
+ QTime t = QTime::fromString(s, Qt::ISODate);
+ if (ok) *ok = t.isValid();
+ return t;
+}
+
+QDateTime QmlStringConverters::dateTimeFromString(const QString &s, bool *ok)
+{
+ QDateTime d = QDateTime::fromString(s, Qt::ISODate);
+ if (ok) *ok = d.isValid();
+ return d;
+}
+
+//expects input of "x,y"
+QPointF QmlStringConverters::pointFFromString(const QString &s, bool *ok)
+{
+ if (s.count(QLatin1Char(',')) != 1) {
+ if (ok)
+ *ok = false;
+ return QPointF();
+ }
+
+ bool xGood, yGood;
+ int index = s.indexOf(QLatin1Char(','));
+ qreal xCoord = s.left(index).toDouble(&xGood);
+ qreal yCoord = s.mid(index+1).toDouble(&yGood);
+ if (!xGood || !yGood) {
+ if (ok)
+ *ok = false;
+ return QPointF();
+ }
+
+ if (ok)
+ *ok = true;
+ return QPointF(xCoord, yCoord);
+}
+
+//expects input of "widthxheight"
+QSizeF QmlStringConverters::sizeFFromString(const QString &s, bool *ok)
+{
+ if (s.count(QLatin1Char('x')) != 1) {
+ if (ok)
+ *ok = false;
+ return QSizeF();
+ }
+
+ bool wGood, hGood;
+ int index = s.indexOf(QLatin1Char('x'));
+ qreal width = s.left(index).toDouble(&wGood);
+ qreal height = s.mid(index+1).toDouble(&hGood);
+ if (!wGood || !hGood) {
+ if (ok)
+ *ok = false;
+ return QSizeF();
+ }
+
+ if (ok)
+ *ok = true;
+ return QSizeF(width, height);
+}
+
+//expects input of "x,y,widthxheight" //### use space instead of second comma?
+QRectF QmlStringConverters::rectFFromString(const QString &s, bool *ok)
+{
+ if (s.count(QLatin1Char(',')) != 2 || s.count(QLatin1Char('x')) != 1) {
+ if (ok)
+ *ok = false;
+ return QRectF();
+ }
+
+ bool xGood, yGood, wGood, hGood;
+ int index = s.indexOf(QLatin1Char(','));
+ qreal x = s.left(index).toDouble(&xGood);
+ int index2 = s.indexOf(QLatin1Char(','), index+1);
+ qreal y = s.mid(index+1, index2-index-1).toDouble(&yGood);
+ index = s.indexOf(QLatin1Char('x'), index2+1);
+ qreal width = s.mid(index2+1, index-index2-1).toDouble(&wGood);
+ qreal height = s.mid(index+1).toDouble(&hGood);
+ if (!xGood || !yGood || !wGood || !hGood) {
+ if (ok)
+ *ok = false;
+ return QRectF();
+ }
+
+ if (ok)
+ *ok = true;
+ return QRectF(x, y, width, height);
+}
+
+//expects input of "x,y,z"
+QVector3D QmlStringConverters::vector3DFromString(const QString &s, bool *ok)
+{
+ if (s.count(QLatin1Char(',')) != 2) {
+ if (ok)
+ *ok = false;
+ return QVector3D();
+ }
+
+ bool xGood, yGood, zGood;
+ int index = s.indexOf(QLatin1Char(','));
+ int index2 = s.indexOf(QLatin1Char(','), index+1);
+ qreal xCoord = s.left(index).toDouble(&xGood);
+ qreal yCoord = s.mid(index+1, index2-index-1).toDouble(&yGood);
+ qreal zCoord = s.mid(index2+1).toDouble(&zGood);
+ if (!xGood || !yGood || !zGood) {
+ if (ok)
+ *ok = false;
+ return QVector3D();
+ }
+
+ if (ok)
+ *ok = true;
+ return QVector3D(xCoord, yCoord, zCoord);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlstringconverters_p.h b/src/declarative/qml/qmlstringconverters_p.h
new file mode 100644
index 0000000..dfc59ce
--- /dev/null
+++ b/src/declarative/qml/qmlstringconverters_p.h
@@ -0,0 +1,87 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSTRINGCONVERTERS_P_H
+#define QMLSTRINGCONVERTERS_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/qvariant.h>
+
+class QColor;
+class QPointF;
+class QSizeF;
+class QRectF;
+class QString;
+class QByteArray;
+class QVector3D;
+
+QT_BEGIN_NAMESPACE
+
+// XXX - Bauhaus currently uses these methods which is why they're exported
+namespace QmlStringConverters
+{
+ QVariant Q_DECLARATIVE_EXPORT variantFromString(const QString &);
+ QVariant Q_DECLARATIVE_EXPORT variantFromString(const QString &, int preferredType, bool *ok = 0);
+
+ QColor Q_DECLARATIVE_EXPORT colorFromString(const QString &, bool *ok = 0);
+ QDate Q_DECLARATIVE_EXPORT dateFromString(const QString &, bool *ok = 0);
+ QTime Q_DECLARATIVE_EXPORT timeFromString(const QString &, bool *ok = 0);
+ QDateTime Q_DECLARATIVE_EXPORT dateTimeFromString(const QString &, bool *ok = 0);
+ QPointF Q_DECLARATIVE_EXPORT pointFFromString(const QString &, bool *ok = 0);
+ QSizeF Q_DECLARATIVE_EXPORT sizeFFromString(const QString &, bool *ok = 0);
+ QRectF Q_DECLARATIVE_EXPORT rectFFromString(const QString &, bool *ok = 0);
+ QVector3D Q_DECLARATIVE_EXPORT vector3DFromString(const QString &, bool *ok = 0);
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLSTRINGCONVERTERS_P_H
diff --git a/src/declarative/qml/qmltypenamecache.cpp b/src/declarative/qml/qmltypenamecache.cpp
new file mode 100644
index 0000000..7e68492
--- /dev/null
+++ b/src/declarative/qml/qmltypenamecache.cpp
@@ -0,0 +1,103 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmltypenamecache_p.h"
+
+#include "qmlengine_p.h"
+
+QT_BEGIN_NAMESPACE
+
+QmlTypeNameCache::QmlTypeNameCache(QmlEngine *e)
+: QmlCleanup(e), engine(e)
+{
+}
+
+QmlTypeNameCache::~QmlTypeNameCache()
+{
+ clear();
+}
+
+void QmlTypeNameCache::clear()
+{
+ qDeleteAll(stringCache);
+ stringCache.clear();
+ identifierCache.clear();
+ engine = 0;
+}
+
+void QmlTypeNameCache::add(const QString &name, QmlType *type)
+{
+ if (stringCache.contains(name))
+ return;
+
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+
+ RData *data = new RData;
+ // ### Use typename class
+ data->identifier = ep->objectClass->createPersistentIdentifier(name);
+ data->type = type;
+ stringCache.insert(name, data);
+ identifierCache.insert(data->identifier.identifier, data);
+}
+
+void QmlTypeNameCache::add(const QString &name, QmlTypeNameCache *typeNamespace)
+{
+ if (stringCache.contains(name))
+ return;
+
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+
+ RData *data = new RData;
+ // ### Use typename class
+ data->identifier = ep->objectClass->createPersistentIdentifier(name);
+ data->typeNamespace = typeNamespace;
+ stringCache.insert(name, data);
+ identifierCache.insert(data->identifier.identifier, data);
+ typeNamespace->addref();
+}
+
+QmlTypeNameCache::Data *QmlTypeNameCache::data(const QString &id) const
+{
+ return stringCache.value(id);
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/qml/qmltypenamecache_p.h b/src/declarative/qml/qmltypenamecache_p.h
new file mode 100644
index 0000000..754399f
--- /dev/null
+++ b/src/declarative/qml/qmltypenamecache_p.h
@@ -0,0 +1,117 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLTYPENAMECACHE_P_H
+#define QMLTYPENAMECACHE_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 "qmlrefcount_p.h"
+#include "qmlcleanup_p.h"
+
+#include <private/qscriptdeclarativeclass_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlType;
+class QmlEngine;
+class QmlTypeNameCache : public QmlRefCount, public QmlCleanup
+{
+public:
+ QmlTypeNameCache(QmlEngine *);
+ virtual ~QmlTypeNameCache();
+
+ struct Data {
+ inline Data();
+ inline ~Data();
+ QmlType *type;
+ QmlTypeNameCache *typeNamespace;
+ };
+
+ void add(const QString &, QmlType *);
+ void add(const QString &, QmlTypeNameCache *);
+
+ Data *data(const QString &) const;
+ inline Data *data(const QScriptDeclarativeClass::Identifier &id) const;
+
+protected:
+ virtual void clear();
+
+private:
+ struct RData : public Data {
+ QScriptDeclarativeClass::PersistentIdentifier identifier;
+ };
+ typedef QHash<QString, RData *> StringCache;
+ typedef QHash<QScriptDeclarativeClass::Identifier, RData *> IdentifierCache;
+
+ StringCache stringCache;
+ IdentifierCache identifierCache;
+ QmlEngine *engine;
+};
+
+QmlTypeNameCache::Data::Data()
+: type(0), typeNamespace(0)
+{
+}
+
+QmlTypeNameCache::Data::~Data()
+{
+ if (typeNamespace) typeNamespace->release();
+}
+
+QmlTypeNameCache::Data *QmlTypeNameCache::data(const QScriptDeclarativeClass::Identifier &id) const
+{
+ return identifierCache.value(id);
+}
+
+QT_END_NAMESPACE
+
+#endif // QMLTYPENAMECACHE_P_H
+
diff --git a/src/declarative/qml/qmltypenamescriptclass.cpp b/src/declarative/qml/qmltypenamescriptclass.cpp
new file mode 100644
index 0000000..14c8652
--- /dev/null
+++ b/src/declarative/qml/qmltypenamescriptclass.cpp
@@ -0,0 +1,166 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmltypenamescriptclass_p.h"
+
+#include "qmlengine_p.h"
+#include "qmltypenamecache_p.h"
+
+QT_BEGIN_NAMESPACE
+
+struct TypeNameData : public QScriptDeclarativeClass::Object {
+ TypeNameData(QObject *o, QmlType *t, QmlTypeNameScriptClass::TypeNameMode m) : object(o), type(t), typeNamespace(0), mode(m) {}
+ TypeNameData(QObject *o, QmlTypeNameCache *n, QmlTypeNameScriptClass::TypeNameMode m) : object(o), type(0), typeNamespace(n), mode(m) {
+ if (typeNamespace) typeNamespace->addref();
+ }
+ ~TypeNameData() {
+ if (typeNamespace) typeNamespace->release();
+ }
+
+ QObject *object;
+ QmlType *type;
+ QmlTypeNameCache *typeNamespace;
+ QmlTypeNameScriptClass::TypeNameMode mode;
+};
+
+QmlTypeNameScriptClass::QmlTypeNameScriptClass(QmlEngine *bindEngine)
+: QmlScriptClass(QmlEnginePrivate::getScriptEngine(bindEngine)),
+ engine(bindEngine), object(0), type(0)
+{
+}
+
+QmlTypeNameScriptClass::~QmlTypeNameScriptClass()
+{
+}
+
+QScriptValue QmlTypeNameScriptClass::newObject(QObject *object, QmlType *type, TypeNameMode mode)
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ return QScriptDeclarativeClass::newObject(scriptEngine, this, new TypeNameData(object, type, mode));
+}
+
+QScriptValue QmlTypeNameScriptClass::newObject(QObject *object, QmlTypeNameCache *ns, TypeNameMode mode)
+{
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+
+ return QScriptDeclarativeClass::newObject(scriptEngine, this, new TypeNameData(object, ns, mode));
+}
+
+QScriptClass::QueryFlags
+QmlTypeNameScriptClass::queryProperty(Object *obj, const Identifier &name,
+ QScriptClass::QueryFlags flags)
+{
+ Q_UNUSED(flags);
+
+ TypeNameData *data = (TypeNameData *)obj;
+
+ object = 0;
+ type = 0;
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+
+ if (data->typeNamespace) {
+
+ QmlTypeNameCache::Data *d = data->typeNamespace->data(name);
+ if (d && d->type) {
+ type = d->type;
+ return QScriptClass::HandlesReadAccess;
+ } else {
+ return 0;
+ }
+
+ } else {
+ Q_ASSERT(data->type);
+
+ QString strName = toString(name);
+
+ if (strName.at(0).isUpper()) {
+ // Must be an enum
+ if (data->mode == IncludeEnums) {
+ // ### Optimize
+ QByteArray enumName = strName.toUtf8();
+ const QMetaObject *metaObject = data->type->baseMetaObject();
+ for (int ii = metaObject->enumeratorCount() - 1; ii >= 0; --ii) {
+ QMetaEnum e = metaObject->enumerator(ii);
+ int value = e.keyToValue(enumName.constData());
+ if (value != -1) {
+ enumValue = value;
+ return QScriptClass::HandlesReadAccess;
+ }
+ }
+ }
+ return 0;
+ } else if (data->object) {
+ // Must be an attached property
+ object = qmlAttachedPropertiesObjectById(data->type->index(), data->object);
+ if (!object) return 0;
+ return ep->objectClass->queryProperty(object, name, flags, 0);
+ }
+ }
+
+ return 0;
+}
+
+QmlTypeNameScriptClass::ScriptValue
+QmlTypeNameScriptClass::property(Object *obj, const Identifier &name)
+{
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+ if (type) {
+ return Value(scriptEngine, newObject(((TypeNameData *)obj)->object, type, ((TypeNameData *)obj)->mode));
+ } else if (object) {
+ return ep->objectClass->property(object, name);
+ } else {
+ return Value(scriptEngine, enumValue);
+ }
+}
+
+void QmlTypeNameScriptClass::setProperty(Object *o, const Identifier &n, const QScriptValue &v)
+{
+ Q_ASSERT(object);
+ Q_ASSERT(!type);
+
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(engine);
+ ep->objectClass->setProperty(((TypeNameData *)o)->object, n, v);
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/qml/qmltypenamescriptclass_p.h b/src/declarative/qml/qmltypenamescriptclass_p.h
new file mode 100644
index 0000000..cf8c621
--- /dev/null
+++ b/src/declarative/qml/qmltypenamescriptclass_p.h
@@ -0,0 +1,93 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLTYPENAMESCRIPTCLASS_P_H
+#define QMLTYPENAMESCRIPTCLASS_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 "qmlengine_p.h"
+
+#include <QtScript/qscriptclass.h>
+
+#include <private/qmlscriptclass_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlEngine;
+class QmlType;
+class QmlTypeNameCache;
+class QmlTypeNameScriptClass : public QmlScriptClass
+{
+public:
+ QmlTypeNameScriptClass(QmlEngine *);
+ ~QmlTypeNameScriptClass();
+
+ enum TypeNameMode { IncludeEnums, ExcludeEnums };
+ QScriptValue newObject(QObject *, QmlType *, TypeNameMode = IncludeEnums);
+ QScriptValue newObject(QObject *, QmlTypeNameCache *, TypeNameMode = IncludeEnums);
+
+protected:
+ virtual QScriptClass::QueryFlags queryProperty(Object *, const Identifier &,
+ QScriptClass::QueryFlags flags);
+
+ virtual ScriptValue property(Object *, const Identifier &);
+ virtual void setProperty(Object *, const Identifier &name, const QScriptValue &);
+
+private:
+ QmlEngine *engine;
+ QObject *object;
+ QmlType *type;
+ quint32 enumValue;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLTYPENAMESCRIPTCLASS_P_H
+
diff --git a/src/declarative/qml/qmlvaluetype.cpp b/src/declarative/qml/qmlvaluetype.cpp
new file mode 100644
index 0000000..058fd6e
--- /dev/null
+++ b/src/declarative/qml/qmlvaluetype.cpp
@@ -0,0 +1,636 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlvaluetype_p.h"
+
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+QmlValueTypeFactory::QmlValueTypeFactory()
+{
+ // ### Optimize
+ for (unsigned int ii = 0; ii < (QVariant::UserType - 1); ++ii)
+ valueTypes[ii] = valueType(ii);
+}
+
+QmlValueTypeFactory::~QmlValueTypeFactory()
+{
+ for (unsigned int ii = 0; ii < (QVariant::UserType - 1); ++ii)
+ delete valueTypes[ii];
+}
+
+QmlValueType *QmlValueTypeFactory::valueType(int t)
+{
+ switch (t) {
+ case QVariant::Point:
+ return new QmlPointValueType;
+ case QVariant::PointF:
+ return new QmlPointFValueType;
+ case QVariant::Size:
+ return new QmlSizeValueType;
+ case QVariant::SizeF:
+ return new QmlSizeFValueType;
+ case QVariant::Rect:
+ return new QmlRectValueType;
+ case QVariant::RectF:
+ return new QmlRectFValueType;
+ case QVariant::Vector3D:
+ return new QmlVector3DValueType;
+ case QVariant::Font:
+ return new QmlFontValueType;
+ default:
+ return 0;
+ }
+}
+
+QmlValueType::QmlValueType(QObject *parent)
+: QObject(parent)
+{
+}
+
+QmlPointFValueType::QmlPointFValueType(QObject *parent)
+: QmlValueType(parent)
+{
+}
+
+void QmlPointFValueType::read(QObject *obj, int idx)
+{
+ void *a[] = { &point, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, idx, a);
+}
+
+void QmlPointFValueType::write(QObject *obj, int idx, QmlMetaProperty::WriteFlags flags)
+{
+ int status = -1;
+ void *a[] = { &point, 0, &status, &flags };
+ QMetaObject::metacall(obj, QMetaObject::WriteProperty, idx, a);
+}
+
+QVariant QmlPointFValueType::value()
+{
+ return QVariant(point);
+}
+
+void QmlPointFValueType::setValue(QVariant value)
+{
+ point = qvariant_cast<QPointF>(value);
+}
+
+qreal QmlPointFValueType::x() const
+{
+ return point.x();
+}
+
+qreal QmlPointFValueType::y() const
+{
+ return point.y();
+}
+
+void QmlPointFValueType::setX(qreal x)
+{
+ point.setX(x);
+}
+
+void QmlPointFValueType::setY(qreal y)
+{
+ point.setY(y);
+}
+
+QmlPointValueType::QmlPointValueType(QObject *parent)
+: QmlValueType(parent)
+{
+}
+
+void QmlPointValueType::read(QObject *obj, int idx)
+{
+ void *a[] = { &point, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, idx, a);
+}
+
+void QmlPointValueType::write(QObject *obj, int idx, QmlMetaProperty::WriteFlags flags)
+{
+ int status = -1;
+ void *a[] = { &point, 0, &status, &flags };
+ QMetaObject::metacall(obj, QMetaObject::WriteProperty, idx, a);
+}
+
+QVariant QmlPointValueType::value()
+{
+ return QVariant(point);
+}
+
+void QmlPointValueType::setValue(QVariant value)
+{
+ point = qvariant_cast<QPoint>(value);
+}
+
+int QmlPointValueType::x() const
+{
+ return point.x();
+}
+
+int QmlPointValueType::y() const
+{
+ return point.y();
+}
+
+void QmlPointValueType::setX(int x)
+{
+ point.setX(x);
+}
+
+void QmlPointValueType::setY(int y)
+{
+ point.setY(y);
+}
+
+QmlSizeFValueType::QmlSizeFValueType(QObject *parent)
+: QmlValueType(parent)
+{
+}
+
+void QmlSizeFValueType::read(QObject *obj, int idx)
+{
+ void *a[] = { &size, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, idx, a);
+}
+
+void QmlSizeFValueType::write(QObject *obj, int idx, QmlMetaProperty::WriteFlags flags)
+{
+ int status = -1;
+ void *a[] = { &size, 0, &status, &flags };
+ QMetaObject::metacall(obj, QMetaObject::WriteProperty, idx, a);
+}
+
+QVariant QmlSizeFValueType::value()
+{
+ return QVariant(size);
+}
+
+void QmlSizeFValueType::setValue(QVariant value)
+{
+ size = qvariant_cast<QSizeF>(value);
+}
+
+qreal QmlSizeFValueType::width() const
+{
+ return size.width();
+}
+
+qreal QmlSizeFValueType::height() const
+{
+ return size.height();
+}
+
+void QmlSizeFValueType::setWidth(qreal w)
+{
+ size.setWidth(w);
+}
+
+void QmlSizeFValueType::setHeight(qreal h)
+{
+ size.setHeight(h);
+}
+
+QmlSizeValueType::QmlSizeValueType(QObject *parent)
+: QmlValueType(parent)
+{
+}
+
+void QmlSizeValueType::read(QObject *obj, int idx)
+{
+ void *a[] = { &size, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, idx, a);
+}
+
+void QmlSizeValueType::write(QObject *obj, int idx, QmlMetaProperty::WriteFlags flags)
+{
+ int status = -1;
+ void *a[] = { &size, 0, &status, &flags };
+ QMetaObject::metacall(obj, QMetaObject::WriteProperty, idx, a);
+}
+
+QVariant QmlSizeValueType::value()
+{
+ return QVariant(size);
+}
+
+void QmlSizeValueType::setValue(QVariant value)
+{
+ size = qvariant_cast<QSize>(value);
+}
+
+int QmlSizeValueType::width() const
+{
+ return size.width();
+}
+
+int QmlSizeValueType::height() const
+{
+ return size.height();
+}
+
+void QmlSizeValueType::setWidth(int w)
+{
+ size.setWidth(w);
+}
+
+void QmlSizeValueType::setHeight(int h)
+{
+ size.setHeight(h);
+}
+
+QmlRectFValueType::QmlRectFValueType(QObject *parent)
+: QmlValueType(parent)
+{
+}
+
+void QmlRectFValueType::read(QObject *obj, int idx)
+{
+ void *a[] = { &rect, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, idx, a);
+}
+
+void QmlRectFValueType::write(QObject *obj, int idx, QmlMetaProperty::WriteFlags flags)
+{
+ int status = -1;
+ void *a[] = { &rect, 0, &status, &flags };
+ QMetaObject::metacall(obj, QMetaObject::WriteProperty, idx, a);
+}
+
+QVariant QmlRectFValueType::value()
+{
+ return QVariant(rect);
+}
+
+void QmlRectFValueType::setValue(QVariant value)
+{
+ rect = qvariant_cast<QRectF>(value);
+}
+
+qreal QmlRectFValueType::x() const
+{
+ return rect.x();
+}
+
+qreal QmlRectFValueType::y() const
+{
+ return rect.y();
+}
+
+void QmlRectFValueType::setX(qreal x)
+{
+ rect.moveLeft(x);
+}
+
+void QmlRectFValueType::setY(qreal y)
+{
+ rect.moveTop(y);
+}
+
+qreal QmlRectFValueType::width() const
+{
+ return rect.width();
+}
+
+qreal QmlRectFValueType::height() const
+{
+ return rect.height();
+}
+
+void QmlRectFValueType::setWidth(qreal w)
+{
+ rect.setWidth(w);
+}
+
+void QmlRectFValueType::setHeight(qreal h)
+{
+ rect.setHeight(h);
+}
+
+QmlRectValueType::QmlRectValueType(QObject *parent)
+: QmlValueType(parent)
+{
+}
+
+void QmlRectValueType::read(QObject *obj, int idx)
+{
+ void *a[] = { &rect, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, idx, a);
+}
+
+void QmlRectValueType::write(QObject *obj, int idx, QmlMetaProperty::WriteFlags flags)
+{
+ int status = -1;
+ void *a[] = { &rect, 0, &status, &flags };
+ QMetaObject::metacall(obj, QMetaObject::WriteProperty, idx, a);
+}
+
+QVariant QmlRectValueType::value()
+{
+ return QVariant(rect);
+}
+
+void QmlRectValueType::setValue(QVariant value)
+{
+ rect = qvariant_cast<QRect>(value);
+}
+
+int QmlRectValueType::x() const
+{
+ return rect.x();
+}
+
+int QmlRectValueType::y() const
+{
+ return rect.y();
+}
+
+void QmlRectValueType::setX(int x)
+{
+ rect.moveLeft(x);
+}
+
+void QmlRectValueType::setY(int y)
+{
+ rect.moveTop(y);
+}
+
+int QmlRectValueType::width() const
+{
+ return rect.width();
+}
+
+int QmlRectValueType::height() const
+{
+ return rect.height();
+}
+
+void QmlRectValueType::setWidth(int w)
+{
+ rect.setWidth(w);
+}
+
+void QmlRectValueType::setHeight(int h)
+{
+ rect.setHeight(h);
+}
+
+QmlVector3DValueType::QmlVector3DValueType(QObject *parent)
+: QmlValueType(parent)
+{
+}
+
+void QmlVector3DValueType::read(QObject *obj, int idx)
+{
+ void *a[] = { &vector, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, idx, a);
+}
+
+void QmlVector3DValueType::write(QObject *obj, int idx, QmlMetaProperty::WriteFlags flags)
+{
+ int status = -1;
+ void *a[] = { &vector, 0, &status, &flags };
+ QMetaObject::metacall(obj, QMetaObject::WriteProperty, idx, a);
+}
+
+QVariant QmlVector3DValueType::value()
+{
+ return QVariant(vector);
+}
+
+void QmlVector3DValueType::setValue(QVariant value)
+{
+ vector = qvariant_cast<QVector3D>(value);
+}
+
+qreal QmlVector3DValueType::x() const
+{
+ return vector.x();
+}
+
+qreal QmlVector3DValueType::y() const
+{
+ return vector.y();
+}
+
+qreal QmlVector3DValueType::z() const
+{
+ return vector.z();
+}
+
+void QmlVector3DValueType::setX(qreal x)
+{
+ vector.setX(x);
+}
+
+void QmlVector3DValueType::setY(qreal y)
+{
+ vector.setY(y);
+}
+
+void QmlVector3DValueType::setZ(qreal z)
+{
+ vector.setZ(z);
+}
+
+QmlFontValueType::QmlFontValueType(QObject *parent)
+: QmlValueType(parent), hasPixelSize(false)
+{
+}
+
+void QmlFontValueType::read(QObject *obj, int idx)
+{
+ void *a[] = { &font, 0 };
+ QMetaObject::metacall(obj, QMetaObject::ReadProperty, idx, a);
+}
+
+void QmlFontValueType::write(QObject *obj, int idx, QmlMetaProperty::WriteFlags flags)
+{
+ int status = -1;
+ void *a[] = { &font, 0, &status, &flags };
+ QMetaObject::metacall(obj, QMetaObject::WriteProperty, idx, a);
+}
+
+QVariant QmlFontValueType::value()
+{
+ return QVariant(font);
+}
+
+void QmlFontValueType::setValue(QVariant value)
+{
+ font = qvariant_cast<QFont>(value);
+}
+
+
+QString QmlFontValueType::family() const
+{
+ return font.family();
+}
+
+void QmlFontValueType::setFamily(const QString &family)
+{
+ font.setFamily(family);
+}
+
+bool QmlFontValueType::bold() const
+{
+ return font.bold();
+}
+
+void QmlFontValueType::setBold(bool b)
+{
+ font.setBold(b);
+}
+
+QmlFontValueType::FontWeight QmlFontValueType::weight() const
+{
+ return (QmlFontValueType::FontWeight)font.weight();
+}
+
+void QmlFontValueType::setWeight(QmlFontValueType::FontWeight w)
+{
+ font.setWeight((QFont::Weight)w);
+}
+
+bool QmlFontValueType::italic() const
+{
+ return font.italic();
+}
+
+void QmlFontValueType::setItalic(bool b)
+{
+ font.setItalic(b);
+}
+
+bool QmlFontValueType::underline() const
+{
+ return font.underline();
+}
+
+void QmlFontValueType::setUnderline(bool b)
+{
+ font.setUnderline(b);
+}
+
+bool QmlFontValueType::overline() const
+{
+ return font.overline();
+}
+
+void QmlFontValueType::setOverline(bool b)
+{
+ font.setOverline(b);
+}
+
+bool QmlFontValueType::strikeout() const
+{
+ return font.strikeOut();
+}
+
+void QmlFontValueType::setStrikeout(bool b)
+{
+ font.setStrikeOut(b);
+}
+
+qreal QmlFontValueType::pointSize() const
+{
+ return font.pointSizeF();
+}
+
+void QmlFontValueType::setPointSize(qreal size)
+{
+ if (hasPixelSize) {
+ qWarning() << "Both point size and pixel size set. Using pixel size.";
+ return;
+ }
+
+ if (size >= 0.0)
+ font.setPointSizeF(size);
+}
+
+int QmlFontValueType::pixelSize() const
+{
+ return font.pixelSize();
+}
+
+void QmlFontValueType::setPixelSize(int size)
+{
+ if (size >=0) {
+ font.setPixelSize(size);
+ hasPixelSize = true;
+ } else {
+ hasPixelSize = false;
+ }
+}
+
+QmlFontValueType::Capitalization QmlFontValueType::capitalization() const
+{
+ return (QmlFontValueType::Capitalization)font.capitalization();
+}
+
+void QmlFontValueType::setCapitalization(QmlFontValueType::Capitalization c)
+{
+ font.setCapitalization((QFont::Capitalization)c);
+}
+
+qreal QmlFontValueType::letterSpacing() const
+{
+ return font.letterSpacing();
+}
+
+void QmlFontValueType::setLetterSpacing(qreal size)
+{
+ font.setLetterSpacing(QFont::PercentageSpacing, size);
+}
+
+qreal QmlFontValueType::wordSpacing() const
+{
+ return font.wordSpacing();
+}
+
+void QmlFontValueType::setWordSpacing(qreal size)
+{
+ font.setWordSpacing(size);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlvaluetype_p.h b/src/declarative/qml/qmlvaluetype_p.h
new file mode 100644
index 0000000..800edee
--- /dev/null
+++ b/src/declarative/qml/qmlvaluetype_p.h
@@ -0,0 +1,340 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLVALUETYPE_P_H
+#define QMLVALUETYPE_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 "qmlmetaproperty.h"
+
+#include <QtCore/qobject.h>
+#include <QtCore/qrect.h>
+#include <QtCore/qvariant.h>
+#include <QtGui/qvector3d.h>
+#include <QtGui/qfont.h>
+
+QT_BEGIN_NAMESPACE
+
+class Q_DECLARATIVE_EXPORT QmlValueType : public QObject
+{
+ Q_OBJECT
+public:
+ QmlValueType(QObject *parent = 0);
+ virtual void read(QObject *, int) = 0;
+ virtual void write(QObject *, int, QmlMetaProperty::WriteFlags flags) = 0;
+ virtual QVariant value() = 0;
+ virtual void setValue(QVariant) = 0;
+};
+
+class Q_DECLARATIVE_EXPORT QmlValueTypeFactory
+{
+public:
+ QmlValueTypeFactory();
+ ~QmlValueTypeFactory();
+ static QmlValueType *valueType(int);
+
+ QmlValueType *valueTypes[QVariant::UserType - 1];
+ QmlValueType *operator[](int idx) const { return valueTypes[idx]; }
+};
+
+class Q_AUTOTEST_EXPORT QmlPointFValueType : public QmlValueType
+{
+ Q_PROPERTY(qreal x READ x WRITE setX)
+ Q_PROPERTY(qreal y READ y WRITE setY)
+ Q_OBJECT
+public:
+ QmlPointFValueType(QObject *parent = 0);
+
+ virtual void read(QObject *, int);
+ virtual void write(QObject *, int, QmlMetaProperty::WriteFlags);
+ virtual QVariant value();
+ virtual void setValue(QVariant value);
+
+ qreal x() const;
+ qreal y() const;
+ void setX(qreal);
+ void setY(qreal);
+
+private:
+ QPointF point;
+};
+
+class Q_AUTOTEST_EXPORT QmlPointValueType : public QmlValueType
+{
+ Q_PROPERTY(int x READ x WRITE setX)
+ Q_PROPERTY(int y READ y WRITE setY)
+ Q_OBJECT
+public:
+ QmlPointValueType(QObject *parent = 0);
+
+ virtual void read(QObject *, int);
+ virtual void write(QObject *, int, QmlMetaProperty::WriteFlags);
+ virtual QVariant value();
+ virtual void setValue(QVariant value);
+
+ int x() const;
+ int y() const;
+ void setX(int);
+ void setY(int);
+
+private:
+ QPoint point;
+};
+
+class Q_AUTOTEST_EXPORT QmlSizeFValueType : public QmlValueType
+{
+ Q_PROPERTY(qreal width READ width WRITE setWidth)
+ Q_PROPERTY(qreal height READ height WRITE setHeight)
+ Q_OBJECT
+public:
+ QmlSizeFValueType(QObject *parent = 0);
+
+ virtual void read(QObject *, int);
+ virtual void write(QObject *, int, QmlMetaProperty::WriteFlags);
+ virtual QVariant value();
+ virtual void setValue(QVariant value);
+
+ qreal width() const;
+ qreal height() const;
+ void setWidth(qreal);
+ void setHeight(qreal);
+
+private:
+ QSizeF size;
+};
+
+class Q_AUTOTEST_EXPORT QmlSizeValueType : public QmlValueType
+{
+ Q_PROPERTY(int width READ width WRITE setWidth)
+ Q_PROPERTY(int height READ height WRITE setHeight)
+ Q_OBJECT
+public:
+ QmlSizeValueType(QObject *parent = 0);
+
+ virtual void read(QObject *, int);
+ virtual void write(QObject *, int, QmlMetaProperty::WriteFlags);
+ virtual QVariant value();
+ virtual void setValue(QVariant value);
+
+ int width() const;
+ int height() const;
+ void setWidth(int);
+ void setHeight(int);
+
+private:
+ QSize size;
+};
+
+class Q_AUTOTEST_EXPORT QmlRectFValueType : public QmlValueType
+{
+ Q_PROPERTY(qreal x READ x WRITE setX)
+ Q_PROPERTY(qreal y READ y WRITE setY)
+ Q_PROPERTY(qreal width READ width WRITE setWidth)
+ Q_PROPERTY(qreal height READ height WRITE setHeight)
+ Q_OBJECT
+public:
+ QmlRectFValueType(QObject *parent = 0);
+
+ virtual void read(QObject *, int);
+ virtual void write(QObject *, int, QmlMetaProperty::WriteFlags);
+ virtual QVariant value();
+ virtual void setValue(QVariant value);
+
+ qreal x() const;
+ qreal y() const;
+ void setX(qreal);
+ void setY(qreal);
+
+ qreal width() const;
+ qreal height() const;
+ void setWidth(qreal);
+ void setHeight(qreal);
+
+private:
+ QRectF rect;
+};
+
+class Q_AUTOTEST_EXPORT QmlRectValueType : public QmlValueType
+{
+ Q_PROPERTY(int x READ x WRITE setX)
+ Q_PROPERTY(int y READ y WRITE setY)
+ Q_PROPERTY(int width READ width WRITE setWidth)
+ Q_PROPERTY(int height READ height WRITE setHeight)
+ Q_OBJECT
+public:
+ QmlRectValueType(QObject *parent = 0);
+
+ virtual void read(QObject *, int);
+ virtual void write(QObject *, int, QmlMetaProperty::WriteFlags);
+ virtual QVariant value();
+ virtual void setValue(QVariant value);
+
+ int x() const;
+ int y() const;
+ void setX(int);
+ void setY(int);
+
+ int width() const;
+ int height() const;
+ void setWidth(int);
+ void setHeight(int);
+
+private:
+ QRect rect;
+};
+
+class Q_AUTOTEST_EXPORT QmlVector3DValueType : public QmlValueType
+{
+ Q_PROPERTY(qreal x READ x WRITE setX)
+ Q_PROPERTY(qreal y READ y WRITE setY)
+ Q_PROPERTY(qreal z READ z WRITE setZ)
+ Q_OBJECT
+public:
+ QmlVector3DValueType(QObject *parent = 0);
+
+ virtual void read(QObject *, int);
+ virtual void write(QObject *, int, QmlMetaProperty::WriteFlags);
+ virtual QVariant value();
+ virtual void setValue(QVariant value);
+
+ qreal x() const;
+ qreal y() const;
+ qreal z() const;
+ void setX(qreal);
+ void setY(qreal);
+ void setZ(qreal);
+
+private:
+ QVector3D vector;
+};
+
+class Q_AUTOTEST_EXPORT QmlFontValueType : public QmlValueType
+{
+ Q_OBJECT
+ Q_ENUMS(FontWeight)
+ Q_ENUMS(Capitalization)
+
+ Q_PROPERTY(QString family READ family WRITE setFamily)
+ Q_PROPERTY(bool bold READ bold WRITE setBold)
+ Q_PROPERTY(FontWeight weight READ weight WRITE setWeight)
+ Q_PROPERTY(bool italic READ italic WRITE setItalic)
+ Q_PROPERTY(bool underline READ underline WRITE setUnderline)
+ Q_PROPERTY(bool overline READ overline WRITE setOverline)
+ Q_PROPERTY(bool strikeout READ strikeout WRITE setStrikeout)
+ Q_PROPERTY(qreal pointSize READ pointSize WRITE setPointSize)
+ Q_PROPERTY(int pixelSize READ pixelSize WRITE setPixelSize)
+ Q_PROPERTY(Capitalization capitalization READ capitalization WRITE setCapitalization)
+ Q_PROPERTY(qreal letterSpacing READ letterSpacing WRITE setLetterSpacing)
+ Q_PROPERTY(qreal wordSpacing READ wordSpacing WRITE setWordSpacing)
+
+public:
+ enum FontWeight { Light = QFont::Light,
+ Normal = QFont::Normal,
+ DemiBold = QFont::DemiBold,
+ Bold = QFont::Bold,
+ Black = QFont::Black };
+ enum Capitalization { MixedCase = QFont::MixedCase,
+ AllUppercase = QFont::AllUppercase,
+ AllLowercase = QFont::AllLowercase,
+ SmallCaps = QFont::SmallCaps,
+ Capitalize = QFont::Capitalize };
+
+ QmlFontValueType(QObject *parent = 0);
+
+ virtual void read(QObject *, int);
+ virtual void write(QObject *, int, QmlMetaProperty::WriteFlags);
+ virtual QVariant value();
+ virtual void setValue(QVariant value);
+
+ QString family() const;
+ void setFamily(const QString &);
+
+ bool bold() const;
+ void setBold(bool b);
+
+ FontWeight weight() const;
+ void setWeight(FontWeight);
+
+ bool italic() const;
+ void setItalic(bool b);
+
+ bool underline() const;
+ void setUnderline(bool b);
+
+ bool overline() const;
+ void setOverline(bool b);
+
+ bool strikeout() const;
+ void setStrikeout(bool b);
+
+ qreal pointSize() const;
+ void setPointSize(qreal size);
+
+ int pixelSize() const;
+ void setPixelSize(int size);
+
+ Capitalization capitalization() const;
+ void setCapitalization(Capitalization);
+
+ qreal letterSpacing() const;
+ void setLetterSpacing(qreal spacing);
+
+ qreal wordSpacing() const;
+ void setWordSpacing(qreal spacing);
+
+private:
+ QFont font;
+ bool hasPixelSize;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLVALUETYPE_P_H
diff --git a/src/declarative/qml/qmlvaluetypescriptclass.cpp b/src/declarative/qml/qmlvaluetypescriptclass.cpp
new file mode 100644
index 0000000..5e222a1
--- /dev/null
+++ b/src/declarative/qml/qmlvaluetypescriptclass.cpp
@@ -0,0 +1,148 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlvaluetypescriptclass_p.h"
+
+#include "qmlengine_p.h"
+#include "qmlguard_p.h"
+
+QT_BEGIN_NAMESPACE
+
+struct QmlValueTypeReference : public QScriptDeclarativeClass::Object {
+ QmlValueType *type;
+ QmlGuard<QObject> object;
+ int property;
+};
+
+QmlValueTypeScriptClass::QmlValueTypeScriptClass(QmlEngine *bindEngine)
+: QmlScriptClass(QmlEnginePrivate::getScriptEngine(bindEngine)), engine(bindEngine)
+{
+}
+
+QmlValueTypeScriptClass::~QmlValueTypeScriptClass()
+{
+}
+
+QScriptValue QmlValueTypeScriptClass::newObject(QObject *object, int coreIndex, QmlValueType *type)
+{
+ QmlValueTypeReference *ref = new QmlValueTypeReference;
+ ref->type = type;
+ ref->object = object;
+ ref->property = coreIndex;
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+ return QScriptDeclarativeClass::newObject(scriptEngine, this, ref);
+}
+
+QScriptClass::QueryFlags
+QmlValueTypeScriptClass::queryProperty(Object *obj, const Identifier &name,
+ QScriptClass::QueryFlags)
+{
+ QmlValueTypeReference *ref = static_cast<QmlValueTypeReference *>(obj);
+
+ m_lastIndex = -1;
+
+ if (!ref->object)
+ return 0;
+
+ QByteArray propName = toString(name).toUtf8();
+
+ m_lastIndex = ref->type->metaObject()->indexOfProperty(propName.constData());
+ if (m_lastIndex == -1)
+ return 0;
+
+ QMetaProperty prop = ref->object->metaObject()->property(m_lastIndex);
+
+ QScriptClass::QueryFlags rv =
+ QScriptClass::HandlesReadAccess;
+ if (prop.isWritable())
+ rv |= QScriptClass::HandlesWriteAccess;
+
+ return rv;
+}
+
+QmlValueTypeScriptClass::ScriptValue QmlValueTypeScriptClass::property(Object *obj, const Identifier &)
+{
+ QmlValueTypeReference *ref = static_cast<QmlValueTypeReference *>(obj);
+
+ QMetaProperty p = ref->type->metaObject()->property(m_lastIndex);
+ ref->type->read(ref->object, ref->property);
+ QVariant rv = p.read(ref->type);
+
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+ return Value(scriptEngine, static_cast<QmlEnginePrivate *>(QObjectPrivate::get(engine))->scriptValueFromVariant(rv));
+}
+
+void QmlValueTypeScriptClass::setProperty(Object *obj, const Identifier &,
+ const QScriptValue &value)
+{
+ QmlValueTypeReference *ref = static_cast<QmlValueTypeReference *>(obj);
+
+ QVariant v = QmlScriptClass::toVariant(engine, value);
+
+ ref->type->read(ref->object, ref->property);
+ QMetaProperty p = ref->type->metaObject()->property(m_lastIndex);
+ p.write(ref->type, v);
+ ref->type->write(ref->object, ref->property, 0);
+}
+
+QVariant QmlValueTypeScriptClass::toVariant(Object *obj, bool *ok)
+{
+ QmlValueTypeReference *ref = static_cast<QmlValueTypeReference *>(obj);
+
+ if (ok) *ok = true;
+
+ if (ref->object) {
+ ref->type->read(ref->object, ref->property);
+ return ref->type->value();
+ } else {
+ return QVariant();
+ }
+}
+
+QVariant QmlValueTypeScriptClass::toVariant(const QScriptValue &value)
+{
+ Q_ASSERT(scriptClass(value) == this);
+
+ return toVariant(object(value), 0);
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/qml/qmlvaluetypescriptclass_p.h b/src/declarative/qml/qmlvaluetypescriptclass_p.h
new file mode 100644
index 0000000..09af967
--- /dev/null
+++ b/src/declarative/qml/qmlvaluetypescriptclass_p.h
@@ -0,0 +1,86 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLVALUETYPESCRIPTCLASS_P_H
+#define QMLVALUETYPESCRIPTCLASS_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 <private/qmlscriptclass_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlEngine;
+class QmlValueType;
+class QmlValueTypeScriptClass : public QmlScriptClass
+{
+public:
+ QmlValueTypeScriptClass(QmlEngine *);
+ ~QmlValueTypeScriptClass();
+
+ QScriptValue newObject(QObject *object, int coreIndex, QmlValueType *);
+
+ virtual QScriptClass::QueryFlags queryProperty(Object *, const Identifier &,
+ QScriptClass::QueryFlags flags);
+ virtual ScriptValue property(Object *, const Identifier &);
+ virtual void setProperty(Object *, const Identifier &name, const QScriptValue &);
+
+ virtual QVariant toVariant(Object *, bool *ok = 0);
+ QVariant toVariant(const QScriptValue &);
+private:
+ QmlEngine *engine;
+ int m_lastIndex;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLVALUETYPESCRIPTCLASS_P_H
+
diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp
new file mode 100644
index 0000000..e9a0449
--- /dev/null
+++ b/src/declarative/qml/qmlvme.cpp
@@ -0,0 +1,891 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlvme_p.h"
+
+#include "qmlcompiler_p.h"
+#include "qmlboundsignal_p.h"
+#include "qmlstringconverters_p.h"
+#include "qmetaobjectbuilder_p.h"
+#include "qmldeclarativedata_p.h"
+#include "qml.h"
+#include "qmlcustomparser_p.h"
+#include "qmlengine.h"
+#include "qmlcontext.h"
+#include "qmlcomponent.h"
+#include "qmlbinding.h"
+#include "qmlengine_p.h"
+#include "qmlcomponent_p.h"
+#include "qmlvmemetaobject_p.h"
+#include "qmlbinding_p.h"
+#include "qmlcontext_p.h"
+#include "qmlcompiledbindings_p.h"
+#include "qmlglobal_p.h"
+#include "qmlscriptstring.h"
+
+#include <qfxperf_p_p.h>
+
+#include <QStack>
+#include <QWidget>
+#include <QColor>
+#include <QPointF>
+#include <QSizeF>
+#include <QRectF>
+#include <QtCore/qdebug.h>
+#include <QtCore/qvarlengtharray.h>
+#include <QtCore/qcoreapplication.h>
+
+QT_BEGIN_NAMESPACE
+
+QmlVME::QmlVME()
+{
+}
+
+#define VME_EXCEPTION(desc) \
+ { \
+ QmlError error; \
+ error.setDescription(desc.trimmed()); \
+ error.setLine(instr.line); \
+ error.setUrl(comp->url); \
+ vmeErrors << error; \
+ break; \
+ }
+
+struct ListInstance
+{
+ ListInstance() {}
+ ListInstance(QList<void *> *q, int t)
+ : type(t), qListInterface(q), qmlListInterface(0) {}
+ ListInstance(QmlPrivate::ListInterface *q, int t)
+ : type(t), qListInterface(0), qmlListInterface(q) {}
+
+ int type;
+ QList<void *> *qListInterface;
+ QmlPrivate::ListInterface *qmlListInterface;
+};
+
+QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledData *comp,
+ int start, int count,
+ const QBitField &bindingSkipList)
+{
+ QmlVMEStack<QObject *> stack;
+
+ if (start == -1) start = 0;
+ if (count == -1) count = comp->bytecode.count();
+
+ return run(stack, ctxt, comp, start, count, bindingSkipList);
+}
+
+void QmlVME::runDeferred(QObject *object)
+{
+ QmlDeclarativeData *data = QmlDeclarativeData::get(object);
+
+ if (!data || !data->context || !data->deferredComponent)
+ return;
+
+ QmlContext *ctxt = data->context;
+ QmlCompiledData *comp = data->deferredComponent;
+ int start = data->deferredIdx + 1;
+ int count = data->deferredComponent->bytecode.at(data->deferredIdx).defer.deferCount;
+ QmlVMEStack<QObject *> stack;
+ stack.push(object);
+
+ run(stack, ctxt, comp, start, count, QBitField());
+}
+
+QObject *QmlVME::run(QmlVMEStack<QObject *> &stack, QmlContext *ctxt,
+ QmlCompiledData *comp,
+ int start, int count,
+ const QBitField &bindingSkipList)
+{
+ Q_ASSERT(comp);
+ Q_ASSERT(ctxt);
+ const QList<QmlCompiledData::TypeReference> &types = comp->types;
+ const QList<QString> &primitives = comp->primitives;
+ const QList<QByteArray> &datas = comp->datas;
+ const QList<QmlCompiledData::CustomTypeData> &customTypeData = comp->customTypeData;
+ const QList<int> &intData = comp->intData;
+ const QList<float> &floatData = comp->floatData;
+ const QList<QmlPropertyCache *> &propertyCaches = comp->propertyCaches;
+ const QList<QmlParser::Object::ScriptBlock> &scripts = comp->scripts;
+ const QList<QUrl> &urls = comp->urls;
+
+ QmlEnginePrivate::SimpleList<QmlAbstractBinding> bindValues;
+ QmlEnginePrivate::SimpleList<QmlParserStatus> parserStatus;
+
+ QmlVMEStack<ListInstance> qliststack;
+
+ vmeErrors.clear();
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(ctxt->engine());
+ QmlContextPrivate *cp = (QmlContextPrivate *)QObjectPrivate::get(ctxt);
+
+ int status = -1; //for dbus
+ QmlMetaProperty::WriteFlags flags = QmlMetaProperty::BypassInterceptor;
+
+ for (int ii = start; !isError() && ii < (start + count); ++ii) {
+ const QmlInstruction &instr = comp->bytecode.at(ii);
+
+ switch(instr.type) {
+ case QmlInstruction::Init:
+ {
+ if (instr.init.bindingsSize)
+ bindValues = QmlEnginePrivate::SimpleList<QmlAbstractBinding>(instr.init.bindingsSize);
+ if (instr.init.parserStatusSize)
+ parserStatus = QmlEnginePrivate::SimpleList<QmlParserStatus>(instr.init.parserStatusSize);
+ if (instr.init.contextCache != -1)
+ cp->setIdPropertyData(comp->contextCaches.at(instr.init.contextCache));
+ if (instr.init.compiledBinding != -1)
+ cp->optimizedBindings = new QmlCompiledBindings(datas.at(instr.init.compiledBinding).constData(), ctxt);
+ }
+ break;
+
+ case QmlInstruction::CreateObject:
+ {
+ QBitField bindings;
+ if (instr.create.bindingBits != -1) {
+ const QByteArray &bits = datas.at(instr.create.bindingBits);
+ bindings = QBitField((const quint32*)bits.constData(),
+ bits.size() * 8);
+ }
+ if (stack.isEmpty())
+ bindings = bindings.united(bindingSkipList);
+
+ QObject *o =
+ types.at(instr.create.type).createInstance(ctxt, bindings);
+ if (!o) {
+ if(types.at(instr.create.type).component)
+ vmeErrors << types.at(instr.create.type).component->errors();
+
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Unable to create object of type %1").arg(QString::fromLatin1(types.at(instr.create.type).className)));
+ }
+
+ QmlDeclarativeData *ddata = QmlDeclarativeData::get(o);
+ Q_ASSERT(ddata);
+ ddata->outerContext = ctxt;
+ ddata->lineNumber = instr.line;
+ ddata->columnNumber = instr.create.column;
+
+ if (instr.create.data != -1) {
+ QmlCustomParser *customParser =
+ types.at(instr.create.type).type->customParser();
+ customParser->setCustomData(o, datas.at(instr.create.data));
+ }
+ if (!stack.isEmpty()) {
+ QObject *parent = stack.top();
+ if (o->isWidgetType()) {
+ QWidget *widget = static_cast<QWidget*>(o);
+ if (parent->isWidgetType()) {
+ QWidget *parentWidget = static_cast<QWidget*>(parent);
+ widget->setParent(parentWidget);
+ } else {
+ // TODO: parent might be a layout
+ }
+ } else {
+ QmlGraphics_setParent_noEvent(o, parent);
+ // o->setParent(parent);
+ }
+ }
+ stack.push(o);
+ }
+ break;
+
+ case QmlInstruction::SetId:
+ {
+ QObject *target = stack.top();
+ cp->setIdProperty(instr.setId.index, target);
+ }
+ break;
+
+
+ case QmlInstruction::SetDefault:
+ {
+ QObject *target = stack.top();
+ ctxt->addDefaultObject(target);
+ }
+ break;
+
+ case QmlInstruction::CreateComponent:
+ {
+ QObject *qcomp = new QmlComponent(ctxt->engine(), comp, ii + 1, instr.createComponent.count, stack.isEmpty() ? 0 : stack.top());
+
+ QmlEngine::setContextForObject(qcomp, ctxt);
+ QmlDeclarativeData *ddata = QmlDeclarativeData::get(qcomp);
+ Q_ASSERT(ddata);
+ ddata->outerContext = ctxt;
+ ddata->lineNumber = instr.line;
+ ddata->columnNumber = instr.create.column;
+
+ stack.push(qcomp);
+ ii += instr.createComponent.count;
+ }
+ break;
+
+ case QmlInstruction::StoreMetaObject:
+ {
+ QObject *target = stack.top();
+
+ QMetaObject mo;
+ const QByteArray &metadata = datas.at(instr.storeMeta.data);
+ QMetaObjectBuilder::fromRelocatableData(&mo, 0, metadata);
+
+ const QmlVMEMetaData *data =
+ (const QmlVMEMetaData *)datas.at(instr.storeMeta.aliasData).constData();
+
+ (void)new QmlVMEMetaObject(target, &mo, data, comp);
+
+ QmlDeclarativeData *ddata = QmlDeclarativeData::get(target, true);
+ if (ddata->propertyCache) ddata->propertyCache->release();
+ ddata->propertyCache = propertyCaches.at(instr.storeMeta.propertyCache);
+ ddata->propertyCache->addref();
+ }
+ break;
+
+ case QmlInstruction::StoreVariant:
+ {
+ QObject *target = stack.top();
+ // XXX - can be more efficient
+ QVariant v = QmlStringConverters::variantFromString(primitives.at(instr.storeString.value));
+ void *a[] = { &v, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeString.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreString:
+ {
+ QObject *target = stack.top();
+ void *a[] = { (void *)&primitives.at(instr.storeString.value), 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeString.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreUrl:
+ {
+ QObject *target = stack.top();
+ void *a[] = { (void *)&urls.at(instr.storeUrl.value), 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeUrl.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreFloat:
+ {
+ QObject *target = stack.top();
+ float f = instr.storeFloat.value;
+ void *a[] = { &f, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeFloat.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreDouble:
+ {
+ QObject *target = stack.top();
+ double d = instr.storeDouble.value;
+ void *a[] = { &d, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeDouble.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreBool:
+ {
+ QObject *target = stack.top();
+ void *a[] = { (void *)&instr.storeBool.value, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeBool.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreInteger:
+ {
+ QObject *target = stack.top();
+ void *a[] = { (void *)&instr.storeInteger.value, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeInteger.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreColor:
+ {
+ QObject *target = stack.top();
+ QColor c = QColor::fromRgba(instr.storeColor.value);
+ void *a[] = { &c, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeColor.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreDate:
+ {
+ QObject *target = stack.top();
+ QDate d = QDate::fromJulianDay(instr.storeDate.value);
+ void *a[] = { &d, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeDate.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreTime:
+ {
+ QObject *target = stack.top();
+ QTime t;
+ t.setHMS(intData.at(instr.storeTime.valueIndex),
+ intData.at(instr.storeTime.valueIndex+1),
+ intData.at(instr.storeTime.valueIndex+2),
+ intData.at(instr.storeTime.valueIndex+3));
+ void *a[] = { &t, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeTime.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreDateTime:
+ {
+ QObject *target = stack.top();
+ QTime t;
+ t.setHMS(intData.at(instr.storeDateTime.valueIndex+1),
+ intData.at(instr.storeDateTime.valueIndex+2),
+ intData.at(instr.storeDateTime.valueIndex+3),
+ intData.at(instr.storeDateTime.valueIndex+4));
+ QDateTime dt(QDate::fromJulianDay(intData.at(instr.storeDateTime.valueIndex)), t);
+ void *a[] = { &dt, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeDateTime.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StorePoint:
+ {
+ QObject *target = stack.top();
+ QPoint p = QPointF(floatData.at(instr.storeRealPair.valueIndex),
+ floatData.at(instr.storeRealPair.valueIndex+1)).toPoint();
+ void *a[] = { &p, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeRealPair.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StorePointF:
+ {
+ QObject *target = stack.top();
+ QPointF p(floatData.at(instr.storeRealPair.valueIndex),
+ floatData.at(instr.storeRealPair.valueIndex+1));
+ void *a[] = { &p, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeRealPair.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreSize:
+ {
+ QObject *target = stack.top();
+ QSize p = QSizeF(floatData.at(instr.storeRealPair.valueIndex),
+ floatData.at(instr.storeRealPair.valueIndex+1)).toSize();
+ void *a[] = { &p, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeRealPair.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreSizeF:
+ {
+ QObject *target = stack.top();
+ QSizeF s(floatData.at(instr.storeRealPair.valueIndex),
+ floatData.at(instr.storeRealPair.valueIndex+1));
+ void *a[] = { &s, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeRealPair.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreRect:
+ {
+ QObject *target = stack.top();
+ QRect r = QRectF(floatData.at(instr.storeRect.valueIndex),
+ floatData.at(instr.storeRect.valueIndex+1),
+ floatData.at(instr.storeRect.valueIndex+2),
+ floatData.at(instr.storeRect.valueIndex+3)).toRect();
+ void *a[] = { &r, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeRect.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreRectF:
+ {
+ QObject *target = stack.top();
+ QRectF r(floatData.at(instr.storeRect.valueIndex),
+ floatData.at(instr.storeRect.valueIndex+1),
+ floatData.at(instr.storeRect.valueIndex+2),
+ floatData.at(instr.storeRect.valueIndex+3));
+ void *a[] = { &r, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeRect.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreVector3D:
+ {
+ QObject *target = stack.top();
+ QVector3D p(floatData.at(instr.storeVector3D.valueIndex),
+ floatData.at(instr.storeVector3D.valueIndex+1),
+ floatData.at(instr.storeVector3D.valueIndex+2));
+ void *a[] = { &p, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeVector3D.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreObject:
+ {
+ QObject *assignObj = stack.pop();
+ QObject *target = stack.top();
+
+ void *a[] = { (void *)&assignObj, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeObject.propertyIndex, a);
+ }
+ break;
+
+
+ case QmlInstruction::AssignCustomType:
+ {
+ QObject *target = stack.top();
+ QmlCompiledData::CustomTypeData data = customTypeData.at(instr.assignCustomType.valueIndex);
+ const QString &primitive = primitives.at(data.index);
+ QmlMetaType::StringConverter converter =
+ QmlMetaType::customStringConverter(data.type);
+ QVariant v = (*converter)(primitive);
+
+ QMetaProperty prop =
+ target->metaObject()->property(instr.assignCustomType.propertyIndex);
+ if (v.isNull() || ((int)prop.type() != data.type && prop.userType() != data.type))
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Cannot assign value %1 to property %2").arg(primitive).arg(QString::fromUtf8(prop.name())));
+
+ void *a[] = { (void *)v.data(), 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.assignCustomType.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::AssignSignalObject:
+ {
+ // XXX optimize
+
+ QObject *assign = stack.pop();
+ QObject *target = stack.top();
+ int sigIdx = instr.assignSignalObject.signal;
+ const QByteArray &pr = datas.at(sigIdx);
+
+ QmlMetaProperty prop(target, QString::fromUtf8(pr));
+ if (prop.type() & QmlMetaProperty::SignalProperty) {
+
+ QMetaMethod method = QmlMetaType::defaultMethod(assign);
+ if (method.signature() == 0)
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Cannot assign object type %1 with no default method").arg(QString::fromLatin1(assign->metaObject()->className())));
+
+ if (!QMetaObject::checkConnectArgs(prop.method().signature(), method.signature()))
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Cannot connect mismatched signal/slot %1 %vs. %2").arg(QString::fromLatin1(method.signature())).arg(QString::fromLatin1(prop.method().signature())));
+
+ QMetaObject::connect(target, prop.coreIndex(), assign, method.methodIndex());
+
+ } else {
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Cannot assign an object to signal property %1").arg(QString::fromUtf8(pr)));
+ }
+
+
+ }
+ break;
+
+ case QmlInstruction::StoreSignal:
+ {
+ QObject *target = stack.top();
+ // XXX scope
+ QMetaMethod signal =
+ target->metaObject()->method(instr.storeSignal.signalIndex);
+
+ QmlBoundSignal *bs = new QmlBoundSignal(target, signal, target);
+ QmlExpression *expr =
+ new QmlExpression(ctxt, primitives.at(instr.storeSignal.value), target);
+ expr->setSourceLocation(comp->name, instr.line);
+ bs->setExpression(expr);
+ }
+ break;
+
+ case QmlInstruction::StoreScript:
+ {
+ QObject *target = stack.top();
+ cp->addScript(scripts.at(instr.storeScript.value), target);
+ }
+ break;
+
+ case QmlInstruction::StoreScriptString:
+ {
+ QObject *target = stack.top();
+ QObject *scope = stack.at(stack.count() - 1 - instr.storeScriptString.scope);
+ QmlScriptString ss;
+ ss.setContext(ctxt);
+ ss.setScopeObject(scope);
+ ss.setScript(primitives.at(instr.storeScriptString.value));
+
+ void *a[] = { &ss, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeScriptString.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::BeginObject:
+ {
+ QObject *target = stack.top();
+ QmlParserStatus *status = reinterpret_cast<QmlParserStatus *>(reinterpret_cast<char *>(target) + instr.begin.castValue);
+ parserStatus.append(status);
+ status->d = &parserStatus.values[parserStatus.count - 1];
+
+ status->classBegin();
+ }
+ break;
+
+ case QmlInstruction::StoreBinding:
+ {
+ QObject *target =
+ stack.at(stack.count() - 1 - instr.assignBinding.owner);
+ QObject *context =
+ stack.at(stack.count() - 1 - instr.assignBinding.context);
+
+ QmlMetaProperty mp =
+ QmlMetaPropertyPrivate::restore(datas.at(instr.assignBinding.property), target, ctxt);
+
+ int coreIndex = mp.coreIndex();
+
+ if (stack.count() == 1 && bindingSkipList.testBit(coreIndex))
+ break;
+
+ QmlBinding *bind = new QmlBinding((void *)datas.at(instr.assignBinding.value).constData(), comp, context, ctxt, comp->name, instr.line, 0);
+ bindValues.append(bind);
+ bind->m_mePtr = &bindValues.values[bindValues.count - 1];
+ bind->setTarget(mp);
+ bind->addToObject(target);
+ }
+ break;
+
+ case QmlInstruction::StoreCompiledBinding:
+ {
+ QObject *target =
+ stack.at(stack.count() - 1 - instr.assignBinding.owner);
+ QObject *scope =
+ stack.at(stack.count() - 1 - instr.assignBinding.context);
+
+ int property = instr.assignBinding.property;
+ if (stack.count() == 1 && bindingSkipList.testBit(property & 0xFFFF))
+ break;
+
+ QmlAbstractBinding *binding =
+ cp->optimizedBindings->configBinding(instr.assignBinding.value, target, scope, property);
+ bindValues.append(binding);
+ binding->m_mePtr = &bindValues.values[bindValues.count - 1];
+ binding->addToObject(target);
+ }
+ break;
+
+ case QmlInstruction::StoreValueSource:
+ {
+ QObject *obj = stack.pop();
+ QmlPropertyValueSource *vs = reinterpret_cast<QmlPropertyValueSource *>(reinterpret_cast<char *>(obj) + instr.assignValueSource.castValue);
+ QObject *target = stack.at(stack.count() - 1 - instr.assignValueSource.owner);
+
+ QmlMetaProperty prop =
+ QmlMetaPropertyPrivate::restore(datas.at(instr.assignValueSource.property), target, ctxt);
+ obj->setParent(target);
+ vs->setTarget(prop);
+ }
+ break;
+
+ case QmlInstruction::StoreValueInterceptor:
+ {
+ QObject *obj = stack.pop();
+ QmlPropertyValueInterceptor *vi = reinterpret_cast<QmlPropertyValueInterceptor *>(reinterpret_cast<char *>(obj) + instr.assignValueInterceptor.castValue);
+ QObject *target = stack.at(stack.count() - 1 - instr.assignValueInterceptor.owner);
+ QmlMetaProperty prop =
+ QmlMetaPropertyPrivate::restore(datas.at(instr.assignValueInterceptor.property), target, ctxt);
+ obj->setParent(target);
+ vi->setTarget(prop);
+ QmlVMEMetaObject *mo = static_cast<QmlVMEMetaObject *>((QMetaObject*)target->metaObject());
+ mo->registerInterceptor(prop.coreIndex(), prop.valueTypeCoreIndex(), vi);
+ }
+ break;
+
+ case QmlInstruction::StoreObjectQmlList:
+ {
+ QObject *assign = stack.pop();
+ const ListInstance &list = qliststack.top();
+
+ void *d = (void *)&assign;
+ list.qmlListInterface->append(d);
+ }
+ break;
+
+ case QmlInstruction::StoreObjectQList:
+ {
+ QObject *assign = stack.pop();
+
+ const ListInstance &list = qliststack.top();
+ list.qListInterface->append((void *)assign);
+ }
+ break;
+
+ case QmlInstruction::AssignObjectList:
+ {
+ // This is only used for assigning interfaces
+ QObject *assign = stack.pop();
+ const ListInstance &list = qliststack.top();
+
+ int type = list.type;
+
+ void *ptr = 0;
+
+ const char *iid = QmlMetaType::interfaceIId(type);
+ if (iid)
+ ptr = assign->qt_metacast(iid);
+ if (!ptr)
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Cannot assign object to list"));
+
+
+ if (list.qmlListInterface) {
+ void *d = (void *)&ptr;
+ list.qmlListInterface->append(d);
+ } else {
+ list.qListInterface->append(ptr);
+ }
+ }
+ break;
+
+ case QmlInstruction::StoreVariantObject:
+ {
+ QObject *assign = stack.pop();
+ QObject *target = stack.top();
+
+ QVariant v = QVariant::fromValue(assign);
+ void *a[] = { &v, 0, &status, &flags };
+ QMetaObject::metacall(target, QMetaObject::WriteProperty,
+ instr.storeObject.propertyIndex, a);
+ }
+ break;
+
+ case QmlInstruction::StoreInterface:
+ {
+ QObject *assign = stack.pop();
+ QObject *target = stack.top();
+
+ int coreIdx = instr.storeObject.propertyIndex;
+ QMetaProperty prop = target->metaObject()->property(coreIdx);
+ int t = prop.userType();
+ const char *iid = QmlMetaType::interfaceIId(t);
+ bool ok = false;
+ if (iid) {
+ void *ptr = assign->qt_metacast(iid);
+ if (ptr) {
+ void *a[] = { &ptr, 0, &status, &flags };
+ QMetaObject::metacall(target,
+ QMetaObject::WriteProperty,
+ coreIdx, a);
+ ok = true;
+ }
+ }
+
+ if (!ok)
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Cannot assign object to interface property"));
+ }
+ break;
+
+ case QmlInstruction::FetchAttached:
+ {
+ QObject *target = stack.top();
+
+ QObject *qmlObject = qmlAttachedPropertiesObjectById(instr.fetchAttached.id, target);
+
+ if (!qmlObject)
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Unable to create attached object"));
+
+ stack.push(qmlObject);
+ }
+ break;
+
+ case QmlInstruction::FetchQmlList:
+ {
+ QObject *target = stack.top();
+
+ void *a[1];
+ // We know that QmlList<*> can be converted to
+ // QmlPrivate::ListInterface
+ QmlPrivate::ListInterface *list = 0;
+ a[0] = &list;
+ QMetaObject::metacall(target, QMetaObject::ReadProperty,
+ instr.fetchQmlList.property, a);
+ if (!list)
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Cannot assign to null list"));
+
+ qliststack.push(ListInstance(list, instr.fetchQmlList.type));
+ }
+ break;
+
+ case QmlInstruction::FetchQList:
+ {
+ QObject *target = stack.top();
+
+ void *a[1];
+ // We know that QList<T *>* can be converted to
+ // QList<void *>*
+ QList<void *> *list = 0;
+ a[0] = &list;
+ QMetaObject::metacall(target, QMetaObject::ReadProperty,
+ instr.fetchQmlList.property, a);
+ if (!list)
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Cannot assign to null list"));
+
+ qliststack.push(ListInstance(list, instr.fetchQmlList.type));
+ }
+ break;
+
+ case QmlInstruction::FetchObject:
+ {
+ QObject *target = stack.top();
+
+ QObject *obj = 0;
+ // NOTE: This assumes a cast to QObject does not alter the
+ // object pointer
+ void *a[1];
+ a[0] = &obj;
+ QMetaObject::metacall(target, QMetaObject::ReadProperty,
+ instr.fetch.property, a);
+
+ if (!obj)
+ VME_EXCEPTION(QCoreApplication::translate("QmlVME","Cannot set properties on %1 as it is null").arg(QString::fromUtf8(target->metaObject()->property(instr.fetch.property).name())));
+
+ stack.push(obj);
+ }
+ break;
+
+ case QmlInstruction::PopQList:
+ {
+ qliststack.pop();
+ }
+ break;
+
+ case QmlInstruction::Defer:
+ {
+ if (instr.defer.deferCount) {
+ QObject *target = stack.top();
+ QmlDeclarativeData *data =
+ QmlDeclarativeData::get(target, true);
+ comp->addref();
+ data->deferredComponent = comp;
+ data->deferredIdx = ii;
+ ii += instr.defer.deferCount;
+ }
+ }
+ break;
+
+ case QmlInstruction::PopFetchedObject:
+ {
+ stack.pop();
+ }
+ break;
+
+ case QmlInstruction::FetchValueType:
+ {
+ QObject *target = stack.top();
+ QmlValueType *valueHandler =
+ ep->valueTypes[instr.fetchValue.type];
+ valueHandler->read(target, instr.fetchValue.property);
+ stack.push(valueHandler);
+ }
+ break;
+
+ case QmlInstruction::PopValueType:
+ {
+ QmlValueType *valueHandler =
+ static_cast<QmlValueType *>(stack.pop());
+ QObject *target = stack.top();
+ valueHandler->write(target, instr.fetchValue.property, QmlMetaProperty::BypassInterceptor);
+ }
+ break;
+
+ default:
+ qFatal("QmlCompiledData: Internal error - unknown instruction %d", instr.type);
+ break;
+ }
+ }
+
+ if (isError()) {
+ if (!stack.isEmpty()) {
+ delete stack.at(0);
+ }
+
+ QmlEnginePrivate::clear(bindValues);
+ QmlEnginePrivate::clear(parserStatus);
+ return 0;
+ }
+
+ if (bindValues.count)
+ ep->bindValues << bindValues;
+ if (parserStatus.count)
+ ep->parserStatus << parserStatus;
+
+ if (stack.isEmpty())
+ return 0;
+ else
+ return stack.top();
+ return 0;
+}
+
+bool QmlVME::isError() const
+{
+ return !vmeErrors.isEmpty();
+}
+
+QList<QmlError> QmlVME::errors() const
+{
+ return vmeErrors;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlvme_p.h b/src/declarative/qml/qmlvme_p.h
new file mode 100644
index 0000000..9c45dc1
--- /dev/null
+++ b/src/declarative/qml/qmlvme_p.h
@@ -0,0 +1,119 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLVME_P_H
+#define QMLVME_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 "qmlerror.h"
+#include "qbitfield_p.h"
+
+#include <QtCore/QString>
+#include <QtCore/QStack>
+
+QT_BEGIN_NAMESPACE
+
+class QObject;
+class QmlInstruction;
+class QmlCompiledData;
+class QmlCompiledData;
+class QmlContext;
+
+template<typename T, int N = 128>
+class QmlVMEStack {
+public:
+ QmlVMEStack() : index(-1), maxSize(N), data(fixedData) {}
+ ~QmlVMEStack() { if (data != fixedData) qFree(fixedData); }
+
+ bool isEmpty() const { return index == -1; }
+ const T &top() const { return data[index]; }
+ void push(const T &i) { ++index; if (index == maxSize) realloc(); data[index] = i; }
+ const T &pop() { --index; return data[index + 1]; }
+ int count() const { return index + 1; }
+ const T &at(int idx) { return data[idx]; }
+
+private:
+ void realloc() {
+ maxSize += N;
+ if (data != fixedData) {
+ data = (T*)qRealloc(data, maxSize * sizeof(T));
+ } else {
+ data = (T*)qMalloc(maxSize * sizeof(T));
+ }
+ }
+ int index;
+ int maxSize;
+ T *data;
+ T fixedData[N];
+};
+
+class QmlVME
+{
+public:
+ QmlVME();
+
+ QObject *run(QmlContext *, QmlCompiledData *,
+ int start = -1, int count = -1,
+ const QBitField & = QBitField());
+ void runDeferred(QObject *);
+
+ bool isError() const;
+ QList<QmlError> errors() const;
+
+private:
+ QObject *run(QmlVMEStack<QObject *> &, QmlContext *, QmlCompiledData *,
+ int start, int count, const QBitField &);
+ QList<QmlError> vmeErrors;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLVME_P_H
diff --git a/src/declarative/qml/qmlvmemetaobject.cpp b/src/declarative/qml/qmlvmemetaobject.cpp
new file mode 100644
index 0000000..8faa922
--- /dev/null
+++ b/src/declarative/qml/qmlvmemetaobject.cpp
@@ -0,0 +1,340 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlvmemetaobject_p.h"
+
+#include "qml.h"
+#include "qmlrefcount_p.h"
+#include "qmlexpression.h"
+#include "qmlexpression_p.h"
+#include "qmlcontext_p.h"
+
+#include <QColor>
+#include <QDate>
+#include <QtCore/qlist.h>
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+QmlVMEMetaObject::QmlVMEMetaObject(QObject *obj,
+ const QMetaObject *other,
+ const QmlVMEMetaData *meta,
+ QmlCompiledData *cdata)
+: object(obj), compiledData(cdata), ctxt(qmlContext(obj)), metaData(meta), methods(0),
+ parent(0)
+{
+ compiledData->addref();
+
+ *static_cast<QMetaObject *>(this) = *other;
+ this->d.superdata = obj->metaObject();
+
+ QObjectPrivate *op = QObjectPrivate::get(obj);
+ if (op->metaObject)
+ parent = static_cast<QAbstractDynamicMetaObject*>(op->metaObject);
+ op->metaObject = this;
+
+ propOffset = QAbstractDynamicMetaObject::propertyOffset();
+ methodOffset = QAbstractDynamicMetaObject::methodOffset();
+
+ data = new QVariant[metaData->propertyCount];
+ aConnected.resize(metaData->aliasCount);
+
+ int list_type = qMetaTypeId<QmlList<QObject*>* >();
+ // ### Optimize
+ for (int ii = 0; ii < metaData->propertyCount; ++ii) {
+ int t = (metaData->propertyData() + ii)->propertyType;
+ if (t == list_type) {
+ listProperties.append(new List(this, ii));
+ data[ii] = QVariant::fromValue((QmlList<QObject *>*)listProperties.last());
+ } else if (t != -1) {
+ data[ii] = QVariant((QVariant::Type)t);
+ }
+ }
+}
+
+QmlVMEMetaObject::~QmlVMEMetaObject()
+{
+ compiledData->release();
+ delete parent;
+ qDeleteAll(listProperties);
+ delete [] data;
+ delete [] methods;
+}
+
+int QmlVMEMetaObject::metaCall(QMetaObject::Call c, int _id, void **a)
+{
+ int id = _id;
+ if(c == QMetaObject::WriteProperty) {
+ int flags = *reinterpret_cast<int*>(a[3]);
+ if (!(flags & QmlMetaProperty::BypassInterceptor)
+ && !aInterceptors.isEmpty()
+ && aInterceptors.testBit(id)) {
+ QPair<int, QmlPropertyValueInterceptor*> pair = interceptors.value(id);
+ int valueIndex = pair.first;
+ QmlPropertyValueInterceptor *vi = pair.second;
+ int type = property(id).userType();
+
+ if (type != QVariant::Invalid) {
+ if (valueIndex != -1) {
+ QmlEnginePrivate *ep = ctxt?QmlEnginePrivate::get(ctxt->engine()):0;
+ QmlValueType *valueType = 0;
+ if (ep) valueType = ep->valueTypes[type];
+ else valueType = QmlValueTypeFactory::valueType(type);
+ Q_ASSERT(valueType);
+
+ valueType->setValue(QVariant(type, a[0]));
+ QMetaProperty valueProp = valueType->metaObject()->property(valueIndex);
+ vi->write(valueProp.read(valueType));
+
+ if (!ep) delete valueType;
+ return -1;
+ } else {
+ vi->write(QVariant(type, a[0]));
+ return -1;
+ }
+ }
+ }
+ }
+ if(c == QMetaObject::ReadProperty || c == QMetaObject::WriteProperty) {
+ if (id >= propOffset) {
+ id -= propOffset;
+
+ if (id < metaData->propertyCount) {
+ int t = (metaData->propertyData() + id)->propertyType;
+ bool needActivate = false;
+
+ if (t == -1) {
+
+ if (c == QMetaObject::ReadProperty) {
+ *reinterpret_cast<QVariant *>(a[0]) = data[id];
+ } else if (c == QMetaObject::WriteProperty) {
+ needActivate =
+ (data[id] != *reinterpret_cast<QVariant *>(a[0]));
+ data[id] = *reinterpret_cast<QVariant *>(a[0]);
+ }
+
+ } else {
+
+ if (c == QMetaObject::ReadProperty) {
+ switch(t) {
+ case QVariant::Int:
+ *reinterpret_cast<int *>(a[0]) = data[id].toInt();
+ break;
+ case QVariant::Bool:
+ *reinterpret_cast<bool *>(a[0]) = data[id].toBool();
+ break;
+ case QVariant::Double:
+ *reinterpret_cast<double *>(a[0]) = data[id].toDouble();
+ break;
+ case QVariant::String:
+ *reinterpret_cast<QString *>(a[0]) = data[id].toString();
+ break;
+ case QVariant::Url:
+ *reinterpret_cast<QUrl *>(a[0]) = data[id].toUrl();
+ break;
+ case QVariant::Color:
+ *reinterpret_cast<QColor *>(a[0]) = data[id].value<QColor>();
+ break;
+ case QVariant::Date:
+ *reinterpret_cast<QDate *>(a[0]) = data[id].toDate();
+ break;
+ case QMetaType::QObjectStar:
+ *reinterpret_cast<QObject **>(a[0]) = data[id].value<QObject*>();
+ break;
+ default:
+ break;
+ }
+ if (t == qMetaTypeId<QmlList<QObject*>* >()) {
+ *reinterpret_cast<QmlList<QObject *> **>(a[0]) = data[id].value<QmlList<QObject*>*>();
+ }
+
+ } else if (c == QMetaObject::WriteProperty) {
+
+ QVariant value = QVariant((QVariant::Type)data[id].type(), a[0]);
+ needActivate = (data[id] != value);
+ data[id] = value;
+ }
+
+ }
+
+ if (c == QMetaObject::WriteProperty && needActivate) {
+ activate(object, methodOffset + id, 0);
+ }
+
+ return -1;
+ }
+
+ id -= metaData->propertyCount;
+
+ if (id < metaData->aliasCount) {
+
+ QmlVMEMetaData::AliasData *d = metaData->aliasData() + id;
+
+ if (d->flags & QML_ALIAS_FLAG_PTR && c == QMetaObject::ReadProperty)
+ *reinterpret_cast<void **>(a[0]) = 0;
+
+ if (!ctxt) return -1;
+ QmlContextPrivate *ctxtPriv =
+ (QmlContextPrivate *)QObjectPrivate::get(ctxt);
+
+ QObject *target = ctxtPriv->idValues[d->contextIdx].data();
+ if (!target)
+ return -1;
+
+ if (c == QMetaObject::ReadProperty && !aConnected.testBit(id)) {
+ int sigIdx = methodOffset + id + metaData->propertyCount;
+ QMetaObject::connect(ctxt, d->contextIdx + ctxtPriv->notifyIndex, object, sigIdx);
+
+ if (d->propertyIdx != -1) {
+ QMetaProperty prop =
+ target->metaObject()->property(d->propertyIdx);
+ if (prop.hasNotifySignal())
+ QMetaObject::connect(target, prop.notifySignalIndex(),
+ object, sigIdx);
+ }
+ aConnected.setBit(id);
+ }
+
+ if (d->propertyIdx == -1) {
+ *reinterpret_cast<QObject **>(a[0]) = target;
+ return -1;
+ } else {
+ return QMetaObject::metacall(target, c, d->propertyIdx, a);
+ }
+
+ }
+ return -1;
+
+ }
+
+ } else if(c == QMetaObject::InvokeMetaMethod) {
+
+ if (id >= methodOffset) {
+
+ id -= methodOffset;
+ int plainSignals = metaData->signalCount + metaData->propertyCount +
+ metaData->aliasCount;
+ if (id < plainSignals) {
+ QMetaObject::activate(object, _id, a);
+ return -1;
+ }
+
+ id -= plainSignals;
+
+ if (id < metaData->methodCount) {
+ if (!ctxt->engine())
+ return -1; // We can't run the method
+
+ QmlEnginePrivate *ep = QmlEnginePrivate::get(ctxt->engine());
+
+ QScriptValue function = method(id);
+
+ QScriptValueList args;
+ QmlVMEMetaData::MethodData *data = metaData->methodData() + id;
+ if (data->parameterCount) {
+ for (int ii = 0; ii < data->parameterCount; ++ii) {
+ args << ep->scriptValueFromVariant(*(QVariant *)a[ii + 1]);
+ }
+ }
+ QScriptValue rv = function.call(ep->objectClass->newQObject(object), args);
+
+ if (a[0]) *reinterpret_cast<QVariant *>(a[0]) = ep->scriptValueToVariant(rv);
+
+ return -1;
+ }
+ return -1;
+ }
+ }
+
+ if (parent)
+ return parent->metaCall(c, _id, a);
+ else
+ return object->qt_metacall(c, _id, a);
+}
+
+QScriptValue QmlVMEMetaObject::method(int index)
+{
+ if (!methods)
+ methods = new QScriptValue[metaData->methodCount];
+
+ if (!methods[index].isValid()) {
+ QmlVMEMetaData::MethodData *data = metaData->methodData() + index;
+
+ const QChar *body =
+ (const QChar *)(((const char*)metaData) + data->bodyOffset);
+
+ QString code = QString::fromRawData(body, data->bodyLength);
+
+ // XXX Use QScriptProgram
+ // XXX We should evaluate all methods in a single big script block to
+ // improve the call time between dynamic methods defined on the same
+ // object
+ methods[index] = QmlExpressionPrivate::evalInObjectScope(ctxt, object, code);
+ }
+
+ return methods[index];
+}
+
+void QmlVMEMetaObject::listChanged(int id)
+{
+ activate(object, methodOffset + id, 0);
+}
+
+void QmlVMEMetaObject::registerInterceptor(int index, int valueIndex, QmlPropertyValueInterceptor *interceptor)
+{
+ if (aInterceptors.isEmpty())
+ aInterceptors.resize(propertyCount() + metaData->propertyCount);
+ aInterceptors.setBit(index);
+ interceptors.insert(index, qMakePair(valueIndex, interceptor));
+}
+
+QScriptValue QmlVMEMetaObject::vmeMethod(int index)
+{
+ if (index < methodOffset) {
+ Q_ASSERT(parent);
+ return static_cast<QmlVMEMetaObject *>(parent)->vmeMethod(index);
+ }
+ int plainSignals = metaData->signalCount + metaData->propertyCount + metaData->aliasCount;
+ Q_ASSERT(index >= (methodOffset + plainSignals) && index < (methodOffset + plainSignals + metaData->methodCount));
+ return method(index - methodOffset - plainSignals);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlvmemetaobject_p.h b/src/declarative/qml/qmlvmemetaobject_p.h
new file mode 100644
index 0000000..497d8f6
--- /dev/null
+++ b/src/declarative/qml/qmlvmemetaobject_p.h
@@ -0,0 +1,172 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLVMEMETAOBJECT_P_H
+#define QMLVMEMETAOBJECT_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 "qml.h"
+
+#include <QtCore/QMetaObject>
+#include <QtCore/QBitArray>
+#include <QtCore/QPair>
+
+#include <private/qobject_p.h>
+
+#include "qmlguard_p.h"
+#include "qmlcompiler_p.h"
+
+QT_BEGIN_NAMESPACE
+
+#define QML_ALIAS_FLAG_PTR 0x00000001
+
+struct QmlVMEMetaData
+{
+ short propertyCount;
+ short aliasCount;
+ short signalCount;
+ short methodCount;
+
+ struct AliasData {
+ int contextIdx;
+ int propertyIdx;
+ int flags;
+ };
+
+ struct PropertyData {
+ int propertyType;
+ };
+
+ struct MethodData {
+ int parameterCount;
+ int bodyOffset;
+ int bodyLength;
+ int scriptProgram;
+ };
+
+ PropertyData *propertyData() const {
+ return (PropertyData *)(((const char *)this) + sizeof(QmlVMEMetaData));
+ }
+
+ AliasData *aliasData() const {
+ return (AliasData *)(propertyData() + propertyCount);
+ }
+
+ MethodData *methodData() const {
+ return (MethodData *)(aliasData() + aliasCount);
+ }
+};
+
+class QmlRefCount;
+class QmlVMEMetaObject : public QAbstractDynamicMetaObject
+{
+public:
+ QmlVMEMetaObject(QObject *obj, const QMetaObject *other, const QmlVMEMetaData *data,
+ QmlCompiledData *compiledData);
+ ~QmlVMEMetaObject();
+
+ void registerInterceptor(int index, int valueIndex, QmlPropertyValueInterceptor *interceptor);
+ QScriptValue vmeMethod(int index);
+protected:
+ virtual int metaCall(QMetaObject::Call _c, int _id, void **_a);
+
+private:
+ QObject *object;
+ QmlCompiledData *compiledData;
+ QmlGuard<QmlContext> ctxt;
+
+ const QmlVMEMetaData *metaData;
+ int propOffset;
+ int methodOffset;
+
+ QVariant *data;
+ QBitArray aConnected;
+ QBitArray aInterceptors;
+ QHash<int, QPair<int, QmlPropertyValueInterceptor*> > interceptors;
+
+ QScriptValue *methods;
+ QScriptValue method(int);
+
+ QAbstractDynamicMetaObject *parent;
+
+ void listChanged(int);
+ class List : public QmlConcreteList<QObject*>
+ {
+ public:
+ List(QmlVMEMetaObject *p, int propIdx)
+ : parent(p), parentProperty(propIdx) { }
+
+ virtual void append(QObject *v) {
+ QmlConcreteList<QObject*>::append(v);
+ parent->listChanged(parentProperty);
+ }
+ virtual void insert(int i, QObject *v) {
+ QmlConcreteList<QObject*>::insert(i, v);
+ parent->listChanged(parentProperty);
+ }
+ virtual void clear() {
+ QmlConcreteList<QObject*>::clear();
+ parent->listChanged(parentProperty);
+ }
+ virtual void removeAt(int i) {
+ QmlConcreteList<QObject*>::removeAt(i);
+ parent->listChanged(parentProperty);
+ }
+ private:
+ QmlVMEMetaObject *parent;
+ int parentProperty;
+ };
+ QList<List *> listProperties;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLVMEMETAOBJECT_P_H
diff --git a/src/declarative/qml/qmlwatcher.cpp b/src/declarative/qml/qmlwatcher.cpp
new file mode 100644
index 0000000..507c11d
--- /dev/null
+++ b/src/declarative/qml/qmlwatcher.cpp
@@ -0,0 +1,185 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlwatcher_p.h"
+
+#include "qmlexpression.h"
+#include "qmlcontext.h"
+#include "qml.h"
+
+#include <qmldebugservice_p.h>
+
+#include <QtCore/qmetaobject.h>
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+
+class QmlWatchProxy : public QObject
+{
+ Q_OBJECT
+public:
+ QmlWatchProxy(int id,
+ QObject *object,
+ int debugId,
+ const QMetaProperty &prop,
+ QmlWatcher *parent = 0);
+
+ QmlWatchProxy(int id,
+ QmlExpression *exp,
+ int debugId,
+ QmlWatcher *parent = 0);
+
+public slots:
+ void notifyValueChanged();
+
+private:
+ friend class QmlWatcher;
+ int m_id;
+ QmlWatcher *m_watch;
+ QObject *m_object;
+ int m_debugId;
+ QMetaProperty m_property;
+
+ QmlExpression *m_expr;
+};
+
+QmlWatchProxy::QmlWatchProxy(int id,
+ QmlExpression *exp,
+ int debugId,
+ QmlWatcher *parent)
+: QObject(parent), m_id(id), m_watch(parent), m_object(0), m_debugId(debugId), m_expr(exp)
+{
+ QObject::connect(m_expr, SIGNAL(valueChanged()), this, SLOT(notifyValueChanged()));
+}
+
+QmlWatchProxy::QmlWatchProxy(int id,
+ QObject *object,
+ int debugId,
+ const QMetaProperty &prop,
+ QmlWatcher *parent)
+: QObject(parent), m_id(id), m_watch(parent), m_object(object), m_debugId(debugId), m_property(prop), m_expr(0)
+{
+ static int refreshIdx = -1;
+ if(refreshIdx == -1)
+ refreshIdx = QmlWatchProxy::staticMetaObject.indexOfMethod("notifyValueChanged()");
+
+ if (prop.hasNotifySignal())
+ QMetaObject::connect(m_object, prop.notifySignalIndex(), this, refreshIdx);
+}
+
+void QmlWatchProxy::notifyValueChanged()
+{
+ QVariant v;
+ if (m_expr)
+ v = m_expr->value();
+ else
+ v = m_property.read(m_object);
+
+ emit m_watch->propertyChanged(m_id, m_debugId, m_property, v);
+}
+
+
+QmlWatcher::QmlWatcher(QObject *parent)
+ : QObject(parent)
+{
+}
+
+bool QmlWatcher::addWatch(int id, quint32 debugId)
+{
+ QObject *object = QmlDebugService::objectForId(debugId);
+ if (object) {
+ int propCount = object->metaObject()->propertyCount();
+ for (int ii=0; ii<propCount; ii++)
+ addPropertyWatch(id, object, debugId, object->metaObject()->property(ii));
+ return true;
+ }
+ return false;
+}
+
+bool QmlWatcher::addWatch(int id, quint32 debugId, const QByteArray &property)
+{
+ QObject *object = QmlDebugService::objectForId(debugId);
+ if (object) {
+ int index = object->metaObject()->indexOfProperty(property.constData());
+ if (index >= 0) {
+ addPropertyWatch(id, object, debugId, object->metaObject()->property(index));
+ return true;
+ }
+ }
+ return false;
+}
+
+bool QmlWatcher::addWatch(int id, quint32 objectId, const QString &expr)
+{
+ QObject *object = QmlDebugService::objectForId(objectId);
+ QmlContext *context = qmlContext(object);
+ if (context) {
+ QmlExpression *exprObj = new QmlExpression(context, expr, object);
+ QmlWatchProxy *proxy = new QmlWatchProxy(id, exprObj, objectId, this);
+ exprObj->setParent(proxy);
+ m_proxies[id].append(proxy);
+ proxy->notifyValueChanged();
+ return true;
+ }
+ return false;
+}
+
+void QmlWatcher::removeWatch(int id)
+{
+ if (!m_proxies.contains(id))
+ return;
+
+ QList<QPointer<QmlWatchProxy> > proxies = m_proxies.take(id);
+ qDeleteAll(proxies);
+}
+
+void QmlWatcher::addPropertyWatch(int id, QObject *object, quint32 debugId, const QMetaProperty &property)
+{
+ QmlWatchProxy *proxy = new QmlWatchProxy(id, object, debugId, property, this);
+ m_proxies[id].append(proxy);
+
+ proxy->notifyValueChanged();
+}
+
+QT_END_NAMESPACE
+
+#include <qmlwatcher.moc>
diff --git a/src/declarative/qml/qmlwatcher_p.h b/src/declarative/qml/qmlwatcher_p.h
new file mode 100644
index 0000000..5050949
--- /dev/null
+++ b/src/declarative/qml/qmlwatcher_p.h
@@ -0,0 +1,94 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLWATCHER_P_H
+#define QMLWATCHER_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/qobject.h>
+#include <QtCore/qlist.h>
+#include <QtCore/qpair.h>
+#include <QtCore/qhash.h>
+#include <QtCore/qset.h>
+#include <QtCore/qpointer.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlWatchProxy;
+class QmlExpression;
+class QmlContext;
+class QMetaProperty;
+
+class QmlWatcher : public QObject
+{
+ Q_OBJECT
+public:
+ QmlWatcher(QObject * = 0);
+
+ bool addWatch(int id, quint32 objectId);
+ bool addWatch(int id, quint32 objectId, const QByteArray &property);
+ bool addWatch(int id, quint32 objectId, const QString &expr);
+
+ void removeWatch(int id);
+
+Q_SIGNALS:
+ void propertyChanged(int id, int objectId, const QMetaProperty &property, const QVariant &value);
+
+private:
+ friend class QmlWatchProxy;
+ void addPropertyWatch(int id, QObject *object, quint32 objectId, const QMetaProperty &property);
+
+ QHash<int, QList<QPointer<QmlWatchProxy> > > m_proxies;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLWATCHER_P_H
diff --git a/src/declarative/qml/qmlworkerscript.cpp b/src/declarative/qml/qmlworkerscript.cpp
new file mode 100644
index 0000000..5e39eaf
--- /dev/null
+++ b/src/declarative/qml/qmlworkerscript.cpp
@@ -0,0 +1,1037 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlworkerscript_p.h"
+
+#include "qmlengine_p.h"
+
+#include <QtCore/qcoreevent.h>
+#include <QtCore/qcoreapplication.h>
+#include <QtCore/qdebug.h>
+#include <QtScript/qscriptengine.h>
+#include <QtCore/qmutex.h>
+#include <QtCore/qwaitcondition.h>
+#include <QtScript/qscriptvalueiterator.h>
+#include <QtCore/qfile.h>
+#include <QtNetwork/qnetworkaccessmanager.h>
+#include <QtDeclarative/qmlinfo.h>
+#include "qmlnetworkaccessmanagerfactory.h"
+
+QT_BEGIN_NAMESPACE
+
+class WorkerDataEvent : public QEvent
+{
+public:
+ enum Type { WorkerData = QEvent::User };
+
+ WorkerDataEvent(int workerId, const QVariant &data);
+ virtual ~WorkerDataEvent();
+
+ int workerId() const;
+ QVariant data() const;
+
+private:
+ int m_id;
+ QVariant m_data;
+};
+
+class WorkerLoadEvent : public QEvent
+{
+public:
+ enum Type { WorkerLoad = WorkerDataEvent::WorkerData + 1 };
+
+ WorkerLoadEvent(int workerId, const QUrl &url);
+
+ int workerId() const;
+ QUrl url() const;
+
+private:
+ int m_id;
+ QUrl m_url;
+};
+
+class WorkerRemoveEvent : public QEvent
+{
+public:
+ enum Type { WorkerRemove = WorkerLoadEvent::WorkerLoad + 1 };
+
+ WorkerRemoveEvent(int workerId);
+
+ int workerId() const;
+
+private:
+ int m_id;
+};
+
+class QmlWorkerScriptEnginePrivate : public QObject
+{
+public:
+ QmlWorkerScriptEnginePrivate(QmlEngine *eng);
+
+ struct ScriptEngine : public QmlScriptEngine
+ {
+ ScriptEngine(QmlWorkerScriptEnginePrivate *parent) : QmlScriptEngine(0), p(parent), accessManager(0) {}
+ ~ScriptEngine() { delete accessManager; }
+ QmlWorkerScriptEnginePrivate *p;
+ QNetworkAccessManager *accessManager;
+
+ virtual QNetworkAccessManager *networkAccessManager() {
+ if (!accessManager) {
+ if (p->qmlengine && p->qmlengine->networkAccessManagerFactory()) {
+ accessManager = p->qmlengine->networkAccessManagerFactory()->create(this);
+ } else {
+ accessManager = new QNetworkAccessManager(this);
+ }
+ }
+ return accessManager;
+ }
+ };
+ ScriptEngine *workerEngine;
+ static QmlWorkerScriptEnginePrivate *get(QScriptEngine *e) {
+ return static_cast<ScriptEngine *>(e)->p;
+ }
+
+ QmlEngine *qmlengine;
+
+ QMutex m_lock;
+ QWaitCondition m_wait;
+
+ struct WorkerScript {
+ WorkerScript();
+
+ int id;
+ bool initialized;
+ QmlWorkerScript *owner;
+ QScriptValue object;
+
+ QScriptValue callback;
+ };
+
+ QHash<int, WorkerScript *> workers;
+ QScriptValue getWorker(int);
+
+ int m_nextId;
+
+ static QVariant scriptValueToVariant(const QScriptValue &);
+ static QScriptValue variantToScriptValue(const QVariant &, QScriptEngine *);
+
+ static QScriptValue onMessage(QScriptContext *ctxt, QScriptEngine *engine);
+ static QScriptValue sendMessage(QScriptContext *ctxt, QScriptEngine *engine);
+
+protected:
+ virtual bool event(QEvent *);
+
+private:
+ void processMessage(int, const QVariant &);
+ void processLoad(int, const QUrl &);
+};
+
+// Currently this will leak as no-one releases it in the worker thread
+class QmlWorkerListModelAgent : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int count READ count);
+
+public:
+ QmlWorkerListModelAgent(QmlWorkerListModel *);
+ ~QmlWorkerListModelAgent();
+
+ void addref();
+ void release();
+
+ int count() const;
+
+ Q_INVOKABLE void clear();
+ Q_INVOKABLE void remove(int index);
+ Q_INVOKABLE void append(const QScriptValue &);
+ Q_INVOKABLE void insert(int index, const QScriptValue&);
+ Q_INVOKABLE QScriptValue get(int index) const;
+ Q_INVOKABLE void set(int index, const QScriptValue &);
+ Q_INVOKABLE void sync();
+
+ struct VariantRef
+ {
+ VariantRef() : a(0) {}
+ VariantRef(const VariantRef &r) : a(r.a) { if (a) a->addref(); }
+ VariantRef(QmlWorkerListModelAgent *_a) : a(_a) { if (a) a->addref(); }
+ ~VariantRef() { if (a) a->release(); }
+
+ VariantRef &operator=(const VariantRef &o) {
+ if (o.a) o.a->addref();
+ if (a) a->release(); a = o.a;
+ return *this;
+ }
+
+ QmlWorkerListModelAgent *a;
+ };
+protected:
+ virtual bool event(QEvent *);
+
+private:
+ friend class QmlWorkerScriptEnginePrivate;
+ friend class QmlWorkerListModel;
+ QScriptEngine *m_engine;
+
+ struct Change {
+ enum { Inserted, Removed, Moved, Changed } type;
+ int index; // Inserted/Removed/Moved/Changed
+ int count; // Inserted/Removed/Moved/Changed
+ int to; // Moved
+ };
+
+ struct Data {
+ QHash<int, QString> roles;
+ QHash<QString, int> strings;
+ QList<QHash<int, QVariant> > values;
+ QList<Change> changes;
+
+ void clearChange();
+ void insertChange(int index, int count);
+ void removeChange(int index, int count);
+ void changedChange(int index, int count);
+ };
+ Data data;
+
+ struct Sync : public QEvent {
+ Sync() : QEvent(QEvent::User) {}
+ Data data;
+ };
+
+ QAtomicInt m_ref;
+ QmlWorkerListModel *m_model;
+};
+Q_DECLARE_METATYPE(QmlWorkerListModelAgent::VariantRef);
+
+QmlWorkerScriptEnginePrivate::QmlWorkerScriptEnginePrivate(QmlEngine *engine)
+: workerEngine(0), qmlengine(engine), m_nextId(0)
+{
+}
+
+QScriptValue QmlWorkerScriptEnginePrivate::onMessage(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ QmlWorkerScriptEnginePrivate *p = QmlWorkerScriptEnginePrivate::get(engine);
+
+ int id = ctxt->thisObject().data().toVariant().toInt();
+
+ WorkerScript *script = p->workers.value(id);
+ if (!script)
+ return engine->undefinedValue();
+
+ if (ctxt->argumentCount() >= 1)
+ script->callback = ctxt->argument(0);
+
+ return script->callback;
+}
+
+QScriptValue QmlWorkerScriptEnginePrivate::sendMessage(QScriptContext *ctxt, QScriptEngine *engine)
+{
+ if (!ctxt->argumentCount())
+ return engine->undefinedValue();
+
+ QmlWorkerScriptEnginePrivate *p = QmlWorkerScriptEnginePrivate::get(engine);
+
+ int id = ctxt->thisObject().data().toVariant().toInt();
+
+ WorkerScript *script = p->workers.value(id);
+ if (!script)
+ return engine->undefinedValue();
+
+ p->m_lock.lock();
+ if (script->owner)
+ QCoreApplication::postEvent(script->owner,
+ new WorkerDataEvent(0, scriptValueToVariant(ctxt->argument(0))));
+ p->m_lock.unlock();
+
+ return engine->undefinedValue();
+}
+
+QScriptValue QmlWorkerScriptEnginePrivate::getWorker(int id)
+{
+ QHash<int, WorkerScript *>::ConstIterator iter = workers.find(id);
+
+ if (iter == workers.end())
+ return workerEngine->nullValue();
+
+ WorkerScript *script = *iter;
+ if (!script->initialized) {
+
+ script->initialized = true;
+ script->object = workerEngine->newObject();
+
+ QScriptValue api = workerEngine->newObject();
+ api.setData(script->id);
+
+ api.setProperty(QLatin1String("onMessage"), workerEngine->newFunction(onMessage),
+ QScriptValue::PropertyGetter | QScriptValue::PropertySetter);
+ api.setProperty(QLatin1String("sendMessage"), workerEngine->newFunction(sendMessage));
+
+ script->object.setProperty(QLatin1String("WorkerScript"), api);
+ }
+
+ return script->object;
+}
+
+bool QmlWorkerScriptEnginePrivate::event(QEvent *event)
+{
+ if (event->type() == (QEvent::Type)WorkerDataEvent::WorkerData) {
+ WorkerDataEvent *workerEvent = static_cast<WorkerDataEvent *>(event);
+ processMessage(workerEvent->workerId(), workerEvent->data());
+ return true;
+ } else if (event->type() == (QEvent::Type)WorkerLoadEvent::WorkerLoad) {
+ WorkerLoadEvent *workerEvent = static_cast<WorkerLoadEvent *>(event);
+ processLoad(workerEvent->workerId(), workerEvent->url());
+ return true;
+ } else {
+ return QObject::event(event);
+ }
+}
+
+void QmlWorkerScriptEnginePrivate::processMessage(int id, const QVariant &data)
+{
+ WorkerScript *script = workers.value(id);
+ if (!script)
+ return;
+
+ if (script->callback.isFunction()) {
+ QScriptValue args = workerEngine->newArray(1);
+ args.setProperty(0, variantToScriptValue(data, workerEngine));
+
+ script->callback.call(script->object, args);
+ }
+}
+
+void QmlWorkerScriptEnginePrivate::processLoad(int id, const QUrl &url)
+{
+ if (url.isRelative() || url.scheme() != QLatin1String("file"))
+ return;
+
+ QString fileName = url.toLocalFile();
+
+ QFile f(fileName);
+ if (f.open(QIODevice::ReadOnly)) {
+ QByteArray data = f.readAll();
+ QString script = QString::fromUtf8(data);
+
+ QScriptValue activation = getWorker(id);
+
+ QScriptContext *ctxt = workerEngine->pushContext();
+ ctxt->setActivationObject(activation);
+
+ workerEngine->baseUrl = url;
+ workerEngine->evaluate(script);
+
+ workerEngine->popContext();
+ }
+}
+
+QVariant QmlWorkerScriptEnginePrivate::scriptValueToVariant(const QScriptValue &value)
+{
+ if (value.isBool()) {
+ return QVariant(value.toBool());
+ } else if (value.isString()) {
+ return QVariant(value.toString());
+ } else if (value.isNumber()) {
+ return QVariant((qreal)value.toNumber());
+ } else if (value.isArray()) {
+ QVariantList list;
+
+ quint32 length = (quint32)value.property(QLatin1String("length")).toNumber();
+
+ for (quint32 ii = 0; ii < length; ++ii) {
+ QVariant v = scriptValueToVariant(ii);
+ list << v;
+ }
+
+ return QVariant(list);
+ } else if (value.isQObject()) {
+ QmlWorkerListModel *lm = qobject_cast<QmlWorkerListModel *>(value.toQObject());
+ if (lm) {
+ QmlWorkerListModelAgent::VariantRef v(lm->agent());
+ return qVariantFromValue(v);
+ } else {
+ // No other QObject's are allowed to be sent
+ return QVariant();
+ }
+ } else if (value.isObject()) {
+ QVariantHash hash;
+
+ QScriptValueIterator iter(value);
+
+ while (iter.hasNext()) {
+ iter.next();
+ hash.insert(iter.name(), scriptValueToVariant(iter.value()));
+ }
+
+ return QVariant(hash);
+ }
+
+ return QVariant();
+
+}
+
+QScriptValue QmlWorkerScriptEnginePrivate::variantToScriptValue(const QVariant &value, QScriptEngine *engine)
+{
+ if (value.userType() == QVariant::Bool) {
+ return QScriptValue(value.toBool());
+ } else if (value.userType() == QVariant::String) {
+ return QScriptValue(value.toString());
+ } else if (value.userType() == QMetaType::QReal) {
+ return QScriptValue(value.toReal());
+ } else if (value.userType() == qMetaTypeId<QmlWorkerListModelAgent::VariantRef>()) {
+ QmlWorkerListModelAgent::VariantRef vr = qvariant_cast<QmlWorkerListModelAgent::VariantRef>(value);
+ if (vr.a->m_engine == 0)
+ vr.a->m_engine = engine;
+ else if (vr.a->m_engine != engine)
+ return engine->nullValue();
+ QScriptValue o = engine->newQObject(vr.a);
+ o.setData(engine->newVariant(value)); // Keeps the agent ref so that it is cleaned up on gc
+ return o;
+ } else if (value.userType() == QMetaType::QVariantList) {
+ QVariantList list = qvariant_cast<QVariantList>(value);
+ QScriptValue rv = engine->newArray(list.count());
+
+ for (quint32 ii = 0; ii < quint32(list.count()); ++ii)
+ rv.setProperty(ii, variantToScriptValue(list.at(ii), engine));
+
+ return rv;
+ } else if (value.userType() == QMetaType::QVariantHash) {
+
+ QVariantHash hash = qvariant_cast<QVariantHash>(value);
+
+ QScriptValue rv = engine->newObject();
+
+ for (QVariantHash::ConstIterator iter = hash.begin(); iter != hash.end(); ++iter)
+ rv.setProperty(iter.key(), variantToScriptValue(iter.value(), engine));
+
+ return rv;
+ } else {
+ return engine->nullValue();
+ }
+}
+
+WorkerDataEvent::WorkerDataEvent(int workerId, const QVariant &data)
+: QEvent((QEvent::Type)WorkerData), m_id(workerId), m_data(data)
+{
+}
+
+WorkerDataEvent::~WorkerDataEvent()
+{
+}
+
+int WorkerDataEvent::workerId() const
+{
+ return m_id;
+}
+
+QVariant WorkerDataEvent::data() const
+{
+ return m_data;
+}
+
+WorkerLoadEvent::WorkerLoadEvent(int workerId, const QUrl &url)
+: QEvent((QEvent::Type)WorkerLoad), m_id(workerId), m_url(url)
+{
+}
+
+int WorkerLoadEvent::workerId() const
+{
+ return m_id;
+}
+
+QUrl WorkerLoadEvent::url() const
+{
+ return m_url;
+}
+
+WorkerRemoveEvent::WorkerRemoveEvent(int workerId)
+: QEvent((QEvent::Type)WorkerRemove), m_id(workerId)
+{
+}
+
+int WorkerRemoveEvent::workerId() const
+{
+ return m_id;
+}
+
+QmlWorkerScriptEngine::QmlWorkerScriptEngine(QmlEngine *parent)
+: QThread(parent), d(new QmlWorkerScriptEnginePrivate(parent))
+{
+ d->m_lock.lock();
+ start(QThread::LowPriority);
+ d->m_wait.wait(&d->m_lock);
+ d->moveToThread(this);
+ d->m_lock.unlock();
+}
+
+QmlWorkerScriptEngine::~QmlWorkerScriptEngine()
+{
+ qDeleteAll(d->workers);
+ delete d; d = 0;
+}
+
+QmlWorkerScriptEnginePrivate::WorkerScript::WorkerScript()
+: id(-1), initialized(false), owner(0)
+{
+}
+
+int QmlWorkerScriptEngine::registerWorkerScript(QmlWorkerScript *owner)
+{
+ QmlWorkerScriptEnginePrivate::WorkerScript *script = new QmlWorkerScriptEnginePrivate::WorkerScript;
+ script->id = d->m_nextId++;
+ script->owner = owner;
+
+ d->m_lock.lock();
+ d->workers.insert(script->id, script);
+ d->m_lock.unlock();
+
+ return script->id;
+}
+
+void QmlWorkerScriptEngine::removeWorkerScript(int id)
+{
+ QCoreApplication::postEvent(d, new WorkerRemoveEvent(id));
+}
+
+void QmlWorkerScriptEngine::executeUrl(int id, const QUrl &url)
+{
+ QCoreApplication::postEvent(d, new WorkerLoadEvent(id, url));
+}
+
+void QmlWorkerScriptEngine::sendMessage(int id, const QVariant &data)
+{
+ QCoreApplication::postEvent(d, new WorkerDataEvent(id, data));
+}
+
+void QmlWorkerScriptEngine::run()
+{
+ d->m_lock.lock();
+
+ d->workerEngine = new QmlWorkerScriptEnginePrivate::ScriptEngine(d);
+
+ d->m_wait.wakeAll();
+
+ d->m_lock.unlock();
+
+ exec();
+
+ delete d->workerEngine; d->workerEngine = 0;
+}
+
+QmlWorkerScript::QmlWorkerScript(QObject *parent)
+: QObject(parent), m_engine(0), m_scriptId(-1)
+{
+}
+
+QmlWorkerScript::~QmlWorkerScript()
+{
+ if (m_scriptId != -1) m_engine->removeWorkerScript(m_scriptId);
+}
+
+QUrl QmlWorkerScript::source() const
+{
+ return m_source;
+}
+
+void QmlWorkerScript::setSource(const QUrl &source)
+{
+ if (m_source == source)
+ return;
+
+ m_source = source;
+
+ if (m_engine)
+ m_engine->executeUrl(m_scriptId, m_source);
+
+ emit sourceChanged();
+}
+
+void QmlWorkerScript::sendMessage(const QScriptValue &message)
+{
+ if (!m_engine) {
+ qWarning("QmlWorkerScript: Attempt to send message before WorkerScript establishment");
+ return;
+ }
+
+ m_engine->sendMessage(m_scriptId, QmlWorkerScriptEnginePrivate::scriptValueToVariant(message));
+}
+
+void QmlWorkerScript::componentComplete()
+{
+ if (!m_engine) {
+ QmlEngine *engine = qmlEngine(this);
+ if (!engine) {
+ qWarning("QmlWorkerScript: componentComplete() called without qmlEngine() set");
+ return;
+ }
+
+ m_engine = QmlEnginePrivate::get(engine)->getWorkerScriptEngine();
+ m_scriptId = m_engine->registerWorkerScript(this);
+
+ if (m_source.isValid())
+ m_engine->executeUrl(m_scriptId, m_source);
+ }
+}
+
+bool QmlWorkerScript::event(QEvent *event)
+{
+ if (event->type() == (QEvent::Type)WorkerDataEvent::WorkerData) {
+ QmlEngine *engine = qmlEngine(this);
+ if (engine) {
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+ WorkerDataEvent *workerEvent = static_cast<WorkerDataEvent *>(event);
+ QScriptValue value =
+ QmlWorkerScriptEnginePrivate::variantToScriptValue(workerEvent->data(), scriptEngine);
+ emit message(value);
+ }
+ return true;
+ } else {
+ return QObject::event(event);
+ }
+}
+
+QML_DEFINE_TYPE(Qt, 4, 6, WorkerScript, QmlWorkerScript);
+
+void QmlWorkerListModelAgent::Data::clearChange()
+{
+ changes.clear();
+}
+
+void QmlWorkerListModelAgent::Data::insertChange(int index, int count)
+{
+ Change c = { Change::Inserted, index, count, 0 };
+ changes << c;
+}
+
+void QmlWorkerListModelAgent::Data::removeChange(int index, int count)
+{
+ Change c = { Change::Removed, index, count, 0 };
+ changes << c;
+}
+
+void QmlWorkerListModelAgent::Data::changedChange(int index, int count)
+{
+ Change c = { Change::Changed, index, count, 0 };
+ changes << c;
+}
+
+QmlWorkerListModelAgent::QmlWorkerListModelAgent(QmlWorkerListModel *m)
+: m_engine(0), m_ref(1), m_model(m)
+{
+ data.roles = m_model->m_roles;
+ data.strings = m_model->m_strings;
+ data.values = m_model->m_values;
+}
+
+QmlWorkerListModelAgent::~QmlWorkerListModelAgent()
+{
+}
+
+void QmlWorkerListModelAgent::addref()
+{
+ m_ref.ref();
+}
+
+void QmlWorkerListModelAgent::release()
+{
+ bool del = !m_ref.deref();
+
+ if (del)
+ delete this;
+}
+
+int QmlWorkerListModelAgent::count() const
+{
+ return data.values.count();
+}
+
+void QmlWorkerListModelAgent::clear()
+{
+ data.clearChange();
+ data.removeChange(0, data.values.count());
+ data.values.clear();
+}
+
+void QmlWorkerListModelAgent::remove(int index)
+{
+ if (data.values.count() <= index)
+ return;
+
+ data.values.removeAt(index);
+ data.removeChange(index, 1);
+}
+
+void QmlWorkerListModelAgent::append(const QScriptValue &value)
+{
+ QHash<int, QVariant> row;
+
+ QScriptValueIterator it(value);
+ while (it.hasNext()) {
+ it.next();
+ QString name = it.name();
+ QVariant v = it.value().toVariant();
+
+ QHash<QString, int>::Iterator iter = data.strings.find(name);
+ if (iter == data.strings.end()) {
+ int role = data.roles.count();
+ data.roles.insert(role, name);
+ iter = data.strings.insert(name, role);
+ }
+ row.insert(*iter, v);
+ }
+
+ data.values.append(row);
+ data.insertChange(data.values.count() - 1, 1);
+}
+
+void QmlWorkerListModelAgent::insert(int index, const QScriptValue &value)
+{
+ if (index > data.values.count())
+ return;
+
+ QHash<int, QVariant> row;
+
+ QScriptValueIterator it(value);
+ while (it.hasNext()) {
+ it.next();
+ QString name = it.name();
+ QVariant v = it.value().toVariant();
+
+ QHash<QString, int>::Iterator iter = data.strings.find(name);
+ if (iter == data.strings.end()) {
+ int role = data.roles.count();
+ data.roles.insert(role, name);
+ iter = data.strings.insert(name, role);
+ }
+ row.insert(*iter, v);
+ }
+
+ data.values.insert(index, row);
+ data.insertChange(index, 1);
+}
+
+void QmlWorkerListModelAgent::set(int index, const QScriptValue &value)
+{
+ if (data.values.count() <= index)
+ return;
+
+ QHash<int, QVariant> row;
+
+ QScriptValueIterator it(value);
+ while (it.hasNext()) {
+ it.next();
+ QString name = it.name();
+ QVariant v = it.value().toVariant();
+
+ QHash<QString, int>::Iterator iter = data.strings.find(name);
+ if (iter == data.strings.end()) {
+ int role = data.roles.count();
+ data.roles.insert(role, name);
+ iter = data.strings.insert(name, role);
+ }
+ row.insert(*iter, v);
+ }
+
+ if (data.values.at(index) != row) {
+ data.values[index] = row;
+ data.changedChange(index, 1);
+ }
+}
+
+QScriptValue QmlWorkerListModelAgent::get(int index) const
+{
+ if (data.values.count() <= index)
+ return m_engine->undefinedValue();
+
+ QScriptValue rv = m_engine->newObject();
+
+ QHash<int, QVariant> row = data.values.at(index);
+ for (QHash<int, QVariant>::ConstIterator iter = row.begin(); iter != row.end(); ++iter)
+ rv.setProperty(data.roles.value(iter.key()), qScriptValueFromValue(m_engine, iter.value()));
+
+ return rv;
+}
+
+void QmlWorkerListModelAgent::sync()
+{
+ Sync *s = new Sync;
+ s->data = data;
+ data.changes.clear();
+ QCoreApplication::postEvent(this, s);
+}
+
+bool QmlWorkerListModelAgent::event(QEvent *e)
+{
+ if (e->type() == QEvent::User) {
+ Sync *s = static_cast<Sync *>(e);
+
+ const QList<Change> &changes = s->data.changes;
+
+ if (m_model) {
+ bool cc = m_model->m_values.count() != s->data.values.count();
+
+ m_model->m_roles = s->data.roles;
+ m_model->m_strings = s->data.strings;
+ m_model->m_values = s->data.values;
+
+ for (int ii = 0; ii < changes.count(); ++ii) {
+ const Change &change = changes.at(ii);
+ switch (change.type) {
+ case Change::Inserted:
+ emit m_model->itemsInserted(change.index, change.count);
+ break;
+ case Change::Removed:
+ emit m_model->itemsRemoved(change.index, change.count);
+ break;
+ case Change::Moved:
+ emit m_model->itemsMoved(change.index, change.to, change.count);
+ break;
+ case Change::Changed:
+ emit m_model->itemsMoved(change.index, change.to, change.count);
+ break;
+ }
+ }
+
+ if (cc)
+ emit m_model->countChanged();
+ }
+ }
+
+ return QObject::event(e);
+}
+
+QmlWorkerListModel::QmlWorkerListModel(QObject *parent)
+: QListModelInterface(parent), m_agent(0)
+{
+}
+
+QmlWorkerListModel::~QmlWorkerListModel()
+{
+ if (m_agent) {
+ m_agent->m_model = 0;
+ m_agent->release();
+ }
+}
+
+void QmlWorkerListModel::clear()
+{
+ if (m_agent) {
+ qmlInfo(this) << "List can only be modified from a WorkerScript";
+ return;
+ }
+
+ int count = m_values.count();
+ m_values.clear();
+ if (count) {
+ emit itemsRemoved(0, count);
+ emit countChanged();
+ }
+}
+
+void QmlWorkerListModel::remove(int index)
+{
+ if (m_agent) {
+ qmlInfo(this) << "List can only be modified from a WorkerScript";
+ return;
+ }
+
+ if (m_values.count() <= index)
+ return;
+
+ m_values.removeAt(index);
+ emit itemsRemoved(index, 1);
+ emit countChanged();
+}
+
+void QmlWorkerListModel::append(const QScriptValue &value)
+{
+ if (m_agent) {
+ qmlInfo(this) << "List can only be modified from a WorkerScript";
+ return;
+ }
+
+ QHash<int, QVariant> data;
+
+ QScriptValueIterator it(value);
+ while (it.hasNext()) {
+ it.next();
+ QString name = it.name();
+ QVariant v = it.value().toVariant();
+
+ QHash<QString, int>::Iterator iter = m_strings.find(name);
+ if (iter == m_strings.end()) {
+ int role = m_roles.count();
+ m_roles.insert(role, name);
+ iter = m_strings.insert(name, role);
+ }
+ data.insert(*iter, v);
+ }
+
+ m_values.append(data);
+
+ emit itemsInserted(m_values.count() - 1, 1);
+ emit countChanged();
+}
+
+void QmlWorkerListModel::insert(int index, const QScriptValue &value)
+{
+ if (m_agent) {
+ qmlInfo(this) << "List can only be modified from a WorkerScript";
+ return;
+ }
+
+ if (index > m_values.count())
+ return;
+
+ QHash<int, QVariant> data;
+
+ QScriptValueIterator it(value);
+ while (it.hasNext()) {
+ it.next();
+ QString name = it.name();
+ QVariant v = it.value().toVariant();
+
+ QHash<QString, int>::Iterator iter = m_strings.find(name);
+ if (iter == m_strings.end()) {
+ int role = m_roles.count();
+ m_roles.insert(role, name);
+ iter = m_strings.insert(name, role);
+ }
+ data.insert(*iter, v);
+ }
+
+ m_values.insert(index, data);
+ emit itemsInserted(index, 1);
+ emit countChanged();
+}
+
+QScriptValue QmlWorkerListModel::get(int index) const
+{
+ QmlEngine *engine = qmlEngine(this);
+ if (!engine || m_values.count() <= index)
+ return QScriptValue();
+
+ QScriptEngine *scriptEngine = QmlEnginePrivate::getScriptEngine(engine);
+ QScriptValue rv = scriptEngine->newObject();
+
+ QHash<int, QVariant> data = m_values.at(index);
+ for (QHash<int, QVariant>::ConstIterator iter = data.begin(); iter != data.end(); ++iter)
+ rv.setProperty(m_roles.value(iter.key()), qScriptValueFromValue(scriptEngine, iter.value()));
+
+ return rv;
+}
+
+void QmlWorkerListModel::set(int index, const QScriptValue &value)
+{
+ if (m_agent) {
+ qmlInfo(this) << "List can only be modified from a WorkerScript";
+ return;
+ }
+
+ if (m_values.count() <= index)
+ return;
+
+ QHash<int, QVariant> data;
+
+ QScriptValueIterator it(value);
+ while (it.hasNext()) {
+ it.next();
+ QString name = it.name();
+ QVariant v = it.value().toVariant();
+
+ QHash<QString, int>::Iterator iter = m_strings.find(name);
+ if (iter == m_strings.end()) {
+ int role = m_roles.count();
+ m_roles.insert(role, name);
+ iter = m_strings.insert(name, role);
+ }
+ data.insert(*iter, v);
+ }
+
+ if (m_values.at(index) != data) {
+ m_values[index] = data;
+ emit itemsChanged(index, 1, m_roles.keys());
+ }
+}
+
+QmlWorkerListModelAgent *QmlWorkerListModel::agent()
+{
+ if (!m_agent)
+ m_agent = new QmlWorkerListModelAgent(this);
+
+ return m_agent;
+}
+
+QList<int> QmlWorkerListModel::roles() const
+{
+ return m_roles.keys();
+}
+
+QString QmlWorkerListModel::toString(int role) const
+{
+ return m_roles.value(role);
+}
+
+int QmlWorkerListModel::count() const
+{
+ return m_values.count();
+}
+
+QHash<int,QVariant> QmlWorkerListModel::data(int index, const QList<int> &) const
+{
+ if (m_values.count() <= index)
+ return QHash<int, QVariant>();
+ else
+ return m_values.at(index);
+}
+
+QVariant QmlWorkerListModel::data(int index, int role) const
+{
+ if (m_values.count() <= index)
+ return QVariant();
+ else
+ return m_values.at(index).value(role);
+}
+
+QML_DEFINE_TYPE(Qt,4,6,WorkerListModel,QmlWorkerListModel)
+
+#include "qmlworkerscript.moc"
+
+QT_END_NAMESPACE
diff --git a/src/declarative/qml/qmlworkerscript_p.h b/src/declarative/qml/qmlworkerscript_p.h
new file mode 100644
index 0000000..3a29498
--- /dev/null
+++ b/src/declarative/qml/qmlworkerscript_p.h
@@ -0,0 +1,160 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLWORKERSCRIPT_P_H
+#define QMLWORKERSCRIPT_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 "qml.h"
+#include "qmlparserstatus.h"
+#include <private/qlistmodelinterface_p.h>
+
+#include <QtCore/qthread.h>
+#include <QtScript/qscriptvalue.h>
+#include <QtCore/qurl.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlWorkerScript;
+class QmlWorkerScriptEnginePrivate;
+class QmlWorkerScriptEngine : public QThread
+{
+Q_OBJECT
+public:
+ QmlWorkerScriptEngine(QmlEngine *parent = 0);
+ virtual ~QmlWorkerScriptEngine();
+
+ int registerWorkerScript(QmlWorkerScript *);
+ void removeWorkerScript(int);
+ void executeUrl(int, const QUrl &);
+ void sendMessage(int, const QVariant &);
+
+protected:
+ virtual void run();
+
+private:
+ QmlWorkerScriptEnginePrivate *d;
+};
+
+class QmlWorkerScript : public QObject, public QmlParserStatus
+{
+ Q_OBJECT
+ Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
+
+ Q_INTERFACES(QmlParserStatus)
+public:
+ QmlWorkerScript(QObject *parent = 0);
+ virtual ~QmlWorkerScript();
+
+ QUrl source() const;
+ void setSource(const QUrl &);
+
+public slots:
+ void sendMessage(const QScriptValue &);
+
+signals:
+ void sourceChanged();
+ void message(const QScriptValue &messageObject);
+
+protected:
+ virtual void componentComplete();
+ virtual bool event(QEvent *);
+
+private:
+ QmlWorkerScriptEngine *m_engine;
+ int m_scriptId;
+ QUrl m_source;
+};
+
+class QmlWorkerListModelAgent;
+class QmlWorkerListModel : public QListModelInterface
+{
+ Q_OBJECT
+ Q_PROPERTY(int count READ count NOTIFY countChanged)
+
+public:
+ QmlWorkerListModel(QObject * = 0);
+ virtual ~QmlWorkerListModel();
+
+ Q_INVOKABLE void clear();
+ Q_INVOKABLE void remove(int index);
+ Q_INVOKABLE void append(const QScriptValue &);
+ Q_INVOKABLE void insert(int index, const QScriptValue&);
+ Q_INVOKABLE QScriptValue get(int index) const;
+ Q_INVOKABLE void set(int index, const QScriptValue &);
+
+ QmlWorkerListModelAgent *agent();
+
+ virtual QList<int> roles() const;
+ virtual QString toString(int role) const;
+ virtual int count() const;
+ virtual QHash<int,QVariant> data(int index, const QList<int> &roles = (QList<int>())) const;
+ virtual QVariant data(int index, int role) const;
+
+Q_SIGNALS:
+ void countChanged();
+
+private:
+ friend class QmlWorkerListModelAgent;
+
+ QHash<int, QString> m_roles;
+ QHash<QString, int> m_strings;
+ QList<QHash<int, QVariant> > m_values;
+
+ QmlWorkerListModelAgent *m_agent;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlWorkerScript);
+QML_DECLARE_TYPE(QmlWorkerListModel);
+
+#endif // QMLWORKERSCRIPT_P_H
diff --git a/src/declarative/qml/qmlxmlhttprequest.cpp b/src/declarative/qml/qmlxmlhttprequest.cpp
new file mode 100644
index 0000000..1883d1b
--- /dev/null
+++ b/src/declarative/qml/qmlxmlhttprequest.cpp
@@ -0,0 +1,1627 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlxmlhttprequest_p.h"
+
+#include "qmlengine.h"
+#include "qmlengine_p.h"
+#include "qmlrefcount_p.h"
+#include "qmlengine_p.h"
+#include "qmlexpression_p.h"
+
+#include <QtCore/qobject.h>
+#include <QtScript/qscriptvalue.h>
+#include <QtScript/qscriptcontext.h>
+#include <QtScript/qscriptengine.h>
+#include <QtNetwork/qnetworkreply.h>
+#include <QtCore/qxmlstream.h>
+#include <QtCore/qstack.h>
+#include <QtCore/qdebug.h>
+
+// From DOM-Level-3-Core spec
+// http://www.w3.org/TR/DOM-Level-3-Core/core.html
+#define INDEX_SIZE_ERR 1
+#define DOMSTRING_SIZE_ERR 2
+#define HIERARCHY_REQUEST_ERR 3
+#define WRONG_DOCUMENT_ERR 4
+#define INVALID_CHARACTER_ERR 5
+#define NO_DATA_ALLOWED_ERR 6
+#define NO_MODIFICATION_ALLOWED_ERR 7
+#define NOT_FOUND_ERR 8
+#define NOT_SUPPORTED_ERR 9
+#define INUSE_ATTRIBUTE_ERR 10
+#define INVALID_STATE_ERR 11
+#define SYNTAX_ERR 12
+#define INVALID_MODIFICATION_ERR 13
+#define NAMESPACE_ERR 14
+#define INVALID_ACCESS_ERR 15
+#define VALIDATION_ERR 16
+#define TYPE_MISMATCH_ERR 17
+
+#define THROW_DOM(error, desc) \
+{ \
+ QScriptValue errorValue = context->throwError(QLatin1String(desc)); \
+ errorValue.setProperty(QLatin1String("code"), error); \
+ return errorValue; \
+}
+
+#define THROW_SYNTAX(desc) \
+ return context->throwError(QScriptContext::SyntaxError, QLatin1String(desc));
+#define THROW_REFERENCE(desc) \
+ return context->throwError(QScriptContext::ReferenceError, QLatin1String(desc));
+
+#define D(arg) (arg)->release()
+#define A(arg) (arg)->addref()
+
+namespace {
+
+class DocumentImpl;
+class NodeImpl
+{
+public:
+ NodeImpl() : type(Element), document(0), parent(0) {}
+ virtual ~NodeImpl() {
+ for (int ii = 0; ii < children.count(); ++ii)
+ delete children.at(ii);
+ for (int ii = 0; ii < attributes.count(); ++ii)
+ delete attributes.at(ii);
+ }
+
+ // These numbers are copied from the Node IDL definition
+ enum Type {
+ Attr = 2,
+ CDATA = 4,
+ Comment = 8,
+ Document = 9,
+ DocumentFragment = 11,
+ DocumentType = 10,
+ Element = 1,
+ Entity = 6,
+ EntityReference = 5,
+ Notation = 12,
+ ProcessingInstruction = 7,
+ Text = 3
+ };
+ Type type;
+
+ QString namespaceUri;
+ QString name;
+
+ QString data;
+
+ void addref();
+ void release();
+
+ DocumentImpl *document;
+ NodeImpl *parent;
+
+ QList<NodeImpl *> children;
+ QList<NodeImpl *> attributes;
+};
+
+class DocumentImpl : public QmlRefCount, public NodeImpl
+{
+public:
+ DocumentImpl() : root(0) { type = Document; }
+ virtual ~DocumentImpl() {
+ if (root) delete root;
+ }
+
+ QString version;
+ QString encoding;
+ bool isStandalone;
+
+ NodeImpl *root;
+
+ void addref() { QmlRefCount::addref(); }
+ void release() { QmlRefCount::release(); }
+};
+
+class NamedNodeMap
+{
+public:
+ // JS API
+ static QScriptValue length(QScriptContext *context, QScriptEngine *engine);
+
+ // C++ API
+ static QScriptValue prototype(QScriptEngine *);
+ static QScriptValue create(QScriptEngine *, NodeImpl *, QList<NodeImpl *> *);
+
+ NamedNodeMap();
+ NamedNodeMap(const NamedNodeMap &);
+ ~NamedNodeMap();
+ bool isNull();
+
+ NodeImpl *d;
+ QList<NodeImpl *> *list;
+private:
+ NamedNodeMap &operator=(const NamedNodeMap &);
+};
+
+class NamedNodeMapClass : public QScriptClass
+{
+public:
+ NamedNodeMapClass(QScriptEngine *engine) : QScriptClass(engine) {}
+
+ virtual QueryFlags queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id);
+ virtual QScriptValue property(const QScriptValue &object, const QScriptString &name, uint id);
+};
+
+class NodeList
+{
+public:
+ // JS API
+ static QScriptValue length(QScriptContext *context, QScriptEngine *engine);
+
+ // C++ API
+ static QScriptValue prototype(QScriptEngine *);
+ static QScriptValue create(QScriptEngine *, NodeImpl *);
+
+ NodeList();
+ NodeList(const NodeList &);
+ ~NodeList();
+ bool isNull();
+
+ NodeImpl *d;
+private:
+ NodeList &operator=(const NodeList &);
+};
+
+class NodeListClass : public QScriptClass
+{
+public:
+ NodeListClass(QScriptEngine *engine) : QScriptClass(engine) {}
+ virtual QueryFlags queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id);
+ virtual QScriptValue property(const QScriptValue &object, const QScriptString &name, uint id);
+};
+
+class Node
+{
+public:
+ // JS API
+ static QScriptValue nodeName(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue nodeValue(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue nodeType(QScriptContext *context, QScriptEngine *engine);
+
+ static QScriptValue parentNode(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue childNodes(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue firstChild(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue lastChild(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue previousSibling(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue nextSibling(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue attributes(QScriptContext *context, QScriptEngine *engine);
+
+ //static QScriptValue ownerDocument(QScriptContext *context, QScriptEngine *engine);
+ //static QScriptValue namespaceURI(QScriptContext *context, QScriptEngine *engine);
+ //static QScriptValue prefix(QScriptContext *context, QScriptEngine *engine);
+ //static QScriptValue localName(QScriptContext *context, QScriptEngine *engine);
+ //static QScriptValue baseURI(QScriptContext *context, QScriptEngine *engine);
+ //static QScriptValue textContent(QScriptContext *context, QScriptEngine *engine);
+
+ // C++ API
+ static QScriptValue prototype(QScriptEngine *);
+ static QScriptValue create(QScriptEngine *, NodeImpl *);
+
+ Node();
+ Node(const Node &o);
+ ~Node();
+ bool isNull() const;
+
+ NodeImpl *d;
+
+private:
+ Node &operator=(const Node &);
+};
+
+class Element : public Node
+{
+public:
+ // C++ API
+ static QScriptValue prototype(QScriptEngine *);
+};
+
+class Attr : public Node
+{
+public:
+ // JS API
+ static QScriptValue name(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue specified(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue value(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue ownerElement(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue schemaTypeInfo(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue isId(QScriptContext *context, QScriptEngine *engine);
+
+ // C++ API
+ static QScriptValue prototype(QScriptEngine *);
+};
+
+class CharacterData : public Node
+{
+public:
+ // JS API
+ static QScriptValue length(QScriptContext *context, QScriptEngine *engine);
+
+ // C++ API
+ static QScriptValue prototype(QScriptEngine *);
+};
+
+class Text : public CharacterData
+{
+public:
+ // JS API
+ static QScriptValue isElementContentWhitespace(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue wholeText(QScriptContext *context, QScriptEngine *engine);
+
+ // C++ API
+ static QScriptValue prototype(QScriptEngine *);
+};
+
+class CDATA : public Text
+{
+public:
+ // C++ API
+ static QScriptValue prototype(QScriptEngine *);
+};
+
+class Document : public Node
+{
+public:
+ // JS API
+ static QScriptValue xmlVersion(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue xmlEncoding(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue xmlStandalone(QScriptContext *context, QScriptEngine *engine);
+ static QScriptValue documentElement(QScriptContext *context, QScriptEngine *engine);
+
+ // C++ API
+ static QScriptValue prototype(QScriptEngine *);
+ static QScriptValue load(QScriptEngine *engine, const QString &data);
+};
+
+}; // namespace
+
+Q_DECLARE_METATYPE(Node);
+Q_DECLARE_METATYPE(NodeList);
+Q_DECLARE_METATYPE(NamedNodeMap);
+
+void NodeImpl::addref()
+{
+ A(document);
+}
+
+void NodeImpl::release()
+{
+ D(document);
+}
+
+QScriptValue Node::nodeName(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ switch (node.d->type) {
+ case NodeImpl::Document:
+ return QScriptValue(QLatin1String("#document"));
+ case NodeImpl::CDATA:
+ return QScriptValue(QLatin1String("#cdata-section"));
+ case NodeImpl::Text:
+ return QScriptValue(QLatin1String("#text"));
+ default:
+ return QScriptValue(node.d->name);
+ }
+}
+
+QScriptValue Node::nodeValue(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ if (node.d->type == NodeImpl::Document ||
+ node.d->type == NodeImpl::DocumentFragment ||
+ node.d->type == NodeImpl::DocumentType ||
+ node.d->type == NodeImpl::Element ||
+ node.d->type == NodeImpl::Entity ||
+ node.d->type == NodeImpl::EntityReference ||
+ node.d->type == NodeImpl::Notation)
+ return engine->nullValue();
+
+ return QScriptValue(node.d->data);
+}
+
+QScriptValue Node::nodeType(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+ return QScriptValue(node.d->type);
+}
+
+QScriptValue Node::parentNode(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ if (node.d->parent) return Node::create(engine, node.d->parent);
+ else return engine->nullValue();
+}
+
+QScriptValue Node::childNodes(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ return NodeList::create(engine, node.d);
+}
+
+QScriptValue Node::firstChild(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ if (node.d->children.isEmpty()) return engine->nullValue();
+ else return Node::create(engine, node.d->children.first());
+}
+
+QScriptValue Node::lastChild(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ if (node.d->children.isEmpty()) return engine->nullValue();
+ else return Node::create(engine, node.d->children.last());
+}
+
+QScriptValue Node::previousSibling(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ if (!node.d->parent) return engine->nullValue();
+
+ for (int ii = 0; ii < node.d->parent->children.count(); ++ii) {
+ if (node.d->parent->children.at(ii) == node.d) {
+ if (ii == 0) return engine->nullValue();
+ else return Node::create(engine, node.d->parent->children.at(ii - 1));
+ }
+ }
+
+ return engine->nullValue();
+}
+
+QScriptValue Node::nextSibling(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ if (!node.d->parent) return engine->nullValue();
+
+ for (int ii = 0; ii < node.d->parent->children.count(); ++ii) {
+ if (node.d->parent->children.at(ii) == node.d) {
+ if ((ii + 1) == node.d->parent->children.count()) return engine->nullValue();
+ else return Node::create(engine, node.d->parent->children.at(ii + 1));
+ }
+ }
+
+ return engine->nullValue();
+}
+
+QScriptValue Node::attributes(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ if (node.d->type != NodeImpl::Element)
+ return engine->nullValue();
+ else
+ return NamedNodeMap::create(engine, node.d, &node.d->attributes);
+}
+
+QScriptValue Node::prototype(QScriptEngine *engine)
+{
+ QScriptValue proto = engine->newObject();
+
+ proto.setProperty(QLatin1String("nodeName"), engine->newFunction(nodeName), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("nodeValue"), engine->newFunction(nodeValue), QScriptValue::ReadOnly | QScriptValue::PropertyGetter | QScriptValue::PropertySetter);
+ proto.setProperty(QLatin1String("nodeType"), engine->newFunction(nodeType), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("parentNode"), engine->newFunction(parentNode), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("childNodes"), engine->newFunction(childNodes), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("firstChild"), engine->newFunction(firstChild), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("lastChild"), engine->newFunction(lastChild), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("previousSibling"), engine->newFunction(previousSibling), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("nextSibling"), engine->newFunction(nextSibling), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("attributes"), engine->newFunction(attributes), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+
+ return proto;
+}
+
+QScriptValue Node::create(QScriptEngine *engine, NodeImpl *data)
+{
+ QScriptValue instance = engine->newObject();
+
+ switch (data->type) {
+ case NodeImpl::Attr:
+ instance.setPrototype(Attr::prototype(engine));
+ break;
+ case NodeImpl::Comment:
+ case NodeImpl::Document:
+ case NodeImpl::DocumentFragment:
+ case NodeImpl::DocumentType:
+ case NodeImpl::Entity:
+ case NodeImpl::EntityReference:
+ case NodeImpl::Notation:
+ case NodeImpl::ProcessingInstruction:
+ return QScriptValue();
+ case NodeImpl::CDATA:
+ instance.setPrototype(CDATA::prototype(engine));
+ break;
+ case NodeImpl::Text:
+ instance.setPrototype(Text::prototype(engine));
+ break;
+ case NodeImpl::Element:
+ instance.setPrototype(Element::prototype(engine));
+ break;
+ }
+
+ Node node;
+ node.d = data;
+ if (data) A(data);
+
+ return engine->newVariant(instance, qVariantFromValue(node));
+}
+
+QScriptValue Element::prototype(QScriptEngine *engine)
+{
+ QScriptValue proto = engine->newObject();
+ proto.setPrototype(Node::prototype(engine));
+
+ proto.setProperty(QLatin1String("tagName"), engine->newFunction(nodeName), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+
+ return proto;
+}
+
+QScriptValue Attr::prototype(QScriptEngine *engine)
+{
+ QScriptValue proto = engine->newObject();
+ proto.setPrototype(Node::prototype(engine));
+
+ proto.setProperty(QLatin1String("name"), engine->newFunction(name), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("value"), engine->newFunction(value), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("ownerElement"), engine->newFunction(ownerElement), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+
+ return proto;
+}
+
+QScriptValue Attr::name(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ return QScriptValue(node.d->name);
+}
+
+QScriptValue Attr::value(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ return QScriptValue(node.d->data);
+}
+
+QScriptValue Attr::ownerElement(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ return Node::create(engine, node.d->parent);
+}
+
+QScriptValue CharacterData::length(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ return QScriptValue(node.d->data.length());
+}
+
+QScriptValue CharacterData::prototype(QScriptEngine *engine)
+{
+ QScriptValue proto = engine->newObject();
+ proto.setPrototype(Node::prototype(engine));
+
+ proto.setProperty(QLatin1String("data"), engine->newFunction(nodeValue), QScriptValue::ReadOnly | QScriptValue::PropertyGetter | QScriptValue::PropertySetter);
+ proto.setProperty(QLatin1String("length"), engine->newFunction(length), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+
+ return proto;
+}
+
+QScriptValue Text::isElementContentWhitespace(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ return node.d->data.trimmed().isEmpty();
+}
+
+QScriptValue Text::wholeText(QScriptContext *context, QScriptEngine *engine)
+{
+ Node node = qscriptvalue_cast<Node>(context->thisObject());
+ if (node.isNull()) return engine->undefinedValue();
+
+ return node.d->data;
+}
+
+QScriptValue Text::prototype(QScriptEngine *engine)
+{
+ QScriptValue proto = engine->newObject();
+ proto.setPrototype(CharacterData::prototype(engine));
+
+ proto.setProperty(QLatin1String("isElementContentWhitespace"), engine->newFunction(isElementContentWhitespace), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ proto.setProperty(QLatin1String("wholeText"), engine->newFunction(wholeText), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+
+ return proto;
+}
+
+QScriptValue CDATA::prototype(QScriptEngine *engine)
+{
+ QScriptValue proto = engine->newObject();
+ proto.setPrototype(Text::prototype(engine));
+ return proto;
+}
+
+QScriptValue Document::prototype(QScriptEngine *engine)
+{
+ QScriptValue proto = engine->newObject();
+ proto.setPrototype(Node::prototype(engine));
+
+ proto.setProperty(QLatin1String("xmlVersion"), engine->newFunction(xmlVersion), QScriptValue::ReadOnly | QScriptValue::PropertyGetter | QScriptValue::PropertySetter);
+ proto.setProperty(QLatin1String("xmlEncoding"), engine->newFunction(xmlEncoding), QScriptValue::ReadOnly | QScriptValue::PropertyGetter | QScriptValue::PropertySetter);
+ proto.setProperty(QLatin1String("xmlStandalone"), engine->newFunction(xmlStandalone), QScriptValue::ReadOnly | QScriptValue::PropertyGetter | QScriptValue::PropertySetter);
+ proto.setProperty(QLatin1String("documentElement"), engine->newFunction(documentElement), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+
+ return proto;
+}
+
+QScriptValue Document::load(QScriptEngine *engine, const QString &data)
+{
+ Q_ASSERT(engine);
+
+ DocumentImpl *document = 0;
+ QStack<NodeImpl *> nodeStack;
+
+ QXmlStreamReader reader(data);
+
+ while (!reader.atEnd()) {
+ switch (reader.readNext()) {
+ case QXmlStreamReader::NoToken:
+ break;
+ case QXmlStreamReader::Invalid:
+ break;
+ case QXmlStreamReader::StartDocument:
+ Q_ASSERT(!document);
+ document = new DocumentImpl;
+ document->document = document;
+ document->version = reader.documentVersion().toString();
+ document->encoding = reader.documentEncoding().toString();
+ document->isStandalone = reader.isStandaloneDocument();
+ break;
+ case QXmlStreamReader::EndDocument:
+ break;
+ case QXmlStreamReader::StartElement:
+ {
+ Q_ASSERT(document);
+ NodeImpl *node = new NodeImpl;
+ node->document = document;
+ node->namespaceUri = reader.namespaceUri().toString();
+ node->name = reader.name().toString();
+ if (nodeStack.isEmpty()) {
+ document->root = node;
+ } else {
+ node->parent = nodeStack.top();
+ node->parent->children.append(node);
+ }
+ nodeStack.append(node);
+
+ foreach (const QXmlStreamAttribute &a, reader.attributes()) {
+ NodeImpl *attr = new NodeImpl;
+ attr->document = document;
+ attr->type = NodeImpl::Attr;
+ attr->namespaceUri = a.namespaceUri().toString();
+ attr->name = a.name().toString();
+ attr->data = a.value().toString();
+ attr->parent = node;
+ node->attributes.append(attr);
+ }
+ }
+ break;
+ case QXmlStreamReader::EndElement:
+ nodeStack.pop();
+ break;
+ case QXmlStreamReader::Characters:
+ {
+ NodeImpl *node = new NodeImpl;
+ node->document = document;
+ node->type = reader.isCDATA()?NodeImpl::CDATA:NodeImpl::Text;
+ node->parent = nodeStack.top();
+ node->parent->children.append(node);
+ node->data = reader.text().toString();
+ }
+ break;
+ case QXmlStreamReader::Comment:
+ break;
+ case QXmlStreamReader::DTD:
+ break;
+ case QXmlStreamReader::EntityReference:
+ break;
+ case QXmlStreamReader::ProcessingInstruction:
+ break;
+ }
+ }
+
+ if (!document || reader.hasError()) {
+ if (document) D(document);
+ return engine->nullValue();
+ }
+
+ QScriptValue instance = engine->newObject();
+ instance.setPrototype(Document::prototype(engine));
+ Node documentNode;
+ documentNode.d = document;
+ return engine->newVariant(instance, qVariantFromValue(documentNode));
+}
+
+Node::Node()
+: d(0)
+{
+}
+
+Node::Node(const Node &o)
+: d(o.d)
+{
+ if (d) A(d);
+}
+
+Node::~Node()
+{
+ if (d) D(d);
+}
+
+bool Node::isNull() const
+{
+ return d == 0;
+}
+
+QScriptValue NamedNodeMap::length(QScriptContext *context, QScriptEngine *engine)
+{
+ NamedNodeMap map = qscriptvalue_cast<NamedNodeMap>(context->thisObject().data());
+ if (map.isNull()) return engine->undefinedValue();
+
+ return QScriptValue(map.list->count());
+}
+
+QScriptValue NamedNodeMap::prototype(QScriptEngine *engine)
+{
+ QScriptValue proto = engine->newObject();
+
+ proto.setProperty(QLatin1String("length"), engine->newFunction(length), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+
+ return proto;
+}
+
+QScriptValue NamedNodeMap::create(QScriptEngine *engine, NodeImpl *data, QList<NodeImpl *> *list)
+{
+ QScriptValue instance = engine->newObject();
+ instance.setPrototype(NamedNodeMap::prototype(engine));
+
+ NamedNodeMap map;
+ map.d = data;
+ map.list = list;
+ if (data) A(data);
+
+ instance.setData(engine->newVariant(qVariantFromValue(map)));
+
+ if (!QmlScriptEngine::get(engine)->namedNodeMapClass)
+ QmlScriptEngine::get(engine)->namedNodeMapClass= new NamedNodeMapClass(engine);
+
+ instance.setScriptClass(QmlScriptEngine::get(engine)->namedNodeMapClass);
+
+ return instance;
+}
+
+NamedNodeMap::NamedNodeMap()
+: d(0), list(0)
+{
+}
+
+NamedNodeMap::NamedNodeMap(const NamedNodeMap &o)
+: d(o.d), list(o.list)
+{
+ if (d) A(d);
+}
+
+NamedNodeMap::~NamedNodeMap()
+{
+ if (d) D(d);
+}
+
+bool NamedNodeMap::isNull()
+{
+ return d == 0;
+}
+
+QScriptValue NodeList::length(QScriptContext *context, QScriptEngine *engine)
+{
+ NodeList list = qscriptvalue_cast<NodeList>(context->thisObject().data());
+ if (list.isNull()) return engine->undefinedValue();
+
+ return QScriptValue(list.d->children.count());
+}
+
+QScriptValue NodeList::prototype(QScriptEngine *engine)
+{
+ QScriptValue proto = engine->newObject();
+
+ proto.setProperty(QLatin1String("length"), engine->newFunction(length), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+
+ return proto;
+}
+
+QScriptValue NodeList::create(QScriptEngine *engine, NodeImpl *data)
+{
+ QScriptValue instance = engine->newObject();
+ instance.setPrototype(NodeList::prototype(engine));
+
+ NodeList list;
+ list.d = data;
+ if (data) A(data);
+
+ instance.setData(engine->newVariant(qVariantFromValue(list)));
+
+ if (!QmlScriptEngine::get(engine)->nodeListClass)
+ QmlScriptEngine::get(engine)->nodeListClass= new NodeListClass(engine);
+
+ instance.setScriptClass(QmlScriptEngine::get(engine)->nodeListClass);
+
+ return instance;
+}
+
+NodeList::NodeList()
+: d(0)
+{
+}
+
+NodeList::NodeList(const NodeList &o)
+: d(o.d)
+{
+ if (d) A(d);
+}
+
+NodeList::~NodeList()
+{
+ if (d) D(d);
+}
+
+bool NodeList::isNull()
+{
+ return d == 0;
+}
+
+NamedNodeMapClass::QueryFlags NamedNodeMapClass::queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id)
+{
+ if (!(flags & HandlesReadAccess))
+ return 0;
+
+ NamedNodeMap map = qscriptvalue_cast<NamedNodeMap>(object.data());
+ Q_ASSERT(!map.isNull());
+
+ bool ok = false;
+ QString nameString = name.toString();
+ uint index = nameString.toUInt(&ok);
+ if (ok) {
+ if ((uint)map.list->count() <= index)
+ return 0;
+
+ *id = index;
+ return HandlesReadAccess;
+ } else {
+ for (int ii = 0; ii < map.list->count(); ++ii) {
+ if (map.list->at(ii) && map.list->at(ii)->name == nameString) {
+ *id = ii;
+ return HandlesReadAccess;
+ }
+ }
+ }
+
+ return 0;
+}
+
+QScriptValue NamedNodeMapClass::property(const QScriptValue &object, const QScriptString &, uint id)
+{
+ NamedNodeMap map = qscriptvalue_cast<NamedNodeMap>(object.data());
+ return Node::create(engine(), map.list->at(id));
+}
+
+NodeListClass::QueryFlags NodeListClass::queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id)
+{
+ if (!(flags & HandlesReadAccess))
+ return 0;
+
+ bool ok = false;
+ uint index = name.toString().toUInt(&ok);
+ if (!ok)
+ return 0;
+
+ NodeList list = qscriptvalue_cast<NodeList>(object.data());
+ if (list.isNull() || (uint)list.d->children.count() <= index)
+ return 0; // ### I think we're meant to raise an exception
+
+ *id = index;
+ return HandlesReadAccess;
+}
+
+QScriptValue NodeListClass::property(const QScriptValue &object, const QScriptString &, uint id)
+{
+ NodeList list = qscriptvalue_cast<NodeList>(object.data());
+ return Node::create(engine(), list.d->children.at(id));
+}
+
+QScriptValue Document::documentElement(QScriptContext *context, QScriptEngine *engine)
+{
+ Node document = qscriptvalue_cast<Node>(context->thisObject());
+ if (document.isNull() || document.d->type != NodeImpl::Document) return engine->undefinedValue();
+
+ return Node::create(engine, static_cast<DocumentImpl *>(document.d)->root);
+}
+
+QScriptValue Document::xmlStandalone(QScriptContext *context, QScriptEngine *engine)
+{
+ Node document = qscriptvalue_cast<Node>(context->thisObject());
+ if (document.isNull() || document.d->type != NodeImpl::Document) return engine->undefinedValue();
+
+ return QScriptValue(static_cast<DocumentImpl *>(document.d)->isStandalone);
+}
+
+QScriptValue Document::xmlVersion(QScriptContext *context, QScriptEngine *engine)
+{
+ Node document = qscriptvalue_cast<Node>(context->thisObject());
+ if (document.isNull() || document.d->type != NodeImpl::Document) return engine->undefinedValue();
+
+ return QScriptValue(static_cast<DocumentImpl *>(document.d)->version);
+}
+
+QScriptValue Document::xmlEncoding(QScriptContext *context, QScriptEngine *engine)
+{
+ Node document = qscriptvalue_cast<Node>(context->thisObject());
+ if (document.isNull() || document.d->type != NodeImpl::Document) return engine->undefinedValue();
+
+ return QScriptValue(static_cast<DocumentImpl *>(document.d)->encoding);
+}
+
+class QmlXMLHttpRequest : public QObject
+{
+Q_OBJECT
+public:
+ enum State { Unsent = 0,
+ Opened = 1, HeadersReceived = 2,
+ Loading = 3, Done = 4 };
+
+ QmlXMLHttpRequest(QNetworkAccessManager *manager);
+ virtual ~QmlXMLHttpRequest();
+
+ bool sendFlag() const;
+ bool errorFlag() const;
+ quint32 readyState() const;
+ int replyStatus() const;
+ QString replyStatusText() const;
+
+ QScriptValue open(QScriptValue *me, const QString &, const QUrl &);
+
+ void addHeader(const QString &, const QString &);
+ QString header(const QString &name);
+ QString headers();
+ QScriptValue send(QScriptValue *me, const QByteArray &);
+ QScriptValue abort(QScriptValue *me);
+
+ QString responseBody() const;
+private slots:
+ void downloadProgress(qint64);
+ void error(QNetworkReply::NetworkError);
+ void finished();
+
+private:
+ void requestFromUrl(const QUrl &url);
+
+ State m_state;
+ bool m_errorFlag;
+ bool m_sendFlag;
+ QString m_method;
+ QUrl m_url;
+ QByteArray m_responseEntityBody;
+ QByteArray m_data;
+ int m_redirectCount;
+
+ typedef QPair<QByteArray, QByteArray> HeaderPair;
+ typedef QList<HeaderPair> HeadersList;
+ HeadersList m_headersList;
+ void fillHeadersList();
+
+ QScriptValue m_me; // Set to the data object while a send() is ongoing (to access the callback)
+
+ QScriptValue dispatchCallback(QScriptValue *me);
+ void printError(const QScriptValue&);
+
+ int m_status;
+ QString m_statusText;
+ QNetworkRequest m_request;
+ QNetworkReply *m_network;
+ void destroyNetwork();
+
+ QNetworkAccessManager *m_nam;
+ QNetworkAccessManager *networkAccessManager() { return m_nam; }
+};
+
+QmlXMLHttpRequest::QmlXMLHttpRequest(QNetworkAccessManager *manager)
+: m_state(Unsent), m_errorFlag(false), m_sendFlag(false),
+ m_redirectCount(0), m_network(0), m_nam(manager)
+{
+}
+
+QmlXMLHttpRequest::~QmlXMLHttpRequest()
+{
+ destroyNetwork();
+}
+
+bool QmlXMLHttpRequest::sendFlag() const
+{
+ return m_sendFlag;
+}
+
+bool QmlXMLHttpRequest::errorFlag() const
+{
+ return m_errorFlag;
+}
+
+quint32 QmlXMLHttpRequest::readyState() const
+{
+ return m_state;
+}
+
+int QmlXMLHttpRequest::replyStatus() const
+{
+ return m_status;
+}
+
+QString QmlXMLHttpRequest::replyStatusText() const
+{
+ return m_statusText;
+}
+
+QScriptValue QmlXMLHttpRequest::open(QScriptValue *me, const QString &method, const QUrl &url)
+{
+ destroyNetwork();
+ m_sendFlag = false;
+ m_errorFlag = false;
+ m_responseEntityBody = QByteArray();
+ m_method = method;
+ m_url = url;
+ m_state = Opened;
+ return dispatchCallback(me);
+}
+
+void QmlXMLHttpRequest::addHeader(const QString &name, const QString &value)
+{
+ QByteArray utfname = name.toUtf8();
+
+ if (m_request.hasRawHeader(utfname)) {
+ m_request.setRawHeader(utfname, m_request.rawHeader(utfname) + ',' + value.toUtf8());
+ } else {
+ m_request.setRawHeader(utfname, value.toUtf8());
+ }
+}
+
+QString QmlXMLHttpRequest::header(const QString &name)
+{
+ QByteArray utfname = name.toLower().toUtf8();
+
+ foreach (const HeaderPair &header, m_headersList) {
+ if (header.first == utfname)
+ return QString::fromUtf8(header.second);
+ }
+ return QString();
+}
+
+QString QmlXMLHttpRequest::headers()
+{
+ QString ret;
+
+ foreach (const HeaderPair &header, m_headersList) {
+ if (ret.length())
+ ret.append(QString::fromUtf8("\r\n"));
+ ret.append(QString::fromUtf8(header.first));
+ ret.append(QString::fromUtf8(": "));
+ ret.append(QString::fromUtf8(header.second));
+ }
+ return ret;
+}
+
+void QmlXMLHttpRequest::fillHeadersList()
+{
+ QList<QByteArray> headerList = m_network->rawHeaderList();
+
+ m_headersList.clear();
+ foreach (const QByteArray &header, headerList) {
+ HeaderPair pair (header.toLower(), m_network->rawHeader(header));
+ if (pair.first == "set-cookie" ||
+ pair.first == "set-cookie2")
+ continue;
+
+ m_headersList << pair;
+ }
+}
+
+void QmlXMLHttpRequest::requestFromUrl(const QUrl &url)
+{
+ QNetworkRequest request = m_request;
+ request.setUrl(url);
+ if(m_method == QLatin1String("POST") ||
+ m_method == QLatin1String("PUT")) {
+ QVariant var = request.header(QNetworkRequest::ContentTypeHeader);
+ if (var.isValid()) {
+ QString str = var.toString();
+ int charsetIdx = str.indexOf(QLatin1String("charset="));
+ if (charsetIdx == -1) {
+ // No charset - append
+ if (!str.isEmpty()) str.append(QLatin1Char(';'));
+ str.append(QLatin1String("charset=UTF-8"));
+ } else {
+ charsetIdx += 8;
+ int n = 0;
+ int semiColon = str.indexOf(QLatin1Char(';'), charsetIdx);
+ if (semiColon == -1) {
+ n = str.length() - charsetIdx;
+ } else {
+ n = semiColon - charsetIdx;
+ }
+
+ str.replace(charsetIdx, n, QLatin1String("UTF-8"));
+ }
+ request.setHeader(QNetworkRequest::ContentTypeHeader, str);
+ } else {
+ request.setHeader(QNetworkRequest::ContentTypeHeader,
+ QLatin1String("text/plain;charset=UTF-8"));
+ }
+ }
+
+ if (m_method == QLatin1String("GET"))
+ m_network = networkAccessManager()->get(request);
+ else if (m_method == QLatin1String("HEAD"))
+ m_network = networkAccessManager()->head(request);
+ else if(m_method == QLatin1String("POST"))
+ m_network = networkAccessManager()->post(request, m_data);
+ else if(m_method == QLatin1String("PUT"))
+ m_network = networkAccessManager()->put(request, m_data);
+
+ QObject::connect(m_network, SIGNAL(downloadProgress(qint64,qint64)),
+ this, SLOT(downloadProgress(qint64)));
+ QObject::connect(m_network, SIGNAL(error(QNetworkReply::NetworkError)),
+ this, SLOT(error(QNetworkReply::NetworkError)));
+ QObject::connect(m_network, SIGNAL(finished()),
+ this, SLOT(finished()));
+}
+
+QScriptValue QmlXMLHttpRequest::send(QScriptValue *me, const QByteArray &data)
+{
+ m_errorFlag = false;
+ m_sendFlag = true;
+ m_redirectCount = 0;
+ m_data = data;
+ m_me = *me;
+
+ requestFromUrl(m_url);
+
+ return QScriptValue();
+}
+
+QScriptValue QmlXMLHttpRequest::abort(QScriptValue *me)
+{
+ destroyNetwork();
+ m_responseEntityBody = QByteArray();
+ m_errorFlag = true;
+ m_request = QNetworkRequest();
+
+ if (!(m_state == Unsent ||
+ (m_state == Opened && !m_sendFlag) ||
+ m_state == Done)) {
+
+ m_state = Done;
+ m_sendFlag = false;
+ QScriptValue cbv = dispatchCallback(me);
+ if (cbv.isError()) return cbv;
+ }
+
+ m_state = Unsent;
+ return QScriptValue();
+}
+
+void QmlXMLHttpRequest::downloadProgress(qint64 bytes)
+{
+ Q_UNUSED(bytes)
+ m_status =
+ m_network->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ m_statusText =
+ QString::fromUtf8(m_network->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray());
+
+ // ### We assume if this is called the headers are now available
+ if (m_state < HeadersReceived) {
+ m_state = HeadersReceived;
+ fillHeadersList ();
+ QScriptValue cbv = dispatchCallback(&m_me);
+ if (cbv.isError()) printError(cbv);
+ }
+
+ bool wasEmpty = m_responseEntityBody.isEmpty();
+ m_responseEntityBody.append(m_network->readAll());
+ if (wasEmpty && !m_responseEntityBody.isEmpty()) {
+ m_state = Loading;
+ QScriptValue cbv = dispatchCallback(&m_me);
+ if (cbv.isError()) printError(cbv);
+ }
+}
+
+void QmlXMLHttpRequest::error(QNetworkReply::NetworkError error)
+{
+ Q_UNUSED(error)
+ m_status =
+ m_network->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ m_statusText =
+ QString::fromUtf8(m_network->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray());
+
+ m_responseEntityBody = QByteArray();
+
+ m_request = QNetworkRequest();
+ m_data.clear();
+ destroyNetwork();
+
+ if (error == QNetworkReply::ContentAccessDenied ||
+ error == QNetworkReply::ContentOperationNotPermittedError ||
+ error == QNetworkReply::ContentNotFoundError ||
+ error == QNetworkReply::AuthenticationRequiredError ||
+ error == QNetworkReply::ContentReSendError) {
+ m_state = Loading;
+ QScriptValue cbv = dispatchCallback(&m_me);
+ if (cbv.isError()) printError(cbv);
+ } else {
+ m_errorFlag = true;
+ }
+
+ m_state = Done;
+ QScriptValue cbv = dispatchCallback(&m_me);
+ if (cbv.isError()) printError(cbv);
+}
+
+#define XMLHTTPREQUEST_MAXIMUM_REDIRECT_RECURSION 15
+void QmlXMLHttpRequest::finished()
+{
+ m_redirectCount++;
+ if (m_redirectCount < XMLHTTPREQUEST_MAXIMUM_REDIRECT_RECURSION) {
+ QVariant redirect = m_network->attribute(QNetworkRequest::RedirectionTargetAttribute);
+ if (redirect.isValid()) {
+ QUrl url = redirect.toUrl();
+ destroyNetwork();
+ requestFromUrl(url);
+ return;
+ }
+ }
+
+ m_status =
+ m_network->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ m_statusText =
+ QString::fromUtf8(m_network->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray());
+
+ if (m_state < HeadersReceived) {
+ m_state = HeadersReceived;
+ fillHeadersList ();
+ QScriptValue cbv = dispatchCallback(&m_me);
+ if (cbv.isError()) printError(cbv);
+ }
+ m_responseEntityBody.append(m_network->readAll());
+ m_data.clear();
+ destroyNetwork();
+ if (m_state < Loading) {
+ m_state = Loading;
+ QScriptValue cbv = dispatchCallback(&m_me);
+ if (cbv.isError()) printError(cbv);
+ }
+ m_state = Done;
+ QScriptValue cbv = dispatchCallback(&m_me);
+ if (cbv.isError()) printError(cbv);
+
+ m_me = QScriptValue();
+}
+
+
+QString QmlXMLHttpRequest::responseBody() const
+{
+ return QString::fromUtf8(m_responseEntityBody);
+}
+
+QScriptValue QmlXMLHttpRequest::dispatchCallback(QScriptValue *me)
+{
+ QScriptValue v = me->property(QLatin1String("callback"));
+ return v.call();
+}
+
+void QmlXMLHttpRequest::printError(const QScriptValue& sv)
+{
+ QmlError error;
+ QmlExpressionPrivate::exceptionToError(sv.engine(), error);
+ qWarning().nospace() << qPrintable(error.toString());
+}
+
+void QmlXMLHttpRequest::destroyNetwork()
+{
+ if (m_network) {
+ m_network->disconnect();
+ m_network->deleteLater();
+ m_network = 0;
+ }
+}
+
+// XMLHttpRequest methods
+static QScriptValue qmlxmlhttprequest_open(QScriptContext *context, QScriptEngine *engine)
+{
+ QScriptValue dataObject = context->thisObject().data();
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(dataObject.toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ if (context->argumentCount() < 2 || context->argumentCount() > 5)
+ THROW_DOM(SYNTAX_ERR, "Incorrect argument count");
+
+ // Argument 0 - Method
+ QString method = context->argument(0).toString().toUpper();
+ if (method != QLatin1String("GET") &&
+ method != QLatin1String("PUT") &&
+ method != QLatin1String("HEAD") &&
+ method != QLatin1String("POST"))
+ THROW_DOM(SYNTAX_ERR, "Unsupported HTTP method type");
+
+
+ // Argument 1 - URL
+ QUrl url = QUrl::fromEncoded(context->argument(1).toString().toUtf8());
+
+ if (url.isRelative()) {
+ url = QmlScriptEngine::get(engine)->resolvedUrl(context,url);
+ }
+
+ // Argument 2 - async (optional)
+ if (context->argumentCount() > 2 && !context->argument(2).toBoolean())
+ THROW_DOM(NOT_SUPPORTED_ERR, "Synchronous XMLHttpRequest calls are not supported");
+
+
+ // Argument 3/4 - user/pass (optional)
+ QString username, password;
+ if (context->argumentCount() > 3)
+ username = context->argument(3).toString();
+ if (context->argumentCount() > 4)
+ password = context->argument(4).toString();
+
+
+ // Clear the fragment (if any)
+ url.setFragment(QString());
+ // Set username/password
+ if (!username.isNull()) url.setUserName(username);
+ if (!password.isNull()) url.setPassword(password);
+
+ return request->open(&dataObject, method, url);
+}
+
+static QScriptValue qmlxmlhttprequest_setRequestHeader(QScriptContext *context, QScriptEngine *engine)
+{
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(context->thisObject().data().toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ if (context->argumentCount() != 2)
+ THROW_DOM(SYNTAX_ERR, "Incorrect argument count");
+
+
+ if (request->readyState() != QmlXMLHttpRequest::Opened ||
+ request->sendFlag())
+ THROW_DOM(INVALID_STATE_ERR, "Invalid state");
+
+
+ QString name = context->argument(0).toString();
+ QString value = context->argument(1).toString();
+
+ // ### Check that name and value are well formed
+
+ QString nameUpper = name.toUpper();
+ if (nameUpper == QLatin1String("ACCEPT-CHARSET") ||
+ nameUpper == QLatin1String("ACCEPT-ENCODING") ||
+ nameUpper == QLatin1String("CONNECTION") ||
+ nameUpper == QLatin1String("CONTENT-LENGTH") ||
+ nameUpper == QLatin1String("COOKIE") ||
+ nameUpper == QLatin1String("COOKIE2") ||
+ nameUpper == QLatin1String("CONTENT-TRANSFER-ENCODING") ||
+ nameUpper == QLatin1String("DATE") ||
+ nameUpper == QLatin1String("EXPECT") ||
+ nameUpper == QLatin1String("HOST") ||
+ nameUpper == QLatin1String("KEEP-ALIVE") ||
+ nameUpper == QLatin1String("REFERER") ||
+ nameUpper == QLatin1String("TE") ||
+ nameUpper == QLatin1String("TRAILER") ||
+ nameUpper == QLatin1String("TRANSFER-ENCODING") ||
+ nameUpper == QLatin1String("UPGRADE") ||
+ nameUpper == QLatin1String("USER-AGENT") ||
+ nameUpper == QLatin1String("VIA") ||
+ nameUpper.startsWith(QLatin1String("PROXY-")) ||
+ nameUpper.startsWith(QLatin1String("SEC-")))
+ return engine->undefinedValue();
+
+ request->addHeader(nameUpper, value);
+
+ return engine->undefinedValue();
+}
+
+static QScriptValue qmlxmlhttprequest_send(QScriptContext *context, QScriptEngine *)
+{
+ QScriptValue dataObject = context->thisObject().data();
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(dataObject.toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ if (request->readyState() != QmlXMLHttpRequest::Opened)
+ THROW_DOM(INVALID_STATE_ERR, "Invalid state");
+
+ if (request->sendFlag())
+ THROW_DOM(INVALID_STATE_ERR, "Invalid state");
+
+ QByteArray data;
+ if (context->argumentCount() > 0)
+ data = context->argument(0).toString().toUtf8();
+
+ return request->send(&dataObject, data);
+}
+
+static QScriptValue qmlxmlhttprequest_abort(QScriptContext *context, QScriptEngine *)
+{
+ QScriptValue dataObject = context->thisObject().data();
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(dataObject.toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ return request->abort(&dataObject);
+}
+
+static QScriptValue qmlxmlhttprequest_getResponseHeader(QScriptContext *context, QScriptEngine *engine)
+{
+ Q_UNUSED(engine)
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(context->thisObject().data().toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ if (context->argumentCount() != 1)
+ THROW_DOM(SYNTAX_ERR, "Incorrect argument count");
+
+ if (request->readyState() != QmlXMLHttpRequest::Loading &&
+ request->readyState() != QmlXMLHttpRequest::Done &&
+ request->readyState() != QmlXMLHttpRequest::HeadersReceived)
+ THROW_DOM(INVALID_STATE_ERR, "Invalid state");
+
+ QString headerName = context->argument(0).toString();
+
+ return QScriptValue(request->header(headerName));
+}
+
+static QScriptValue qmlxmlhttprequest_getAllResponseHeaders(QScriptContext *context, QScriptEngine *engine)
+{
+ Q_UNUSED(engine)
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(context->thisObject().data().toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ if (context->argumentCount() != 0)
+ THROW_DOM(SYNTAX_ERR, "Incorrect argument count");
+
+ if (request->readyState() != QmlXMLHttpRequest::Loading &&
+ request->readyState() != QmlXMLHttpRequest::Done &&
+ request->readyState() != QmlXMLHttpRequest::HeadersReceived)
+ THROW_DOM(INVALID_STATE_ERR, "Invalid state");
+
+ return QScriptValue(request->headers());
+}
+
+// XMLHttpRequest properties
+static QScriptValue qmlxmlhttprequest_readyState(QScriptContext *context, QScriptEngine *engine)
+{
+ Q_UNUSED(engine)
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(context->thisObject().data().toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ return QScriptValue(request->readyState());
+}
+
+static QScriptValue qmlxmlhttprequest_status(QScriptContext *context, QScriptEngine *engine)
+{
+ Q_UNUSED(engine)
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(context->thisObject().data().toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ if (request->readyState() == QmlXMLHttpRequest::Unsent ||
+ request->readyState() == QmlXMLHttpRequest::Opened)
+ THROW_DOM(INVALID_STATE_ERR, "Invalid state");
+
+ if (request->errorFlag())
+ return QScriptValue(0);
+ else
+ return QScriptValue(request->replyStatus());
+}
+
+static QScriptValue qmlxmlhttprequest_statusText(QScriptContext *context, QScriptEngine *engine)
+{
+ Q_UNUSED(engine)
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(context->thisObject().data().toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ if (request->readyState() == QmlXMLHttpRequest::Unsent ||
+ request->readyState() == QmlXMLHttpRequest::Opened)
+ THROW_DOM(INVALID_STATE_ERR, "Invalid state");
+
+ if (request->errorFlag())
+ return QScriptValue(0);
+ else
+ return QScriptValue(request->replyStatusText());
+}
+
+static QScriptValue qmlxmlhttprequest_responseText(QScriptContext *context, QScriptEngine *engine)
+{
+ Q_UNUSED(engine)
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(context->thisObject().data().toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ if (request->readyState() != QmlXMLHttpRequest::Loading &&
+ request->readyState() != QmlXMLHttpRequest::Done)
+ return QScriptValue(QString());
+ else
+ return QScriptValue(request->responseBody());
+}
+
+static QScriptValue qmlxmlhttprequest_responseXML(QScriptContext *context, QScriptEngine *engine)
+{
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(context->thisObject().data().toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ if (request->readyState() != QmlXMLHttpRequest::Loading &&
+ request->readyState() != QmlXMLHttpRequest::Done)
+ return engine->nullValue();
+ else
+ return Document::load(engine, request->responseBody());
+}
+
+static QScriptValue qmlxmlhttprequest_onreadystatechange(QScriptContext *context, QScriptEngine *engine)
+{
+ Q_UNUSED(engine);
+ QScriptValue dataObject = context->thisObject().data();
+ QmlXMLHttpRequest *request = qobject_cast<QmlXMLHttpRequest *>(dataObject.toQObject());
+ if (!request)
+ THROW_REFERENCE("Not an XMLHttpRequest object");
+
+ if (context->argumentCount()) {
+ QScriptValue v = context->argument(0);
+ dataObject.setProperty(QLatin1String("callback"), v);
+ return v;
+ } else {
+ return dataObject.property(QLatin1String("callback"));
+ }
+}
+
+// Constructor
+static QScriptValue qmlxmlhttprequest_new(QScriptContext *context, QScriptEngine *engine)
+{
+ if (context->isCalledAsConstructor()) {
+ context->thisObject().setData(engine->newQObject(new QmlXMLHttpRequest(QmlScriptEngine::get(engine)->networkAccessManager()), QScriptEngine::ScriptOwnership));
+ }
+ return engine->undefinedValue();
+}
+
+void qt_add_qmlxmlhttprequest(QScriptEngine *engine)
+{
+ QScriptValue prototype = engine->newObject();
+
+ // Methods
+ prototype.setProperty(QLatin1String("open"), engine->newFunction(qmlxmlhttprequest_open, 2));
+ prototype.setProperty(QLatin1String("setRequestHeader"), engine->newFunction(qmlxmlhttprequest_setRequestHeader, 2));
+ prototype.setProperty(QLatin1String("send"), engine->newFunction(qmlxmlhttprequest_send));
+ prototype.setProperty(QLatin1String("abort"), engine->newFunction(qmlxmlhttprequest_abort));
+ prototype.setProperty(QLatin1String("getResponseHeader"), engine->newFunction(qmlxmlhttprequest_getResponseHeader, 1));
+ prototype.setProperty(QLatin1String("getAllResponseHeaders"), engine->newFunction(qmlxmlhttprequest_getAllResponseHeaders));
+
+ // Read-only properties
+ prototype.setProperty(QLatin1String("readyState"), engine->newFunction(qmlxmlhttprequest_readyState), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ prototype.setProperty(QLatin1String("status"), engine->newFunction(qmlxmlhttprequest_status), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ prototype.setProperty(QLatin1String("statusText"), engine->newFunction(qmlxmlhttprequest_statusText), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ prototype.setProperty(QLatin1String("responseText"), engine->newFunction(qmlxmlhttprequest_responseText), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ prototype.setProperty(QLatin1String("responseXML"), engine->newFunction(qmlxmlhttprequest_responseXML), QScriptValue::ReadOnly | QScriptValue::PropertyGetter);
+ prototype.setProperty(QLatin1String("onreadystatechange"), engine->newFunction(qmlxmlhttprequest_onreadystatechange), QScriptValue::PropertyGetter | QScriptValue::PropertySetter);
+
+ // State values
+ prototype.setProperty(QLatin1String("UNSENT"), 0, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ prototype.setProperty(QLatin1String("OPENED"), 1, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ prototype.setProperty(QLatin1String("HEADERS_RECEIVED"), 2, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ prototype.setProperty(QLatin1String("LOADING"), 3, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ prototype.setProperty(QLatin1String("DONE"), 4, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+
+ // Constructor
+ QScriptValue constructor = engine->newFunction(qmlxmlhttprequest_new, prototype);
+ constructor.setProperty(QLatin1String("UNSENT"), 0, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ constructor.setProperty(QLatin1String("OPENED"), 1, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ constructor.setProperty(QLatin1String("HEADERS_RECEIVED"), 2, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ constructor.setProperty(QLatin1String("LOADING"), 3, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ constructor.setProperty(QLatin1String("DONE"), 4, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ engine->globalObject().setProperty(QLatin1String("XMLHttpRequest"), constructor);
+
+ // DOM Exception
+ QScriptValue domExceptionPrototype = engine->newObject();
+ domExceptionPrototype.setProperty(QLatin1String("INDEX_SIZE_ERR"), INDEX_SIZE_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("DOMSTRING_SIZE_ERR"), DOMSTRING_SIZE_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("HIERARCHY_REQUEST_ERR"), HIERARCHY_REQUEST_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("WRONG_DOCUMENT_ERR"), WRONG_DOCUMENT_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("INVALID_CHARACTER_ERR"), INVALID_CHARACTER_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("NO_DATA_ALLOWED_ERR"), NO_DATA_ALLOWED_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("NO_MODIFICATION_ALLOWED_ERR"), NO_MODIFICATION_ALLOWED_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("NOT_FOUND_ERR"), NOT_FOUND_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("NOT_SUPPORTED_ERR"), NOT_SUPPORTED_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("INUSE_ATTRIBUTE_ERR"), INUSE_ATTRIBUTE_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("INVALID_STATE_ERR"), INVALID_STATE_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("SYNTAX_ERR"), SYNTAX_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("INVALID_MODIFICATION_ERR"), INVALID_MODIFICATION_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("NAMESPACE_ERR"), NAMESPACE_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("INVALID_ACCESS_ERR"), INVALID_ACCESS_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("VALIDATION_ERR"), VALIDATION_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+ domExceptionPrototype.setProperty(QLatin1String("TYPE_MISMATCH_ERR"), TYPE_MISMATCH_ERR, QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
+
+ engine->globalObject().setProperty(QLatin1String("DOMException"), domExceptionPrototype);
+}
+
+#include <qmlxmlhttprequest.moc>
diff --git a/src/declarative/qml/qmlxmlhttprequest_p.h b/src/declarative/qml/qmlxmlhttprequest_p.h
new file mode 100644
index 0000000..dfed5d2
--- /dev/null
+++ b/src/declarative/qml/qmlxmlhttprequest_p.h
@@ -0,0 +1,60 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLXMLHTTPREQUEST_P_H
+#define QMLXMLHTTPREQUEST_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.
+//
+
+class QScriptEngine;
+void qt_add_qmlxmlhttprequest(QScriptEngine *engine);
+
+#endif // QMLXMLHTTPREQUEST_P_H
+
diff --git a/src/declarative/qml/qpodvector_p.h b/src/declarative/qml/qpodvector_p.h
new file mode 100644
index 0000000..42d6017
--- /dev/null
+++ b/src/declarative/qml/qpodvector_p.h
@@ -0,0 +1,173 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QPODVECTOR_P_H
+#define QPODVECTOR_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 <QDebug>
+
+QT_BEGIN_NAMESPACE
+
+template<class T, int Increment=1024>
+class QPODVector
+{
+public:
+ QPODVector()
+ : m_count(0), m_capacity(0), m_data(0) {}
+ ~QPODVector() { if (m_data) ::free(m_data); }
+
+ const T &at(int idx) const {
+ return m_data[idx];
+ }
+
+ T &operator[](int idx) {
+ return m_data[idx];
+ }
+
+ void clear() {
+ m_count = 0;
+ }
+
+ void prepend(const T &v) {
+ insert(0, v);
+ }
+
+ void append(const T &v) {
+ insert(m_count, v);
+ }
+
+ void insert(int idx, const T &v) {
+ if (m_count == m_capacity) {
+ m_capacity += Increment;
+ m_data = (T *)realloc(m_data, m_capacity * sizeof(T));
+ }
+ int moveCount = m_count - idx;
+ if (moveCount)
+ ::memmove(m_data + idx + 1, m_data + idx, moveCount * sizeof(T));
+ m_count++;
+ m_data[idx] = v;
+ }
+
+ void reserve(int count) {
+ if (count >= m_capacity) {
+ m_capacity = (count + (Increment-1)) & (0xFFFFFFFF - Increment + 1);
+ m_data = (T *)realloc(m_data, m_capacity * sizeof(T));
+ }
+ }
+
+ void insertBlank(int idx, int count) {
+ int newSize = m_count + count;
+ reserve(newSize);
+ int moveCount = m_count - idx;
+ if (moveCount)
+ ::memmove(m_data + idx + count, m_data + idx,
+ moveCount * sizeof(T));
+ m_count = newSize;
+ }
+
+ void remove(int idx, int count = 1) {
+ int moveCount = m_count - (idx + count);
+ if (moveCount)
+ ::memmove(m_data + idx, m_data + idx + count,
+ moveCount * sizeof(T));
+ m_count -= count;
+ }
+
+ void removeOne(const T &v) {
+ int idx = 0;
+ while (idx < m_count) {
+ if (m_data[idx] == v) {
+ remove(idx);
+ return;
+ }
+ ++idx;
+ }
+ }
+
+ int find(const T &v) {
+ for (int idx = 0; idx < m_count; ++idx)
+ if (m_data[idx] == v)
+ return idx;
+ return -1;
+ }
+
+ bool contains(const T &v) {
+ return find(v) != -1;
+ }
+
+ int count() const {
+ return m_count;
+ }
+
+ void copyAndClear(QPODVector<T,Increment> &other) {
+ if (other.m_data) ::free(other.m_data);
+ other.m_count = m_count;
+ other.m_capacity = m_capacity;
+ other.m_data = m_data;
+ m_count = 0;
+ m_capacity = 0;
+ m_data = 0;
+ }
+
+ QPODVector<T,Increment> &operator<<(const T &v) { append(v); return *this; }
+private:
+ QPODVector(const QPODVector &);
+ QPODVector &operator=(const QPODVector &);
+ int m_count;
+ int m_capacity;
+ T *m_data;
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/declarative/qml/rewriter/rewriter.cpp b/src/declarative/qml/rewriter/rewriter.cpp
new file mode 100644
index 0000000..237d33f
--- /dev/null
+++ b/src/declarative/qml/rewriter/rewriter.cpp
@@ -0,0 +1,102 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "rewriter_p.h"
+
+#include <qmljsast_p.h>
+
+QT_QML_BEGIN_NAMESPACE
+
+using namespace QmlJS;
+
+void Rewriter::replace(const AST::SourceLocation &loc, const QString &text)
+{ replace(loc.offset, loc.length, text); }
+
+void Rewriter::remove(const AST::SourceLocation &loc)
+{ return replace(loc.offset, loc.length, QString()); }
+
+void Rewriter::remove(const AST::SourceLocation &firstLoc, const AST::SourceLocation &lastLoc)
+{ return replace(firstLoc.offset, lastLoc.offset + lastLoc.length - firstLoc.offset, QString()); }
+
+void Rewriter::insertTextBefore(const AST::SourceLocation &loc, const QString &text)
+{ replace(loc.offset, 0, text); }
+
+void Rewriter::insertTextAfter(const AST::SourceLocation &loc, const QString &text)
+{ replace(loc.offset + loc.length, 0, text); }
+
+void Rewriter::replace(int offset, int length, const QString &text)
+{ textWriter.replace(offset, length, text); }
+
+void Rewriter::insertText(int offset, const QString &text)
+{ replace(offset, 0, text); }
+
+void Rewriter::removeText(int offset, int length)
+{ replace(offset, length, QString()); }
+
+QString Rewriter::textAt(const AST::SourceLocation &loc) const
+{ return _code.mid(loc.offset, loc.length); }
+
+QString Rewriter::textAt(const AST::SourceLocation &firstLoc, const AST::SourceLocation &lastLoc) const
+{ return _code.mid(firstLoc.offset, lastLoc.offset + lastLoc.length - firstLoc.offset); }
+
+void Rewriter::accept(QmlJS::AST::Node *node)
+{ QmlJS::AST::Node::acceptChild(node, this); }
+
+void Rewriter::moveTextBefore(const AST::SourceLocation &firstLoc,
+ const AST::SourceLocation &lastLoc,
+ const AST::SourceLocation &loc)
+{
+ move(firstLoc.offset, lastLoc.offset + lastLoc.length - firstLoc.offset, loc.offset);
+}
+
+void Rewriter::moveTextAfter(const AST::SourceLocation &firstLoc,
+ const AST::SourceLocation &lastLoc,
+ const AST::SourceLocation &loc)
+{
+ move(firstLoc.offset, lastLoc.offset + lastLoc.length - firstLoc.offset, loc.offset + loc.length);
+}
+
+void Rewriter::move(int pos, int length, int to)
+{
+ textWriter.move(pos, length, to);
+}
+
+QT_QML_END_NAMESPACE
diff --git a/src/declarative/qml/rewriter/rewriter.pri b/src/declarative/qml/rewriter/rewriter.pri
new file mode 100644
index 0000000..2c29061
--- /dev/null
+++ b/src/declarative/qml/rewriter/rewriter.pri
@@ -0,0 +1,9 @@
+INCLUDEPATH += $$PWD
+
+HEADERS += $$PWD/textwriter_p.h
+SOURCES += $$PWD/textwriter.cpp
+
+!no_ast_rewriter {
+ HEADERS += $$PWD/rewriter_p.h
+ SOURCES += $$PWD/rewriter.cpp
+}
diff --git a/src/declarative/qml/rewriter/rewriter_p.h b/src/declarative/qml/rewriter/rewriter_p.h
new file mode 100644
index 0000000..57e7ea2
--- /dev/null
+++ b/src/declarative/qml/rewriter/rewriter_p.h
@@ -0,0 +1,153 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef REWRITER_H
+#define REWRITER_H
+
+#include "textwriter_p.h"
+
+#include <qmljsastvisitor_p.h>
+
+#include <QtCore/QList>
+#include <QtCore/QString>
+
+QT_BEGIN_HEADER
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS {
+
+////////////////////////////////////////////////////////////////////////////////
+// Replacement
+////////////////////////////////////////////////////////////////////////////////
+class Replacement
+{
+ int _offset;
+ int _length;
+ QString _text;
+
+public:
+ Replacement(int offset = 0, int length = 0, const QString &text = QString())
+ : _offset(offset), _length(length), _text(text)
+ { }
+
+ bool isNull() const { return _offset == _length; }
+ operator bool() const { return ! isNull(); }
+
+ int offset() const { return _offset; }
+ int length() const { return _length; }
+ QString text() const { return _text; }
+};
+
+
+
+////////////////////////////////////////////////////////////////////////////////
+// Rewriter
+////////////////////////////////////////////////////////////////////////////////
+class Rewriter: public AST::Visitor
+{
+protected:
+ TextWriter textWriter;
+public:
+ //
+ // Token based API
+ //
+
+ /// Returns the text of the token at the given \a location.
+ QString textAt(const AST::SourceLocation &location) const;
+
+ QString textAt(const AST::SourceLocation &firstLoc,
+ const AST::SourceLocation &lastLoc) const;
+
+ /// Replace the token at \a loc with the given \a text.
+ void replace(const AST::SourceLocation &loc, const QString &text);
+
+ /// Remove the token at the given \a location.
+ void remove(const AST::SourceLocation &location);
+
+ /// Remove all tokens in the range [\a firstLoc, \a lastLoc].
+ void remove(const AST::SourceLocation &firstLoc, const AST::SourceLocation &lastLoc);
+
+ /// Insert \a text before the token at the given \a location.
+ void insertTextBefore(const AST::SourceLocation &location, const QString &text);
+
+ /// Insert \a text after the token at the given \a location.
+ void insertTextAfter(const AST::SourceLocation &loc, const QString &text);
+
+ void moveTextBefore(const AST::SourceLocation &firstLoc,
+ const AST::SourceLocation &lastLoc,
+ const AST::SourceLocation &loc);
+
+ void moveTextAfter(const AST::SourceLocation &firstLoc,
+ const AST::SourceLocation &lastLoc,
+ const AST::SourceLocation &loc);
+
+ //
+ // low-level offset based API
+ //
+ virtual void replace(int offset, int length, const QString &text);
+ virtual void move(int pos, int length, int to);
+ void insertText(int offset, const QString &text);
+ void removeText(int offset, int length);
+
+ /// Visit the given \a node.
+ void accept(AST::Node *node);
+
+ /// Returns the original unchanged source code.
+ QString code() const { return _code; }
+
+ /// Returns the list of replacements.
+ QList<Replacement> replacementList() const { return _replacementList; }
+
+protected:
+ /// \internal
+ void setCode(const QString &code) { _code = code; }
+
+private:
+ QString _code;
+ QList<Replacement> _replacementList;
+};
+
+} // end of namespace QmlJS
+
+QT_QML_END_NAMESPACE
+QT_END_HEADER
+
+#endif // REWRITER_H
diff --git a/src/declarative/qml/rewriter/textwriter.cpp b/src/declarative/qml/rewriter/textwriter.cpp
new file mode 100644
index 0000000..8f89f12
--- /dev/null
+++ b/src/declarative/qml/rewriter/textwriter.cpp
@@ -0,0 +1,217 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "textwriter_p.h"
+
+QT_QML_BEGIN_NAMESPACE
+
+using namespace QmlJS;
+
+TextWriter::TextWriter()
+ :string(0), cursor(0)
+{
+}
+
+static bool overlaps(int posA, int lengthA, int posB, int lengthB) {
+ return (posA < posB + lengthB && posA + lengthA > posB + lengthB)
+ || (posA < posB && posA + lengthA > posB);
+}
+
+bool TextWriter::hasOverlap(int pos, int length)
+{
+ {
+ QListIterator<Replace> i(replaceList);
+ while (i.hasNext()) {
+ const Replace &cmd = i.next();
+ if (overlaps(pos, length, cmd.pos, cmd.length))
+ return true;
+ }
+ }
+ {
+ QListIterator<Move> i(moveList);
+ while (i.hasNext()) {
+ const Move &cmd = i.next();
+ if (overlaps(pos, length, cmd.pos, cmd.length))
+ return true;
+ }
+ return false;
+ }
+}
+
+bool TextWriter::hasMoveInto(int pos, int length)
+{
+ QListIterator<Move> i(moveList);
+ while (i.hasNext()) {
+ const Move &cmd = i.next();
+ if (cmd.to >= pos && cmd.to < pos + length)
+ return true;
+ }
+ return false;
+}
+
+void TextWriter::replace(int pos, int length, const QString &replacement)
+{
+ Q_ASSERT(!hasOverlap(pos, length));
+ Q_ASSERT(!hasMoveInto(pos, length));
+
+ Replace cmd;
+ cmd.pos = pos;
+ cmd.length = length;
+ cmd.replacement = replacement;
+ replaceList += cmd;
+}
+
+void TextWriter::move(int pos, int length, int to)
+{
+ Q_ASSERT(!hasOverlap(pos, length));
+
+ Move cmd;
+ cmd.pos = pos;
+ cmd.length = length;
+ cmd.to = to;
+ moveList += cmd;
+}
+
+void TextWriter::doReplace(const Replace &replace)
+{
+ int diff = replace.replacement.size() - replace.length;
+ {
+ QMutableListIterator<Replace> i(replaceList);
+ while (i.hasNext()) {
+ Replace &c = i.next();
+ if (replace.pos < c.pos)
+ c.pos += diff;
+ else if (replace.pos + replace.length < c.pos + c.length)
+ c.length += diff;
+ }
+ }
+ {
+ QMutableListIterator<Move> i(moveList);
+ while (i.hasNext()) {
+ Move &c = i.next();
+ if (replace.pos < c.pos)
+ c.pos += diff;
+ else if (replace.pos + replace.length < c.pos + c.length)
+ c.length += diff;
+
+ if (replace.pos < c.to)
+ c.to += diff;
+ }
+ }
+
+ if (string) {
+ string->replace(replace.pos, replace.length, replace.replacement);
+ } else if (cursor) {
+ cursor->setPosition(replace.pos);
+ cursor->setPosition(replace.pos + replace.length, QTextCursor::KeepAnchor);
+ cursor->insertText(replace.replacement);
+ }
+}
+
+void TextWriter::doMove(const Move &move)
+{
+ QString text;
+ if (string) {
+ text = string->mid(move.pos, move.length);
+ } else if (cursor) {
+ cursor->setPosition(move.pos);
+ cursor->setPosition(move.pos + move.length, QTextCursor::KeepAnchor);
+ text = cursor->selectedText();
+ }
+
+ Replace cut;
+ cut.pos = move.pos;
+ cut.length = move.length;
+ Replace paste;
+ paste.pos = move.to;
+ paste.length = 0;
+ paste.replacement = text;
+
+ replaceList.append(cut);
+ replaceList.append(paste);
+
+ Replace cmd;
+ while (!replaceList.isEmpty()) {
+ cmd = replaceList.first();
+ replaceList.removeFirst();
+ doReplace(cmd);
+ }
+}
+
+void TextWriter::write(QString *s)
+{
+ string = s;
+ write_helper();
+ string = 0;
+}
+
+void TextWriter::write(QTextCursor *textCursor)
+{
+ cursor = textCursor;
+ write_helper();
+ cursor = 0;
+}
+
+void TextWriter::write_helper()
+{
+ if (cursor)
+ cursor->beginEditBlock();
+ {
+ Replace cmd;
+ while (!replaceList.isEmpty()) {
+ cmd = replaceList.first();
+ replaceList.removeFirst();
+ doReplace(cmd);
+ }
+ }
+ {
+ Move cmd;
+ while (!moveList.isEmpty()) {
+ cmd = moveList.first();
+ moveList.removeFirst();
+ doMove(cmd);
+ }
+ }
+ if (cursor)
+ cursor->endEditBlock();
+}
+
+QT_QML_END_NAMESPACE
diff --git a/src/declarative/qml/rewriter/textwriter_p.h b/src/declarative/qml/rewriter/textwriter_p.h
new file mode 100644
index 0000000..a19fa5e
--- /dev/null
+++ b/src/declarative/qml/rewriter/textwriter_p.h
@@ -0,0 +1,101 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef TEXTWRITER_H
+#define TEXTWRITER_H
+
+#include <qmljsglobal_p.h>
+
+#include <QtCore/QString>
+#include <QtCore/QList>
+#include <QtGui/QTextCursor>
+
+QT_BEGIN_HEADER
+QT_QML_BEGIN_NAMESPACE
+
+namespace QmlJS {
+
+class TextWriter
+{
+ QString *string;
+ QTextCursor *cursor;
+
+ struct Replace {
+ int pos;
+ int length;
+ QString replacement;
+ };
+
+ QList<Replace> replaceList;
+
+ struct Move {
+ int pos;
+ int length;
+ int to;
+ };
+
+ QList<Move> moveList;
+
+ bool hasOverlap(int pos, int length);
+ bool hasMoveInto(int pos, int length);
+
+ void doReplace(const Replace &replace);
+ void doMove(const Move &move);
+
+ void write_helper();
+
+public:
+ TextWriter();
+
+ void replace(int pos, int length, const QString &replacement);
+ void move(int pos, int length, int to);
+
+ void write(QString *s);
+ void write(QTextCursor *textCursor);
+
+};
+
+} // end of namespace QmlJS
+
+QT_QML_END_NAMESPACE
+QT_END_HEADER
+
+#endif // TEXTWRITER_H
diff --git a/src/declarative/util/qfxperf.cpp b/src/declarative/util/qfxperf.cpp
new file mode 100644
index 0000000..f62f810
--- /dev/null
+++ b/src/declarative/util/qfxperf.cpp
@@ -0,0 +1,67 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qfxperf_p_p.h"
+
+QT_BEGIN_NAMESPACE
+
+Q_DEFINE_PERFORMANCE_LOG(QmlPerf, "QmlGraphics") {
+ Q_DEFINE_PERFORMANCE_METRIC(QmlParsing, "Compilation: QML Parsing")
+ Q_DEFINE_PERFORMANCE_METRIC(Compilation, " QML Compilation")
+ Q_DEFINE_PERFORMANCE_METRIC(VMEExecution, "Execution: QML VME Execution")
+ Q_DEFINE_PERFORMANCE_METRIC(BindInit, "BindValue Initialization")
+ Q_DEFINE_PERFORMANCE_METRIC(BindValue, "BindValue execution")
+ Q_DEFINE_PERFORMANCE_METRIC(BindValueSSE, "BindValue execution SSE")
+ Q_DEFINE_PERFORMANCE_METRIC(BindValueQt, "BindValue execution QtScript")
+ Q_DEFINE_PERFORMANCE_METRIC(BindableValueUpdate, "QmlBinding::update")
+ Q_DEFINE_PERFORMANCE_METRIC(PixmapLoad, "Pixmap loading")
+ Q_DEFINE_PERFORMANCE_METRIC(FontDatabase, "Font database creation")
+ Q_DEFINE_PERFORMANCE_METRIC(QmlGraphicsPathViewPathCache, "FX Items: QmlGraphicsPathView: Path cache")
+ Q_DEFINE_PERFORMANCE_METRIC(CreateParticle, " QmlGraphicsParticles: Particle creation")
+ Q_DEFINE_PERFORMANCE_METRIC(ItemComponentComplete, " QmlGraphicsItem::componentComplete")
+ Q_DEFINE_PERFORMANCE_METRIC(ImageComponentComplete, " QmlGraphicsImage::componentComplete")
+ Q_DEFINE_PERFORMANCE_METRIC(BaseLayoutComponentComplete, " QmlGraphicsBasePositioner::componentComplete")
+ Q_DEFINE_PERFORMANCE_METRIC(TextComponentComplete, " QmlGraphicsText::componentComplete")
+ Q_DEFINE_PERFORMANCE_METRIC(QmlGraphicsText_setText, " QmlGraphicsText::setText")
+ Q_DEFINE_PERFORMANCE_METRIC(AddScript, "QmlScript::addScriptToEngine")
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qfxperf_p_p.h b/src/declarative/util/qfxperf_p_p.h
new file mode 100644
index 0000000..e3f820c
--- /dev/null
+++ b/src/declarative/util/qfxperf_p_p.h
@@ -0,0 +1,90 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+#ifndef QFXPERF_H
+#define QFXPERF_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 "qperformancelog_p_p.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+Q_DECLARE_PERFORMANCE_LOG(QmlPerf) {
+ Q_DECLARE_PERFORMANCE_METRIC(QmlParsing)
+
+ Q_DECLARE_PERFORMANCE_METRIC(Compilation)
+ Q_DECLARE_PERFORMANCE_METRIC(VMEExecution)
+
+ Q_DECLARE_PERFORMANCE_METRIC(BindInit)
+ Q_DECLARE_PERFORMANCE_METRIC(BindValue)
+ Q_DECLARE_PERFORMANCE_METRIC(BindValueSSE)
+ Q_DECLARE_PERFORMANCE_METRIC(BindValueQt)
+ Q_DECLARE_PERFORMANCE_METRIC(BindableValueUpdate)
+ Q_DECLARE_PERFORMANCE_METRIC(PixmapLoad)
+ Q_DECLARE_PERFORMANCE_METRIC(FontDatabase)
+ Q_DECLARE_PERFORMANCE_METRIC(QmlGraphicsPathViewPathCache)
+ Q_DECLARE_PERFORMANCE_METRIC(CreateParticle)
+ Q_DECLARE_PERFORMANCE_METRIC(ItemComponentComplete)
+ Q_DECLARE_PERFORMANCE_METRIC(ImageComponentComplete)
+ Q_DECLARE_PERFORMANCE_METRIC(BaseLayoutComponentComplete)
+ Q_DECLARE_PERFORMANCE_METRIC(TextComponentComplete)
+ Q_DECLARE_PERFORMANCE_METRIC(QmlGraphicsText_setText)
+ Q_DECLARE_PERFORMANCE_METRIC(AddScript)
+}
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QFXPERF_H
diff --git a/src/declarative/util/qmlanimation.cpp b/src/declarative/util/qmlanimation.cpp
new file mode 100644
index 0000000..abffefe
--- /dev/null
+++ b/src/declarative/util/qmlanimation.cpp
@@ -0,0 +1,2337 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlanimation_p.h"
+#include "qmlanimation_p_p.h"
+
+#include "qmlbehavior_p.h"
+#include "qmlstateoperations_p.h"
+
+#include <qmlpropertyvaluesource.h>
+#include <qml.h>
+#include <qmlinfo.h>
+#include <qmlexpression.h>
+#include <qmlstringconverters_p.h>
+#include <qmlglobal_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 <private/qvariantanimation_p.h>
+
+QT_BEGIN_NAMESPACE
+
+static QEasingCurve stringToCurve(const QString &curve, QObject *obj)
+{
+ QEasingCurve easingCurve;
+
+ QString normalizedCurve = curve;
+ bool hasParams = curve.contains(QLatin1Char('('));
+ QStringList props;
+
+ if (hasParams) {
+ QString easeName = curve.trimmed();
+ if (!easeName.endsWith(QLatin1Char(')'))) {
+ qmlInfo(obj) << obj->tr("Unmatched parenthesis in easing function \"%1\"").arg(curve);
+ return easingCurve;
+ }
+
+ int idx = easeName.indexOf(QLatin1Char('('));
+ QString prop_str =
+ easeName.mid(idx + 1, easeName.length() - 1 - idx - 1);
+ normalizedCurve = easeName.left(idx);
+ if (!normalizedCurve.startsWith(QLatin1String("ease"))) {
+ qmlInfo(obj) << obj->tr("Easing function \"%1\" must start with \"ease\"").arg(curve);
+ return easingCurve;
+ }
+
+ props = prop_str.split(QLatin1Char(','));
+ }
+
+ if (normalizedCurve.startsWith(QLatin1String("ease")))
+ normalizedCurve = normalizedCurve.mid(4);
+
+ static int index = QEasingCurve::staticMetaObject.indexOfEnumerator("Type");
+ static QMetaEnum me = QEasingCurve::staticMetaObject.enumerator(index);
+
+ int value = me.keyToValue(normalizedCurve.toUtf8().constData());
+ if (value < 0) {
+ qmlInfo(obj) << obj->tr("Unknown easing curve \"%1\"").arg(curve);
+ return easingCurve;
+ }
+ easingCurve.setType((QEasingCurve::Type)value);
+
+ if (hasParams) {
+ foreach(const QString &str, props) {
+ int sep = str.indexOf(QLatin1Char(':'));
+
+ if (sep == -1) {
+ qmlInfo(obj) << obj->tr("Improperly specified parameter in easing function \"%1\"").arg(curve);
+ continue;
+ }
+
+ QString propName = str.left(sep).trimmed();
+ bool isOk;
+ qreal propValue = str.mid(sep + 1).trimmed().toDouble(&isOk);
+
+ if (propName.isEmpty() || !isOk) {
+ qmlInfo(obj) << obj->tr("Improperly specified parameter in easing function \"%1\"").arg(curve);
+ continue;
+ }
+
+ if (propName == QLatin1String("amplitude")) {
+ easingCurve.setAmplitude(propValue);
+ } else if (propName == QLatin1String("period")) {
+ easingCurve.setPeriod(propValue);
+ } else if (propName == QLatin1String("overshoot")) {
+ easingCurve.setOvershoot(propValue);
+ } else {
+ qmlInfo(obj) << obj->tr("Unknown easing parameter \"%1\"").arg(propName);
+ continue;
+ }
+ }
+ }
+ return easingCurve;
+}
+
+QML_DEFINE_NOCREATE_TYPE(QmlAbstractAnimation)
+
+/*!
+ \qmlclass Animation QmlAbstractAnimation
+ \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.
+*/
+
+/*!
+ \class QmlAbstractAnimation
+ \internal
+*/
+
+QmlAbstractAnimation::QmlAbstractAnimation(QObject *parent)
+: QObject(*(new QmlAbstractAnimationPrivate), parent)
+{
+}
+
+QmlAbstractAnimation::~QmlAbstractAnimation()
+{
+}
+
+QmlAbstractAnimation::QmlAbstractAnimation(QmlAbstractAnimationPrivate &dd, QObject *parent)
+: QObject(dd, parent)
+{
+}
+
+/*!
+ \qmlproperty bool 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 MouseRegion is pressed.
+
+ \code
+ Rectangle {
+ width: 100; height: 100
+ x: NumberAnimation {
+ running: myMouse.pressed
+ from: 0; to: 100
+ }
+ MouseRegion { 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, they are set to running by default.
+*/
+bool QmlAbstractAnimation::isRunning() const
+{
+ Q_D(const QmlAbstractAnimation);
+ return d->running;
+}
+
+void QmlAbstractAnimationPrivate::commence()
+{
+ Q_Q(QmlAbstractAnimation);
+
+ q->prepare(userProperty.value);
+ q->qtAnimation()->start();
+ if (q->qtAnimation()->state() != QAbstractAnimation::Running) {
+ running = false;
+ emit q->completed();
+ }
+}
+
+QmlMetaProperty QmlAbstractAnimationPrivate::createProperty(QObject *obj, const QString &str, QObject *infoObj)
+{
+ QmlMetaProperty prop = QmlMetaProperty::createProperty(obj, str, qmlContext(infoObj));
+ if (!prop.isValid()) {
+ qmlInfo(infoObj) << QmlAbstractAnimation::tr("Cannot animate non-existant property \"%1\"").arg(str);
+ return QmlMetaProperty();
+ } else if (!prop.isWritable()) {
+ qmlInfo(infoObj) << QmlAbstractAnimation::tr("Cannot animate read-only property \"%1\"").arg(str);
+ return QmlMetaProperty();
+ }
+ return prop;
+}
+
+void QmlAbstractAnimation::setRunning(bool r)
+{
+ Q_D(QmlAbstractAnimation);
+
+ if (r == false)
+ d->avoidPropertyValueSourceStart = true;
+
+ if (d->running == r)
+ return;
+
+ if (d->group) {
+ qWarning("QmlAbstractAnimation: setRunning() cannot be used on non-root animation nodes");
+ return;
+ }
+
+ d->running = r;
+ if (d->running) {
+ if (d->alwaysRunToEnd && d->repeat
+ && qtAnimation()->state() == QAbstractAnimation::Running) {
+ qtAnimation()->setLoopCount(-1);
+ }
+
+ if (!d->connectedTimeLine) {
+ QObject::connect(qtAnimation(), SIGNAL(finished()),
+ this, SLOT(timelineComplete()));
+ d->connectedTimeLine = true;
+ }
+ if (d->componentComplete)
+ d->commence();
+ else
+ d->startOnCompletion = true;
+ emit started();
+ } else {
+ if (d->alwaysRunToEnd) {
+ if (d->repeat)
+ qtAnimation()->setLoopCount(qtAnimation()->currentLoop()+1);
+ } else
+ qtAnimation()->stop();
+
+ emit completed();
+ }
+
+ emit runningChanged(d->running);
+}
+
+/*!
+ \qmlproperty bool 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 QmlAbstractAnimation::isPaused() const
+{
+ Q_D(const QmlAbstractAnimation);
+ return d->paused;
+}
+
+void QmlAbstractAnimation::setPaused(bool p)
+{
+ Q_D(QmlAbstractAnimation);
+ if (d->paused == p)
+ return;
+
+ if (d->group) {
+ qWarning("QmlAbstractAnimation: setPaused() cannot be used on non-root animation nodes");
+ return;
+ }
+
+ d->paused = p;
+ if (d->paused)
+ qtAnimation()->pause();
+ else
+ qtAnimation()->resume();
+
+ emit pausedChanged(d->running);
+}
+
+void QmlAbstractAnimation::classBegin()
+{
+ Q_D(QmlAbstractAnimation);
+ d->componentComplete = false;
+}
+
+void QmlAbstractAnimation::componentComplete()
+{
+ Q_D(QmlAbstractAnimation);
+ if (d->startOnCompletion)
+ d->commence();
+ d->componentComplete = true;
+}
+
+/*!
+ \qmlproperty bool 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.
+*/
+bool QmlAbstractAnimation::alwaysRunToEnd() const
+{
+ Q_D(const QmlAbstractAnimation);
+ return d->alwaysRunToEnd;
+}
+
+void QmlAbstractAnimation::setAlwaysRunToEnd(bool f)
+{
+ Q_D(QmlAbstractAnimation);
+ if (d->alwaysRunToEnd == f)
+ return;
+
+ d->alwaysRunToEnd = f;
+ emit alwaysRunToEndChanged(f);
+}
+
+/*!
+ \qmlproperty bool Animation::repeat
+ This property holds whether the animation should repeat.
+
+ If set, 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 indefinately.
+
+ \code
+ Rectangle {
+ rotation: NumberAnimation { running: true; repeat: true; from: 0 to: 360 }
+ }
+ \endcode
+*/
+bool QmlAbstractAnimation::repeat() const
+{
+ Q_D(const QmlAbstractAnimation);
+ return d->repeat;
+}
+
+void QmlAbstractAnimation::setRepeat(bool r)
+{
+ Q_D(QmlAbstractAnimation);
+ if (r == d->repeat)
+ return;
+
+ d->repeat = r;
+ int lc = r ? -1 : 1;
+ qtAnimation()->setLoopCount(lc);
+ emit repeatChanged(r);
+}
+
+int QmlAbstractAnimation::currentTime()
+{
+ return qtAnimation()->currentLoopTime();
+}
+
+void QmlAbstractAnimation::setCurrentTime(int time)
+{
+ qtAnimation()->setCurrentTime(time);
+}
+
+QmlAnimationGroup *QmlAbstractAnimation::group() const
+{
+ Q_D(const QmlAbstractAnimation);
+ return d->group;
+}
+
+void QmlAbstractAnimation::setGroup(QmlAnimationGroup *g)
+{
+ Q_D(QmlAbstractAnimation);
+ if (d->group == g)
+ return;
+ if (d->group)
+ static_cast<QmlAnimationGroupPrivate *>(d->group->d_func())->animations.removeAll(this);
+
+ d->group = g;
+
+ if (d->group && !static_cast<QmlAnimationGroupPrivate *>(d->group->d_func())->animations.contains(this))
+ static_cast<QmlAnimationGroupPrivate *>(d->group->d_func())->animations.append(this);
+
+ if (d->group)
+ ((QAnimationGroup*)d->group->qtAnimation())->addAnimation(qtAnimation());
+
+ //if (g) //if removed from a group, then the group should no longer be the parent
+ setParent(g);
+}
+
+/*!
+ \qmlmethod 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 QmlAbstractAnimation::start()
+{
+ setRunning(true);
+}
+
+/*!
+ \qmlmethod 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 QmlAbstractAnimation::pause()
+{
+ setPaused(true);
+}
+
+/*!
+ \qmlmethod 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 QmlAbstractAnimation::resume()
+{
+ setPaused(false);
+}
+
+/*!
+ \qmlmethod 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 {
+ x: NumberAnimation { 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 QmlAbstractAnimation::stop()
+{
+ setRunning(false);
+}
+
+/*!
+ \qmlmethod Animation::restart()
+ \brief Restarts the animation.
+
+ This is a convenience method, and is equivalent to calling \c stop() and
+ then \c start().
+*/
+void QmlAbstractAnimation::restart()
+{
+ stop();
+ start();
+}
+
+/*!
+ \qmlmethod 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 {
+ x: NumberAnimation { 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 QmlAbstractAnimation::complete()
+{
+ if (isRunning()) {
+ qtAnimation()->setCurrentTime(qtAnimation()->duration());
+ }
+}
+
+void QmlAbstractAnimation::setTarget(const QmlMetaProperty &p)
+{
+ Q_D(QmlAbstractAnimation);
+ if (d->userProperty.isNull)
+ d->userProperty = p;
+
+ if (!d->avoidPropertyValueSourceStart)
+ setRunning(true);
+}
+
+//prepare is called before an animation begins
+//(when an animation is used as a simple animation, and not as part of a transition)
+void QmlAbstractAnimation::prepare(QmlMetaProperty &)
+{
+}
+
+void QmlAbstractAnimation::transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction)
+{
+ Q_UNUSED(actions);
+ Q_UNUSED(modified);
+ Q_UNUSED(direction);
+}
+
+void QmlAbstractAnimation::timelineComplete()
+{
+ Q_D(QmlAbstractAnimation);
+ setRunning(false);
+ if (d->alwaysRunToEnd && d->repeat) {
+ qtAnimation()->setLoopCount(-1);
+ }
+}
+
+/*!
+ \qmlclass PauseAnimation QmlPauseAnimation
+ \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
+*/
+/*!
+ \internal
+ \class QmlPauseAnimation
+*/
+
+QML_DEFINE_TYPE(Qt,4,6,PauseAnimation,QmlPauseAnimation)
+QmlPauseAnimation::QmlPauseAnimation(QObject *parent)
+: QmlAbstractAnimation(*(new QmlPauseAnimationPrivate), parent)
+{
+ Q_D(QmlPauseAnimation);
+ d->init();
+}
+
+QmlPauseAnimation::~QmlPauseAnimation()
+{
+}
+
+void QmlPauseAnimationPrivate::init()
+{
+ Q_Q(QmlPauseAnimation);
+ pa = new QPauseAnimation;
+ QmlGraphics_setParent_noEvent(pa, q);
+}
+
+/*!
+ \qmlproperty int PauseAnimation::duration
+ This property holds the duration of the pause in milliseconds
+
+ The default value is 250.
+*/
+int QmlPauseAnimation::duration() const
+{
+ Q_D(const QmlPauseAnimation);
+ return d->pa->duration();
+}
+
+void QmlPauseAnimation::setDuration(int duration)
+{
+ if (duration < 0) {
+ qmlInfo(this) << tr("Cannot set a duration of < 0");
+ return;
+ }
+
+ Q_D(QmlPauseAnimation);
+ if (d->pa->duration() == duration)
+ return;
+ d->pa->setDuration(duration);
+ emit durationChanged(duration);
+}
+
+QAbstractAnimation *QmlPauseAnimation::qtAnimation()
+{
+ Q_D(QmlPauseAnimation);
+ return d->pa;
+}
+
+/*!
+ \qmlclass ColorAnimation QmlColorAnimation
+ \inherits PropertyAnimation
+ \brief The ColorAnimation element allows you to animate color changes.
+
+ \code
+ ColorAnimation { from: "white"; to: "#c0c0c0"; duration: 100 }
+ \endcode
+
+ When used in a transition, ColorAnimation will by default animate
+ all properties of type color that are changing. If a property or properties
+ are explicitly set for the animation, then those will be used instead.
+*/
+/*!
+ \internal
+ \class QmlColorAnimation
+*/
+
+QmlColorAnimation::QmlColorAnimation(QObject *parent)
+: QmlPropertyAnimation(parent)
+{
+ Q_D(QmlPropertyAnimation);
+ d->interpolatorType = QMetaType::QColor;
+ d->interpolator = QVariantAnimationPrivate::getInterpolator(d->interpolatorType);
+ d->defaultToInterpolatorType = true;
+}
+
+QmlColorAnimation::~QmlColorAnimation()
+{
+}
+
+/*!
+ \qmlproperty color ColorAnimation::from
+ This property holds the starting color.
+*/
+QColor QmlColorAnimation::from() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->from.value<QColor>();
+}
+
+void QmlColorAnimation::setFrom(const QColor &f)
+{
+ QmlPropertyAnimation::setFrom(f);
+}
+
+/*!
+ \qmlproperty color ColorAnimation::from
+ This property holds the ending color.
+*/
+QColor QmlColorAnimation::to() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->to.value<QColor>();
+}
+
+void QmlColorAnimation::setTo(const QColor &t)
+{
+ QmlPropertyAnimation::setTo(t);
+}
+
+QML_DEFINE_TYPE(Qt,4,6,ColorAnimation,QmlColorAnimation)
+
+/*!
+ \qmlclass ScriptAction QmlScriptAction
+ \inherits Animation
+ \brief The ScriptAction element allows scripts to be run during an animation.
+
+*/
+/*!
+ \internal
+ \class QmlScriptAction
+*/
+QmlScriptAction::QmlScriptAction(QObject *parent)
+ :QmlAbstractAnimation(*(new QmlScriptActionPrivate), parent)
+{
+ Q_D(QmlScriptAction);
+ d->init();
+}
+
+QmlScriptAction::~QmlScriptAction()
+{
+}
+
+void QmlScriptActionPrivate::init()
+{
+ Q_Q(QmlScriptAction);
+ rsa = new QActionAnimation(&proxy);
+ QmlGraphics_setParent_noEvent(rsa, q);
+}
+
+/*!
+ \qmlproperty script ScriptAction::script
+ This property holds the script to run.
+*/
+QmlScriptString QmlScriptAction::script() const
+{
+ Q_D(const QmlScriptAction);
+ return d->script;
+}
+
+void QmlScriptAction::setScript(const QmlScriptString &script)
+{
+ Q_D(QmlScriptAction);
+ d->script = script;
+}
+
+/*!
+ \qmlproperty QString ScriptAction::stateChangeScriptName
+ 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 stateChangeScriptName are set, stateChangeScriptName will be used.
+*/
+QString QmlScriptAction::stateChangeScriptName() const
+{
+ Q_D(const QmlScriptAction);
+ return d->name;
+}
+
+void QmlScriptAction::setStateChangeScriptName(const QString &name)
+{
+ Q_D(QmlScriptAction);
+ d->name = name;
+}
+
+void QmlScriptActionPrivate::execute()
+{
+ QmlScriptString scriptStr = hasRunScriptScript ? runScriptScript : script;
+
+ const QString &str = scriptStr.script();
+ if (!str.isEmpty()) {
+ QmlExpression expr(scriptStr.context(), str, scriptStr.scopeObject());
+ expr.setTrackChange(false);
+ expr.value();
+ }
+}
+
+void QmlScriptAction::transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction)
+{
+ Q_D(QmlScriptAction);
+ Q_UNUSED(modified);
+ Q_UNUSED(direction);
+
+ d->hasRunScriptScript = false;
+ for (int ii = 0; ii < actions.count(); ++ii) {
+ QmlAction &action = actions[ii];
+
+ if (action.event && action.event->typeName() == QLatin1String("StateChangeScript")
+ && static_cast<QmlStateChangeScript*>(action.event)->name() == d->name) {
+ //### how should we handle reverse direction?
+ d->runScriptScript = static_cast<QmlStateChangeScript*>(action.event)->script();
+ d->hasRunScriptScript = true;
+ action.actionDone = true;
+ break; //assumes names are unique
+ }
+ }
+}
+
+QAbstractAnimation *QmlScriptAction::qtAnimation()
+{
+ Q_D(QmlScriptAction);
+ return d->rsa;
+}
+
+QML_DEFINE_TYPE(Qt,4,6,ScriptAction,QmlScriptAction)
+
+/*!
+ \qmlclass PropertyAction QmlPropertyAction
+ \inherits Animation
+ \brief The PropertyAction element allows immediate property changes during animation.
+
+ Explicitly set \c theimage.smooth=true during a transition:
+ \code
+ PropertyAction { target: theimage; property: "smooth"; value: true }
+ \endcode
+
+ Set \c thewebview.url to the value set for the destination state:
+ \code
+ PropertyAction { matchTargets: thewebview; matchProperties: "url" }
+ \endcode
+
+ The PropertyAction is immediate -
+ the target property is not animated to the selected value in any way.
+*/
+/*!
+ \internal
+ \class QmlPropertyAction
+*/
+QmlPropertyAction::QmlPropertyAction(QObject *parent)
+: QmlAbstractAnimation(*(new QmlPropertyActionPrivate), parent)
+{
+ Q_D(QmlPropertyAction);
+ d->init();
+}
+
+QmlPropertyAction::~QmlPropertyAction()
+{
+}
+
+void QmlPropertyActionPrivate::init()
+{
+ Q_Q(QmlPropertyAction);
+ spa = new QActionAnimation;
+ QmlGraphics_setParent_noEvent(spa, q);
+}
+
+/*!
+ \qmlproperty Object PropertyAction::target
+ This property holds an explicit target object to animate.
+
+ The exact effect of the \c target property depends on how the animation
+ is being used. Refer to the \l animation documentation for details.
+*/
+
+QObject *QmlPropertyAction::target() const
+{
+ Q_D(const QmlPropertyAction);
+ return d->target;
+}
+
+void QmlPropertyAction::setTarget(QObject *o)
+{
+ Q_D(QmlPropertyAction);
+ if (d->target == o)
+ return;
+
+ d->target = o;
+ if (d->target && !d->propertyName.isEmpty()) {
+ d->userProperty = d->createProperty(d->target, d->propertyName, this);
+ } else {
+ d->userProperty.invalidate();
+ }
+
+ emit targetChanged(d->target, d->propertyName);
+}
+
+/*!
+ \qmlproperty string PropertyAction::property
+ This property holds an explicit property to animated.
+
+ The exact effect of the \c property property depends on how the animation
+ is being used. Refer to the \l animation documentation for details.
+*/
+
+QString QmlPropertyAction::property() const
+{
+ Q_D(const QmlPropertyAction);
+ return d->propertyName;
+}
+
+void QmlPropertyAction::setProperty(const QString &n)
+{
+ Q_D(QmlPropertyAction);
+ if (d->propertyName == n)
+ return;
+
+ d->propertyName = n;
+ if (d->target && !d->propertyName.isEmpty()) {
+ d->userProperty = d->createProperty(d->target, d->propertyName, this);
+ } else {
+ d->userProperty.invalidate();
+ }
+
+ emit targetChanged(d->target, d->propertyName);
+}
+
+/*!
+ \qmlproperty string PropertyAction::matchProperties
+ This property holds a comma-separated list of property names this action
+ will match against. These names are used in conjunction with matchTargets
+ to create a list of properties that the action will set, assuming those
+ properties have changed.
+
+ This property is typically used for an action appearing as part of a Transition.
+
+ By default, no property names will be matched.
+
+ \sa matchTargets PropertyAnimation::matchProperties
+*/
+QString QmlPropertyAction::properties() const
+{
+ Q_D(const QmlPropertyAction);
+ return d->properties;
+}
+
+void QmlPropertyAction::setProperties(const QString &p)
+{
+ Q_D(QmlPropertyAction);
+ if (d->properties == p)
+ return;
+ d->properties = p;
+ emit propertiesChanged(p);
+}
+
+/*!
+ \qmlproperty list<Object> PropertyAction::matchTargets
+ This property holds a list of objects this action will match against.
+ These objects are used in conjunction with matchProperties to create a list of properties
+ that the action will set, assuming those properties have changed.
+
+ This property is typically used for an action appearing as part of a Transition.
+
+ By default, all changing targets will be matched.
+
+ \sa exclude matchProperties PropertyAnimation::matchTargets
+*/
+QList<QObject *> *QmlPropertyAction::targets()
+{
+ Q_D(QmlPropertyAction);
+ return &d->targets;
+}
+
+/*!
+ \qmlproperty list<Object> PropertyAction::exclude
+ This property holds the objects not to be affected by this animation.
+ \sa matchTargets
+*/
+QList<QObject *> *QmlPropertyAction::exclude()
+{
+ Q_D(QmlPropertyAction);
+ return &d->exclude;
+}
+
+/*!
+ \qmlproperty any PropertyAction::value
+ This property holds the value to be set on the property.
+ If not set, then the value defined for the end state of the transition.
+*/
+QVariant QmlPropertyAction::value() const
+{
+ Q_D(const QmlPropertyAction);
+ return d->value;
+}
+
+void QmlPropertyAction::setValue(const QVariant &v)
+{
+ Q_D(QmlPropertyAction);
+ if (d->value.isNull || d->value != v) {
+ d->value = v;
+ emit valueChanged(v);
+ }
+}
+
+void QmlPropertyActionPrivate::doAction()
+{
+ property.write(value, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding);
+}
+
+QAbstractAnimation *QmlPropertyAction::qtAnimation()
+{
+ Q_D(QmlPropertyAction);
+ return d->spa;
+}
+
+void QmlPropertyAction::prepare(QmlMetaProperty &p)
+{
+ Q_D(QmlPropertyAction);
+
+ if (d->userProperty.isNull)
+ d->property = p;
+ else
+ d->property = d->userProperty;
+
+ d->spa->setAnimAction(&d->proxy, QAbstractAnimation::KeepWhenStopped);
+}
+
+void QmlPropertyAction::transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction)
+{
+ Q_D(QmlPropertyAction);
+ Q_UNUSED(direction);
+
+ struct QmlSetPropertyAnimationAction : public QAbstractAnimationAction
+ {
+ QmlStateActions actions;
+ virtual void doAction()
+ {
+ for (int ii = 0; ii < actions.count(); ++ii) {
+ const QmlAction &action = actions.at(ii);
+ action.property.write(action.toValue, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::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();
+
+ bool hasSelectors = !props.isEmpty() || !d->targets.isEmpty() || !d->exclude.isEmpty();
+ bool hasTarget = !d->propertyName.isEmpty() || d->target;
+
+ if (hasSelectors && hasTarget) {
+ qmlInfo(this) << tr("matchTargets/matchProperties/exclude and target/property are mutually exclusive.");
+ return;
+ }
+
+ QmlSetPropertyAnimationAction *data = new QmlSetPropertyAnimationAction;
+
+ bool hasExplicit = false;
+ if (hasTarget && d->value.isValid()) {
+ QmlAction myAction;
+ myAction.property = d->createProperty(target(), d->propertyName, this);
+ if (myAction.property.isValid()) {
+ myAction.toValue = d->value;
+ data->actions << myAction;
+ hasExplicit = true;
+ for (int ii = 0; ii < actions.count(); ++ii) {
+ QmlAction &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) {
+ QmlAction &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 ((d->targets.isEmpty() || d->targets.contains(obj) || (!same && d->targets.contains(sObj))) &&
+ (!d->exclude.contains(obj)) && (same || (!d->exclude.contains(sObj))) &&
+ (props.contains(propertyName) || (!same && props.contains(sPropertyName)))) {
+ QmlAction myAction = action;
+
+ if (d->value.isValid())
+ myAction.toValue = d->value;
+
+ modified << action.property;
+ data->actions << myAction;
+ action.fromValue = myAction.toValue;
+ } else if (d->userProperty.isValid() &&
+ !hasSelectors && !hasTarget) {
+ if ((d->userProperty.value.object() == obj || (!same && d->userProperty.value.object() == sObj)) &&
+ (d->userProperty.value.name() == propertyName || (!same && d->userProperty.value.name() == sPropertyName))) {
+ //### same as above. merge
+ QmlAction myAction = action;
+
+ if (d->value.isValid())
+ myAction.toValue = d->value;
+
+ modified << action.property;
+ data->actions << myAction;
+ action.fromValue = myAction.toValue;
+ }
+ }
+ }
+
+ if (data->actions.count()) {
+ d->spa->setAnimAction(data, QAbstractAnimation::DeleteWhenStopped);
+ } else {
+ delete data;
+ }
+}
+
+QML_DEFINE_TYPE(Qt,4,6,PropertyAction,QmlPropertyAction)
+
+/*!
+ \qmlclass ParentAction QmlParentAction
+ \inherits Animation
+ \brief The ParentAction element allows parent changes during animation.
+
+ ParentAction provides a way to specify at what point in a Transition a ParentChange should
+ occur.
+ \qml
+ State {
+ ParentChange {
+ target: myItem
+ parent: newParent
+ }
+ }
+ Transition {
+ SequentialAnimation {
+ PropertyAnimation { ... }
+ ParentAction {} //reparent myItem now
+ PropertyAnimation { ... }
+ }
+ }
+ \endqml
+
+ It also provides a way to explicitly reparent an item during an animation.
+ \qml
+ SequentialAnimation {
+ ParentAction { target: myItem; parent: newParent }
+ PropertyAnimation {}
+ }
+ \endqml
+
+ The ParentAction is immediate - it is not animated in any way.
+*/
+
+QmlParentAction::QmlParentAction(QObject *parent)
+: QmlAbstractAnimation(*(new QmlParentActionPrivate), parent)
+{
+ Q_D(QmlParentAction);
+ d->init();
+}
+
+QmlParentAction::~QmlParentAction()
+{
+}
+
+void QmlParentActionPrivate::init()
+{
+ Q_Q(QmlParentAction);
+ cpa = new QActionAnimation;
+ QmlGraphics_setParent_noEvent(cpa, q);
+}
+
+/*!
+ \qmlproperty Item ParentAction::target
+
+ This property holds an explicit target item to reparent.
+ */
+QmlGraphicsItem *QmlParentAction::object() const
+{
+ Q_D(const QmlParentAction);
+ return d->pcTarget;
+}
+
+void QmlParentAction::setObject(QmlGraphicsItem *target)
+{
+ Q_D(QmlParentAction);
+ d->pcTarget = target;
+}
+
+/*!
+ \qmlproperty Item ParentAction::matchTarget
+ This property holds the item this action will match against -- the item
+ that the action will reparent, assuming its parent has changed.
+
+ In the following example, \c myItem will be reparented by the ParentAction, while
+ \c myOtherItem will not.
+ \qml
+ State {
+ ParentChange {
+ target: myItem
+ parent: newParent
+ }
+ ParentChange {
+ target: myOtherItem
+ parent: otherNewParent
+ }
+ }
+ Transition {
+ SequentialAnimation {
+ PropertyAnimation { ... }
+ ParentAction { matchTargets: myItem }
+ PropertyAnimation { ... }
+ }
+ }
+ \endqml
+
+ This property is typically used for an action appearing as part of a Transition.
+ */
+QmlGraphicsItem *QmlParentAction::matchTarget() const
+{
+ Q_D(const QmlParentAction);
+ return d->pcTarget;
+}
+
+void QmlParentAction::setMatchTarget(QmlGraphicsItem *target)
+{
+ Q_D(QmlParentAction);
+ d->pcMatchTarget = target;
+}
+
+/*!
+ \qmlproperty Item ParentAction::parent
+
+ The item to reparent to (i.e. the new parent).
+ */
+QmlGraphicsItem *QmlParentAction::parent() const
+{
+ Q_D(const QmlParentAction);
+ return d->pcParent;
+}
+
+void QmlParentAction::setParent(QmlGraphicsItem *parent)
+{
+ Q_D(QmlParentAction);
+ d->pcParent = parent;
+}
+
+void QmlParentActionPrivate::doAction()
+{
+ QmlParentChange pc;
+ pc.setObject(pcTarget);
+ pc.setParent(pcParent);
+ pc.execute();
+}
+
+QAbstractAnimation *QmlParentAction::qtAnimation()
+{
+ Q_D(QmlParentAction);
+ return d->cpa;
+}
+
+void QmlParentAction::transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction)
+{
+ Q_D(QmlParentAction);
+ Q_UNUSED(modified);
+ Q_UNUSED(direction);
+
+ struct QmlParentActionData : public QAbstractAnimationAction
+ {
+ QmlParentActionData(): pc(0) {}
+ ~QmlParentActionData() { delete pc; }
+
+ QmlStateActions actions;
+ bool reverse;
+ QmlParentChange *pc;
+ virtual void doAction()
+ {
+ for (int ii = 0; ii < actions.count(); ++ii) {
+ const QmlAction &action = actions.at(ii);
+ if (reverse)
+ action.event->reverse();
+ else
+ action.event->execute();
+ }
+ }
+ };
+
+ QmlParentActionData *data = new QmlParentActionData;
+
+ if (d->pcTarget && d->pcMatchTarget) {
+ qmlInfo(this) << tr("matchTarget and target are mutually exclusive.");
+ return;
+ }
+
+ for (int ii = 0; ii < actions.count(); ++ii) {
+ QmlAction &action = actions[ii];
+
+ if (action.event && action.event->typeName() == QLatin1String("ParentChange")
+ && !d->pcTarget
+ && (!d->pcMatchTarget || static_cast<QmlParentChange*>(action.event)->object() == d->pcMatchTarget)) {
+ QmlAction myAction = action;
+ data->reverse = action.reverseEvent;
+ //### this logic differs from PropertyAnimation
+ // (probably a result of modified vs. done)
+ if (d->pcParent) {
+ //### should we disallow this case?
+ QmlParentChange *pc = new QmlParentChange;
+ pc->setObject(d->pcTarget);
+ pc->setParent(static_cast<QmlParentChange*>(action.event)->parent());
+ myAction.event = pc;
+ data->pc = pc;
+ data->actions << myAction;
+ break; //only match one
+ } else {
+ action.actionDone = true;
+ data->actions << myAction;
+ }
+ }
+ }
+
+ if (d->pcTarget && d->pcParent) {
+ data->reverse = false;
+ QmlAction myAction;
+ QmlParentChange *pc = new QmlParentChange;
+ pc->setObject(d->pcTarget);
+ pc->setParent(d->pcParent);
+ myAction.event = pc;
+ data->pc = pc;
+ data->actions << myAction;
+ }
+
+ if (data->actions.count()) {
+ d->cpa->setAnimAction(data, QAbstractAnimation::DeleteWhenStopped);
+ } else {
+ delete data;
+ }
+}
+
+QML_DEFINE_TYPE(Qt,4,6,ParentAction,QmlParentAction)
+
+/*!
+ \qmlclass NumberAnimation QmlNumberAnimation
+ \inherits PropertyAnimation
+ \brief The NumberAnimation element allows you to animate changes in properties of type qreal.
+
+ Animate a set of properties over 200ms, from their values in the start state to
+ their values in the end state of the transition:
+ \code
+ NumberAnimation { matchProperties: "x,y,scale"; duration: 200 }
+ \endcode
+*/
+
+/*!
+ \internal
+ \class QmlNumberAnimation
+*/
+
+QmlNumberAnimation::QmlNumberAnimation(QObject *parent)
+: QmlPropertyAnimation(parent)
+{
+ Q_D(QmlPropertyAnimation);
+ d->interpolatorType = QMetaType::QReal;
+ d->interpolator = QVariantAnimationPrivate::getInterpolator(d->interpolatorType);
+}
+
+QmlNumberAnimation::~QmlNumberAnimation()
+{
+}
+
+/*!
+ \qmlproperty real NumberAnimation::from
+ This property holds the starting value.
+ If not set, then the value defined in the start state of the transition.
+*/
+qreal QmlNumberAnimation::from() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->from.toReal();
+}
+
+void QmlNumberAnimation::setFrom(qreal f)
+{
+ QmlPropertyAnimation::setFrom(f);
+}
+
+/*!
+ \qmlproperty real NumberAnimation::to
+ This property holds the ending value.
+ If not set, then the value defined in the end state of the transition.
+*/
+qreal QmlNumberAnimation::to() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->to.toReal();
+}
+
+void QmlNumberAnimation::setTo(qreal t)
+{
+ QmlPropertyAnimation::setTo(t);
+}
+
+QML_DEFINE_TYPE(Qt,4,6,NumberAnimation,QmlNumberAnimation)
+
+/*!
+ \qmlclass Vector3dAnimation QmlVector3dAnimation
+ \inherits PropertyAnimation
+ \brief The Vector3dAnimation element allows you to animate changes in properties of type QVector3d.
+*/
+
+/*!
+ \internal
+ \class QmlVector3dAnimation
+*/
+
+QmlVector3dAnimation::QmlVector3dAnimation(QObject *parent)
+: QmlPropertyAnimation(parent)
+{
+ Q_D(QmlPropertyAnimation);
+ d->interpolatorType = QMetaType::QVector3D;
+ d->interpolator = QVariantAnimationPrivate::getInterpolator(d->interpolatorType);
+ d->defaultToInterpolatorType = true;
+}
+
+QmlVector3dAnimation::~QmlVector3dAnimation()
+{
+}
+
+/*!
+ \qmlproperty real Vector3dAnimation::from
+ This property holds the starting value.
+ If not set, then the value defined in the start state of the transition.
+*/
+QVector3D QmlVector3dAnimation::from() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->from.value<QVector3D>();
+}
+
+void QmlVector3dAnimation::setFrom(QVector3D f)
+{
+ QmlPropertyAnimation::setFrom(f);
+}
+
+/*!
+ \qmlproperty real Vector3dAnimation::to
+ This property holds the ending value.
+ If not set, then the value defined in the end state of the transition.
+*/
+QVector3D QmlVector3dAnimation::to() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->to.value<QVector3D>();
+}
+
+void QmlVector3dAnimation::setTo(QVector3D t)
+{
+ QmlPropertyAnimation::setTo(t);
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Vector3dAnimation,QmlVector3dAnimation)
+
+QmlAnimationGroup::QmlAnimationGroup(QObject *parent)
+: QmlAbstractAnimation(*(new QmlAnimationGroupPrivate), parent)
+{
+}
+
+QmlAnimationGroup::~QmlAnimationGroup()
+{
+}
+
+QmlList<QmlAbstractAnimation *> *QmlAnimationGroup::animations()
+{
+ Q_D(QmlAnimationGroup);
+ return &d->animations;
+}
+
+/*!
+ \qmlclass SequentialAnimation QmlSequentialAnimation
+ \inherits Animation
+ \brief The SequentialAnimation element allows you to run animations sequentially.
+
+ Animations controlled in SequentialAnimation will be run one after the other.
+
+ The following example chains two numeric animations together. The \c MyItem
+ object will animate from its current x position to 100, and then back to 0.
+
+ \code
+ SequentialAnimation {
+ NumberAnimation { target: MyItem; property: "x"; to: 100 }
+ NumberAnimation { target: MyItem; property: "x"; to: 0 }
+ }
+ \endcode
+
+ \sa ParallelAnimation
+*/
+
+QmlSequentialAnimation::QmlSequentialAnimation(QObject *parent) :
+ QmlAnimationGroup(parent)
+{
+ Q_D(QmlAnimationGroup);
+ d->ag = new QSequentialAnimationGroup(this);
+}
+
+QmlSequentialAnimation::~QmlSequentialAnimation()
+{
+}
+
+void QmlSequentialAnimation::prepare(QmlMetaProperty &p)
+{
+ Q_D(QmlAnimationGroup);
+ if (d->userProperty.isNull)
+ d->property = p;
+ else
+ d->property = d->userProperty;
+
+ for (int i = 0; i < d->animations.size(); ++i)
+ d->animations.at(i)->prepare(d->property);
+}
+
+QAbstractAnimation *QmlSequentialAnimation::qtAnimation()
+{
+ Q_D(QmlAnimationGroup);
+ return d->ag;
+}
+
+void QmlSequentialAnimation::transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction)
+{
+ Q_D(QmlAnimationGroup);
+
+ int inc = 1;
+ int from = 0;
+ if (direction == Backward) {
+ inc = -1;
+ from = d->animations.count() - 1;
+ }
+
+ //needed for Behavior
+ if (d->userProperty.isValid()) {
+ for (int i = 0; i < d->animations.count(); ++i)
+ d->animations.at(i)->setTarget(d->userProperty);
+ }
+
+ for (int ii = from; ii < d->animations.count() && ii >= 0; ii += inc) {
+ d->animations.at(ii)->transition(actions, modified, direction);
+ }
+}
+
+QML_DEFINE_TYPE(Qt,4,6,SequentialAnimation,QmlSequentialAnimation)
+
+/*!
+ \qmlclass ParallelAnimation QmlParallelAnimation
+ \inherits Animation
+ \brief The ParallelAnimation element allows you to run animations in parallel.
+
+ Animations contained in ParallelAnimation will be run at the same time.
+
+ The following animation demonstrates animating the \c MyItem item
+ to (100,100) by animating the x and y properties in parallel.
+
+ \code
+ ParallelAnimation {
+ NumberAnimation { target: MyItem; property: "x"; to: 100 }
+ NumberAnimation { target: MyItem; property: "y"; to: 100 }
+ }
+ \endcode
+
+ \sa SequentialAnimation
+*/
+/*!
+ \internal
+ \class QmlParallelAnimation
+*/
+
+QmlParallelAnimation::QmlParallelAnimation(QObject *parent) :
+ QmlAnimationGroup(parent)
+{
+ Q_D(QmlAnimationGroup);
+ d->ag = new QParallelAnimationGroup(this);
+}
+
+QmlParallelAnimation::~QmlParallelAnimation()
+{
+}
+
+void QmlParallelAnimation::prepare(QmlMetaProperty &p)
+{
+ Q_D(QmlAnimationGroup);
+ if (d->userProperty.isNull)
+ d->property = p;
+ else
+ d->property = d->userProperty;
+
+ for (int i = 0; i < d->animations.size(); ++i)
+ d->animations.at(i)->prepare(d->property);
+}
+
+QAbstractAnimation *QmlParallelAnimation::qtAnimation()
+{
+ Q_D(QmlAnimationGroup);
+ return d->ag;
+}
+
+void QmlParallelAnimation::transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction)
+{
+ Q_D(QmlAnimationGroup);
+
+ //needed for Behavior
+ if (d->userProperty.isValid()) {
+ for (int i = 0; i < d->animations.count(); ++i)
+ d->animations.at(i)->setTarget(d->userProperty);
+ }
+
+ for (int ii = 0; ii < d->animations.count(); ++ii) {
+ d->animations.at(ii)->transition(actions, modified, direction);
+ }
+}
+
+QML_DEFINE_TYPE(Qt,4,6,ParallelAnimation,QmlParallelAnimation)
+
+//convert a variant from string type to another animatable type
+void QmlPropertyAnimationPrivate::convertVariant(QVariant &variant, int type)
+{
+ if (variant.userType() != QVariant::String) {
+ variant.convert((QVariant::Type)type);
+ return;
+ }
+
+ switch (type) {
+ case QVariant::Rect: {
+ variant.setValue(QmlStringConverters::rectFFromString(variant.toString()).toRect());
+ break;
+ }
+ case QVariant::RectF: {
+ variant.setValue(QmlStringConverters::rectFFromString(variant.toString()));
+ break;
+ }
+ case QVariant::Point: {
+ variant.setValue(QmlStringConverters::pointFFromString(variant.toString()).toPoint());
+ break;
+ }
+ case QVariant::PointF: {
+ variant.setValue(QmlStringConverters::pointFFromString(variant.toString()));
+ break;
+ }
+ case QVariant::Size: {
+ variant.setValue(QmlStringConverters::sizeFFromString(variant.toString()).toSize());
+ break;
+ }
+ case QVariant::SizeF: {
+ variant.setValue(QmlStringConverters::sizeFFromString(variant.toString()));
+ break;
+ }
+ case QVariant::Color: {
+ variant.setValue(QmlStringConverters::colorFromString(variant.toString()));
+ break;
+ }
+ case QVariant::Vector3D: {
+ variant.setValue(QmlStringConverters::vector3DFromString(variant.toString()));
+ break;
+ }
+ default:
+ if ((uint)type >= QVariant::UserType) {
+ QmlMetaType::StringConverter converter = QmlMetaType::customStringConverter(type);
+ if (converter)
+ variant = converter(variant.toString());
+ } else
+ variant.convert((QVariant::Type)type);
+ break;
+ }
+}
+
+/*!
+ \qmlclass PropertyAnimation QmlPropertyAnimation
+ \inherits Animation
+ \brief The PropertyAnimation element allows you to animate property changes.
+
+ Animate theObject's size property over 200ms, from its current size to 20-by-20:
+ \code
+ PropertyAnimation { target: theObject; property: "size"; to: "20x20"; duration: 200 }
+ \endcode
+
+ For an introduction to animation in QML, see \l{QML Animation}.
+*/
+
+QmlPropertyAnimation::QmlPropertyAnimation(QObject *parent)
+: QmlAbstractAnimation(*(new QmlPropertyAnimationPrivate), parent)
+{
+ Q_D(QmlPropertyAnimation);
+ d->init();
+}
+
+QmlPropertyAnimation::~QmlPropertyAnimation()
+{
+}
+
+void QmlPropertyAnimationPrivate::init()
+{
+ Q_Q(QmlPropertyAnimation);
+ va = new QmlTimeLineValueAnimator;
+ QmlGraphics_setParent_noEvent(va, q);
+}
+
+/*!
+ \qmlproperty int PropertyAnimation::duration
+ This property holds the duration of the transition, in milliseconds.
+
+ The default value is 250.
+*/
+int QmlPropertyAnimation::duration() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->va->duration();
+}
+
+void QmlPropertyAnimation::setDuration(int duration)
+{
+ if (duration < 0) {
+ qmlInfo(this) << tr("Cannot set a duration of < 0");
+ return;
+ }
+
+ Q_D(QmlPropertyAnimation);
+ if (d->va->duration() == duration)
+ return;
+ d->va->setDuration(duration);
+ emit durationChanged(duration);
+}
+
+/*!
+ \qmlproperty real PropertyAnimation::from
+ This property holds the starting value.
+ If not set, then the value defined in the start state of the transition.
+*/
+QVariant QmlPropertyAnimation::from() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->from;
+}
+
+void QmlPropertyAnimation::setFrom(const QVariant &f)
+{
+ Q_D(QmlPropertyAnimation);
+ if (d->fromIsDefined && f == d->from)
+ return;
+ d->from = f;
+ d->fromIsDefined = f.isValid();
+ emit fromChanged(f);
+}
+
+/*!
+ \qmlproperty real PropertyAnimation::to
+ This property holds the ending value.
+ If not set, then the value defined in the end state of the transition.
+*/
+QVariant QmlPropertyAnimation::to() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->to;
+}
+
+void QmlPropertyAnimation::setTo(const QVariant &t)
+{
+ Q_D(QmlPropertyAnimation);
+ if (d->toIsDefined && t == d->to)
+ return;
+ d->to = t;
+ d->toIsDefined = t.isValid();
+ emit toChanged(t);
+}
+
+/*!
+ \qmlproperty string PropertyAnimation::easing
+ \brief the easing curve used for the transition.
+
+ Available values are:
+
+ \table
+ \row
+ \o \c easeLinear
+ \o Easing curve for a linear (t) function: velocity is constant.
+ \o \inlineimage qeasingcurve-linear.png
+ \row
+ \o \c easeInQuad
+ \o Easing curve for a quadratic (t^2) function: accelerating from zero velocity.
+ \o \inlineimage qeasingcurve-inquad.png
+ \row
+ \o \c easeOutQuad
+ \o Easing curve for a quadratic (t^2) function: decelerating to zero velocity.
+ \o \inlineimage qeasingcurve-outquad.png
+ \row
+ \o \c easeInOutQuad
+ \o Easing curve for a quadratic (t^2) function: acceleration until halfway, then deceleration.
+ \o \inlineimage qeasingcurve-inoutquad.png
+ \row
+ \o \c easeOutInQuad
+ \o Easing curve for a quadratic (t^2) function: deceleration until halfway, then acceleration.
+ \o \inlineimage qeasingcurve-outinquad.png
+ \row
+ \o \c easeInCubic
+ \o Easing curve for a cubic (t^3) function: accelerating from zero velocity.
+ \o \inlineimage qeasingcurve-incubic.png
+ \row
+ \o \c easeOutCubic
+ \o Easing curve for a cubic (t^3) function: decelerating from zero velocity.
+ \o \inlineimage qeasingcurve-outcubic.png
+ \row
+ \o \c easeInOutCubic
+ \o Easing curve for a cubic (t^3) function: acceleration until halfway, then deceleration.
+ \o \inlineimage qeasingcurve-inoutcubic.png
+ \row
+ \o \c easeOutInCubic
+ \o Easing curve for a cubic (t^3) function: deceleration until halfway, then acceleration.
+ \o \inlineimage qeasingcurve-outincubic.png
+ \row
+ \o \c easeInQuart
+ \o Easing curve for a quartic (t^4) function: accelerating from zero velocity.
+ \o \inlineimage qeasingcurve-inquart.png
+ \row
+ \o \c easeOutQuart
+ \o Easing curve for a cubic (t^4) function: decelerating from zero velocity.
+ \o \inlineimage qeasingcurve-outquart.png
+ \row
+ \o \c easeInOutQuart
+ \o Easing curve for a cubic (t^4) function: acceleration until halfway, then deceleration.
+ \o \inlineimage qeasingcurve-inoutquart.png
+ \row
+ \o \c easeOutInQuart
+ \o Easing curve for a cubic (t^4) function: deceleration until halfway, then acceleration.
+ \o \inlineimage qeasingcurve-outinquart.png
+ \row
+ \o \c easeInQuint
+ \o Easing curve for a quintic (t^5) function: accelerating from zero velocity.
+ \o \inlineimage qeasingcurve-inquint.png
+ \row
+ \o \c easeOutQuint
+ \o Easing curve for a cubic (t^5) function: decelerating from zero velocity.
+ \o \inlineimage qeasingcurve-outquint.png
+ \row
+ \o \c easeInOutQuint
+ \o Easing curve for a cubic (t^5) function: acceleration until halfway, then deceleration.
+ \o \inlineimage qeasingcurve-inoutquint.png
+ \row
+ \o \c easeOutInQuint
+ \o Easing curve for a cubic (t^5) function: deceleration until halfway, then acceleration.
+ \o \inlineimage qeasingcurve-outinquint.png
+ \row
+ \o \c easeInSine
+ \o Easing curve for a sinusoidal (sin(t)) function: accelerating from zero velocity.
+ \o \inlineimage qeasingcurve-insine.png
+ \row
+ \o \c easeOutSine
+ \o Easing curve for a sinusoidal (sin(t)) function: decelerating from zero velocity.
+ \o \inlineimage qeasingcurve-outsine.png
+ \row
+ \o \c easeInOutSine
+ \o Easing curve for a sinusoidal (sin(t)) function: acceleration until halfway, then deceleration.
+ \o \inlineimage qeasingcurve-inoutsine.png
+ \row
+ \o \c easeOutInSine
+ \o Easing curve for a sinusoidal (sin(t)) function: deceleration until halfway, then acceleration.
+ \o \inlineimage qeasingcurve-outinsine.png
+ \row
+ \o \c easeInExpo
+ \o Easing curve for an exponential (2^t) function: accelerating from zero velocity.
+ \o \inlineimage qeasingcurve-inexpo.png
+ \row
+ \o \c easeOutExpo
+ \o Easing curve for an exponential (2^t) function: decelerating from zero velocity.
+ \o \inlineimage qeasingcurve-outexpo.png
+ \row
+ \o \c easeInOutExpo
+ \o Easing curve for an exponential (2^t) function: acceleration until halfway, then deceleration.
+ \o \inlineimage qeasingcurve-inoutexpo.png
+ \row
+ \o \c easeOutInExpo
+ \o Easing curve for an exponential (2^t) function: deceleration until halfway, then acceleration.
+ \o \inlineimage qeasingcurve-outinexpo.png
+ \row
+ \o \c easeInCirc
+ \o Easing curve for a circular (sqrt(1-t^2)) function: accelerating from zero velocity.
+ \o \inlineimage qeasingcurve-incirc.png
+ \row
+ \o \c easeOutCirc
+ \o Easing curve for a circular (sqrt(1-t^2)) function: decelerating from zero velocity.
+ \o \inlineimage qeasingcurve-outcirc.png
+ \row
+ \o \c easeInOutCirc
+ \o Easing curve for a circular (sqrt(1-t^2)) function: acceleration until halfway, then deceleration.
+ \o \inlineimage qeasingcurve-inoutcirc.png
+ \row
+ \o \c easeOutInCirc
+ \o Easing curve for a circular (sqrt(1-t^2)) function: deceleration until halfway, then acceleration.
+ \o \inlineimage qeasingcurve-outincirc.png
+ \row
+ \o \c easeInElastic
+ \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 easeOutElastic
+ \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 easeInOutElastic
+ \o Easing curve for an elastic (exponentially decaying sine wave) function: acceleration until halfway, then deceleration.
+ \o \inlineimage qeasingcurve-inoutelastic.png
+ \row
+ \o \c easeOutInElastic
+ \o Easing curve for an elastic (exponentially decaying sine wave) function: deceleration until halfway, then acceleration.
+ \o \inlineimage qeasingcurve-outinelastic.png
+ \row
+ \o \c easeInBack
+ \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 easeOutBack
+ \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 easeInOutBack
+ \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 easeOutInBack
+ \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 easeInBounce
+ \o Easing curve for a bounce (exponentially decaying parabolic bounce) function: accelerating from zero velocity.
+ \o \inlineimage qeasingcurve-inbounce.png
+ \row
+ \o \c easeOutBounce
+ \o Easing curve for a bounce (exponentially decaying parabolic bounce) function: decelerating from zero velocity.
+ \o \inlineimage qeasingcurve-outbounce.png
+ \row
+ \o \c easeInOutBounce
+ \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 easeOutInBounce
+ \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
+
+*/
+QString QmlPropertyAnimation::easing() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->easing;
+}
+
+void QmlPropertyAnimation::setEasing(const QString &e)
+{
+ Q_D(QmlPropertyAnimation);
+ if (d->easing == e)
+ return;
+
+ d->easing = e;
+ d->va->setEasingCurve(stringToCurve(d->easing, this));
+ emit easingChanged(e);
+}
+
+/*!
+ \qmlproperty Object PropertyAnimation::target
+ This property holds an explicit target object to animate.
+
+ target is used in conjunction with property to determine
+ what property should be animated.
+
+ \sa property matchTargets
+*/
+
+QObject *QmlPropertyAnimation::target() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->target;
+}
+
+void QmlPropertyAnimation::setTarget(QObject *o)
+{
+ Q_D(QmlPropertyAnimation);
+ if (d->target == o)
+ return;
+
+ d->target = o;
+ if (d->target && !d->propertyName.isEmpty()) {
+ d->userProperty = d->createProperty(d->target, d->propertyName, this);
+ } else {
+ d->userProperty.invalidate();
+ }
+
+ emit targetChanged(d->target, d->propertyName);
+}
+
+/*!
+ \qmlproperty string PropertyAnimation::property
+ This property holds an explicit property name to animate.
+
+ property is used in conjunction with target to determine
+ what property should be animated.
+
+ \sa target matchProperties
+*/
+
+QString QmlPropertyAnimation::property() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->propertyName;
+}
+
+void QmlPropertyAnimation::setProperty(const QString &n)
+{
+ Q_D(QmlPropertyAnimation);
+ if (d->propertyName == n)
+ return;
+
+ d->propertyName = n;
+ if (d->target && !d->propertyName.isEmpty()) {
+ d->userProperty = d->createProperty(d->target, d->propertyName, this);
+ } else {
+ d->userProperty.invalidate();
+ }
+
+ emit targetChanged(d->target, d->propertyName);
+}
+
+/*!
+ \qmlproperty string PropertyAnimation::matchProperties
+ This property holds a comma-separated list of property names this animation
+ will match against. These names are used in conjunction with matchTargets
+ to create a list of properties that the animation will animate, assuming those
+ properties have changed.
+
+ In the following example, the change in 'x' will be animated by the transition, while
+ the change in 'y' will not.
+ \qml
+ State {
+ PropertyChanges {
+ target: myItem
+ x: 15; y: 15
+ }
+ }
+ Transition {
+ PropertyAnimation {
+ matchProperties: "x"
+ }
+ }
+ \endqml
+
+ This property is typically used for an animation appearing as part of a Transition.
+
+ By default, no property names will be matched.
+
+ \sa matchTargets PropertyAction::matchTargets
+*/
+QString QmlPropertyAnimation::properties() const
+{
+ Q_D(const QmlPropertyAnimation);
+ return d->properties;
+}
+
+void QmlPropertyAnimation::setProperties(const QString &prop)
+{
+ Q_D(QmlPropertyAnimation);
+ if (d->properties == prop)
+ return;
+
+ d->properties = prop;
+ emit propertiesChanged(prop);
+}
+
+/*!
+ \qmlproperty list<Object> PropertyAnimation::matchTargets
+ This property holds a list of objects this animation will match against.
+ These objects are used in conjunction with matchProperties to create a list of properties
+ that the animation will animate, assuming those properties have changed.
+
+ In the following example, the changes to \c myItem will be animated by the transition, while
+ the changes to \c myOtherItem will not.
+ \qml
+ State {
+ PropertyChanges {
+ target: myItem
+ x: 15; y: 15
+ }
+ PropertyChanges {
+ target: myOtherItem
+ x: 30; y: 30
+ }
+ }
+ Transition {
+ PropertyAnimation {
+ matchTargets: myItem
+ matchProperties: "x,y"
+ }
+ }
+ \endqml
+
+ This property is typically used for an animation appearing as part of a Transition.
+
+ By default, all changing targets will be matched.
+
+ \sa exclude matchProperties
+*/
+QList<QObject *> *QmlPropertyAnimation::targets()
+{
+ Q_D(QmlPropertyAnimation);
+ return &d->targets;
+}
+
+/*!
+ \qmlproperty list<Object> PropertyAnimation::exclude
+ This property holds the items not to be affected by this animation.
+ \sa matchTargets
+*/
+QList<QObject *> *QmlPropertyAnimation::exclude()
+{
+ Q_D(QmlPropertyAnimation);
+ return &d->exclude;
+}
+
+void QmlPropertyAnimationPrivate::valueChanged(qreal r)
+{
+ if (!fromSourced) {
+ if (!fromIsDefined) {
+ from = property.read();
+ convertVariant(from, interpolatorType ? interpolatorType : property.propertyType());
+ //### check for invalid variant if using property type
+ }
+ fromSourced = true;
+ }
+
+ if (r == 1.) {
+ property.write(to, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding);
+ } else {
+ if (interpolator)
+ property.write(interpolator(from.constData(), to.constData(), r), QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding);
+ }
+}
+
+QAbstractAnimation *QmlPropertyAnimation::qtAnimation()
+{
+ Q_D(QmlPropertyAnimation);
+ return d->va;
+}
+
+void QmlPropertyAnimation::prepare(QmlMetaProperty &p)
+{
+ Q_D(QmlPropertyAnimation);
+ if (d->userProperty.isNull)
+ d->property = p;
+ else
+ d->property = d->userProperty;
+
+ if (!d->rangeIsSet) {
+ d->va->setStartValue(qreal(0));
+ d->va->setEndValue(qreal(1));
+ d->rangeIsSet = true;
+ }
+
+ int propType = d->property.propertyType();
+ d->convertVariant(d->to, d->interpolatorType ? d->interpolatorType : propType);
+ if (d->fromIsDefined)
+ d->convertVariant(d->from, d->interpolatorType ? d->interpolatorType : propType);
+
+ if (!d->interpolatorType) {
+ //### check for invalid variants
+ d->interpolator = QVariantAnimationPrivate::getInterpolator(propType);
+ }
+
+ d->fromSourced = false;
+ d->value.QmlTimeLineValue::setValue(0.);
+ d->va->setAnimValue(&d->value, QAbstractAnimation::KeepWhenStopped);
+ d->va->setFromSourcedValue(&d->fromSourced);
+}
+
+void QmlPropertyAnimation::transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction)
+{
+ Q_D(QmlPropertyAnimation);
+ Q_UNUSED(direction);
+
+ struct PropertyUpdater : public QmlTimeLineValue
+ {
+ QmlStateActions actions;
+ int interpolatorType; //for Number/ColorAnimation
+ int prevInterpolatorType; //for generic
+ QVariantAnimation::Interpolator interpolator;
+ bool reverse;
+ bool *wasDeleted;
+ PropertyUpdater() : wasDeleted(0) {}
+ ~PropertyUpdater() { if (wasDeleted) *wasDeleted = true; }
+ void 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;
+ QmlTimeLineValue::setValue(v);
+ for (int ii = 0; ii < actions.count(); ++ii) {
+ QmlAction &action = actions[ii];
+
+ if (v == 1.)
+ action.property.write(action.toValue, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding);
+ else {
+ if (action.fromValue.isNull()) {
+ action.fromValue = action.property.read();
+ if (interpolatorType)
+ QmlPropertyAnimationPrivate::convertVariant(action.fromValue, interpolatorType);
+ }
+ if (!interpolatorType) {
+ int propType = action.property.propertyType();
+ if (!prevInterpolatorType || prevInterpolatorType != propType) {
+ prevInterpolatorType = propType;
+ interpolator = QVariantAnimationPrivate::getInterpolator(prevInterpolatorType);
+ }
+ }
+ if (interpolator)
+ action.property.write(interpolator(action.fromValue.constData(), action.toValue.constData(), v), QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding);
+ }
+ if (deleted)
+ return;
+ }
+ wasDeleted = 0;
+ }
+ };
+
+ QStringList props = d->properties.isEmpty() ? QStringList() : d->properties.split(QLatin1Char(','));
+ for (int ii = 0; ii < props.count(); ++ii)
+ props[ii] = props.at(ii).trimmed();
+
+ bool hasSelectors = !props.isEmpty() || !d->targets.isEmpty() || !d->exclude.isEmpty();
+ bool hasTarget = !d->propertyName.isEmpty() || d->target;
+
+ if (hasSelectors && hasTarget) {
+ qmlInfo(this) << tr("matchTargets/matchProperties/exclude and target/property are mutually exclusive.");
+ return;
+ }
+
+ bool useType = (props.isEmpty() && d->propertyName.isEmpty() && d->defaultToInterpolatorType) ? true : false;
+
+ PropertyUpdater *data = new PropertyUpdater;
+ data->interpolatorType = d->interpolatorType;
+ data->interpolator = d->interpolator;
+ data->reverse = direction == Backward ? true : false;
+
+ bool hasExplicit = false;
+ //an explicit animation has been specified
+ if (hasTarget && d->toIsDefined) {
+ QmlAction myAction;
+ myAction.property = d->createProperty(target(), d->propertyName, this);
+ if (myAction.property.isValid()) {
+ if (d->fromIsDefined) {
+ d->convertVariant(d->from, d->interpolatorType ? d->interpolatorType : myAction.property.propertyType());
+ myAction.fromValue = d->from;
+ }
+ d->convertVariant(d->to, d->interpolatorType ? d->interpolatorType : myAction.property.propertyType());
+ myAction.toValue = d->to;
+ data->actions << myAction;
+ hasExplicit = true;
+ for (int ii = 0; ii < actions.count(); ++ii) {
+ QmlAction &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) {
+ QmlAction &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 ((d->targets.isEmpty() || d->targets.contains(obj) || (!same && d->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))) {
+ QmlAction 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;
+ } else if (d->userProperty.isValid() &&
+ !hasSelectors && !hasTarget) {
+ if ((d->userProperty.value.object() == obj || (!same && d->userProperty.value.object() == sObj)) &&
+ (d->userProperty.value.name() == propertyName || (!same && d->userProperty.value.name() == sPropertyName))) {
+ //### same as above. merge
+ QmlAction 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);
+ } else {
+ delete data;
+ }
+}
+
+QML_DEFINE_TYPE(Qt,4,6,PropertyAnimation,QmlPropertyAnimation)
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlanimation_p.h b/src/declarative/util/qmlanimation_p.h
new file mode 100644
index 0000000..6a69e4d
--- /dev/null
+++ b/src/declarative/util/qmlanimation_p.h
@@ -0,0 +1,440 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLANIMATION_H
+#define QMLANIMATION_H
+
+#include "qmltransition_p.h"
+#include "qmlstate_p.h"
+#include <QtGui/qvector3d.h>
+
+#include <qmlpropertyvaluesource.h>
+#include <qml.h>
+#include <qmlscriptstring.h>
+
+#include <QtCore/qvariant.h>
+#include <QtCore/QAbstractAnimation>
+#include <QtGui/qcolor.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlAbstractAnimationPrivate;
+class QmlAnimationGroup;
+class Q_AUTOTEST_EXPORT QmlAbstractAnimation : public QObject, public QmlPropertyValueSource, public QmlParserStatus
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlAbstractAnimation)
+
+ Q_INTERFACES(QmlParserStatus)
+ Q_INTERFACES(QmlPropertyValueSource)
+ 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(bool repeat READ repeat WRITE setRepeat NOTIFY repeatChanged)
+ Q_CLASSINFO("DefaultMethod", "start()")
+
+public:
+ QmlAbstractAnimation(QObject *parent=0);
+ virtual ~QmlAbstractAnimation();
+
+ bool isRunning() const;
+ void setRunning(bool);
+ bool isPaused() const;
+ void setPaused(bool);
+ bool alwaysRunToEnd() const;
+ void setAlwaysRunToEnd(bool);
+ bool repeat() const;
+ void setRepeat(bool);
+
+ int currentTime();
+ void setCurrentTime(int);
+
+ QmlAnimationGroup *group() const;
+ void setGroup(QmlAnimationGroup *);
+
+ virtual void setTarget(const QmlMetaProperty &);
+
+ void classBegin();
+ void componentComplete();
+
+Q_SIGNALS:
+ void started();
+ void completed();
+ void runningChanged(bool);
+ void pausedChanged(bool);
+ void repeatChanged(bool);
+ void alwaysRunToEndChanged(bool);
+
+public Q_SLOTS:
+ void restart();
+ void start();
+ void pause();
+ void resume();
+ void stop();
+ void complete();
+
+protected:
+ QmlAbstractAnimation(QmlAbstractAnimationPrivate &dd, QObject *parent);
+
+public:
+ enum TransitionDirection { Forward, Backward };
+ virtual void transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction);
+ virtual void prepare(QmlMetaProperty &);
+ virtual QAbstractAnimation *qtAnimation() = 0;
+
+private Q_SLOTS:
+ void timelineComplete();
+};
+
+class QmlPauseAnimationPrivate;
+class Q_AUTOTEST_EXPORT QmlPauseAnimation : public QmlAbstractAnimation
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlPauseAnimation)
+
+ Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged)
+
+public:
+ QmlPauseAnimation(QObject *parent=0);
+ virtual ~QmlPauseAnimation();
+
+ int duration() const;
+ void setDuration(int);
+
+Q_SIGNALS:
+ void durationChanged(int);
+
+protected:
+ virtual QAbstractAnimation *qtAnimation();
+};
+
+class QmlScriptActionPrivate;
+class QmlScriptAction : public QmlAbstractAnimation
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlScriptAction)
+
+ Q_PROPERTY(QmlScriptString script READ script WRITE setScript)
+ Q_PROPERTY(QString stateChangeScriptName READ stateChangeScriptName WRITE setStateChangeScriptName)
+
+public:
+ QmlScriptAction(QObject *parent=0);
+ virtual ~QmlScriptAction();
+
+ QmlScriptString script() const;
+ void setScript(const QmlScriptString &);
+
+ QString stateChangeScriptName() const;
+ void setStateChangeScriptName(const QString &);
+
+protected:
+ virtual void transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction);
+ virtual QAbstractAnimation *qtAnimation();
+};
+
+class QmlPropertyActionPrivate;
+class QmlPropertyAction : public QmlAbstractAnimation
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlPropertyAction)
+
+ Q_PROPERTY(QObject *target READ target WRITE setTarget NOTIFY targetChanged)
+ Q_PROPERTY(QString property READ property WRITE setProperty NOTIFY targetChanged)
+ Q_PROPERTY(QString matchProperties READ properties WRITE setProperties NOTIFY propertiesChanged)
+ Q_PROPERTY(QList<QObject *>* matchTargets READ targets)
+ Q_PROPERTY(QList<QObject *>* exclude READ exclude)
+ Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged)
+
+public:
+ QmlPropertyAction(QObject *parent=0);
+ virtual ~QmlPropertyAction();
+
+ QObject *target() const;
+ void setTarget(QObject *);
+
+ QString property() const;
+ void setProperty(const QString &);
+
+ QString properties() const;
+ void setProperties(const QString &);
+
+ QList<QObject *> *targets();
+ QList<QObject *> *exclude();
+
+ QVariant value() const;
+ void setValue(const QVariant &);
+
+Q_SIGNALS:
+ void valueChanged(const QVariant &);
+ void propertiesChanged(const QString &);
+ void targetChanged(QObject *, const QString &);
+
+protected:
+ virtual void transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction);
+ virtual QAbstractAnimation *qtAnimation();
+ virtual void prepare(QmlMetaProperty &);
+};
+
+class QmlGraphicsItem;
+class QmlParentActionPrivate;
+class QmlParentAction : public QmlAbstractAnimation
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlParentAction)
+
+ Q_PROPERTY(QmlGraphicsItem *target READ object WRITE setObject)
+ Q_PROPERTY(QmlGraphicsItem *matchTarget READ matchTarget WRITE setMatchTarget)
+ Q_PROPERTY(QmlGraphicsItem *parent READ parent WRITE setParent)
+
+public:
+ QmlParentAction(QObject *parent=0);
+ virtual ~QmlParentAction();
+
+ QmlGraphicsItem *object() const;
+ void setObject(QmlGraphicsItem *);
+
+ QmlGraphicsItem *matchTarget() const;
+ void setMatchTarget(QmlGraphicsItem *);
+
+ QmlGraphicsItem *parent() const;
+ void setParent(QmlGraphicsItem *);
+
+protected:
+ virtual void transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction);
+ virtual QAbstractAnimation *qtAnimation();
+};
+
+class QmlPropertyAnimationPrivate;
+class Q_AUTOTEST_EXPORT QmlPropertyAnimation : public QmlAbstractAnimation
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlPropertyAnimation)
+
+ Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged)
+ Q_PROPERTY(QVariant from READ from WRITE setFrom NOTIFY fromChanged)
+ Q_PROPERTY(QVariant to READ to WRITE setTo NOTIFY toChanged)
+ Q_PROPERTY(QString easing READ easing WRITE setEasing NOTIFY easingChanged)
+ Q_PROPERTY(QObject *target READ target WRITE setTarget NOTIFY targetChanged)
+ Q_PROPERTY(QString property READ property WRITE setProperty NOTIFY targetChanged)
+ Q_PROPERTY(QString matchProperties READ properties WRITE setProperties NOTIFY propertiesChanged)
+ Q_PROPERTY(QList<QObject *>* matchTargets READ targets)
+ Q_PROPERTY(QList<QObject *>* exclude READ exclude)
+
+public:
+ QmlPropertyAnimation(QObject *parent=0);
+ virtual ~QmlPropertyAnimation();
+
+ int duration() const;
+ void setDuration(int);
+
+ QVariant from() const;
+ void setFrom(const QVariant &);
+
+ QVariant to() const;
+ void setTo(const QVariant &);
+
+ QString easing() const;
+ void setEasing(const QString &);
+
+ QObject *target() const;
+ void setTarget(QObject *);
+
+ QString property() const;
+ void setProperty(const QString &);
+
+ QString properties() const;
+ void setProperties(const QString &);
+
+ QList<QObject *> *targets();
+ QList<QObject *> *exclude();
+
+protected:
+ virtual void transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction);
+ virtual QAbstractAnimation *qtAnimation();
+ virtual void prepare(QmlMetaProperty &);
+
+Q_SIGNALS:
+ void durationChanged(int);
+ void fromChanged(QVariant);
+ void toChanged(QVariant);
+ void easingChanged(const QString &);
+ void propertiesChanged(const QString &);
+ void targetChanged(QObject *, const QString &);
+};
+
+class Q_AUTOTEST_EXPORT QmlColorAnimation : public QmlPropertyAnimation
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlPropertyAnimation)
+ Q_PROPERTY(QColor from READ from WRITE setFrom NOTIFY fromChanged)
+ Q_PROPERTY(QColor to READ to WRITE setTo NOTIFY toChanged)
+
+public:
+ QmlColorAnimation(QObject *parent=0);
+ virtual ~QmlColorAnimation();
+
+ QColor from() const;
+ void setFrom(const QColor &);
+
+ QColor to() const;
+ void setTo(const QColor &);
+};
+
+class Q_AUTOTEST_EXPORT QmlNumberAnimation : public QmlPropertyAnimation
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlPropertyAnimation)
+
+ Q_PROPERTY(qreal from READ from WRITE setFrom NOTIFY fromChanged)
+ Q_PROPERTY(qreal to READ to WRITE setTo NOTIFY toChanged)
+
+public:
+ QmlNumberAnimation(QObject *parent=0);
+ virtual ~QmlNumberAnimation();
+
+ qreal from() const;
+ void setFrom(qreal);
+
+ qreal to() const;
+ void setTo(qreal);
+};
+
+class Q_AUTOTEST_EXPORT QmlVector3dAnimation : public QmlPropertyAnimation
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlPropertyAnimation)
+
+ Q_PROPERTY(QVector3D from READ from WRITE setFrom NOTIFY fromChanged)
+ Q_PROPERTY(QVector3D to READ to WRITE setTo NOTIFY toChanged)
+
+public:
+ QmlVector3dAnimation(QObject *parent=0);
+ virtual ~QmlVector3dAnimation();
+
+ QVector3D from() const;
+ void setFrom(QVector3D);
+
+ QVector3D to() const;
+ void setTo(QVector3D);
+};
+
+class QmlAnimationGroupPrivate;
+class QmlAnimationGroup : public QmlAbstractAnimation
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlAnimationGroup)
+
+ Q_CLASSINFO("DefaultProperty", "animations")
+ Q_PROPERTY(QmlList<QmlAbstractAnimation *> *animations READ animations)
+
+public:
+ QmlAnimationGroup(QObject *parent);
+ virtual ~QmlAnimationGroup();
+
+ QmlList<QmlAbstractAnimation *>* animations();
+ friend class QmlAbstractAnimation;
+};
+
+class QmlSequentialAnimation : public QmlAnimationGroup
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlAnimationGroup)
+
+public:
+ QmlSequentialAnimation(QObject *parent=0);
+ virtual ~QmlSequentialAnimation();
+
+protected:
+ virtual void transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction);
+ virtual QAbstractAnimation *qtAnimation();
+ virtual void prepare(QmlMetaProperty &);
+};
+
+class QmlParallelAnimation : public QmlAnimationGroup
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlAnimationGroup)
+
+public:
+ QmlParallelAnimation(QObject *parent=0);
+ virtual ~QmlParallelAnimation();
+
+protected:
+ virtual void transition(QmlStateActions &actions,
+ QmlMetaProperties &modified,
+ TransitionDirection direction);
+ virtual QAbstractAnimation *qtAnimation();
+ virtual void prepare(QmlMetaProperty &);
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlAbstractAnimation)
+QML_DECLARE_TYPE(QmlPauseAnimation)
+QML_DECLARE_TYPE(QmlScriptAction)
+QML_DECLARE_TYPE(QmlPropertyAction)
+QML_DECLARE_TYPE(QmlParentAction)
+QML_DECLARE_TYPE(QmlPropertyAnimation)
+QML_DECLARE_TYPE(QmlColorAnimation)
+QML_DECLARE_TYPE(QmlNumberAnimation)
+QML_DECLARE_TYPE(QmlSequentialAnimation)
+QML_DECLARE_TYPE(QmlParallelAnimation)
+QML_DECLARE_TYPE(QmlVector3dAnimation)
+
+QT_END_HEADER
+
+#endif // QMLANIMATION_H
diff --git a/src/declarative/util/qmlanimation_p_p.h b/src/declarative/util/qmlanimation_p_p.h
new file mode 100644
index 0000000..d680194
--- /dev/null
+++ b/src/declarative/util/qmlanimation_p_p.h
@@ -0,0 +1,384 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLANIMATION_P_H
+#define QMLANIMATION_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 "qmlanimation_p.h"
+
+#include "qmlnullablevalue_p_p.h"
+#include "qmltimeline_p_p.h"
+
+#include <qml.h>
+#include <qmlcontext.h>
+
+#include <QtCore/QPauseAnimation>
+#include <QtCore/QVariantAnimation>
+#include <QtCore/QAnimationGroup>
+#include <QtGui/QColor>
+#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 QmlAbstractAnimationAction)
+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 QActionAnimation : public QAbstractAnimation
+{
+ Q_OBJECT
+public:
+ QActionAnimation(QObject *parent = 0) : QAbstractAnimation(parent), animAction(0), policy(KeepWhenStopped), running(false) {}
+ QActionAnimation(QAbstractAnimationAction *action, QObject *parent = 0)
+ : QAbstractAnimation(parent), animAction(action), policy(KeepWhenStopped), running(false) {}
+ ~QActionAnimation() { if (policy == DeleteWhenStopped) { delete animAction; animAction = 0; } }
+ virtual int duration() const { return 0; }
+ void setAnimAction(QAbstractAnimationAction *action, DeletionPolicy p)
+ {
+ if (state() == Running)
+ stop();
+ animAction = action;
+ policy = p;
+ }
+protected:
+ virtual void updateCurrentTime(int) {}
+
+ virtual void updateState(State newState, State /*oldState*/)
+ {
+ if (newState == Running) {
+ if (animAction) {
+ running = true;
+ animAction->doAction();
+ running = false;
+ if (state() == Stopped && policy == DeleteWhenStopped) {
+ delete animAction;
+ animAction = 0;
+ }
+ }
+ } else if (newState == Stopped && policy == DeleteWhenStopped) {
+ if (!running) {
+ delete animAction;
+ animAction = 0;
+ }
+ }
+ }
+
+private:
+ QAbstractAnimationAction *animAction;
+ DeletionPolicy policy;
+ bool running;
+};
+
+//animates QmlTimeLineValue (assumes start and end values will be reals or compatible)
+class QmlTimeLineValueAnimator : public QVariantAnimation
+{
+ Q_OBJECT
+public:
+ QmlTimeLineValueAnimator(QObject *parent = 0) : QVariantAnimation(parent), animValue(0), fromSourced(0), policy(KeepWhenStopped) {}
+ ~QmlTimeLineValueAnimator() { if (policy == DeleteWhenStopped) { delete animValue; animValue = 0; } }
+ void setAnimValue(QmlTimeLineValue *value, DeletionPolicy p)
+ {
+ if (state() == Running)
+ stop();
+ animValue = value;
+ policy = p;
+ }
+ void setFromSourcedValue(bool *value)
+ {
+ fromSourced = value;
+ }
+protected:
+ virtual void updateCurrentValue(const QVariant &value)
+ {
+ 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;
+ } else if (newState == Stopped && policy == DeleteWhenStopped) {
+ delete animValue;
+ animValue = 0;
+ }
+ }
+
+private:
+ QmlTimeLineValue *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 QmlAbstractAnimationPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlAbstractAnimation)
+public:
+ QmlAbstractAnimationPrivate()
+ : running(false), paused(false), alwaysRunToEnd(false), repeat(false),
+ connectedTimeLine(false), componentComplete(true), startOnCompletion(false),
+ avoidPropertyValueSourceStart(false), group(0) {}
+
+ bool running:1;
+ bool paused:1;
+ bool alwaysRunToEnd:1;
+ bool repeat:1;
+ bool connectedTimeLine:1;
+
+ bool componentComplete:1;
+ bool startOnCompletion:1;
+ bool avoidPropertyValueSourceStart:1;
+
+ void commence();
+
+ QmlNullableValue<QmlMetaProperty> userProperty;
+
+ QmlMetaProperty property;
+ QmlAnimationGroup *group;
+
+ static QmlMetaProperty createProperty(QObject *obj, const QString &str, QObject *infoObj);
+};
+
+class QmlPauseAnimationPrivate : public QmlAbstractAnimationPrivate
+{
+ Q_DECLARE_PUBLIC(QmlPauseAnimation)
+public:
+ QmlPauseAnimationPrivate()
+ : QmlAbstractAnimationPrivate(), pa(0) {}
+
+ void init();
+
+ QPauseAnimation *pa;
+};
+
+class QmlScriptActionPrivate : public QmlAbstractAnimationPrivate
+{
+ Q_DECLARE_PUBLIC(QmlScriptAction)
+public:
+ QmlScriptActionPrivate()
+ : QmlAbstractAnimationPrivate(), hasRunScriptScript(false), proxy(this), rsa(0) {}
+
+ void init();
+
+ QmlScriptString script;
+ QString name;
+ QmlScriptString runScriptScript;
+ bool hasRunScriptScript;
+
+ void execute();
+
+ QAnimationActionProxy<QmlScriptActionPrivate,
+ &QmlScriptActionPrivate::execute> proxy;
+ QActionAnimation *rsa;
+};
+
+class QmlPropertyActionPrivate : public QmlAbstractAnimationPrivate
+{
+ Q_DECLARE_PUBLIC(QmlPropertyAction)
+public:
+ QmlPropertyActionPrivate()
+ : QmlAbstractAnimationPrivate(), target(0), proxy(this), spa(0) {}
+
+ void init();
+
+ QObject *target;
+ QString propertyName;
+ QString properties;
+ QList<QObject *> targets;
+ QList<QObject *> exclude;
+
+ QmlNullableValue<QVariant> value;
+
+ void doAction();
+
+ QAnimationActionProxy<QmlPropertyActionPrivate,
+ &QmlPropertyActionPrivate::doAction> proxy;
+ QActionAnimation *spa;
+};
+
+class QmlParentActionPrivate : public QmlAbstractAnimationPrivate
+{
+ Q_DECLARE_PUBLIC(QmlParentAction)
+public:
+ QmlParentActionPrivate()
+ : QmlAbstractAnimationPrivate(), pcTarget(0), pcMatchTarget(0), pcParent(0) {}
+
+ void init();
+
+ QmlGraphicsItem *pcTarget;
+ QmlGraphicsItem *pcMatchTarget;
+ QmlGraphicsItem *pcParent;
+
+ void doAction();
+ QActionAnimation *cpa;
+};
+
+class QmlAnimationGroupPrivate : public QmlAbstractAnimationPrivate
+{
+ Q_DECLARE_PUBLIC(QmlAnimationGroup)
+public:
+ QmlAnimationGroupPrivate()
+ : QmlAbstractAnimationPrivate(), animations(this), ag(0) {}
+
+ struct AnimationList : public QmlConcreteList<QmlAbstractAnimation *>
+ {
+ AnimationList(QmlAnimationGroupPrivate *p)
+ : anim(p) {}
+ virtual void append(QmlAbstractAnimation *a) {
+ QmlConcreteList<QmlAbstractAnimation *>::append(a);
+ a->setGroup(anim->q_func());
+ }
+ virtual void clear()
+ {
+ for (int i = 0; i < count(); ++i)
+ at(i)->setGroup(0);
+ QmlConcreteList<QmlAbstractAnimation *>::clear();
+ }
+ virtual void removeAt(int i)
+ {
+ at(i)->setGroup(0);
+ QmlConcreteList<QmlAbstractAnimation *>::removeAt(i);
+ }
+ virtual void insert(int i, QmlAbstractAnimation *a)
+ {
+ QmlConcreteList<QmlAbstractAnimation *>::insert(i, a);
+ a->setGroup(anim->q_func());
+ }
+
+ QmlAnimationGroupPrivate *anim;
+ };
+
+ AnimationList animations;
+ QAnimationGroup *ag;
+};
+
+class QmlPropertyAnimationPrivate : public QmlAbstractAnimationPrivate
+{
+ Q_DECLARE_PUBLIC(QmlPropertyAnimation)
+public:
+ QmlPropertyAnimationPrivate()
+ : QmlAbstractAnimationPrivate(), target(0), fromSourced(false), fromIsDefined(false), toIsDefined(false),
+ rangeIsSet(false), defaultToInterpolatorType(0), interpolatorType(0), interpolator(0), va(0),
+ value(this, &QmlPropertyAnimationPrivate::valueChanged) {}
+
+ void init();
+
+ QVariant from;
+ QVariant to;
+
+ QString easing;
+
+ QObject *target;
+ QString propertyName;
+ QString properties;
+ QList<QObject *> targets;
+ QList<QObject *> exclude;
+
+ bool fromSourced;
+ bool fromIsDefined:1;
+ bool toIsDefined:1;
+ bool rangeIsSet:1;
+ bool defaultToInterpolatorType:1;
+ int interpolatorType;
+ QVariantAnimation::Interpolator interpolator;
+
+ QmlTimeLineValueAnimator *va;
+ virtual void valueChanged(qreal);
+
+ QmlTimeLineValueProxy<QmlPropertyAnimationPrivate> value;
+
+ static QVariant interpolateVariant(const QVariant &from, const QVariant &to, qreal progress);
+ static void convertVariant(QVariant &variant, int type);
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLANIMATION_P_H
diff --git a/src/declarative/util/qmlbehavior.cpp b/src/declarative/util/qmlbehavior.cpp
new file mode 100644
index 0000000..b9c77f5
--- /dev/null
+++ b/src/declarative/util/qmlbehavior.cpp
@@ -0,0 +1,189 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlbehavior_p.h"
+
+#include "qmlanimation_p.h"
+#include "qmltransition_p.h"
+
+#include <qmlcontext.h>
+#include <qmlinfo.h>
+
+#include <QtCore/qparallelanimationgroup.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,Behavior,QmlBehavior)
+
+class QmlBehaviorPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlBehavior)
+public:
+ QmlBehaviorPrivate() : animation(0), enabled(true) {}
+
+ QmlMetaProperty property;
+ QVariant currentValue;
+ QmlAbstractAnimation *animation;
+ bool enabled;
+};
+
+/*!
+ \qmlclass Behavior QmlBehavior
+ \brief The Behavior element allows you to specify a default animation for a property change.
+
+ Behaviors provide one way to specify \l{qmlanimation.html}{animations} in QML.
+
+ In the example below, the rect will use a bounce easing curve over 200 millisecond for any changes to its y property:
+ \code
+ Rectangle {
+ width: 20; height: 20
+ color: "#00ff00"
+ y: 200 //initial value
+ y: Behavior {
+ NumberAnimation {
+ easing: "easeOutBounce(amplitude:100)"
+ duration: 200
+ }
+ }
+ }
+ \endcode
+
+ Currently only a single Behavior may be specified for a property;
+ this Behavior can be enabled and disabled via the \l{enabled} property.
+*/
+
+
+QmlBehavior::QmlBehavior(QObject *parent)
+ : QObject(*(new QmlBehaviorPrivate), parent)
+{
+}
+
+QmlBehavior::~QmlBehavior()
+{
+}
+
+/*!
+ \qmlproperty Animation Behavior::animation
+ \default
+
+ The animation to use when the behavior is triggered.
+*/
+
+QmlAbstractAnimation *QmlBehavior::animation()
+{
+ Q_D(QmlBehavior);
+ return d->animation;
+}
+
+void QmlBehavior::setAnimation(QmlAbstractAnimation *animation)
+{
+ Q_D(QmlBehavior);
+ if (d->animation) {
+ qmlInfo(this) << tr("Can't change the animation assigned to a Behavior.");
+ return;
+ }
+
+ d->animation = animation;
+ if (d->animation)
+ d->animation->setTarget(d->property);
+}
+
+/*!
+ \qmlproperty bool Behavior::enabled
+ Whether the Behavior will be triggered when the property it is tracking changes.
+
+ By default a Behavior is enabled.
+*/
+
+bool QmlBehavior::enabled() const
+{
+ Q_D(const QmlBehavior);
+ return d->enabled;
+}
+
+void QmlBehavior::setEnabled(bool enabled)
+{
+ Q_D(QmlBehavior);
+ if (d->enabled == enabled)
+ return;
+ d->enabled = enabled;
+ emit enabledChanged();
+}
+
+void QmlBehavior::write(const QVariant &value)
+{
+ Q_D(QmlBehavior);
+ if (!d->animation || !d->enabled) {
+ d->property.write(value, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding);
+ return;
+ }
+
+ d->currentValue = d->property.read();
+
+ d->animation->qtAnimation()->stop();
+
+ QmlStateOperation::ActionList actions;
+ QmlAction action;
+ action.property = d->property;
+ action.fromValue = d->currentValue;
+ action.toValue = value;
+ actions << action;
+
+ QList<QmlMetaProperty> after;
+ if (d->animation)
+ d->animation->transition(actions, after, QmlAbstractAnimation::Forward);
+ d->animation->qtAnimation()->start();
+ if (!after.contains(d->property))
+ d->property.write(value, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding);
+}
+
+void QmlBehavior::setTarget(const QmlMetaProperty &property)
+{
+ Q_D(QmlBehavior);
+ d->property = property;
+ d->currentValue = property.read();
+ if (d->animation)
+ d->animation->setTarget(property);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlbehavior_p.h b/src/declarative/util/qmlbehavior_p.h
new file mode 100644
index 0000000..da3b40f
--- /dev/null
+++ b/src/declarative/util/qmlbehavior_p.h
@@ -0,0 +1,92 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLBEHAVIOR_H
+#define QMLBEHAVIOR_H
+
+#include "qmlstate_p.h"
+
+#include <qmlpropertyvaluesource.h>
+#include <qmlpropertyvalueinterceptor.h>
+#include <qml.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlAbstractAnimation;
+class QmlBehaviorPrivate;
+class Q_DECLARATIVE_EXPORT QmlBehavior : public QObject, public QmlPropertyValueInterceptor
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlBehavior)
+
+ Q_INTERFACES(QmlPropertyValueInterceptor)
+ Q_CLASSINFO("DefaultProperty", "animation")
+ Q_PROPERTY(QmlAbstractAnimation *animation READ animation WRITE setAnimation)
+ Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
+
+public:
+ QmlBehavior(QObject *parent=0);
+ ~QmlBehavior();
+
+ virtual void setTarget(const QmlMetaProperty &);
+ virtual void write(const QVariant &value);
+
+ QmlAbstractAnimation *animation();
+ void setAnimation(QmlAbstractAnimation *);
+
+ bool enabled() const;
+ void setEnabled(bool enabled);
+
+Q_SIGNALS:
+ void enabledChanged();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlBehavior)
+
+QT_END_HEADER
+
+#endif // QMLBEHAVIOR_H
diff --git a/src/declarative/util/qmlbind.cpp b/src/declarative/util/qmlbind.cpp
new file mode 100644
index 0000000..c68cef2
--- /dev/null
+++ b/src/declarative/util/qmlbind.cpp
@@ -0,0 +1,201 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlbind_p.h"
+
+#include "qmlnullablevalue_p_p.h"
+
+#include <qmlengine.h>
+#include <qmlcontext.h>
+
+#include <QtCore/qfile.h>
+#include <QtCore/qdebug.h>
+#include <QtScript/qscriptvalue.h>
+#include <QtScript/qscriptcontext.h>
+#include <QtScript/qscriptengine.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlBindPrivate : public QObjectPrivate
+{
+public:
+ QmlBindPrivate() : when(true), componentComplete(false), obj(0) {}
+
+ bool when : 1;
+ bool componentComplete : 1;
+ QObject *obj;
+ QString prop;
+ QmlNullableValue<QVariant> value;
+};
+
+QML_DEFINE_TYPE(Qt,4,6,Binding,QmlBind)
+/*!
+ \qmlclass Binding QmlBind
+ \brief The Binding element allows arbitrary property bindings to be created.
+
+ 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.
+
+ If the binding target or binding property is changed, the bound value is
+ immediately pushed onto the new target.
+ */
+/*!
+ \internal
+ \class QmlBind
+ \ingroup group_utility
+ \brief The QmlBind class allows arbitrary property bindings to be created.
+
+ Simple bindings are usually earier to do in-place rather than creating a
+ QmlBind item. For that reason, QmlBind is usually used to transfer property information
+ from Qml to C++.
+
+ \sa cppqml
+ */
+QmlBind::QmlBind(QObject *parent)
+ : QObject(*(new QmlBindPrivate), parent)
+{
+}
+
+QmlBind::~QmlBind()
+{
+}
+
+bool QmlBind::when() const
+{
+ Q_D(const QmlBind);
+ return d->when;
+}
+
+void QmlBind::setWhen(bool v)
+{
+ Q_D(QmlBind);
+ d->when = v;
+ eval();
+}
+
+/*!
+ \qmlproperty Object Binding::target
+
+ The object to be updated.
+*/
+QObject *QmlBind::object()
+{
+ Q_D(const QmlBind);
+ return d->obj;
+}
+
+void QmlBind::setObject(QObject *obj)
+{
+ Q_D(QmlBind);
+ d->obj = obj;
+ eval();
+}
+
+/*!
+ \qmlproperty string Binding::property
+
+ The property to be updated.
+*/
+QString QmlBind::property() const
+{
+ Q_D(const QmlBind);
+ return d->prop;
+}
+
+void QmlBind::setProperty(const QString &p)
+{
+ Q_D(QmlBind);
+ d->prop = p;
+ eval();
+}
+
+/*!
+ \qmlproperty any 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 QmlBind::value() const
+{
+ Q_D(const QmlBind);
+ return d->value.value;
+}
+
+void QmlBind::setValue(const QVariant &v)
+{
+ Q_D(QmlBind);
+ d->value.value = v;
+ d->value.isNull = false;
+ eval();
+}
+
+void QmlBind::componentComplete()
+{
+ Q_D(QmlBind);
+ d->componentComplete = true;
+ eval();
+}
+
+void QmlBind::eval()
+{
+ Q_D(QmlBind);
+ if (!d->obj || d->value.isNull || !d->when || !d->componentComplete)
+ return;
+
+ QmlMetaProperty prop(d->obj, d->prop);
+ prop.write(d->value.value);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlbind_p.h b/src/declarative/util/qmlbind_p.h
new file mode 100644
index 0000000..4d7cd1f
--- /dev/null
+++ b/src/declarative/util/qmlbind_p.h
@@ -0,0 +1,95 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLBIND_H
+#define QMLBIND_H
+
+#include <qml.h>
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlBindPrivate;
+class Q_DECLARATIVE_EXPORT QmlBind : public QObject, public QmlParserStatus
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlBind)
+ Q_INTERFACES(QmlParserStatus)
+ Q_PROPERTY(QObject *target READ object WRITE setObject)
+ Q_PROPERTY(QString property READ property WRITE setProperty)
+ Q_PROPERTY(QVariant value READ value WRITE setValue)
+ Q_PROPERTY(bool when READ when WRITE setWhen)
+
+public:
+ QmlBind(QObject *parent=0);
+ ~QmlBind();
+
+ 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 componentComplete();
+
+private:
+ void eval();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlBind)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/util/qmlconnection.cpp b/src/declarative/util/qmlconnection.cpp
new file mode 100644
index 0000000..800fd6b
--- /dev/null
+++ b/src/declarative/util/qmlconnection.cpp
@@ -0,0 +1,287 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlconnection_p.h"
+
+#include <qmlexpression.h>
+#include <qmlboundsignal_p.h>
+#include <qmlcontext.h>
+
+#include <QtCore/qdebug.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlConnectionPrivate : public QObjectPrivate
+{
+public:
+ QmlConnectionPrivate() : boundsignal(0), signalSender(0), scriptset(false), componentcomplete(false) {}
+
+ QmlBoundSignal *boundsignal;
+ QObject *signalSender;
+ QmlScriptString script;
+ bool scriptset;
+ QString signal;
+ bool componentcomplete;
+};
+
+/*!
+ \qmlclass Connection QmlConnection
+ \brief A Connection object describes generalized connections to signals.
+
+ 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
+ MouseRegion {
+ onClicked: { foo(x+123,y+456) }
+ }
+ \endqml
+
+ However, in some cases, it is not possible to connect to a signal in this
+ way. For example, JavaScript-in-HTML style signal properties do not allow:
+
+ \list
+ \i connecting to signals with the same name but different parameters
+ \i conformance checking that parameters are correctly named
+ \i multiple connections to the same signal
+ \i connections outside the scope of the signal sender
+ \i signals in classes with coincidentally-named on<Signal> properties
+ \endlist
+
+ When any of these are needed, the Connection object can be used instead.
+
+ For example, the above code can be changed to use a Connection object,
+ like this:
+
+ \qml
+ MouseRegion {
+ Connection {
+ signal: "clicked(x,y)"
+ script: { foo(x+123,y+456) }
+ }
+ }
+ \endqml
+
+ More generally, the Connection object can be a child of some other object than
+ the sender of the signal, and the script is the default attribute:
+
+ \qml
+ MouseRegion {
+ id: mr
+ }
+ ...
+ Connection {
+ sender: mr
+ signal: "clicked(x,y)"
+ script: { foo(x+123,y+456) }
+ }
+ \endqml
+*/
+
+/*!
+ \internal
+ \class QmlConnection
+ \brief The QmlConnection class describes generalized connections to signals.
+
+*/
+QmlConnection::QmlConnection(QObject *parent) :
+ QObject(*(new QmlConnectionPrivate), parent)
+{
+}
+
+QmlConnection::~QmlConnection()
+{
+ Q_D(QmlConnection);
+ delete d->boundsignal;
+}
+
+/*!
+ \qmlproperty Object Connection::sender
+ This property holds the object that sends the signal.
+
+ By default, the sender is assumed to be the parent of the Connection.
+*/
+QObject *QmlConnection::signalSender() const
+{
+ Q_D(const QmlConnection);
+ return d->signalSender ? d->signalSender : parent();
+}
+
+void QmlConnection::setSignalSender(QObject *obj)
+{
+ Q_D(QmlConnection);
+ if (d->signalSender == obj)
+ return;
+ disconnectIfValid();
+ d->signalSender = obj;
+ connectIfValid();
+}
+
+void QmlConnection::connectIfValid()
+{
+ Q_D(QmlConnection);
+ if (!d->componentcomplete)
+ return;
+ // boundsignal must not exist
+ if ((d->signalSender || parent()) && !d->signal.isEmpty() && d->scriptset) {
+ // create
+ // XXX scope?
+ int sigIdx = -1;
+ int lparen = d->signal.indexOf(QLatin1Char('('));
+ QList<QByteArray> sigparams;
+ if (lparen >= 0 && d->signal.length() > lparen+2) {
+ QStringList l = d->signal.mid(lparen+1,d->signal.length()-lparen-2).split(QLatin1Char(','));
+ foreach (const QString &s, l) {
+ sigparams.append(s.trimmed().toUtf8());
+ }
+ }
+ QString signalname = d->signal.left(lparen);
+ QObject *sender = d->signalSender ? d->signalSender : parent();
+ const QMetaObject *mo = sender->metaObject();
+ int methods = mo->methodCount();
+ for (int ii = 0; ii < methods; ++ii) {
+ QMetaMethod method = mo->method(ii);
+ QString methodName = QString::fromUtf8(method.signature());
+ int idx = methodName.indexOf(QLatin1Char('('));
+ methodName = methodName.left(idx);
+ if (methodName == signalname && (lparen<0 || method.parameterNames() == sigparams)) {
+ sigIdx = ii;
+ break;
+ }
+ }
+ if (sigIdx < 0) {
+ // Cannot usefully warn, since could be in middle of
+ // changing sender and signal.
+ // XXX need state change transactions to do better
+ return;
+ }
+
+ d->boundsignal = new QmlBoundSignal(qmlContext(this), d->script.script(), sender, mo->method(sigIdx), this);
+ }
+}
+
+void QmlConnection::disconnectIfValid()
+{
+ Q_D(QmlConnection);
+ if (!d->componentcomplete)
+ return;
+ if ((d->signalSender || parent()) && !d->signal.isEmpty() && d->scriptset) {
+ // boundsignal must exist
+ // destroy
+ delete d->boundsignal;
+ d->boundsignal = 0;
+ }
+}
+
+void QmlConnection::componentComplete()
+{
+ Q_D(QmlConnection);
+ d->componentcomplete=true;
+ connectIfValid();
+}
+
+
+/*!
+ \qmlproperty script Connection::script
+ This property holds the JavaScript executed whenever the signal is sent.
+
+ This is the default attribute of Connection.
+*/
+QmlScriptString QmlConnection::script() const
+{
+ Q_D(const QmlConnection);
+ return d->script;
+}
+
+void QmlConnection::setScript(const QmlScriptString& script)
+{
+ Q_D(QmlConnection);
+ if ((d->signalSender || parent()) && !d->signal.isEmpty()) {
+ if (!d->scriptset) {
+ // mustn't exist - create
+ d->scriptset = true;
+ d->script = script;
+ connectIfValid();
+ } else {
+ // must exist - update
+ d->script = script;
+ d->boundsignal->expression()->setExpression(script.script());
+ }
+ } else {
+ d->scriptset = true;
+ d->script = script;
+ }
+}
+
+/*!
+ \qmlproperty string Connection::signal
+ This property holds the signal from the sender to which the script is attached.
+
+ The signal's formal parameter names must be given in parentheses:
+
+ \qml
+Connection {
+ signal: "clicked(x,y)"
+ script: { ... }
+}
+ \endqml
+*/
+QString QmlConnection::signal() const
+{
+ Q_D(const QmlConnection);
+ return d->signal;
+}
+
+void QmlConnection::setSignal(const QString& sig)
+{
+ Q_D(QmlConnection);
+ if (d->signal == sig)
+ return;
+ disconnectIfValid();
+ d->signal = sig;
+ connectIfValid();
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Connection,QmlConnection)
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlconnection_p.h b/src/declarative/util/qmlconnection_p.h
new file mode 100644
index 0000000..52bc247
--- /dev/null
+++ b/src/declarative/util/qmlconnection_p.h
@@ -0,0 +1,93 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLCONNECTION_H
+#define QMLCONNECTION_H
+
+#include <qml.h>
+#include <qmlscriptstring.h>
+
+#include <QtCore/qobject.h>
+#include <QtCore/qstring.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlBoundSignal;
+class QmlContext;
+class QmlConnectionPrivate;
+class Q_DECLARATIVE_EXPORT QmlConnection : public QObject, public QmlParserStatus
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlConnection)
+
+ Q_INTERFACES(QmlParserStatus)
+ Q_PROPERTY(QObject *sender READ signalSender WRITE setSignalSender)
+ Q_PROPERTY(QmlScriptString script READ script WRITE setScript)
+ Q_PROPERTY(QString signal READ signal WRITE setSignal)
+
+public:
+ QmlConnection(QObject *parent=0);
+ ~QmlConnection();
+
+ QObject *signalSender() const;
+ void setSignalSender(QObject *);
+ QmlScriptString script() const;
+ void setScript(const QmlScriptString&);
+ QString signal() const;
+ void setSignal(const QString&);
+
+private:
+ void disconnectIfValid();
+ void connectIfValid();
+ void componentComplete();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlConnection)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/util/qmldatetimeformatter.cpp b/src/declarative/util/qmldatetimeformatter.cpp
new file mode 100644
index 0000000..9d216cf
--- /dev/null
+++ b/src/declarative/util/qmldatetimeformatter.cpp
@@ -0,0 +1,372 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmldatetimeformatter_p.h"
+
+#include <QtCore/qlocale.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+//TODO: may need optimisation as the QDateTime member may not be needed?
+// be able to set a locale?
+
+class QmlDateTimeFormatterPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlDateTimeFormatter)
+public:
+ QmlDateTimeFormatterPrivate() : locale(QLocale::system()), longStyle(false), componentComplete(true) {}
+
+ void updateText();
+
+ QDateTime dateTime;
+ QDate date;
+ QTime time;
+ QLocale locale;
+ QString dateTimeText;
+ QString dateText;
+ QString timeText;
+ QString dateTimeFormat; //set for convienience?
+ QString dateFormat;
+ QString timeFormat;
+ bool longStyle;
+ bool componentComplete;
+};
+
+/*!
+ \qmlclass DateTimeFormatter QmlDateTimeFormatter
+ \brief The DateTimeFormatter allows you to control the format of a date string.
+
+ \code
+ DateTimeFormatter { id: formatter; date: System.date }
+ Text { text: formatter.dateText }
+ \endcode
+
+ By default, the text properties (dateText, timeText, and dateTimeText) will return the
+ date and time using the current system locale's format.
+*/
+
+/*!
+ \internal
+ \class QmlDateTimeFormatter
+ \ingroup group_utility
+ \brief The QmlDateTimeFormatter class allows you to format a date string.
+*/
+
+QmlDateTimeFormatter::QmlDateTimeFormatter(QObject *parent)
+: QObject(*(new QmlDateTimeFormatterPrivate), parent)
+{
+}
+
+QmlDateTimeFormatter::~QmlDateTimeFormatter()
+{
+}
+
+/*!
+ \qmlproperty string DateTimeFormatter::dateText
+ \qmlproperty string DateTimeFormatter::timeText
+ \qmlproperty string DateTimeFormatter::dateTimeText
+
+ Formatted text representations of the \c date, \c time,
+ and \c {date and time}, respectively.
+
+ If there is no explictly specified format the DateTimeFormatter
+ will use the system locale's default 'short' setting.
+
+ \code
+ // specify source date (assuming today is February 19, 2009)
+ DateTimeFormatter { id: formatter; dateTime: Today.date }
+
+ // display the full date and time
+ Text { text: formatter.dateText }
+ \endcode
+
+ Would be equivalent to the following for a US English locale:
+
+ \code
+ // display the date
+ Text { text: "2/19/09" }
+ \endcode
+*/
+QString QmlDateTimeFormatter::dateTimeText() const
+{
+ Q_D(const QmlDateTimeFormatter);
+ return d->dateTimeText;
+}
+
+QString QmlDateTimeFormatter::dateText() const
+{
+ Q_D(const QmlDateTimeFormatter);
+ return d->dateText;
+}
+
+QString QmlDateTimeFormatter::timeText() const
+{
+ Q_D(const QmlDateTimeFormatter);
+ return d->timeText;
+}
+
+/*!
+ \qmlproperty date DateTimeFormatter::date
+ \qmlproperty time DateTimeFormatter::time
+ \qmlproperty datetime DateTimeFormatter::dateTime
+
+ The source date and time to be used by the formatter.
+
+ \code
+ // setting the date and time
+ DateTimeFormatter { date: System.date; time: System.time }
+ \endcode
+
+ For convienience it is possible to set the datetime property to set both the date and the time.
+ \code
+ // setting the datetime
+ DateTimeFormatter { dateTime: System.dateTime }
+ \endcode
+
+ There can only be one instance of date and time per formatter; if date, time, and dateTime are all
+ set the actual date and time used is not guaranteed.
+
+ \note If no date is set, dateTimeText will be just the date;
+ If no time is set, the dateTimeText will be just the time.
+
+*/
+QDate QmlDateTimeFormatter::date() const
+{
+ Q_D(const QmlDateTimeFormatter);
+ return d->date;
+}
+
+QTime QmlDateTimeFormatter::time() const
+{
+ Q_D(const QmlDateTimeFormatter);
+ return d->time;
+}
+
+QDateTime QmlDateTimeFormatter::dateTime() const
+{
+ Q_D(const QmlDateTimeFormatter);
+ return d->dateTime;
+}
+
+/*!
+ \qmlproperty string DateTimeFormatter::dateFormat
+ \qmlproperty string DateTimeFormatter::timeFormat
+ \qmlproperty string DateTimeFormatter::dateTimeFormat
+
+ Specifies a custom format which the DateTime Formatter can use.
+
+ If there is no explictly specified format the DateTimeFormatter
+ will use the system locale's default 'short' setting.
+
+ The text's format may be modified by setting:
+ \list
+ \i \c dateFormat
+ \i \c timeFormat
+ \i \c dateTimeFormat
+ \endlist
+
+ If only the format for date is defined, the time and dateTime formats will be defined
+ as the system locale default and likewise for the others.
+
+ Syntax for the format is based on the QDateTime::toString() formatting options.
+
+ \code
+ // Format the date such that the dateText is: '1997-12-12'
+ DateTimeFormatter { id: formatter; dateTime: Today.dateTime; formatDate: "yyyy-MM-d" }
+ \endcode
+
+ Assigning an empty string to a particular format will reset it.
+*/
+QString QmlDateTimeFormatter::dateTimeFormat() const
+{
+ Q_D(const QmlDateTimeFormatter);
+ return d->dateTimeFormat;
+}
+
+QString QmlDateTimeFormatter::dateFormat() const
+{
+ Q_D(const QmlDateTimeFormatter);
+ return d->dateFormat;
+}
+
+QString QmlDateTimeFormatter::timeFormat() const
+{
+ Q_D(const QmlDateTimeFormatter);
+ return d->timeFormat;
+}
+
+/*!
+ \qmlproperty bool DateTimeFormatter::longStyle
+
+ This property causes the formatter to use the system locale's long format rather than short format
+ by default.
+
+ This setting is off by default.
+*/
+bool QmlDateTimeFormatter::longStyle() const
+{
+ Q_D(const QmlDateTimeFormatter);
+ return d->longStyle;
+}
+
+void QmlDateTimeFormatter::setDateTime(const QDateTime &dateTime)
+{
+ Q_D(QmlDateTimeFormatter);
+ if (d->dateTime == dateTime)
+ return;
+ d->dateTime = dateTime;
+ d->date = d->dateTime.date();
+ d->time = d->dateTime.time();
+ d->updateText();
+}
+
+void QmlDateTimeFormatter::setTime(const QTime &time)
+{
+ Q_D(QmlDateTimeFormatter);
+ if (d->dateTime.time() == time)
+ return;
+ d->time = time;
+ d->dateTime.setTime(time);
+ d->updateText();
+}
+
+void QmlDateTimeFormatter::setDate(const QDate &date)
+{
+ Q_D(QmlDateTimeFormatter);
+ if (d->dateTime.date() == date)
+ return;
+ d->date = date;
+ bool clearTime = d->dateTime.time().isValid() ? false : true; //because setting date generates default time
+ d->dateTime.setDate(date);
+ if (clearTime)
+ d->dateTime.setTime(QTime());
+ d->updateText();
+}
+
+//DateTime formatting may be a combination of date and time?
+void QmlDateTimeFormatter::setDateTimeFormat(const QString &format)
+{
+ Q_D(QmlDateTimeFormatter);
+ //no format checking
+ d->dateTimeFormat = format;
+ d->updateText();
+}
+
+void QmlDateTimeFormatter::setDateFormat(const QString &format)
+{
+ Q_D(QmlDateTimeFormatter);
+ //no format checking
+ d->dateFormat = format;
+ d->updateText();
+}
+
+void QmlDateTimeFormatter::setTimeFormat(const QString &format)
+{
+ Q_D(QmlDateTimeFormatter);
+ //no format checking
+ d->timeFormat = format;
+ d->updateText();
+}
+
+void QmlDateTimeFormatter::setLongStyle(bool longStyle)
+{
+ Q_D(QmlDateTimeFormatter);
+ d->longStyle = longStyle;
+ d->updateText();
+}
+
+void QmlDateTimeFormatterPrivate::updateText()
+{
+ Q_Q(QmlDateTimeFormatter);
+ if (!componentComplete)
+ return;
+
+ QString str;
+ QString str1;
+ QString str2;
+
+ Qt::DateFormat defaultFormat = longStyle ? Qt::SystemLocaleLongDate : Qt::SystemLocaleShortDate;
+
+ if (dateFormat.isEmpty())
+ str1 = date.toString(defaultFormat);
+ else
+ str1 = date.toString(dateFormat);
+
+ if (timeFormat.isEmpty())
+ str2 = time.toString(defaultFormat);
+ else
+ str2 = time.toString(timeFormat);
+
+ if (dateTimeFormat.isEmpty())
+ str = dateTime.toString(defaultFormat);
+ //else if (!formatTime.isEmpty() && !formatDate.isEmpty())
+ // str = str1 + QLatin1Char(' ') + str2;
+ else
+ str = dateTime.toString(dateTimeFormat);
+
+ if (dateTimeText == str && dateText == str1 && timeText == str2)
+ return;
+
+ dateTimeText = str;
+ dateText = str1;
+ timeText = str2;
+
+ emit q->textChanged();
+}
+
+void QmlDateTimeFormatter::classBegin()
+{
+ Q_D(QmlDateTimeFormatter);
+ d->componentComplete = false;
+}
+
+void QmlDateTimeFormatter::componentComplete()
+{
+ Q_D(QmlDateTimeFormatter);
+ d->componentComplete = true;
+ d->updateText();
+}
+
+QML_DEFINE_TYPE(Qt,4,6,DateTimeFormatter,QmlDateTimeFormatter)
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmldatetimeformatter_p.h b/src/declarative/util/qmldatetimeformatter_p.h
new file mode 100644
index 0000000..c90ee8c
--- /dev/null
+++ b/src/declarative/util/qmldatetimeformatter_p.h
@@ -0,0 +1,117 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLDATETIMEFORMATTER_H
+#define QMLDATETIMEFORMATTER_H
+
+#include <qml.h>
+
+#include <QtCore/qdatetime.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlDateTimeFormatterPrivate;
+class Q_DECLARATIVE_EXPORT QmlDateTimeFormatter : public QObject, public QmlParserStatus
+{
+ Q_OBJECT
+ Q_INTERFACES(QmlParserStatus)
+
+ Q_PROPERTY(QString dateText READ dateText NOTIFY textChanged)
+ Q_PROPERTY(QString timeText READ timeText NOTIFY textChanged)
+ Q_PROPERTY(QString dateTimeText READ dateTimeText NOTIFY textChanged)
+ Q_PROPERTY(QDate date READ date WRITE setDate)
+ Q_PROPERTY(QTime time READ time WRITE setTime)
+ Q_PROPERTY(QDateTime dateTime READ dateTime WRITE setDateTime)
+ Q_PROPERTY(QString dateFormat READ dateFormat WRITE setDateFormat)
+ Q_PROPERTY(QString timeFormat READ timeFormat WRITE setTimeFormat)
+ Q_PROPERTY(QString dateTimeFormat READ dateTimeFormat WRITE setDateTimeFormat)
+ Q_PROPERTY(bool longStyle READ longStyle WRITE setLongStyle)
+public:
+ QmlDateTimeFormatter(QObject *parent=0);
+ ~QmlDateTimeFormatter();
+
+ QString dateTimeText() const;
+ QString dateText() const;
+ QString timeText() const;
+
+ QDate date() const;
+ void setDate(const QDate &);
+
+ QTime time() const;
+ void setTime(const QTime &);
+
+ QDateTime dateTime() const;
+ void setDateTime(const QDateTime &);
+
+ QString dateTimeFormat() const;
+ void setDateTimeFormat(const QString &);
+
+ QString dateFormat() const;
+ void setDateFormat(const QString &);
+
+ QString timeFormat() const;
+ void setTimeFormat(const QString &);
+
+ bool longStyle() const;
+ void setLongStyle(bool);
+
+ virtual void classBegin();
+ virtual void componentComplete();
+
+Q_SIGNALS:
+ void textChanged();
+
+private:
+ Q_DISABLE_COPY(QmlDateTimeFormatter)
+ Q_DECLARE_PRIVATE(QmlDateTimeFormatter)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlDateTimeFormatter)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/util/qmleasefollow.cpp b/src/declarative/util/qmleasefollow.cpp
new file mode 100644
index 0000000..e3153b1
--- /dev/null
+++ b/src/declarative/util/qmleasefollow.cpp
@@ -0,0 +1,527 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmleasefollow_p.h"
+
+#include "qmlanimation_p_p.h"
+
+#include <qmlmetaproperty.h>
+
+#include <QtCore/qdebug.h>
+
+#include <math.h>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,EaseFollow,QmlEaseFollow);
+
+class QmlEaseFollowPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlEaseFollow)
+public:
+ QmlEaseFollowPrivate()
+ : source(0), velocity(200), duration(-1), maximumEasingTime(-1),
+ reversingMode(QmlEaseFollow::Eased), initialVelocity(0),
+ initialValue(0), invert(false), enabled(true), trackVelocity(0), clockOffset(0),
+ lastTick(0), clock(this)
+ {}
+
+ qreal source;
+ qreal velocity;
+ qreal duration;
+ qreal maximumEasingTime;
+ QmlEaseFollow::ReversingMode reversingMode;
+
+ qreal initialVelocity;
+ qreal initialValue;
+ bool invert;
+ bool enabled;
+
+ qreal trackVelocity;
+
+ QmlMetaProperty target;
+
+ int clockOffset;
+ int lastTick;
+ void tick(int);
+ void clockStart();
+ void clockStop();
+ QTickAnimationProxy<QmlEaseFollowPrivate, &QmlEaseFollowPrivate::tick> clock;
+
+ void restart();
+
+ // Parameters for use in tick()
+ qreal a; // Acceleration
+ qreal d; // Deceleration
+ qreal tf; // Total time
+ qreal tp; // Time at which peak velocity occurs
+ qreal td; // Time at which decelleration begins
+ qreal vp; // Velocity at tp
+ qreal sp; // Displacement at tp
+ qreal sd; // Displacement at td
+ qreal vi; // "Normalized" initialvelocity
+ bool recalc();
+};
+
+bool QmlEaseFollowPrivate::recalc()
+{
+ qreal s = source - initialValue;
+ vi = initialVelocity;
+
+ s = (invert?-1.0:1.0) * s;
+ vi = (invert?-1.0:1.0) * vi;
+
+ if (duration > 0 && velocity > 0) {
+ tf = s / velocity;
+ if (tf > (duration / 1000.)) tf = (duration / 1000.);
+ } else if (duration > 0) {
+ tf = duration / 1000.;
+ } else if (velocity > 0) {
+ tf = s / velocity;
+ } else {
+ return false;
+ }
+
+ 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.;
+ td = tf - met;
+
+ qreal c1 = td;
+ qreal c2 = (tf - td) * vi - tf * velocity;
+ qreal c3 = -0.5 * (tf - td) * vi * vi;
+
+ qreal vp1 = (-c2 + sqrt(c2 * c2 - 4 * c1 * c3)) / (2. * c1);
+ // qreal vp2 = (-c2 - sqrt(c2 * c2 - 4 * c1 * c3)) / (2. * c1);
+
+ vp = vp1;
+ a = vp / met;
+ d = a;
+ tp = (vp - vi) / a;
+ sp = vi * tp + 0.5 * a * tp * tp;
+ sd = sp + (td - tp) * vp;
+ } 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 a2 = (-c2 - sqrt(c2 * c2 - 4 * c1 * c3)) / (2. * c1);
+
+ qreal tp1 = 0.5 * tf - 0.5 * vi / a1;
+ //qreal tp2 = 0.5 * tf - 0.5 * vi / a2;
+ qreal vp1 = a1 * tp1 + vi;
+ //qreal vp2 = a2 * tp2 + vi;
+
+ qreal sp1 = 0.5 * a1 * tp1 * tp1 + vi * tp1;
+ //qreal sp2 = 0.5 * a2 * tp2 * tp2 + vi * tp2;
+
+ a = a1;
+ d = a1;
+ tp = tp1;
+ td = tp1;
+ vp = vp1;
+ sp = sp1;
+ sd = sp1;
+ }
+
+ /*
+ qWarning() << "a:" << a << "tf:" << tf << "tp:" << tp << "vp:"
+ << vp << "sp:" << sp << "vi:" << vi << "invert:" << invert;
+ */
+ return true;
+}
+
+void QmlEaseFollowPrivate::clockStart()
+{
+ if (clock.state() == QAbstractAnimation::Running) {
+ clockOffset = lastTick;
+ return;
+ } else {
+ clockOffset = 0;
+ lastTick = 0;
+ clock.start();
+ }
+}
+
+void QmlEaseFollowPrivate::clockStop()
+{
+ clockOffset = 0;
+ lastTick = 0;
+ clock.stop();
+}
+
+void QmlEaseFollowPrivate::tick(int t)
+{
+ lastTick = t;
+ t -= clockOffset;
+
+ qreal time_seconds = qreal(t) / 1000.;
+
+ qreal out = 0;
+ if (time_seconds < tp) {
+
+ trackVelocity = vi + time_seconds * a;
+ trackVelocity = (invert?-1.0:1.0) * trackVelocity;
+
+ qreal value = 0.5 * a * time_seconds * time_seconds + vi * time_seconds;
+ value = (invert?-1.0:1.0) * value;
+ target.write(initialValue + value);
+ out = initialValue + value;
+ } else if (time_seconds < td) {
+
+ time_seconds -= tp;
+ trackVelocity = (invert?-1.0:1.0) * vp;
+ qreal value = sp + time_seconds * vp;
+ value = (invert?-1.0:1.0) * value;
+
+ target.write(initialValue + value);
+
+ out = initialValue + value;
+ } else if (time_seconds < tf) {
+
+ time_seconds -= td;
+
+ trackVelocity = vp - time_seconds * a;
+ trackVelocity = (invert?-1.0:1.0) * trackVelocity;
+
+ qreal value = sd - 0.5 * d * time_seconds * time_seconds + vp * time_seconds;
+ value = (invert?-1.0:1.0) * value;
+
+ target.write(initialValue + value);
+
+ out = initialValue + value;
+ } else {
+
+ clock.stop();
+
+ trackVelocity = 0;
+ target.write(source);
+ }
+
+ //qWarning() << out << trackVelocity << t << a;
+}
+
+/*!
+ \qmlclass EaseFollow QmlEaseFollow
+ \brief The EaseFollow element allows a property to smoothly track a value.
+
+ The EaseFollow smoothly animates a property's value to a set target value
+ using an ease in/out quad easing curve. If the target value changes while
+ the animation is in progress, the easing curves used to animate to the old
+ and the new target values are spliced together to avoid any obvious visual
+ glitches.
+
+ The property animation is configured by setting the velocity at which the
+ animation should occur, or the duration that the animation should take.
+ If both a velocity and a 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 follow example shows one rectangle tracking the position of another.
+\code
+import Qt 4.6
+
+Rectangle {
+ width: 800; height: 600; color: "blue"
+
+ Rectangle {
+ color: "green"
+ width: 60; height: 60;
+ x: -5; y: -5;
+ x: EaseFollow { source: rect1.x - 5; velocity: 200 }
+ y: EaseFollow { source: rect1.y - 5; velocity: 200 }
+ }
+
+ Rectangle {
+ id: rect1
+ color: "red"
+ width: 50; height: 50;
+ }
+
+ focus: true
+ Keys.onRightPressed: rect1.x = rect1.x + 100
+ Keys.onLeftPressed: rect1.x = rect1.x - 100
+ Keys.onUpPressed: rect1.y = rect1.y - 100
+ Keys.onDownPressed: rect1.y = rect1.y + 100
+}
+\endcode
+
+ \sa SpringFollow
+*/
+
+QmlEaseFollow::QmlEaseFollow(QObject *parent)
+: QObject(*(new QmlEaseFollowPrivate), parent)
+{
+}
+
+QmlEaseFollow::~QmlEaseFollow()
+{
+}
+
+/*!
+ \qmlproperty qreal EaseFollow::source
+ This property holds the source value which will be tracked.
+
+ Bind to a property in order to track its changes.
+*/
+qreal QmlEaseFollow::sourceValue() const
+{
+ Q_D(const QmlEaseFollow);
+ return d->source;
+}
+
+/*!
+ \qmlproperty enumeration EaseFollow::reversingMode
+
+ Sets how the EaseFollow behaves if an animation direction is reversed.
+
+ If reversing mode is \c Eased, the animation will smoothly decelerate, and
+ then reverse direction. If the reversing mode is \c Immediate, the
+ animation will immediately begin accelerating in the reverse direction,
+ begining with a velocity of 0. If the reversing mode is \c Sync, the
+ property is immediately set to the target value.
+*/
+QmlEaseFollow::ReversingMode QmlEaseFollow::reversingMode() const
+{
+ Q_D(const QmlEaseFollow);
+ return d->reversingMode;
+}
+
+void QmlEaseFollow::setReversingMode(ReversingMode m)
+{
+ Q_D(QmlEaseFollow);
+ if (d->reversingMode == m)
+ return;
+
+ d->reversingMode = m;
+ emit reversingModeChanged();
+}
+
+void QmlEaseFollowPrivate::restart()
+{
+ if (!enabled || velocity == 0) {
+ clockStop();
+ return;
+ }
+
+ initialValue = target.read().toReal();
+
+ if (source == initialValue) {
+ clockStop();
+ return;
+ }
+
+ bool hasReversed = trackVelocity != 0. &&
+ ((trackVelocity > 0) == ((initialValue - source) > 0));
+
+ if (hasReversed) {
+ switch (reversingMode) {
+ default:
+ case QmlEaseFollow::Eased:
+ break;
+ case QmlEaseFollow::Sync:
+ target.write(source);
+ return;
+ case QmlEaseFollow::Immediate:
+ initialVelocity = 0;
+ clockStop();
+ break;
+ }
+ }
+
+ trackVelocity = initialVelocity;
+
+ invert = (source < initialValue);
+
+ if (!recalc()) {
+ target.write(source);
+ clockStop();
+ return;
+ }
+
+ clockStart();
+}
+
+void QmlEaseFollow::setSourceValue(qreal s)
+{
+ Q_D(QmlEaseFollow);
+
+ if (d->clock.state() == QAbstractAnimation::Running && d->source == s)
+ return;
+
+ d->source = s;
+ d->initialVelocity = d->trackVelocity;
+ d->restart();
+
+ emit sourceChanged();
+}
+
+/*!
+ \qmlproperty qreal EaseFollow::duration
+
+ This property holds the animation duration used when tracking the source.
+
+ Setting this to -1 disables the duration value.
+*/
+qreal QmlEaseFollow::duration() const
+{
+ Q_D(const QmlEaseFollow);
+ return d->duration;
+}
+
+void QmlEaseFollow::setDuration(qreal v)
+{
+ Q_D(QmlEaseFollow);
+ if (d->duration == v)
+ return;
+
+ d->duration = v;
+ d->trackVelocity = 0;
+
+ if (d->clock.state() == QAbstractAnimation::Running)
+ d->restart();
+
+ emit durationChanged();
+}
+
+qreal QmlEaseFollow::velocity() const
+{
+ Q_D(const QmlEaseFollow);
+ return d->velocity;
+}
+
+/*!
+ \qmlproperty qreal EaseFollow::velocity
+
+ This property holds the average velocity allowed when tracking the source.
+
+ Setting this to -1 disables the velocity value.
+*/
+void QmlEaseFollow::setVelocity(qreal v)
+{
+ Q_D(QmlEaseFollow);
+ if (d->velocity == v)
+ return;
+
+ d->velocity = v;
+ d->trackVelocity = 0;
+
+ if (d->clock.state() == QAbstractAnimation::Running)
+ d->restart();
+
+ emit velocityChanged();
+}
+
+/*!
+ \qmlproperty bool EaseFollow::enabled
+ This property holds whether the target will track the source.
+*/
+bool QmlEaseFollow::enabled() const
+{
+ Q_D(const QmlEaseFollow);
+ return d->enabled;
+}
+
+void QmlEaseFollow::setEnabled(bool enabled)
+{
+ Q_D(QmlEaseFollow);
+ if (d->enabled == enabled)
+ return;
+
+ d->enabled = enabled;
+ if (enabled)
+ d->restart();
+ else
+ d->clockStop();
+
+ emit enabledChanged();
+}
+
+void QmlEaseFollow::setTarget(const QmlMetaProperty &t)
+{
+ Q_D(QmlEaseFollow);
+ d->target = t;
+}
+
+/*!
+\qmlproperty qreal EaseFollow::maximumEasingTime
+
+This property specifies the maximum time an "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.
+*/
+qreal QmlEaseFollow::maximumEasingTime() const
+{
+ Q_D(const QmlEaseFollow);
+ return d->maximumEasingTime;
+}
+
+void QmlEaseFollow::setMaximumEasingTime(qreal v)
+{
+ Q_D(QmlEaseFollow);
+ d->maximumEasingTime = v;
+
+ if (d->clock.state() == QAbstractAnimation::Running)
+ d->restart();
+
+ emit maximumEasingTimeChanged();
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmleasefollow_p.h b/src/declarative/util/qmleasefollow_p.h
new file mode 100644
index 0000000..ef095a3
--- /dev/null
+++ b/src/declarative/util/qmleasefollow_p.h
@@ -0,0 +1,114 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLEASEFOLLOW_H
+#define QMLEASEFOLLOW_H
+
+#include <qml.h>
+#include <qmlpropertyvaluesource.h>
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlMetaProperty;
+class QmlEaseFollowPrivate;
+class Q_DECLARATIVE_EXPORT QmlEaseFollow : public QObject,
+ public QmlPropertyValueSource
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlEaseFollow)
+ Q_INTERFACES(QmlPropertyValueSource)
+ Q_ENUMS(ReversingMode)
+
+ Q_PROPERTY(qreal source READ sourceValue WRITE setSourceValue NOTIFY sourceChanged)
+ Q_PROPERTY(qreal velocity READ velocity WRITE setVelocity NOTIFY velocityChanged)
+ Q_PROPERTY(qreal duration READ duration WRITE setDuration NOTIFY durationChanged)
+ Q_PROPERTY(ReversingMode reversingMode READ reversingMode WRITE setReversingMode NOTIFY reversingModeChanged)
+ Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
+ Q_PROPERTY(qreal maximumEasingTime READ maximumEasingTime WRITE setMaximumEasingTime NOTIFY maximumEasingTimeChanged)
+
+public:
+ enum ReversingMode { Eased, Immediate, Sync };
+
+ QmlEaseFollow(QObject *parent = 0);
+ ~QmlEaseFollow();
+
+ ReversingMode reversingMode() const;
+ void setReversingMode(ReversingMode);
+
+ qreal sourceValue() const;
+ void setSourceValue(qreal);
+
+ qreal velocity() const;
+ void setVelocity(qreal);
+
+ qreal duration() const;
+ void setDuration(qreal);
+
+ bool enabled() const;
+ void setEnabled(bool enabled);
+
+ qreal maximumEasingTime() const;
+ void setMaximumEasingTime(qreal);
+
+ virtual void setTarget(const QmlMetaProperty &);
+
+Q_SIGNALS:
+ void sourceChanged();
+ void velocityChanged();
+ void durationChanged();
+ void reversingModeChanged();
+ void enabledChanged();
+ void maximumEasingTimeChanged();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlEaseFollow);
+
+QT_END_HEADER
+
+#endif // QMLEASEFOLLOW_H
diff --git a/src/declarative/util/qmlfontloader.cpp b/src/declarative/util/qmlfontloader.cpp
new file mode 100644
index 0000000..b56043b
--- /dev/null
+++ b/src/declarative/util/qmlfontloader.cpp
@@ -0,0 +1,229 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlfontloader_p.h"
+
+#include <qmlcontext.h>
+#include <qmlengine.h>
+
+#include <QUrl>
+#include <QDebug>
+#include <QNetworkRequest>
+#include <QNetworkReply>
+#include <QFile>
+#include <QFontDatabase>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlFontLoaderPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlFontLoader)
+
+public:
+ QmlFontLoaderPrivate() : reply(0), status(QmlFontLoader::Null) {}
+
+ void addFontToDatabase(const QByteArray &);
+
+ QUrl url;
+ QString name;
+ QNetworkReply *reply;
+ QmlFontLoader::Status status;
+};
+
+QML_DEFINE_TYPE(Qt,4,6,FontLoader,QmlFontLoader)
+
+/*!
+ \qmlclass FontLoader QmlFontLoader
+ \ingroup group_utility
+ \brief This item allows using fonts by name or url.
+
+ Example:
+ \qml
+ 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
+*/
+QmlFontLoader::QmlFontLoader(QObject *parent)
+ : QObject(*(new QmlFontLoaderPrivate), parent)
+{
+}
+
+QmlFontLoader::~QmlFontLoader()
+{
+}
+
+static QString toLocalFileOrQrc(const QUrl& url)
+{
+ QString r = url.toLocalFile();
+ if (r.isEmpty() && url.scheme() == QLatin1String("qrc"))
+ r = QLatin1Char(':') + url.path();
+ return r;
+}
+
+
+/*!
+ \qmlproperty url FontLoader::source
+ The url of the font to load.
+*/
+QUrl QmlFontLoader::source() const
+{
+ Q_D(const QmlFontLoader);
+ return d->url;
+}
+
+void QmlFontLoader::setSource(const QUrl &url)
+{
+ Q_D(QmlFontLoader);
+ if (url == d->url)
+ return;
+ d->url = qmlContext(this)->resolvedUrl(url);
+
+ d->status = Loading;
+ emit statusChanged();
+#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
+ QString lf = toLocalFileOrQrc(d->url);
+ if (!lf.isEmpty()) {
+ int id = QFontDatabase::addApplicationFont(lf);
+ if (id != -1) {
+ d->name = QFontDatabase::applicationFontFamilies(id).at(0);
+ emit nameChanged();
+ d->status = QmlFontLoader::Ready;
+ } else {
+ d->status = QmlFontLoader::Error;
+ qWarning() << "Cannot load font:" << url;
+ }
+ emit statusChanged();
+ } else
+#endif
+ {
+ QNetworkRequest req(d->url);
+ req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
+ d->reply = qmlEngine(this)->networkAccessManager()->get(req);
+ QObject::connect(d->reply, SIGNAL(finished()), this, SLOT(replyFinished()));
+ }
+}
+
+/*!
+ \qmlproperty string 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
+ FontLoader { id: webFont; source: "http://www.mysite.com/myfont.ttf" }
+ Text { text: "Fancy font"; font.family: webFont.name }
+ \endqml
+*/
+QString QmlFontLoader::name() const
+{
+ Q_D(const QmlFontLoader);
+ return d->name;
+}
+
+void QmlFontLoader::setName(const QString &name)
+{
+ Q_D(QmlFontLoader);
+ if (d->name == name )
+ return;
+ d->name = name;
+ emit nameChanged();
+ d->status = Ready;
+ emit statusChanged();
+}
+
+/*!
+ \qmlproperty enum FontLoader::status
+
+ This property holds the status of font loading. It can be one of:
+ \list
+ \o Null - no font has been set
+ \o Ready - the font has been loaded
+ \o Loading - the font is currently being loaded
+ \o Error - an error occurred while loading the font
+ \endlist
+*/
+QmlFontLoader::Status QmlFontLoader::status() const
+{
+ Q_D(const QmlFontLoader);
+ return d->status;
+}
+
+void QmlFontLoader::replyFinished()
+{
+ Q_D(QmlFontLoader);
+ if (d->reply) {
+ if (!d->reply->error()) {
+ QByteArray ba = d->reply->readAll();
+ d->addFontToDatabase(ba);
+ } else {
+ d->status = Error;
+ emit statusChanged();
+ }
+ d->reply->deleteLater();
+ d->reply = 0;
+ }
+}
+
+void QmlFontLoaderPrivate::addFontToDatabase(const QByteArray &ba)
+{
+ Q_Q(QmlFontLoader);
+
+ int id = QFontDatabase::addApplicationFontFromData(ba);
+ if (id != -1) {
+ name = QFontDatabase::applicationFontFamilies(id).at(0);
+ emit q->nameChanged();
+ status = QmlFontLoader::Ready;
+ } else {
+ status = QmlFontLoader::Error;
+ qWarning() << "Cannot load font:" << url;
+ }
+ emit q->statusChanged();
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlfontloader_p.h b/src/declarative/util/qmlfontloader_p.h
new file mode 100644
index 0000000..aac8a71
--- /dev/null
+++ b/src/declarative/util/qmlfontloader_p.h
@@ -0,0 +1,95 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLFONTLOADER_H
+#define QMLFONTLOADER_H
+
+#include <qml.h>
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlFontLoaderPrivate;
+class Q_DECLARATIVE_EXPORT QmlFontLoader : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlFontLoader)
+ 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 };
+
+ QmlFontLoader(QObject *parent = 0);
+ ~QmlFontLoader();
+
+ QUrl source() const;
+ void setSource(const QUrl &url);
+
+ QString name() const;
+ void setName(const QString &name);
+
+ Status status() const;
+
+private Q_SLOTS:
+ void replyFinished();
+
+Q_SIGNALS:
+ void nameChanged();
+ void statusChanged();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlFontLoader)
+
+QT_END_HEADER
+
+#endif // QMLFONTLOADER_H
+
diff --git a/src/declarative/util/qmllistaccessor.cpp b/src/declarative/util/qmllistaccessor.cpp
new file mode 100644
index 0000000..6658949
--- /dev/null
+++ b/src/declarative/util/qmllistaccessor.cpp
@@ -0,0 +1,260 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmllistaccessor_p.h"
+
+#include <qmlmetatype.h>
+
+#include <QStringList>
+#include <QtCore/qdebug.h>
+
+// ### Remove me
+#include <qmlengine_p.h>
+
+QT_BEGIN_NAMESPACE
+
+QmlListAccessor::QmlListAccessor()
+: m_type(Invalid)
+{
+}
+
+QmlListAccessor::~QmlListAccessor()
+{
+}
+
+QVariant QmlListAccessor::list() const
+{
+ return d;
+}
+
+void QmlListAccessor::setList(const QVariant &v, QmlEngine *engine)
+{
+ d = v;
+
+ QmlEnginePrivate *enginePrivate = engine?QmlEnginePrivate::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 && QmlMetaType::isQObject(d.userType())) ||
+ (enginePrivate && enginePrivate->isQObject(d.userType()))) {
+ QObject *data = enginePrivate?enginePrivate->toQObject(v):QmlMetaType::toQObject(v);
+ d = QVariant::fromValue(data);
+ m_type = Instance;
+ } else if ((!enginePrivate && QmlMetaType::isQmlList(d.userType())) ||
+ (enginePrivate && enginePrivate->isQmlList(d.userType()))) {
+ m_type = QmlList;
+ } else if (QmlMetaType::isList(d.userType())) {
+ m_type = QListPtr;
+ } else {
+ m_type = Instance;
+ }
+}
+
+int QmlListAccessor::count() const
+{
+ switch(m_type) {
+ case StringList:
+ return qvariant_cast<QStringList>(d).count();
+ case VariantList:
+ return qvariant_cast<QVariantList>(d).count();
+ case QmlList:
+ {
+ QmlPrivate::ListInterface *li = *(QmlPrivate::ListInterface **)d.constData();
+ return li->count();
+ }
+ case QListPtr:
+ {
+ QList<void *> *li = *(QList<void *> **)d.constData();
+ return li->count();
+ }
+ case Instance:
+ return 1;
+ case Integer:
+ return d.toInt();
+ default:
+ case Invalid:
+ return 0;
+ }
+}
+
+QVariant QmlListAccessor::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 QmlList:
+ {
+ QmlPrivate::ListInterface *li = *(QmlPrivate::ListInterface **)d.constData();
+ void *ptr[1];
+ li->at(idx, ptr);
+ return QVariant::fromValue((QObject*)ptr[0]);
+ }
+ case QListPtr:
+ {
+ QList<void *> *li = *(QList<void *> **)d.constData();
+ void *ptr = li->at(idx);
+ return QVariant::fromValue((QObject*)ptr);
+ }
+ case Instance:
+ return d;
+ case Integer:
+ return QVariant(idx);
+ default:
+ case Invalid:
+ return QVariant();
+ }
+}
+
+bool QmlListAccessor::append(const QVariant &value)
+{
+ switch(m_type) {
+ case QmlList:
+ {
+ QmlPrivate::ListInterface *li = *(QmlPrivate::ListInterface **)d.constData();
+ li->append(const_cast<void *>(value.constData())); //XXX Typesafety
+ return true;
+ }
+ case QListPtr:
+ {
+ QList<void *> *li = *(QList<void *> **)d.constData();
+ li->append(*reinterpret_cast<void **>(const_cast<void *>(value.constData()))); //XXX Typesafety
+ return true;
+ }
+ case StringList:
+ case VariantList:
+ case Invalid:
+ case Instance:
+ case Integer:
+ default:
+ return false;
+ }
+}
+
+bool QmlListAccessor::insert(int index, const QVariant &value)
+{
+ switch(m_type) {
+ case QmlList:
+ {
+ QmlPrivate::ListInterface *li = *(QmlPrivate::ListInterface **)d.constData();
+ li->insert(index, const_cast<void *>(value.constData())); //XXX Typesafety
+ return true;
+ }
+ case QListPtr:
+ {
+ QList<void *> *li = *(QList<void *>**)d.constData();
+ li->insert(index, *reinterpret_cast<void **>(const_cast<void *>(value.constData()))); //XXX Typesafety
+ return true;
+ }
+ case StringList:
+ case VariantList:
+ case Invalid:
+ case Instance:
+ case Integer:
+ default:
+ return false;
+ }
+}
+
+bool QmlListAccessor::removeAt(int index)
+{
+ switch(m_type) {
+ case QmlList:
+ {
+ QmlPrivate::ListInterface *li = *(QmlPrivate::ListInterface **)d.constData();
+ li->removeAt(index);
+ return true;
+ }
+ case QListPtr:
+ {
+ QList<void *> *li = *(QList<void *>**)d.constData();
+ li->removeAt(index);
+ return true;
+ }
+ case StringList:
+ case VariantList:
+ case Invalid:
+ case Instance:
+ case Integer:
+ default:
+ return false;
+ }
+}
+
+bool QmlListAccessor::clear()
+{
+ switch(m_type) {
+ case QmlList:
+ {
+ QmlPrivate::ListInterface *li = *(QmlPrivate::ListInterface **)d.constData();
+ li->clear();
+ return true;
+ }
+ case QListPtr:
+ {
+ QList<void *> *li = *(QList<void *>**)d.constData();
+ li->clear();
+ return true;
+ }
+ case StringList:
+ case VariantList:
+ case Invalid:
+ case Instance:
+ case Integer:
+ default:
+ return false;
+ }
+}
+
+bool QmlListAccessor::isValid() const
+{
+ return m_type != Invalid;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmllistaccessor_p.h b/src/declarative/util/qmllistaccessor_p.h
new file mode 100644
index 0000000..3c67e3a
--- /dev/null
+++ b/src/declarative/util/qmllistaccessor_p.h
@@ -0,0 +1,85 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLLISTACCESSOR_H
+#define QMLLISTACCESSOR_H
+
+#include <QtCore/QVariant>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlEngine;
+class Q_DECLARATIVE_EXPORT QmlListAccessor
+{
+public:
+ QmlListAccessor();
+ ~QmlListAccessor();
+
+ QVariant list() const;
+ void setList(const QVariant &, QmlEngine * = 0);
+
+ bool isValid() const;
+
+ int count() const;
+ QVariant at(int) const;
+
+ bool append(const QVariant &);
+ bool insert(int, const QVariant &);
+ bool removeAt(int);
+ bool clear();
+
+ enum Type { Invalid, StringList, VariantList, QmlList, QListPtr, Instance, Integer };
+ Type type() const { return m_type; }
+
+private:
+ Type m_type;
+ QVariant d;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLLISTACCESSOR_H
diff --git a/src/declarative/util/qmllistmodel.cpp b/src/declarative/util/qmllistmodel.cpp
new file mode 100644
index 0000000..61fc50d
--- /dev/null
+++ b/src/declarative/util/qmllistmodel.cpp
@@ -0,0 +1,990 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmllistmodel_p.h"
+
+#include "qmlopenmetaobject_p.h"
+
+#include <qmlcustomparser_p.h>
+#include <qmlparser_p.h>
+#include <qmlengine_p.h>
+#include <qmlcontext.h>
+#include <qmlinfo.h>
+
+#include <QtCore/qdebug.h>
+#include <QtCore/qstack.h>
+#include <QXmlStreamReader>
+#include <QtScript/qscriptvalueiterator.h>
+
+Q_DECLARE_METATYPE(QListModelInterface *)
+
+QT_BEGIN_NAMESPACE
+
+#define DATA_ROLE_ID 1
+#define DATA_ROLE_NAME "data"
+
+struct ListInstruction
+{
+ enum { Push, Pop, Value, Set } type;
+ int dataIdx;
+};
+
+struct ListModelData
+{
+ int dataOffset;
+ int instrCount;
+ ListInstruction *instructions() const { return (ListInstruction *)((char *)this + sizeof(ListModelData)); }
+};
+
+static void dump(ModelNode *node, int ind);
+
+/*!
+ \qmlclass ListModel QmlListModel
+ \brief The ListModel element defines a free-form list data source.
+
+ The ListModel is a simple hierarchy of elements containing data roles. The contents can
+ be defined dynamically, or explicitly in QML:
+
+ For example:
+
+ \code
+ ListModel {
+ id: fruitModel
+ ListElement {
+ name: "Apple"
+ cost: 2.45
+ }
+ ListElement {
+ name: "Orange"
+ cost: 3.25
+ }
+ ListElement {
+ name: "Banana"
+ cost: 1.95
+ }
+ }
+ \endcode
+
+ Roles (properties) must begin with a lower-case letter. The above example defines a
+ ListModel containing three elements, with the roles "name" and "cost".
+
+ The defined model can be used in views such as ListView:
+ \code
+ Component {
+ id: fruitDelegate
+ Item {
+ width: 200; height: 50
+ Text { text: name }
+ Text { text: '$'+cost; anchors.right: parent.right }
+ }
+ }
+
+ ListView {
+ model: fruitModel
+ delegate: fruitDelegate
+ anchors.fill: parent
+ }
+ \endcode
+
+ It is possible for roles to contain list data. In the example below we create a list of fruit attributes:
+
+ \code
+ ListModel {
+ id: fruitModel
+ ListElement {
+ name: "Apple"
+ cost: 2.45
+ attributes: [
+ ListElement { description: "Core" },
+ ListElement { description: "Deciduous" }
+ ]
+ }
+ ListElement {
+ name: "Orange"
+ cost: 3.25
+ attributes: [
+ ListElement { description: "Citrus" }
+ ]
+ }
+ ListElement {
+ name: "Banana"
+ cost: 1.95
+ attributes: [
+ ListElement { description: "Tropical" },
+ ListElement { description: "Seedless" }
+ ]
+ }
+ }
+ \endcode
+
+ The delegate below will list all the fruit attributes:
+ \code
+ Component {
+ id: fruitDelegate
+ Item {
+ width: 200; height: 50
+ Text { id: name; text: name }
+ Text { text: '$'+cost; anchors.right: parent.right }
+ Row {
+ anchors.top: name.bottom
+ spacing: 5
+ Text { text: "Attributes:" }
+ Repeater {
+ dataSource: attributes
+ Component { Text { text: description } }
+ }
+ }
+ }
+ }
+ \endcode
+
+ The content of a ListModel may be created and modified using the clear(),
+ append(), and set() methods. For example:
+
+ \code
+ Component {
+ id: fruitDelegate
+ Item {
+ width: 200; height: 50
+ Text { text: name }
+ Text { text: '$'+cost; anchors.right: parent.right }
+
+ // Double the price when clicked.
+ MouseRegion {
+ anchors.fill: parent
+ onClicked: fruitModel.set(index, "cost", cost*2)
+ }
+ }
+ }
+ \endcode
+
+ When creating content dynamically, note that the set of available properties cannot be changed
+ except by first clearing the model - whatever properties are first added are then the
+ only permitted properties in the model.
+
+ \sa {qmlmodels}{Data Models}
+*/
+
+class ModelObject : public QObject
+{
+ Q_OBJECT
+public:
+ ModelObject();
+
+ void setValue(const QByteArray &name, const QVariant &val)
+ {
+ _mo->setValue(name, val);
+ }
+
+private:
+ QmlOpenMetaObject *_mo;
+};
+
+struct ModelNode
+{
+ ModelNode();
+ ~ModelNode();
+
+ QList<QVariant> values;
+ QHash<QString, ModelNode *> properties;
+
+ QmlListModel *model(const QmlListModel *parent) {
+ if (!modelCache) {
+ modelCache = new QmlListModel;
+ QmlEngine::setContextForObject(modelCache,QmlEngine::contextForObject(parent));
+
+ modelCache->_root = this;
+ }
+ return modelCache;
+ }
+
+ ModelObject *object(const QmlListModel *parent) {
+ if (!objectCache) {
+ objectCache = new ModelObject();
+ QHash<QString, ModelNode *>::iterator it;
+ for (it = properties.begin(); it != properties.end(); ++it) {
+ objectCache->setValue(it.key().toUtf8(), parent->valueForNode(*it));
+ }
+ }
+ return objectCache;
+ }
+
+ void setObjectValue(const QScriptValue& valuemap);
+ void setListValue(const QScriptValue& valuelist);
+
+ void setProperty(const QString& prop, const QVariant& val) {
+ QHash<QString, ModelNode *>::const_iterator it = properties.find(prop);
+ if (it != properties.end()) {
+ (*it)->values[0] = val;
+ } else {
+ ModelNode *n = new ModelNode;
+ n->values << val;
+ properties.insert(prop,n);
+ }
+ if (objectCache)
+ objectCache->setValue(prop.toUtf8(), val);
+ }
+
+ QmlListModel *modelCache;
+ ModelObject *objectCache;
+ bool isArray;
+};
+
+QT_END_NAMESPACE
+
+Q_DECLARE_METATYPE(ModelNode *)
+
+QT_BEGIN_NAMESPACE
+
+void ModelNode::setObjectValue(const QScriptValue& valuemap) {
+ QScriptValueIterator it(valuemap);
+ while (it.hasNext()) {
+ it.next();
+ ModelNode *value = new ModelNode;
+ QScriptValue v = it.value();
+ if (v.isArray()) {
+ value->isArray = true;
+ value->setListValue(v);
+ } else {
+ value->values << v.toVariant();
+ }
+ properties.insert(it.name(),value);
+ }
+}
+
+void ModelNode::setListValue(const QScriptValue& valuelist) {
+ QScriptValueIterator it(valuelist);
+ values.clear();
+ while (it.hasNext()) {
+ it.next();
+ ModelNode *value = new ModelNode;
+ QScriptValue v = it.value();
+ if (v.isArray()) {
+ value->isArray = true;
+ value->setListValue(v);
+ } else if (v.isObject()) {
+ value->setObjectValue(v);
+ } else {
+ value->values << v.toVariant();
+ }
+ values.append(qVariantFromValue(value));
+
+ }
+}
+
+
+ModelObject::ModelObject()
+: _mo(new QmlOpenMetaObject(this))
+{
+}
+
+QmlListModel::QmlListModel(QObject *parent)
+: QListModelInterface(parent), _rolesOk(false), _root(0)
+{
+}
+
+QmlListModel::~QmlListModel()
+{
+ delete _root;
+}
+
+void QmlListModel::checkRoles() const
+{
+ if (_rolesOk || !_root)
+ return;
+
+ for (int ii = 0; ii < _root->values.count(); ++ii) {
+ ModelNode *node = qvariant_cast<ModelNode *>(_root->values.at(ii));
+ if (node) {
+ foreach (const QString &role, node->properties.keys())
+ addRole(role);
+ }
+ }
+
+ _rolesOk = true;
+}
+
+void QmlListModel::addRole(const QString &role) const
+{
+ if (!roleStrings.contains(role))
+ roleStrings << role;
+}
+
+QList<int> QmlListModel::roles() const
+{
+ checkRoles();
+ QList<int> rv;
+ for (int ii = 0; ii < roleStrings.count(); ++ii)
+ rv << ii;
+ return rv;
+}
+
+QString QmlListModel::toString(int role) const
+{
+ checkRoles();
+ if (role < roleStrings.count())
+ return roleStrings.at(role);
+ else
+ return QString();
+}
+
+QVariant QmlListModel::valueForNode(ModelNode *node) const
+{
+ QObject *rv = 0;
+
+ if (node->isArray) {
+ // List
+ rv = node->model(this);
+ } else {
+ if (!node->properties.isEmpty()) {
+ // Object
+ rv = node->object(this);
+ } else if (node->values.count() == 0) {
+ // Invalid
+ return QVariant();
+ } else if (node->values.count() == 1) {
+ // Value
+ QVariant &var = node->values[0];
+ ModelNode *valueNode = qvariant_cast<ModelNode *>(var);
+ if (valueNode) {
+ if (!valueNode->properties.isEmpty())
+ rv = valueNode->object(this);
+ else
+ rv = valueNode->model(this);
+ } else {
+ return var;
+ }
+ }
+ }
+
+ if (rv)
+ return QVariant::fromValue(rv);
+ else
+ return QVariant();
+}
+
+QHash<int,QVariant> QmlListModel::data(int index, const QList<int> &roles) const
+{
+ checkRoles();
+ QHash<int, QVariant> rv;
+ if (index >= count() || index < 0)
+ return rv;
+
+ ModelNode *node = qvariant_cast<ModelNode *>(_root->values.at(index));
+ if (!node)
+ return rv;
+
+ for (int ii = 0; ii < roles.count(); ++ii) {
+ const QString &roleString = roleStrings.at(roles.at(ii));
+
+ QHash<QString, ModelNode *>::ConstIterator iter =
+ node->properties.find(roleString);
+ if (iter != node->properties.end()) {
+ ModelNode *row = *iter;
+ rv.insert(roles.at(ii), valueForNode(row));
+ }
+ }
+
+ return rv;
+}
+
+QVariant QmlListModel::data(int index, int role) const
+{
+ checkRoles();
+ QVariant rv;
+ if (index >= count() || index < 0)
+ return rv;
+
+ ModelNode *node = qvariant_cast<ModelNode *>(_root->values.at(index));
+ if (!node)
+ return rv;
+
+ const QString &roleString = roleStrings.at(role);
+
+ QHash<QString, ModelNode *>::ConstIterator iter =
+ node->properties.find(roleString);
+ if (iter != node->properties.end()) {
+ ModelNode *row = *iter;
+ rv = valueForNode(row);
+ }
+
+ return rv;
+}
+
+/*!
+ \qmlproperty int ListModel::count
+ The number of data entries in the model.
+*/
+int QmlListModel::count() const
+{
+ if (!_root) return 0;
+ return _root->values.count();
+}
+
+/*!
+ \qmlmethod ListModel::clear()
+
+ Deletes all content from the model. The properties are cleared such that
+ different properties may be set on subsequent additions.
+
+ \sa append() remove()
+*/
+void QmlListModel::clear()
+{
+ int cleared = count();
+ _rolesOk = false;
+ delete _root;
+ _root = 0;
+ roleStrings.clear();
+ emit itemsRemoved(0,cleared);
+ emit countChanged(0);
+}
+
+/*!
+ \qmlmethod ListModel::remove(int index)
+
+ Deletes the content at \a index from the model.
+
+ \sa clear()
+*/
+void QmlListModel::remove(int index)
+{
+ if (!_root || index < 0 || index >= _root->values.count()) {
+ qmlInfo(this) << tr("remove: index %1 out of range").arg(index);
+ return;
+ }
+
+ ModelNode *node = qvariant_cast<ModelNode *>(_root->values.at(index));
+ _root->values.removeAt(index);
+ if (node)
+ delete node;
+ emit itemsRemoved(index,1);
+ emit countChanged(_root->values.count());
+}
+
+/*!
+ \qmlmethod ListModel::insert(int index, jsobject dict)
+
+ Adds a new item to the list model at position \a index, with the
+ values in \a dict.
+
+ \code
+ FruitModel.insert(2, {"cost": 5.95, "name":"Pizza"})
+ \endcode
+
+ The \a index must be to an existing item in the list, or one past
+ the end of the list (equivalent to append).
+
+ \sa set() append()
+*/
+void QmlListModel::insert(int index, const QScriptValue& valuemap)
+{
+ if (!valuemap.isObject() || valuemap.isArray()) {
+ qmlInfo(this) << tr("insert: value is not an object");
+ return;
+ }
+ if (!_root)
+ _root = new ModelNode;
+ if (index >= _root->values.count() || index<0) {
+ if (index == _root->values.count())
+ append(valuemap);
+ else
+ qmlInfo(this) << tr("insert: index %1 out of range").arg(index);
+ return;
+ }
+ ModelNode *mn = new ModelNode;
+ mn->setObjectValue(valuemap);
+ _root->values.insert(index,qVariantFromValue(mn));
+ emit itemsInserted(index,1);
+ emit countChanged(_root->values.count());
+}
+
+/*!
+ \qmlmethod ListModel::move(int from, int to, int n)
+
+ Moves \a n items \a from one position \a to another.
+
+ The from and to ranges must exist; for example, to move the first 3 items
+ to the end of the list:
+
+ \code
+ FruitModel.move(0,FruitModel.count-3,3)
+ \endcode
+
+ \sa append()
+*/
+void QmlListModel::move(int from, int to, int n)
+{
+ if (n==0 || from==to)
+ return;
+ if (from+n > count() || to+n > count() || from < 0 || to < 0 || n < 0) {
+ qmlInfo(this) << tr("move: out of range");
+ return;
+ }
+ int origfrom=from; // preserve actual move, so any animations are correct
+ int origto=to;
+ int orign=n;
+ if (from > to) {
+ // Only move forwards - flip if backwards moving
+ int tfrom = from;
+ int tto = to;
+ from = tto;
+ to = tto+n;
+ n = tfrom-tto;
+ }
+ if (n==1) {
+ _root->values.move(from,to);
+ } else {
+ QList<QVariant> replaced;
+ int i=0;
+ QVariantList::const_iterator it=_root->values.begin(); it += from+n;
+ for (; i<to-from; ++i,++it)
+ replaced.append(*it);
+ i=0;
+ it=_root->values.begin(); it += from;
+ for (; i<n; ++i,++it)
+ replaced.append(*it);
+ QVariantList::const_iterator f=replaced.begin();
+ QVariantList::iterator t=_root->values.begin(); t += from;
+ for (; f != replaced.end(); ++f, ++t)
+ *t = *f;
+ }
+ emit itemsMoved(origfrom,origto,orign);
+}
+
+/*!
+ \qmlmethod ListModel::append(jsobject dict)
+
+ Adds a new item to the end of the list model, with the
+ values in \a dict.
+
+ \code
+ FruitModel.append({"cost": 5.95, "name":"Pizza"})
+ \endcode
+
+ \sa set() remove()
+*/
+void QmlListModel::append(const QScriptValue& valuemap)
+{
+ if (!valuemap.isObject() || valuemap.isArray()) {
+ qmlInfo(this) << tr("append: value is not an object");
+ return;
+ }
+ if (!_root)
+ _root = new ModelNode;
+ ModelNode *mn = new ModelNode;
+ mn->setObjectValue(valuemap);
+ _root->values << qVariantFromValue(mn);
+ emit itemsInserted(count()-1,1);
+ emit countChanged(_root->values.count());
+}
+
+/*!
+ \qmlmethod object ListModel::get(int index)
+
+ Returns the item at \a index in the list model.
+
+ \code
+ FruitModel.append({"cost": 5.95, "name":"Jackfruit"})
+ FruitModel.get(0).cost
+ \endcode
+
+ The \a index must be an element in the list.
+
+ Note that properties of the returned object that are themselves objects
+ will also be models, and this get() method is used to access elements:
+
+ \code
+ FruitModel.append(..., "attributes":
+ [{"name":"spikes","value":"7mm"},
+ {"name":"color","value":"green"}]);
+ FruitModel.get(0).attributes.get(1).value; // == "green"
+ \endcode
+
+ \sa append()
+*/
+QScriptValue QmlListModel::get(int index) const
+{
+ if (index >= count() || index < 0) {
+ qmlInfo(this) << tr("get: index %1 out of range").arg(index);
+ return 0;
+ }
+
+ ModelNode *node = qvariant_cast<ModelNode *>(_root->values.at(index));
+ if (!node)
+ return 0;
+ QmlEngine *eng = qmlEngine(this);
+ if (!eng) {
+ qWarning("Cannot call QmlListModel::get() without a QmlEngine");
+ return 0;
+ }
+ return QmlEnginePrivate::qmlScriptObject(node->object(this), eng);
+}
+
+/*!
+ \qmlmethod ListModel::set(int index, jsobject dict)
+
+ Changes the item at \a index in the list model with the
+ values in \a dict. Properties not appearing in \a valuemap
+ are left unchanged.
+
+ \code
+ FruitModel.set(3, {"cost": 5.95, "name":"Pizza"})
+ \endcode
+
+ The \a index must be an element in the list.
+
+ \sa append()
+*/
+void QmlListModel::set(int index, const QScriptValue& valuemap)
+{
+ if (!valuemap.isObject() || valuemap.isArray()) {
+ qmlInfo(this) << tr("set: value is not an object");
+ return;
+ }
+ if ( !_root || index > _root->values.count() || index < 0) {
+ qmlInfo(this) << tr("set: index %1 out of range").arg(index);
+ return;
+ }
+ if (index == _root->values.count())
+ append(valuemap);
+ else {
+ ModelNode *node = qvariant_cast<ModelNode *>(_root->values.at(index));
+ QList<int> roles;
+ node->setObjectValue(valuemap);
+ QScriptValueIterator it(valuemap);
+ while (it.hasNext()) {
+ it.next();
+ int r = roleStrings.indexOf(it.name());
+ if (r<0) {
+ r = roleStrings.count();
+ roleStrings << it.name();
+ }
+ roles.append(r);
+ }
+ emit itemsChanged(index,1,roles);
+ }
+}
+
+/*!
+ \qmlmethod ListModel::setProperty(int index, string property, variant value)
+
+ Changes the \a property of the item at \a index in the list model to \a value.
+
+ \code
+ FruitModel.set(3, "cost", 5.95)
+ \endcode
+
+ The \a index must be an element in the list.
+
+ \sa append()
+*/
+void QmlListModel::setProperty(int index, const QString& property, const QVariant& value)
+{
+ if ( !_root || index >= _root->values.count() || index < 0) {
+ qmlInfo(this) << tr("set: index %1 out of range").arg(index);
+ return;
+ }
+ ModelNode *node = qvariant_cast<ModelNode *>(_root->values.at(index));
+ int r = roleStrings.indexOf(property);
+ if (r<0) {
+ r = roleStrings.count();
+ roleStrings << property;
+ }
+ QList<int> roles;
+ roles.append(r);
+
+ if (node)
+ node->setProperty(property,value);
+ emit itemsChanged(index,1,roles);
+}
+
+class QmlListModelParser : public QmlCustomParser
+{
+public:
+ QByteArray compile(const QList<QmlCustomParserProperty> &);
+ bool compileProperty(const QmlCustomParserProperty &prop, QList<ListInstruction> &instr, QByteArray &data);
+ void setCustomData(QObject *, const QByteArray &);
+
+private:
+ bool definesEmptyList(const QString &);
+};
+
+bool QmlListModelParser::compileProperty(const QmlCustomParserProperty &prop, QList<ListInstruction> &instr, QByteArray &data)
+{
+ QList<QVariant> values = prop.assignedValues();
+ for(int ii = 0; ii < values.count(); ++ii) {
+ const QVariant &value = values.at(ii);
+
+ if(value.userType() == qMetaTypeId<QmlCustomParserNode>()) {
+ QmlCustomParserNode node =
+ qvariant_cast<QmlCustomParserNode>(value);
+
+ {
+ ListInstruction li;
+ li.type = ListInstruction::Push;
+ li.dataIdx = -1;
+ instr << li;
+ }
+
+ QList<QmlCustomParserProperty> props = node.properties();
+ for(int jj = 0; jj < props.count(); ++jj) {
+ const QmlCustomParserProperty &nodeProp = props.at(jj);
+ if (nodeProp.name() == "") {
+ error(nodeProp, QmlListModel::tr("ListElement: cannot use default property"));
+ return false;
+ }
+ if (nodeProp.name() == "id") {
+ error(nodeProp, QmlListModel::tr("ListElement: cannot use reserved \"id\" property"));
+ return false;
+ }
+
+ ListInstruction li;
+ int ref = data.count();
+ data.append(nodeProp.name());
+ data.append('\0');
+ li.type = ListInstruction::Set;
+ li.dataIdx = ref;
+ instr << li;
+
+ if(!compileProperty(nodeProp, instr, data))
+ return false;
+
+ li.type = ListInstruction::Pop;
+ li.dataIdx = -1;
+ instr << li;
+ }
+
+ {
+ ListInstruction li;
+ li.type = ListInstruction::Pop;
+ li.dataIdx = -1;
+ instr << li;
+ }
+
+ } else {
+
+ QmlParser::Variant variant =
+ qvariant_cast<QmlParser::Variant>(value);
+
+ int ref = data.count();
+ QByteArray d = variant.asScript().toUtf8();
+ d.append('\0');
+ data.append(d);
+
+ ListInstruction li;
+ li.type = ListInstruction::Value;
+ li.dataIdx = ref;
+ instr << li;
+
+ }
+ }
+
+ return true;
+}
+
+QByteArray QmlListModelParser::compile(const QList<QmlCustomParserProperty> &customProps)
+{
+ QList<ListInstruction> instr;
+ QByteArray data;
+
+ for(int ii = 0; ii < customProps.count(); ++ii) {
+ const QmlCustomParserProperty &prop = customProps.at(ii);
+ if(prop.name() != "") { // isn't default property
+ error(prop, QmlListModel::tr("ListModel: undefined property '%1'").arg(QString::fromUtf8(prop.name())));
+ return QByteArray();
+ }
+
+ if(!compileProperty(prop, instr, data)) {
+ return QByteArray();
+ }
+ }
+
+ int size = sizeof(ListModelData) +
+ instr.count() * sizeof(ListInstruction) +
+ data.count();
+
+ QByteArray rv;
+ rv.resize(size);
+
+ ListModelData *lmd = (ListModelData *)rv.data();
+ lmd->dataOffset = sizeof(ListModelData) +
+ instr.count() * sizeof(ListInstruction);
+ lmd->instrCount = instr.count();
+ for (int ii = 0; ii < instr.count(); ++ii)
+ lmd->instructions()[ii] = instr.at(ii);
+ ::memcpy(rv.data() + lmd->dataOffset, data.constData(), data.count());
+
+ return rv;
+}
+
+void QmlListModelParser::setCustomData(QObject *obj, const QByteArray &d)
+{
+ QmlListModel *rv = static_cast<QmlListModel *>(obj);
+
+ ModelNode *root = new ModelNode;
+ rv->_root = root;
+ QStack<ModelNode *> nodes;
+ nodes << root;
+
+ bool processingSet = false;
+
+ const ListModelData *lmd = (const ListModelData *)d.constData();
+ const char *data = ((const char *)lmd) + lmd->dataOffset;
+
+ for (int ii = 0; ii < lmd->instrCount; ++ii) {
+ const ListInstruction &instr = lmd->instructions()[ii];
+
+ switch(instr.type) {
+ case ListInstruction::Push:
+ {
+ ModelNode *n = nodes.top();
+ ModelNode *n2 = new ModelNode;
+ n->values << qVariantFromValue(n2);
+ nodes.push(n2);
+ if (processingSet)
+ n->isArray = true;
+ }
+ break;
+
+ case ListInstruction::Pop:
+ nodes.pop();
+ break;
+
+ case ListInstruction::Value:
+ {
+ ModelNode *n = nodes.top();
+ QString s = QString::fromUtf8(QByteArray(data + instr.dataIdx));
+
+ bool isEmptyList = false;
+ if (!n->isArray)
+ isEmptyList = definesEmptyList(s);
+ if (isEmptyList)
+ n->isArray = true;
+ else
+ n->values.append(s);
+
+ processingSet = false;
+ }
+ break;
+
+ case ListInstruction::Set:
+ {
+ ModelNode *n = nodes.top();
+ ModelNode *n2 = new ModelNode;
+ n->properties.insert(QString::fromUtf8(data + instr.dataIdx), n2);
+ nodes.push(n2);
+ processingSet = true;
+ }
+ break;
+ }
+ }
+}
+
+bool QmlListModelParser::definesEmptyList(const QString &s)
+{
+ if (s.startsWith(QLatin1Char('[')) && s.endsWith(QLatin1Char(']'))) {
+ for (int i=1; i<s.length()-1; i++) {
+ if (!s[i].isSpace())
+ return false;
+ }
+ return true;
+ }
+ return false;
+}
+
+QML_DEFINE_CUSTOM_TYPE(Qt, 4,6, ListModel, QmlListModel, QmlListModelParser)
+
+/*!
+ \qmlclass ListElement
+ \brief The ListElement element defines a data item in a ListModel.
+
+ \sa ListModel
+*/
+// ### FIXME
+class QmlListElement : public QObject
+{
+Q_OBJECT
+};
+QML_DEFINE_TYPE(Qt,4,6,ListElement,QmlListElement)
+
+static void dump(ModelNode *node, int ind)
+{
+ QByteArray indentBa(ind * 4, ' ');
+ const char *indent = indentBa.constData();
+
+ for (int ii = 0; ii < node->values.count(); ++ii) {
+ ModelNode *subNode = qvariant_cast<ModelNode *>(node->values.at(ii));
+ if (subNode) {
+ qWarning().nospace() << indent << "Sub-node " << ii;
+ dump(subNode, ind + 1);
+ } else {
+ qWarning().nospace() << indent << "Sub-node " << ii << ": " << node->values.at(ii).toString();
+ }
+ }
+
+ for (QHash<QString, ModelNode *>::ConstIterator iter = node->properties.begin(); iter != node->properties.end(); ++iter) {
+ qWarning().nospace() << indent << "Property " << iter.key() << ':';
+ dump(iter.value(), ind + 1);
+ }
+}
+
+ModelNode::ModelNode()
+: modelCache(0), objectCache(0), isArray(false)
+{
+}
+
+ModelNode::~ModelNode()
+{
+ qDeleteAll(properties);
+ for (int ii = 0; ii < values.count(); ++ii) {
+ ModelNode *node = qvariant_cast<ModelNode *>(values.at(ii));
+ if (node) { delete node; node = 0; }
+ }
+ if (modelCache) { modelCache->_root = 0/* ==this */; delete modelCache; modelCache = 0; }
+ if (objectCache) { delete objectCache; }
+}
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlListElement)
+
+#include <qmllistmodel.moc>
diff --git a/src/declarative/util/qmllistmodel_p.h b/src/declarative/util/qmllistmodel_p.h
new file mode 100644
index 0000000..e18d3fd
--- /dev/null
+++ b/src/declarative/util/qmllistmodel_p.h
@@ -0,0 +1,107 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLLISTMODEL_H
+#define QMLLISTMODEL_H
+
+#include <qml.h>
+
+#include <QtCore/QObject>
+#include <QtCore/QStringList>
+#include <QtCore/QHash>
+#include <QtCore/QList>
+#include <QtCore/QVariant>
+#include "../3rdparty/qlistmodelinterface_p.h"
+#include <QtScript/qscriptvalue.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+struct ModelNode;
+class Q_DECLARATIVE_EXPORT QmlListModel : public QListModelInterface
+{
+ Q_OBJECT
+ Q_PROPERTY(int count READ count NOTIFY countChanged)
+
+public:
+ QmlListModel(QObject *parent=0);
+ ~QmlListModel();
+
+ virtual QList<int> roles() const;
+ virtual QString toString(int role) const;
+ virtual int count() const;
+ virtual QHash<int,QVariant> data(int index, const QList<int> &roles = (QList<int>())) const;
+ virtual QVariant data(int index, int role) const;
+
+ Q_INVOKABLE void clear();
+ Q_INVOKABLE void remove(int index);
+ Q_INVOKABLE void append(const QScriptValue&);
+ Q_INVOKABLE void insert(int index, const QScriptValue&);
+ Q_INVOKABLE QScriptValue get(int index) const;
+ Q_INVOKABLE void set(int index, const QScriptValue&);
+ Q_INVOKABLE void setProperty(int index, const QString& property, const QVariant& value);
+ Q_INVOKABLE void move(int from, int to, int count);
+
+Q_SIGNALS:
+ void countChanged(int);
+
+private:
+ QVariant valueForNode(ModelNode *) const;
+ mutable QStringList roleStrings;
+ friend class QmlListModelParser;
+ friend struct ModelNode;
+
+ void checkRoles() const;
+ void addRole(const QString &) const;
+ mutable bool _rolesOk;
+ ModelNode *_root;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlListModel)
+
+QT_END_HEADER
+
+#endif // QMLLISTMODEL_H
diff --git a/src/declarative/util/qmlnullablevalue_p_p.h b/src/declarative/util/qmlnullablevalue_p_p.h
new file mode 100644
index 0000000..151a3d4
--- /dev/null
+++ b/src/declarative/util/qmlnullablevalue_p_p.h
@@ -0,0 +1,81 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLNULLABLEVALUE_P_H
+#define QMLNULLABLEVALUE_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.
+//
+
+QT_BEGIN_NAMESPACE
+
+template<typename T>
+struct QmlNullableValue
+{
+ QmlNullableValue()
+ : isNull(true), value(T()) {}
+ QmlNullableValue(const QmlNullableValue<T> &o)
+ : isNull(o.isNull), value(o.value) {}
+ QmlNullableValue(const T &t)
+ : isNull(false), value(t) {}
+ QmlNullableValue<T> &operator=(const T &t)
+ { isNull = false; value = t; return *this; }
+ QmlNullableValue<T> &operator=(const QmlNullableValue<T> &o)
+ { isNull = o.isNull; value = o.value; return *this; }
+ operator T() const { return value; }
+
+ void invalidate() { isNull = true; }
+ bool isValid() const { return !isNull; }
+ bool isNull;
+ T value;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLNULLABLEVALUE_P_H
diff --git a/src/declarative/util/qmlnumberformatter.cpp b/src/declarative/util/qmlnumberformatter.cpp
new file mode 100644
index 0000000..073dc68
--- /dev/null
+++ b/src/declarative/util/qmlnumberformatter.cpp
@@ -0,0 +1,260 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlnumberformatter_p.h"
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+//TODO: set locale
+// docs
+// this is a wrapper around qnumberformat (test integration)
+// if number or format haven't been explictly set, text should be an empty string
+
+class QmlNumberFormatterPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlNumberFormatter)
+public:
+ QmlNumberFormatterPrivate() : locale(QLocale::system()), number(0), componentComplete(true) {}
+
+ void updateText();
+
+ QLocale locale;
+ QString format;
+ QNumberFormat numberFormat;
+ QString text;
+ qreal number;
+ bool componentComplete;
+};
+/*!
+ \qmlclass NumberFormatter
+ \brief The NumberFormatter allows you to control the format of a number string.
+
+ The format property documentation has more details on how the format can be manipulated.
+
+ In the following example, the text element will display the text "1,234.57".
+ \code
+ NumberFormatter { id: formatter; number: 1234.5678; format: "##,##0.##" }
+ Text { text: formatter.text }
+ \endcode
+
+ */
+/*!
+ \internal
+ \class QmlNumberFormatter
+ \ingroup group_utility
+ \brief The QmlNumberFormatter class allows you to format a number to a particular string format/locale specific number format.
+*/
+
+QmlNumberFormatter::QmlNumberFormatter(QObject *parent)
+: QObject(*(new QmlNumberFormatterPrivate), parent)
+{
+}
+
+QmlNumberFormatter::~QmlNumberFormatter()
+{
+}
+
+/*!
+ \qmlproperty string NumberFormatter::text
+
+ The number in the specified format.
+
+ If no format is specified the text will be empty.
+*/
+
+QString QmlNumberFormatter::text() const
+{
+ Q_D(const QmlNumberFormatter);
+ return d->text;
+}
+
+/*!
+ \qmlproperty real NumberFormatter::number
+
+ A single point precision number. (Doubles are not yet supported)
+
+*/
+qreal QmlNumberFormatter::number() const
+{
+ Q_D(const QmlNumberFormatter);
+ return d->number;
+}
+
+/*!
+ \qmlproperty string NumberFormatter::format
+
+ The particular format the number will adhere to during the conversion to text.
+
+ The format syntax follows a style similar to the Unicode Standard (UTS35).
+
+ The table below shows the characters, patterns that can be used in the format.
+
+ \table
+ \header
+ \o Character
+ \o Meaning
+ \row
+ \o #
+ \o Any digit(s), zero shows as absent (for leading/trailing zeroes).
+ \row
+ \o 0
+ \o Implicit digit. Zero will show in the case that the input number is too small.
+ \row
+ \o .
+ \o Decimal separator. Output decimal seperator will be dependant on system locale.
+ \row
+ \o ,
+ \o Grouping separator. The number of digits (either #, or 0) between the grouping separator and the decimal (or the rightmost digit) will determine the groupingSize).
+ \row
+ \o other
+ \o Any other character will be taken as a string literal and placed directly into the output string.
+ \endtable
+
+ Invalid formats will not guarantee a meaningful text output.
+
+ \note Input numbers that are too long for the given format will be rounded dependent on precison based on the position of the decimal point.
+
+ The following table illustrates the output text created by applying some examples of numeric formats to the formatter.
+
+ \table
+ \header
+ \o Format
+ \o Number
+ \o Output
+ \row
+ \o ###
+ \o 123456
+ \o 123456
+ \row
+ \o 000
+ \o 123456
+ \o 123456
+ \row
+ \o ######
+ \o 1234
+ \o 1234
+ \row
+ \o 000000
+ \o 1234
+ \o 001234
+ \row
+ \o ##,##0.##
+ \o 1234.456
+ \o 1,234.46 (for US locale)
+ \codeline 1 234,46 (for FR locale)
+ \row
+ \o 000000,000.#
+ \o 123456
+ \o 000,123,456 (for US locale)
+ \codeline 000 123 456 (for FR locale)
+ \row
+ \o 0.0###
+ \o 0.999997
+ \o 1.0
+ \row
+ \o (000) 000 - 000
+ \o 12345678
+ \o (012) 345 - 678
+ \row
+ \o #A
+ \o 12
+ \o 12A
+ \endtable
+
+*/
+QString QmlNumberFormatter::format() const
+{
+ Q_D(const QmlNumberFormatter);
+ return d->format;
+}
+
+void QmlNumberFormatter::setNumber(const qreal &number)
+{
+ Q_D(QmlNumberFormatter);
+ if (d->number == number)
+ return;
+ d->number = number;
+ d->updateText();
+}
+
+void QmlNumberFormatter::setFormat(const QString &format)
+{
+ Q_D(QmlNumberFormatter);
+ //no format checking
+ if (format.isEmpty())
+ d->format = QString::null;
+ else
+ d->format = format;
+ d->updateText();
+}
+
+void QmlNumberFormatterPrivate::updateText()
+{
+ Q_Q(QmlNumberFormatter);
+ if (!componentComplete)
+ return;
+
+ QNumberFormat tempFormat;
+ tempFormat.setFormat(format);
+ tempFormat.setNumber(number);
+
+ text = tempFormat.text();
+
+ emit q->textChanged();
+}
+
+void QmlNumberFormatter::classBegin()
+{
+ Q_D(QmlNumberFormatter);
+ d->componentComplete = false;
+}
+
+void QmlNumberFormatter::componentComplete()
+{
+ Q_D(QmlNumberFormatter);
+ d->componentComplete = true;
+ d->updateText();
+}
+QML_DEFINE_TYPE(Qt,4,6,NumberFormatter,QmlNumberFormatter);
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlnumberformatter_p.h b/src/declarative/util/qmlnumberformatter_p.h
new file mode 100644
index 0000000..71fceb2
--- /dev/null
+++ b/src/declarative/util/qmlnumberformatter_p.h
@@ -0,0 +1,93 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLNUMBERFORMATTER_H
+#define QMLNUMBERFORMATTER_H
+
+#include "qnumberformat_p.h"
+
+#include <qml.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlNumberFormatterPrivate;
+class Q_DECLARATIVE_EXPORT QmlNumberFormatter : public QObject, public QmlParserStatus
+{
+ Q_OBJECT
+ Q_INTERFACES(QmlParserStatus)
+
+ Q_PROPERTY(QString text READ text NOTIFY textChanged)
+ Q_PROPERTY(QString format READ format WRITE setFormat)
+ Q_PROPERTY(qreal number READ number WRITE setNumber)
+public:
+ QmlNumberFormatter(QObject *parent=0);
+ ~QmlNumberFormatter();
+
+ QString text() const;
+
+ qreal number() const;
+ void setNumber(const qreal &);
+
+ QString format() const;
+ void setFormat(const QString &);
+
+ virtual void classBegin();
+ virtual void componentComplete();
+
+Q_SIGNALS:
+ void textChanged();
+
+private:
+ Q_DISABLE_COPY(QmlNumberFormatter)
+ Q_DECLARE_PRIVATE(QmlNumberFormatter)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlNumberFormatter)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/util/qmlopenmetaobject.cpp b/src/declarative/util/qmlopenmetaobject.cpp
new file mode 100644
index 0000000..1be81de
--- /dev/null
+++ b/src/declarative/util/qmlopenmetaobject.cpp
@@ -0,0 +1,355 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlopenmetaobject_p.h"
+#include "qmlpropertycache_p.h"
+#include "qmldeclarativedata_p.h"
+#include <qmetaobjectbuilder_p.h>
+#include <qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+
+class QmlOpenMetaObjectTypePrivate
+{
+public:
+ QmlOpenMetaObjectTypePrivate() : mem(0), cache(0), engine(0) {}
+
+ void init(const QMetaObject *metaObj);
+
+ int propertyOffset;
+ int signalOffset;
+ QHash<QByteArray, int> names;
+ QMetaObjectBuilder mob;
+ QMetaObject *mem;
+ QmlPropertyCache *cache;
+ QmlEngine *engine;
+ QSet<QmlOpenMetaObject*> referers;
+};
+
+QmlOpenMetaObjectType::QmlOpenMetaObjectType(const QMetaObject *base, QmlEngine *engine)
+ : d(new QmlOpenMetaObjectTypePrivate)
+{
+ d->engine = engine;
+ d->init(base);
+}
+
+QmlOpenMetaObjectType::~QmlOpenMetaObjectType()
+{
+ if (d->mem)
+ qFree(d->mem);
+ if (d->cache)
+ d->cache->release();
+ delete d;
+}
+
+
+int QmlOpenMetaObjectType::propertyOffset() const
+{
+ return d->propertyOffset;
+}
+
+int QmlOpenMetaObjectType::signalOffset() const
+{
+ return d->signalOffset;
+}
+
+int QmlOpenMetaObjectType::createProperty(const QByteArray &name)
+{
+ int id = d->mob.propertyCount();
+ d->mob.addSignal("__" + QByteArray::number(id) + "()");
+ QMetaPropertyBuilder build = d->mob.addProperty(name, "QVariant", id);
+ build.setDynamic(true);
+ propertyCreated(id, build);
+ qFree(d->mem);
+ d->mem = d->mob.toMetaObject();
+ d->names.insert(name, id);
+ QSet<QmlOpenMetaObject*>::iterator it = d->referers.begin();
+ while (it != d->referers.end()) {
+ QmlOpenMetaObject *omo = *it;
+ *static_cast<QMetaObject *>(omo) = *d->mem;
+ if (d->cache)
+ d->cache->update(d->engine, omo);
+ ++it;
+ }
+
+ return d->propertyOffset + id;
+}
+
+void QmlOpenMetaObjectType::propertyCreated(int id, QMetaPropertyBuilder &builder)
+{
+ if (d->referers.count())
+ (*d->referers.begin())->propertyCreated(id, builder);
+}
+
+void QmlOpenMetaObjectTypePrivate::init(const QMetaObject *metaObj)
+{
+ if (!mem) {
+ mob.setSuperClass(metaObj);
+ mob.setClassName(metaObj->className());
+ mob.setFlags(QMetaObjectBuilder::DynamicMetaObject);
+
+ mem = mob.toMetaObject();
+
+ propertyOffset = mem->propertyOffset();
+ signalOffset = mem->methodOffset();
+ }
+}
+
+//----------------------------------------------------------------------------
+
+class QmlOpenMetaObjectPrivate
+{
+public:
+ QmlOpenMetaObjectPrivate(QmlOpenMetaObject *_q)
+ : q(_q), parent(0), type(0), cacheProperties(false) {}
+
+ inline QVariant &getData(int idx) {
+ while (data.count() <= idx)
+ data << QPair<QVariant, bool>(QVariant(), false);
+ QPair<QVariant, bool> &prop = data[idx];
+ if (!prop.second) {
+ prop.first = q->initialValue(idx);
+ prop.second = true;
+ }
+ return prop.first;
+ }
+
+ inline void writeData(int idx, const QVariant &value) {
+ while (data.count() <= idx)
+ data << QPair<QVariant, bool>(QVariant(), false);
+ QPair<QVariant, bool> &prop = data[idx];
+ prop.first = value;
+ prop.second = true;
+ }
+
+ bool autoCreate;
+ QmlOpenMetaObject *q;
+ QAbstractDynamicMetaObject *parent;
+ QList<QPair<QVariant, bool> > data;
+ QObject *object;
+ QmlOpenMetaObjectType *type;
+ bool cacheProperties;
+};
+
+QmlOpenMetaObject::QmlOpenMetaObject(QObject *obj, bool automatic)
+: d(new QmlOpenMetaObjectPrivate(this))
+{
+ d->autoCreate = automatic;
+ d->object = obj;
+
+ d->type = new QmlOpenMetaObjectType(obj->metaObject(), 0);
+ d->type->d->referers.insert(this);
+
+ QObjectPrivate *op = QObjectPrivate::get(obj);
+ *static_cast<QMetaObject *>(this) = *d->type->d->mem;
+ op->metaObject = this;
+}
+
+QmlOpenMetaObject::QmlOpenMetaObject(QObject *obj, QmlOpenMetaObjectType *type, bool automatic)
+: d(new QmlOpenMetaObjectPrivate(this))
+{
+ d->autoCreate = automatic;
+ d->object = obj;
+
+ d->type = type;
+ d->type->addref();
+ d->type->d->referers.insert(this);
+
+ QObjectPrivate *op = QObjectPrivate::get(obj);
+ *static_cast<QMetaObject *>(this) = *d->type->d->mem;
+ op->metaObject = this;
+}
+
+QmlOpenMetaObject::~QmlOpenMetaObject()
+{
+ if (d->parent)
+ delete d->parent;
+ d->type->d->referers.remove(this);
+ d->type->release();
+ delete d;
+}
+
+QmlOpenMetaObjectType *QmlOpenMetaObject::type() const
+{
+ return d->type;
+}
+
+int QmlOpenMetaObject::metaCall(QMetaObject::Call c, int id, void **a)
+{
+ if (( c == QMetaObject::ReadProperty || c == QMetaObject::WriteProperty)
+ && id >= d->type->d->propertyOffset) {
+ int propId = id - d->type->d->propertyOffset;
+ if (c == QMetaObject::ReadProperty) {
+ propertyRead(propId);
+ *reinterpret_cast<QVariant *>(a[0]) = d->getData(propId);
+ } else if (c == QMetaObject::WriteProperty) {
+ if (d->data[propId].first != *reinterpret_cast<QVariant *>(a[0])) {
+ propertyWrite(propId);
+ d->writeData(propId, *reinterpret_cast<QVariant *>(a[0]));
+ activate(d->object, d->type->d->signalOffset + propId, 0);
+ }
+ }
+ return -1;
+ } else {
+ if (d->parent)
+ return d->parent->metaCall(c, id, a);
+ else
+ return d->object->qt_metacall(c, id, a);
+ }
+}
+
+QAbstractDynamicMetaObject *QmlOpenMetaObject::parent() const
+{
+ return d->parent;
+}
+
+QVariant QmlOpenMetaObject::value(int id) const
+{
+ return d->getData(id);
+}
+
+void QmlOpenMetaObject::setValue(int id, const QVariant &value)
+{
+ d->writeData(id, value);
+ activate(d->object, id + d->type->d->signalOffset, 0);
+}
+
+QVariant QmlOpenMetaObject::value(const QByteArray &name) const
+{
+ QHash<QByteArray, int>::ConstIterator iter = d->type->d->names.find(name);
+ if (iter == d->type->d->names.end())
+ return QVariant();
+
+ return d->getData(*iter);
+}
+
+QVariant &QmlOpenMetaObject::operator[](const QByteArray &name)
+{
+ QHash<QByteArray, int>::ConstIterator iter = d->type->d->names.find(name);
+ Q_ASSERT(iter != d->type->d->names.end());
+
+ return d->getData(*iter);
+}
+
+void QmlOpenMetaObject::setValue(const QByteArray &name, const QVariant &val)
+{
+ QHash<QByteArray, int>::ConstIterator iter = d->type->d->names.find(name);
+
+ int id = -1;
+ if (iter == d->type->d->names.end()) {
+ id = d->type->createProperty(name.constData()) - d->type->d->propertyOffset;
+ } else {
+ id = *iter;
+ }
+
+ QVariant &dataVal = d->getData(id);
+ if (dataVal == val)
+ return;
+
+ dataVal = val;
+ activate(d->object, id + d->type->d->signalOffset, 0);
+}
+
+void QmlOpenMetaObject::setCached(bool c)
+{
+ if (c == d->cacheProperties || !d->type->d->engine)
+ return;
+
+ d->cacheProperties = c;
+
+ QmlDeclarativeData *qmldata = QmlDeclarativeData::get(d->object, true);
+ if (d->cacheProperties) {
+ if (!d->type->d->cache)
+ d->type->d->cache = QmlPropertyCache::create(d->type->d->engine, this);
+ qmldata->propertyCache = d->type->d->cache;
+ d->type->d->cache->addref();
+ } else {
+ if (d->type->d->cache)
+ d->type->d->cache->release();
+ qmldata->propertyCache = 0;
+ }
+}
+
+
+int QmlOpenMetaObject::createProperty(const char *name, const char *)
+{
+ if (d->autoCreate)
+ return d->type->createProperty(name);
+ else
+ return -1;
+}
+
+void QmlOpenMetaObject::propertyRead(int)
+{
+}
+
+void QmlOpenMetaObject::propertyWrite(int)
+{
+}
+
+void QmlOpenMetaObject::propertyCreated(int, QMetaPropertyBuilder &)
+{
+}
+
+QVariant QmlOpenMetaObject::initialValue(int)
+{
+ return QVariant();
+}
+
+int QmlOpenMetaObject::count() const
+{
+ return d->type->d->names.count();
+}
+
+QByteArray QmlOpenMetaObject::name(int idx) const
+{
+ Q_ASSERT(idx >= 0 && idx < d->type->d->names.count());
+
+ return d->type->d->mob.property(idx).name();
+}
+
+QObject *QmlOpenMetaObject::object() const
+{
+ return d->object;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlopenmetaobject_p.h b/src/declarative/util/qmlopenmetaobject_p.h
new file mode 100644
index 0000000..c6da71a
--- /dev/null
+++ b/src/declarative/util/qmlopenmetaobject_p.h
@@ -0,0 +1,125 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLOPENMETAOBJECT_H
+#define QMLOPENMETAOBJECT_H
+
+#include <private/qmlrefcount_p.h>
+#include <QtCore/QMetaObject>
+#include <QtCore/QObject>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlEngine;
+class QMetaPropertyBuilder;
+class QmlOpenMetaObjectTypePrivate;
+class Q_DECLARATIVE_EXPORT QmlOpenMetaObjectType : public QmlRefCount
+{
+public:
+ QmlOpenMetaObjectType(const QMetaObject *base, QmlEngine *engine);
+ ~QmlOpenMetaObjectType();
+
+ int createProperty(const QByteArray &name);
+
+ int propertyOffset() const;
+ int signalOffset() const;
+
+protected:
+ virtual void propertyCreated(int, QMetaPropertyBuilder &);
+
+private:
+ QmlOpenMetaObjectTypePrivate *d;
+ friend class QmlOpenMetaObject;
+ friend class QmlOpenMetaObjectPrivate;
+};
+
+class QmlOpenMetaObjectPrivate;
+class Q_DECLARATIVE_EXPORT QmlOpenMetaObject : public QAbstractDynamicMetaObject
+{
+public:
+ QmlOpenMetaObject(QObject *, bool = true);
+ QmlOpenMetaObject(QObject *, QmlOpenMetaObjectType *, bool = true);
+ ~QmlOpenMetaObject();
+
+ QVariant value(const QByteArray &) const;
+ void setValue(const QByteArray &, const QVariant &);
+ QVariant value(int) const;
+ void setValue(int, const QVariant &);
+ QVariant &operator[](const QByteArray &);
+
+ int count() const;
+ QByteArray name(int) const;
+
+ QObject *object() const;
+ virtual QVariant initialValue(int);
+
+ // Be careful - once setCached(true) is called createProperty() is no
+ // longer automatically called for new properties.
+ void setCached(bool);
+
+ QmlOpenMetaObjectType *type() const;
+
+protected:
+ virtual int metaCall(QMetaObject::Call _c, int _id, void **_a);
+ virtual int createProperty(const char *, const char *);
+
+ virtual void propertyRead(int);
+ virtual void propertyWrite(int);
+ virtual void propertyCreated(int, QMetaPropertyBuilder &);
+
+ QAbstractDynamicMetaObject *parent() const;
+
+private:
+ QmlOpenMetaObjectPrivate *d;
+ friend class QmlOpenMetaObjectType;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLOPENMETAOBJECT_H
diff --git a/src/declarative/util/qmlpackage.cpp b/src/declarative/util/qmlpackage.cpp
new file mode 100644
index 0000000..3214dc8
--- /dev/null
+++ b/src/declarative/util/qmlpackage.cpp
@@ -0,0 +1,177 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlpackage_p.h"
+
+#include <private/qobject_p.h>
+#include "private/qmlguard_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlPackagePrivate : public QObjectPrivate
+{
+public:
+ QmlPackagePrivate() {}
+
+ class DataList;
+ struct DataGuard : public QmlGuard<QObject>
+ {
+ DataGuard(QObject *obj, DataList *l) : list(l) { (QmlGuard<QObject>&)*this = obj; }
+ DataList *list;
+ void objectDestroyed(QObject *) {
+ // we assume priv will always be destroyed after objectDestroyed calls
+ list->removeOne(*this);
+ }
+ };
+
+ class DataList : public QList<DataGuard>, public QmlList<QObject*>
+ {
+ public:
+ virtual void append(QObject* v) { QList<DataGuard>::append(DataGuard(v, this)); }
+ virtual void insert(int i, QObject* v) { QList<DataGuard>::insert(i, DataGuard(v, this)); }
+ virtual void clear() { QList<DataGuard>::clear(); }
+ virtual QObject* at(int i) const { return QList<DataGuard>::at(i); }
+ virtual void removeAt(int i) { QList<DataGuard>::removeAt(i); }
+ virtual int count() const { return QList<DataGuard>::count(); }
+ };
+ DataList dataList;
+};
+
+class QmlPackageAttached : public QObject
+{
+Q_OBJECT
+Q_PROPERTY(QString name READ name WRITE setName)
+public:
+ QmlPackageAttached(QObject *parent);
+ virtual ~QmlPackageAttached();
+
+ QString name() const;
+ void setName(const QString &n);
+
+ static QHash<QObject *, QmlPackageAttached *> attached;
+private:
+ QString _name;
+};
+
+QHash<QObject *, QmlPackageAttached *> QmlPackageAttached::attached;
+
+QmlPackageAttached::QmlPackageAttached(QObject *parent)
+: QObject(parent)
+{
+ attached.insert(parent, this);
+}
+
+QmlPackageAttached::~QmlPackageAttached()
+{
+ attached.remove(parent());
+}
+
+QString QmlPackageAttached::name() const
+{
+ return _name;
+}
+
+void QmlPackageAttached::setName(const QString &n)
+{
+ _name = n;
+}
+
+QmlPackage::QmlPackage(QObject *parent)
+ : QObject(*(new QmlPackagePrivate), parent)
+{
+}
+
+QmlPackage::~QmlPackage()
+{
+ Q_D(QmlPackage);
+ for (int ii = 0; ii < d->dataList.count(); ++ii) {
+ QObject *obj = d->dataList.at(ii);
+ obj->setParent(this);
+ }
+}
+
+QmlList<QObject *> *QmlPackage::data()
+{
+ Q_D(QmlPackage);
+ return &d->dataList;
+}
+
+bool QmlPackage::hasPart(const QString &name)
+{
+ Q_D(QmlPackage);
+ for (int ii = 0; ii < d->dataList.count(); ++ii) {
+ QObject *obj = d->dataList.at(ii);
+ QmlPackageAttached *a = QmlPackageAttached::attached.value(obj);
+ if (a && a->name() == name)
+ return true;
+ }
+ return false;
+}
+
+QObject *QmlPackage::part(const QString &name)
+{
+ Q_D(QmlPackage);
+ 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);
+ QmlPackageAttached *a = QmlPackageAttached::attached.value(obj);
+ if (a && a->name() == name)
+ return obj;
+ }
+
+ if (name == QLatin1String("default") && !d->dataList.isEmpty())
+ return d->dataList.at(0);
+
+ return 0;
+}
+
+QmlPackageAttached *QmlPackage::qmlAttachedProperties(QObject *o)
+{
+ return new QmlPackageAttached(o);
+}
+
+QML_DEFINE_TYPE(Qt,4,6,Package,QmlPackage)
+
+QT_END_NAMESPACE
+
+#include <qmlpackage.moc>
diff --git a/src/declarative/util/qmlpackage_p.h b/src/declarative/util/qmlpackage_p.h
new file mode 100644
index 0000000..ff42aad
--- /dev/null
+++ b/src/declarative/util/qmlpackage_p.h
@@ -0,0 +1,88 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPACKAGE_H
+#define QMLPACKAGE_H
+
+#include <qml.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+/*****************************************************************************
+ *****************************************************************************
+ XXX Experimental
+ *****************************************************************************
+*****************************************************************************/
+
+class QmlPackagePrivate;
+class QmlPackageAttached;
+class QmlPackage : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlPackage)
+
+ Q_CLASSINFO("DefaultProperty", "data")
+ Q_PROPERTY(QmlList<QObject *> *data READ data SCRIPTABLE false)
+
+public:
+ QmlPackage(QObject *parent=0);
+ virtual ~QmlPackage();
+
+ QmlList<QObject *> *data();
+
+ QObject *part(const QString & = QString());
+ bool hasPart(const QString &);
+
+ static QmlPackageAttached *qmlAttachedProperties(QObject *);
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlPackage)
+QML_DECLARE_TYPEINFO(QmlPackage, QML_HAS_ATTACHED_PROPERTIES)
+
+QT_END_HEADER
+
+#endif // QMLPACKAGE_H
diff --git a/src/declarative/util/qmlpixmapcache.cpp b/src/declarative/util/qmlpixmapcache.cpp
new file mode 100644
index 0000000..c03b5df
--- /dev/null
+++ b/src/declarative/util/qmlpixmapcache.cpp
@@ -0,0 +1,605 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlpixmapcache_p.h"
+#include "qmlnetworkaccessmanagerfactory.h"
+
+#include "qfxperf_p_p.h"
+
+#include <qmlengine.h>
+#include <private/qmlglobal_p.h>
+
+#include <QCoreApplication>
+#include <QImageReader>
+#include <QHash>
+#include <QNetworkReply>
+#include <QPixmapCache>
+#include <QFile>
+#include <QThread>
+#include <QMutex>
+#include <QWaitCondition>
+#include <QtCore/qdebug.h>
+#include <private/qobject_p.h>
+#include <QSslError>
+
+#ifdef Q_OS_LINUX
+#include <pthread.h>
+#include <linux/sched.h>
+#endif
+
+// Maximum number of simultaneous image requests to send.
+static const int maxImageRequestCount = 8;
+
+QT_BEGIN_NAMESPACE
+
+#if (QT_VERSION < QT_VERSION_CHECK(4, 7, 0))
+inline uint qHash(const QUrl &uri)
+{
+ return qHash(uri.toEncoded(QUrl::FormattingOption(0x100)));
+}
+#endif
+
+class QmlImageReaderEvent : public QEvent
+{
+public:
+ enum ReadError { NoError, Loading, Decoding };
+
+ QmlImageReaderEvent(QmlImageReaderEvent::ReadError err, const QString &errStr, QImage &img)
+ : QEvent(QEvent::User), error(err), errorString(errStr), image(img) {}
+
+ ReadError error;
+ QString errorString;
+ QImage image;
+};
+
+class QmlImageRequestHandler;
+class QmlImageReader : public QThread
+{
+ Q_OBJECT
+public:
+ QmlImageReader(QmlEngine *eng);
+ ~QmlImageReader();
+
+ QmlPixmapReply *getImage(const QUrl &url);
+ void cancel(QmlPixmapReply *rep);
+
+ static QmlImageReader *instance(QmlEngine *engine);
+
+protected:
+ void run();
+
+private:
+ QList<QmlPixmapReply*> jobs;
+ QList<QmlPixmapReply*> cancelled;
+ QmlEngine *engine;
+ QmlImageRequestHandler *handler;
+ QMutex mutex;
+
+ static QHash<QmlEngine *,QmlImageReader*> readers;
+ static QMutex readerMutex;
+ friend class QmlImageRequestHandler;
+};
+
+QHash<QmlEngine *,QmlImageReader*> QmlImageReader::readers;
+QMutex QmlImageReader::readerMutex;
+
+
+class QmlImageRequestHandler : public QObject
+{
+ Q_OBJECT
+public:
+ QmlImageRequestHandler(QmlImageReader *read, QmlEngine *eng)
+ : QObject(), accessManager(0), engine(eng), reader(read)
+ {
+ QCoreApplication::postEvent(this, new QEvent(QEvent::User));
+ }
+
+ QmlPixmapReply *getImage(const QUrl &url);
+ void cancel(QmlPixmapReply *reply);
+
+protected:
+ bool event(QEvent *event);
+
+private slots:
+ void networkRequestDone();
+
+private:
+ QNetworkAccessManager *networkAccessManager() {
+ if (!accessManager) {
+ if (engine && engine->networkAccessManagerFactory()) {
+ accessManager = engine->networkAccessManagerFactory()->create(this);
+ } else {
+ accessManager = new QNetworkAccessManager(this);
+ }
+ }
+ return accessManager;
+ }
+
+ QHash<QNetworkReply*,QmlPixmapReply*> replies;
+ QNetworkAccessManager *accessManager;
+ QmlEngine *engine;
+ QmlImageReader *reader;
+};
+
+//===========================================================================
+
+bool QmlImageRequestHandler::event(QEvent *event)
+{
+ if (event->type() == QEvent::User) {
+ static int replyDownloadProgress = -1;
+ static int replyFinished = -1;
+ static int downloadProgress = -1;
+ static int thisNetworkRequestDone = -1;
+
+ if (replyDownloadProgress == -1) {
+ replyDownloadProgress = QNetworkReply::staticMetaObject.indexOfSignal("downloadProgress(qint64,qint64)");
+ replyFinished = QNetworkReply::staticMetaObject.indexOfSignal("finished()");
+ downloadProgress = QmlPixmapReply::staticMetaObject.indexOfSignal("downloadProgress(qint64,qint64)");
+ thisNetworkRequestDone = QmlImageRequestHandler::staticMetaObject.indexOfSlot("networkRequestDone()");
+ }
+
+ while (1) {
+ reader->mutex.lock();
+
+ if (reader->cancelled.count()) {
+ for (int i = 0; i < reader->cancelled.count(); ++i) {
+ QmlPixmapReply *job = reader->cancelled.at(i);
+ QNetworkReply *reply = replies.key(job, 0);
+ if (reply && reply->isRunning()) {
+ replies.remove(reply);
+ reply->close();
+ job->release(true);
+ }
+ }
+ reader->cancelled.clear();
+ }
+
+ if (!reader->jobs.count() || replies.count() > maxImageRequestCount) {
+ reader->mutex.unlock();
+ break;
+ }
+
+ QmlPixmapReply *runningJob = reader->jobs.takeFirst();
+ runningJob->addRef();
+ runningJob->setLoading();
+ QUrl url = runningJob->url();
+ reader->mutex.unlock();
+
+ // fetch
+ QNetworkRequest req(url);
+ req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
+ QNetworkReply *reply = networkAccessManager()->get(req);
+
+ QMetaObject::connect(reply, replyDownloadProgress, runningJob, downloadProgress);
+ QMetaObject::connect(reply, replyFinished, this, thisNetworkRequestDone);
+
+ replies.insert(reply, runningJob);
+ }
+ return true;
+ }
+
+ return QObject::event(event);
+}
+
+void QmlImageRequestHandler::networkRequestDone()
+{
+ QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
+ QmlPixmapReply *job = replies.take(reply);
+ if (job) {
+ QImage image;
+ QmlImageReaderEvent::ReadError error;
+ QString errorString;
+ if (reply->error()) {
+ error = QmlImageReaderEvent::Loading;
+ errorString = reply->errorString();
+ } else {
+ QImageReader imgio(reply);
+ if (imgio.read(&image)) {
+ error = QmlImageReaderEvent::NoError;
+ } else {
+ errorString = QLatin1String("Error decoding: ") + reply->url().toString()
+ + QLatin1String(" \"") + imgio.errorString() + QLatin1String("\"");
+ error = QmlImageReaderEvent::Decoding;
+ }
+ }
+ // send completion event to the QmlPixmapReply
+ QCoreApplication::postEvent(job, new QmlImageReaderEvent(error, errorString, image));
+ }
+ // kick off event loop again if we have dropped below max request count
+ if (replies.count() == maxImageRequestCount)
+ QCoreApplication::postEvent(this, new QEvent(QEvent::User));
+ reply->deleteLater();
+}
+
+//===========================================================================
+
+QmlImageReader::QmlImageReader(QmlEngine *eng)
+ : QThread(eng), engine(eng), handler(0)
+{
+ start(QThread::LowPriority);
+}
+
+QmlImageReader::~QmlImageReader()
+{
+ quit();
+ wait();
+ readerMutex.lock();
+ readers.remove(engine);
+ readerMutex.unlock();
+ delete handler;
+}
+
+QmlImageReader *QmlImageReader::instance(QmlEngine *engine)
+{
+ readerMutex.lock();
+ QmlImageReader *reader = readers.value(engine);
+ if (!reader) {
+ reader = new QmlImageReader(engine);
+ readers.insert(engine, reader);
+ }
+ readerMutex.unlock();
+
+ return reader;
+}
+
+QmlPixmapReply *QmlImageReader::getImage(const QUrl &url)
+{
+ mutex.lock();
+ QmlPixmapReply *reply = new QmlPixmapReply(this, url);
+ jobs.append(reply);
+ if (jobs.count() == 1 && handler)
+ QCoreApplication::postEvent(handler, new QEvent(QEvent::User));
+ mutex.unlock();
+ return reply;
+}
+
+void QmlImageReader::cancel(QmlPixmapReply *reply)
+{
+ mutex.lock();
+ if (reply->isLoading()) {
+ // Already requested. Add to cancel list to be cancelled in reader thread.
+ cancelled.append(reply);
+ if (cancelled.count() == 1 && handler)
+ QCoreApplication::postEvent(handler, new QEvent(QEvent::User));
+ } else {
+ // Not yet processed - just remove from waiting list
+ QList<QmlPixmapReply*>::iterator it = jobs.begin();
+ while (it != jobs.end()) {
+ QmlPixmapReply *job = *it;
+ if (job == reply) {
+ jobs.erase(it);
+ break;
+ }
+ ++it;
+ }
+ }
+ mutex.unlock();
+}
+
+void QmlImageReader::run()
+{
+#if defined(Q_OS_LINUX) && defined(SCHED_IDLE)
+ struct sched_param param;
+ int policy;
+
+ pthread_getschedparam(pthread_self(), &policy, &param);
+ pthread_setschedparam(pthread_self(), SCHED_IDLE, &param);
+#endif
+
+ handler = new QmlImageRequestHandler(this, engine);
+
+ exec();
+}
+
+//===========================================================================
+
+static bool readImage(QIODevice *dev, QPixmap *pixmap, QString &errorString)
+{
+ QImageReader imgio(dev);
+
+//#define QT_TEST_SCALED_SIZE
+#ifdef QT_TEST_SCALED_SIZE
+ /*
+ Some mechanism is needed for loading images at a limited size, especially
+ for remote images. Loading only thumbnails of remote progressive JPEG
+ images can be efficient. (Qt jpeg handler does not do so currently)
+ */
+
+ QSize limit(60,60);
+ QSize sz = imgio.size();
+ if (sz.width() > limit.width() || sz.height() > limit.height()) {
+ sz.scale(limit,Qt::KeepAspectRatio);
+ imgio.setScaledSize(sz);
+ }
+#endif
+
+ QImage img;
+ if (imgio.read(&img)) {
+#ifdef QT_TEST_SCALED_SIZE
+ if (!sz.isValid())
+ img = img.scaled(limit,Qt::KeepAspectRatio);
+#endif
+ *pixmap = QPixmap::fromImage(img);
+ return true;
+ } else {
+ errorString = imgio.errorString();
+ return false;
+ }
+}
+
+/*!
+ \internal
+ \class QmlPixmapCache
+ \brief Enacapsultes a pixmap for QmlGraphics items.
+
+ This class is NOT reentrant.
+ */
+
+static QString toLocalFileOrQrc(const QUrl& url)
+{
+ QString r = url.toLocalFile();
+ if (r.isEmpty() && url.scheme() == QLatin1String("qrc"))
+ r = QLatin1Char(':') + url.path();
+ return r;
+}
+
+typedef QHash<QUrl, QmlPixmapReply *> QmlPixmapReplyHash;
+Q_GLOBAL_STATIC(QmlPixmapReplyHash, qmlActivePixmapReplies);
+
+class QmlPixmapReplyPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlPixmapReply)
+
+public:
+ QmlPixmapReplyPrivate(QmlImageReader *r, const QUrl &u)
+ : QObjectPrivate(), refCount(1), url(u), status(QmlPixmapReply::Loading), loading(false), reader(r) {
+ }
+
+ int refCount;
+ QUrl url;
+ QPixmap pixmap; // ensure reference to pixmap so QPixmapCache does not discard
+ QmlPixmapReply::Status status;
+ bool loading;
+ QmlImageReader *reader;
+};
+
+
+QmlPixmapReply::QmlPixmapReply(QmlImageReader *reader, const QUrl &url)
+ : QObject(*new QmlPixmapReplyPrivate(reader, url), 0)
+{
+}
+
+QmlPixmapReply::~QmlPixmapReply()
+{
+}
+
+const QUrl &QmlPixmapReply::url() const
+{
+ Q_D(const QmlPixmapReply);
+ return d->url;
+}
+
+bool QmlPixmapReply::event(QEvent *event)
+{
+ Q_D(QmlPixmapReply);
+ if (event->type() == QEvent::User) {
+ d->loading = false;
+ if (!release(true)) {
+ QmlImageReaderEvent *de = static_cast<QmlImageReaderEvent*>(event);
+ d->status = (de->error == QmlImageReaderEvent::NoError) ? Ready : Error;
+ if (d->status == Ready)
+ d->pixmap = QPixmap::fromImage(de->image);
+ else
+ qWarning() << de->errorString;
+ QByteArray key = d->url.toEncoded(QUrl::FormattingOption(0x100));
+ QString strKey = QString::fromLatin1(key.constData(), key.count());
+ QPixmapCache::insert(strKey, d->pixmap); // note: may fail (returns false)
+ emit finished();
+ }
+ return true;
+ }
+
+ return QObject::event(event);
+}
+
+QmlPixmapReply::Status QmlPixmapReply::status() const
+{
+ Q_D(const QmlPixmapReply);
+ return d->status;
+}
+
+bool QmlPixmapReply::isLoading() const
+{
+ Q_D(const QmlPixmapReply);
+ return d->loading;
+}
+
+void QmlPixmapReply::setLoading()
+{
+ Q_D(QmlPixmapReply);
+ d->loading = true;
+}
+
+void QmlPixmapReply::addRef()
+{
+ Q_D(QmlPixmapReply);
+ ++d->refCount;
+}
+
+bool QmlPixmapReply::release(bool defer)
+{
+ Q_D(QmlPixmapReply);
+ Q_ASSERT(d->refCount > 0);
+ --d->refCount;
+ if (d->refCount == 0) {
+ qmlActivePixmapReplies()->remove(d->url);
+ if (d->status == Loading && !d->loading)
+ d->reader->cancel(this);
+ if (defer)
+ deleteLater();
+ else
+ delete this;
+ return true;
+ } else if (d->refCount == 1 && d->loading) {
+ // The only reference left is the reader thread.
+ qmlActivePixmapReplies()->remove(d->url);
+ d->reader->cancel(this);
+ }
+
+ return false;
+}
+
+/*!
+ Finds the cached pixmap corresponding to \a url.
+ If the image is a network resource and has not yet
+ been retrieved and cached, request() must be called.
+
+ Returns Ready, or Error if the image has been retrieved,
+ otherwise the current retrieval status.
+*/
+QmlPixmapReply::Status QmlPixmapCache::get(const QUrl& url, QPixmap *pixmap)
+{
+ QmlPixmapReply::Status status = QmlPixmapReply::Unrequested;
+
+#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
+ QString lf = toLocalFileOrQrc(url);
+ if (!lf.isEmpty()) {
+ status = QmlPixmapReply::Ready;
+ if (!QPixmapCache::find(lf,pixmap)) {
+ QFile f(lf);
+ if (f.open(QIODevice::ReadOnly)) {
+ QString errorString;
+ if (!readImage(&f, pixmap, errorString)) {
+ errorString = QLatin1String("Error decoding: ") + url.toString()
+ + QLatin1String(" \"") + errorString + QLatin1String("\"");
+ qWarning() << errorString;
+ *pixmap = QPixmap();
+ status = QmlPixmapReply::Error;
+ }
+ } else {
+ qWarning() << "Cannot open" << url;
+ *pixmap = QPixmap();
+ status = QmlPixmapReply::Error;
+ }
+ if (status == QmlPixmapReply::Ready)
+ QPixmapCache::insert(lf, *pixmap);
+ }
+ return status;
+ }
+#endif
+
+ QByteArray key = url.toEncoded(QUrl::FormattingOption(0x100));
+ QString strKey = QString::fromLatin1(key.constData(), key.count());
+ QmlPixmapReplyHash::Iterator iter = qmlActivePixmapReplies()->find(url);
+ if (iter != qmlActivePixmapReplies()->end() && (*iter)->status() == QmlPixmapReply::Ready) {
+ // Must check this, since QPixmapCache::insert may have failed.
+ *pixmap = (*iter)->d_func()->pixmap;
+ status = (*iter)->status();
+ (*iter)->release();
+ } else if (QPixmapCache::find(strKey, pixmap)) {
+ if (iter != qmlActivePixmapReplies()->end()) {
+ status = (*iter)->status();
+ (*iter)->release();
+ } else {
+ status = pixmap->isNull() ? QmlPixmapReply::Error : QmlPixmapReply::Ready;
+ }
+ } else if (iter != qmlActivePixmapReplies()->end()) {
+ status = QmlPixmapReply::Loading;
+ }
+
+ return status;
+}
+
+/*!
+ Starts a network request to load \a url.
+
+ Returns a QmlPixmapReply. Caller should connect to QmlPixmapReply::finished()
+ and call get() when the image is available.
+
+ The returned QmlPixmapReply will be deleted when all request() calls are
+ matched by a corresponding get() call.
+*/
+QmlPixmapReply *QmlPixmapCache::request(QmlEngine *engine, const QUrl &url)
+{
+ QmlPixmapReplyHash::Iterator iter = qmlActivePixmapReplies()->find(url);
+ if (iter == qmlActivePixmapReplies()->end()) {
+ QmlImageReader *reader = QmlImageReader::instance(engine);
+ QmlPixmapReply *item = reader->getImage(url);
+ iter = qmlActivePixmapReplies()->insert(url, item);
+ } else {
+ (*iter)->addRef();
+ }
+
+ return (*iter);
+}
+
+/*!
+ Cancels a previous call to request().
+
+ May also cancel loading (eg. if no other pending request).
+
+ Any connections from the QmlPixmapReply returned by request() to \a obj will be
+ disconnected.
+*/
+void QmlPixmapCache::cancel(const QUrl& url, QObject *obj)
+{
+ QmlPixmapReplyHash::Iterator iter = qmlActivePixmapReplies()->find(url);
+ if (iter == qmlActivePixmapReplies()->end())
+ return;
+
+ QmlPixmapReply *reply = *iter;
+ if (obj)
+ QObject::disconnect(reply, 0, obj, 0);
+ reply->release();
+}
+
+/*!
+ This function is mainly for test verification. It returns the number of
+ requests that are still unfinished.
+*/
+int QmlPixmapCache::pendingRequests()
+{
+ return qmlActivePixmapReplies()->count();
+}
+
+#include <qmlpixmapcache.moc>
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlpixmapcache_p.h b/src/declarative/util/qmlpixmapcache_p.h
new file mode 100644
index 0000000..462faf6
--- /dev/null
+++ b/src/declarative/util/qmlpixmapcache_p.h
@@ -0,0 +1,107 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPIXMAPCACHE_H
+#define QMLPIXMAPCACHE_H
+
+#include <QtCore/QString>
+#include <QtGui/QPixmap>
+#include <QtCore/qurl.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+class QmlEngine;
+class QNetworkReply;
+class QmlImageReader;
+
+class QmlPixmapReplyPrivate;
+class Q_DECLARATIVE_EXPORT QmlPixmapReply : public QObject
+{
+ Q_OBJECT
+public:
+ ~QmlPixmapReply();
+
+ enum Status { Ready, Error, Unrequested, Loading };
+ Status status() const;
+
+ const QUrl &url() const;
+
+Q_SIGNALS:
+ void finished();
+ void downloadProgress(qint64, qint64);
+
+protected:
+ bool event(QEvent *event);
+
+private:
+ void addRef();
+ bool release(bool defer=false);
+ bool isLoading() const;
+ void setLoading();
+
+private:
+ QmlPixmapReply(QmlImageReader *reader, const QUrl &url);
+ Q_DISABLE_COPY(QmlPixmapReply)
+ Q_DECLARE_PRIVATE(QmlPixmapReply)
+ friend class QmlImageRequestHandler;
+ friend class QmlImageReader;
+ friend class QmlPixmapCache;
+};
+
+class Q_DECLARATIVE_EXPORT QmlPixmapCache
+{
+public:
+ static QmlPixmapReply::Status get(const QUrl& url, QPixmap *pixmap);
+ static QmlPixmapReply *request(QmlEngine *, const QUrl& url);
+ static void cancel(const QUrl& url, QObject *obj);
+ static int pendingRequests();
+};
+
+
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QMLPIXMAPCACHE_H
diff --git a/src/declarative/util/qmlpropertychanges.cpp b/src/declarative/util/qmlpropertychanges.cpp
new file mode 100644
index 0000000..68fc5cc
--- /dev/null
+++ b/src/declarative/util/qmlpropertychanges.cpp
@@ -0,0 +1,468 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlpropertychanges_p.h"
+
+#include "qmlopenmetaobject_p.h"
+
+#include <qmlinfo.h>
+#include <qmlcustomparser_p.h>
+#include <qmlparser_p.h>
+#include <qmlexpression.h>
+#include <qmlbinding.h>
+#include <qmlcontext.h>
+#include <qmlguard_p.h>
+
+#include <QtCore/qdebug.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \qmlclass PropertyChanges QmlPropertyChanges
+ \brief The PropertyChanges element describes new property values for a state.
+
+ PropertyChanges provides a state change that modifies the properties of an item.
+
+ Here is a property change that modifies the text and color of a Text element
+ when it is clicked:
+
+ \qml
+ Text {
+ id: myText
+ width: 100; height: 100
+ text: "Hello"
+ color: "blue"
+
+ states: State {
+ name: "myState"
+
+ PropertyChanges {
+ target: myText
+ text: "Goodbye"
+ color: "red"
+ }
+ }
+
+ MouseRegion { anchors.fill: parent; onClicked: myText.state = 'myState' }
+ }
+ \endqml
+
+ State-specific script for signal handlers can also be specified:
+
+ \qml
+ PropertyChanges {
+ target: myMouseRegion
+ onClicked: doSomethingDifferent()
+ }
+ \endqml
+
+ Changes to an Item's parent or anchors should be done using the associated change elements
+ (ParentChange and AnchorChanges, respectively) rather than PropertyChanges.
+
+ \sa {qmlstate}{States}
+*/
+
+/*!
+ \internal
+ \class QmlPropertyChanges
+ \brief The QmlPropertyChanges class describes new property values for a state.
+*/
+
+/*!
+ \qmlproperty Object PropertyChanges::target
+ This property holds the object which contains the properties to be changed.
+*/
+
+class QmlReplaceSignalHandler : public QmlActionEvent
+{
+public:
+ QmlReplaceSignalHandler() : expression(0), reverseExpression(0),
+ rewindExpression(0), ownedExpression(0) {}
+ ~QmlReplaceSignalHandler() {
+ delete ownedExpression;
+ }
+
+ virtual QString typeName() const { return QLatin1String("ReplaceSignalHandler"); }
+
+ QmlMetaProperty property;
+ QmlExpression *expression;
+ QmlExpression *reverseExpression;
+ QmlExpression *rewindExpression;
+ QmlGuard<QmlExpression> ownedExpression;
+
+ virtual void execute() {
+ ownedExpression = property.setSignalExpression(expression);
+ }
+
+ virtual bool isReversable() { return true; }
+ virtual void reverse() {
+ ownedExpression = property.setSignalExpression(reverseExpression);
+ }
+
+ virtual void saveOriginals() {
+ saveCurrentValues();
+ reverseExpression = rewindExpression;
+ }
+
+ virtual void rewind() {
+ ownedExpression = property.setSignalExpression(rewindExpression);
+ }
+ virtual void saveCurrentValues() { rewindExpression = property.signalExpression(); }
+
+ virtual bool override(QmlActionEvent*other) {
+ if (other == this)
+ return true;
+ if (other->typeName() != typeName())
+ return false;
+ if (static_cast<QmlReplaceSignalHandler*>(other)->property == property)
+ return true;
+ return false;
+ }
+};
+
+
+class QmlPropertyChangesPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlPropertyChanges)
+public:
+ QmlPropertyChangesPrivate() : object(0), decoded(true), restore(true),
+ isExplicit(false) {}
+
+ QObject *object;
+ QByteArray data;
+
+ bool decoded : 1;
+ bool restore : 1;
+ bool isExplicit : 1;
+
+ void decode();
+
+ QList<QPair<QByteArray, QVariant> > properties;
+ QList<QPair<QByteArray, QmlExpression *> > expressions;
+ QList<QmlReplaceSignalHandler*> signalReplacements;
+
+ QmlMetaProperty property(const QByteArray &);
+};
+
+class QmlPropertyChangesParser : public QmlCustomParser
+{
+public:
+ void compileList(QList<QPair<QByteArray, QVariant> > &list, const QByteArray &pre, const QmlCustomParserProperty &prop);
+
+ virtual QByteArray compile(const QList<QmlCustomParserProperty> &);
+ virtual void setCustomData(QObject *, const QByteArray &);
+};
+
+void
+QmlPropertyChangesParser::compileList(QList<QPair<QByteArray, QVariant> > &list,
+ const QByteArray &pre,
+ const QmlCustomParserProperty &prop)
+{
+ QByteArray 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<QmlCustomParserNode>()) {
+ continue;
+ } else if(value.userType() == qMetaTypeId<QmlCustomParserProperty>()) {
+
+ QmlCustomParserProperty prop =
+ qvariant_cast<QmlCustomParserProperty>(value);
+ QByteArray pre = propName + '.';
+ compileList(list, pre, prop);
+
+ } else {
+ list << qMakePair(propName, value);
+ }
+ }
+}
+
+QByteArray
+QmlPropertyChangesParser::compile(const QList<QmlCustomParserProperty> &props)
+{
+ QList<QPair<QByteArray, QVariant> > data;
+ for(int ii = 0; ii < props.count(); ++ii)
+ compileList(data, QByteArray(), props.at(ii));
+
+ QByteArray rv;
+ QDataStream ds(&rv, QIODevice::WriteOnly);
+
+ ds << data.count();
+ for(int ii = 0; ii < data.count(); ++ii) {
+ QmlParser::Variant v = qvariant_cast<QmlParser::Variant>(data.at(ii).second);
+ QVariant var;
+ bool isScript = v.isScript();
+ switch(v.type()) {
+ case QmlParser::Variant::Boolean:
+ var = QVariant(v.asBoolean());
+ break;
+ case QmlParser::Variant::Number:
+ var = QVariant(v.asNumber());
+ break;
+ case QmlParser::Variant::String:
+ var = QVariant(v.asString());
+ break;
+ case QmlParser::Variant::Invalid:
+ case QmlParser::Variant::Script:
+ var = QVariant(v.asScript());
+ break;
+ }
+
+ ds << data.at(ii).first << isScript << var;
+ }
+
+ return rv;
+}
+
+void QmlPropertyChangesPrivate::decode()
+{
+ Q_Q(QmlPropertyChanges);
+ if (decoded)
+ return;
+
+ QDataStream ds(&data, QIODevice::ReadOnly);
+
+ int count;
+ ds >> count;
+ for (int ii = 0; ii < count; ++ii) {
+ QByteArray name;
+ bool isScript;
+ QVariant data;
+ ds >> name;
+ ds >> isScript;
+ ds >> data;
+
+ QmlMetaProperty prop = property(name); //### better way to check for signal property?
+ if (prop.type() & QmlMetaProperty::SignalProperty) {
+ QmlExpression *expression = new QmlExpression(qmlContext(q), data.toString(), object);
+ expression->setTrackChange(false);
+ QmlReplaceSignalHandler *handler = new QmlReplaceSignalHandler;
+ handler->property = prop;
+ handler->expression = expression;
+ signalReplacements << handler;
+ } else if (isScript) {
+ QmlExpression *expression = new QmlExpression(qmlContext(q), data.toString(), object);
+ expression->setTrackChange(false);
+ expressions << qMakePair(name, expression);
+ } else {
+ properties << qMakePair(name, data);
+ }
+ }
+
+ decoded = true;
+ data.clear();
+}
+
+void QmlPropertyChangesParser::setCustomData(QObject *object,
+ const QByteArray &data)
+{
+ QmlPropertyChangesPrivate *p =
+ static_cast<QmlPropertyChangesPrivate *>(QObjectPrivate::get(object));
+ p->data = data;
+ p->decoded = false;
+}
+
+QmlPropertyChanges::QmlPropertyChanges()
+: QmlStateOperation(*(new QmlPropertyChangesPrivate))
+{
+}
+
+QmlPropertyChanges::~QmlPropertyChanges()
+{
+ Q_D(QmlPropertyChanges);
+ for(int ii = 0; ii < d->expressions.count(); ++ii)
+ delete d->expressions.at(ii).second;
+ for(int ii = 0; ii < d->signalReplacements.count(); ++ii)
+ delete d->signalReplacements.at(ii);
+}
+
+QObject *QmlPropertyChanges::object() const
+{
+ Q_D(const QmlPropertyChanges);
+ return d->object;
+}
+
+void QmlPropertyChanges::setObject(QObject *o)
+{
+ Q_D(QmlPropertyChanges);
+ d->object = o;
+}
+
+/*!
+ \qmlproperty bool PropertyChanges::restoreEntryValues
+
+ Whether or not the previous values should be restored when
+ leaving the state. By default, restoreEntryValues is true.
+
+ By setting restoreEntryValues to false, you can create a temporary state
+ that has permanent effects on property values.
+*/
+bool QmlPropertyChanges::restoreEntryValues() const
+{
+ Q_D(const QmlPropertyChanges);
+ return d->restore;
+}
+
+void QmlPropertyChanges::setRestoreEntryValues(bool v)
+{
+ Q_D(QmlPropertyChanges);
+ d->restore = v;
+}
+
+QmlMetaProperty
+QmlPropertyChangesPrivate::property(const QByteArray &property)
+{
+ Q_Q(QmlPropertyChanges);
+ QmlMetaProperty prop = QmlMetaProperty::createProperty(object, QString::fromUtf8(property));
+ if (!prop.isValid()) {
+ qmlInfo(q) << QmlPropertyChanges::tr("Cannot assign to non-existant property \"%1\"").arg(QString::fromUtf8(property));
+ return QmlMetaProperty();
+ } else if (!(prop.type() & QmlMetaProperty::SignalProperty) && !prop.isWritable()) {
+ qmlInfo(q) << QmlPropertyChanges::tr("Cannot assign to read-only property \"%1\"").arg(QString::fromUtf8(property));
+ return QmlMetaProperty();
+ }
+ return prop;
+}
+
+QmlPropertyChanges::ActionList QmlPropertyChanges::actions()
+{
+ Q_D(QmlPropertyChanges);
+
+ d->decode();
+
+ ActionList list;
+
+ for (int ii = 0; ii < d->properties.count(); ++ii) {
+
+ QByteArray property = d->properties.at(ii).first;
+
+ QmlAction a(d->object, QString::fromLatin1(property),
+ d->properties.at(ii).second);
+
+ if (a.property.isValid()) {
+ a.restore = restoreEntryValues();
+
+ if (a.property.propertyType() == QVariant::Url &&
+ (a.toValue.userType() == QVariant::String || a.toValue.userType() == QVariant::ByteArray) && !a.toValue.isNull())
+ a.toValue.setValue(qmlContext(this)->resolvedUrl(QUrl(a.toValue.toString())));
+
+ list << a;
+ }
+ }
+
+ for (int ii = 0; ii < d->signalReplacements.count(); ++ii) {
+
+ QmlReplaceSignalHandler *handler = d->signalReplacements.at(ii);
+
+ if (handler->property.isValid()) {
+ QmlAction a;
+ a.event = handler;
+ list << a;
+ }
+ }
+
+ for (int ii = 0; ii < d->expressions.count(); ++ii) {
+
+ QByteArray property = d->expressions.at(ii).first;
+ QmlMetaProperty prop = d->property(property);
+
+ if (prop.isValid()) {
+ QmlAction a;
+ a.restore = restoreEntryValues();
+ a.property = prop;
+ a.fromValue = a.property.read();
+ a.specifiedObject = d->object;
+ a.specifiedProperty = QString::fromLatin1(property);
+
+ if (d->isExplicit) {
+ a.toValue = d->expressions.at(ii).second->value();
+ } else {
+ QmlBinding *newBinding = new QmlBinding(d->expressions.at(ii).second->expression(), object(), qmlContext(this));
+ newBinding->setTarget(prop);
+ a.toBinding = newBinding;
+ a.deletableToBinding = true;
+ }
+
+ list << a;
+ }
+ }
+
+ return list;
+}
+
+/*!
+ \qmlproperty bool 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 myItem.width from
+ being bound to parent.width. Instead, it is assigned the value of 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 QmlPropertyChanges::isExplicit() const
+{
+ Q_D(const QmlPropertyChanges);
+ return d->isExplicit;
+}
+
+void QmlPropertyChanges::setIsExplicit(bool e)
+{
+ Q_D(QmlPropertyChanges);
+ d->isExplicit = e;
+}
+
+QML_DEFINE_CUSTOM_TYPE(Qt, 4,6, PropertyChanges, QmlPropertyChanges, QmlPropertyChangesParser)
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlpropertychanges_p.h b/src/declarative/util/qmlpropertychanges_p.h
new file mode 100644
index 0000000..461730d
--- /dev/null
+++ b/src/declarative/util/qmlpropertychanges_p.h
@@ -0,0 +1,84 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPROPERTYCHANGES_H
+#define QMLPROPERTYCHANGES_H
+
+#include "qmlstateoperations_p.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlPropertyChangesPrivate;
+class Q_DECLARATIVE_EXPORT QmlPropertyChanges : public QmlStateOperation
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlPropertyChanges)
+
+ 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:
+ QmlPropertyChanges();
+ ~QmlPropertyChanges();
+
+ QObject *object() const;
+ void setObject(QObject *);
+
+ bool restoreEntryValues() const;
+ void setRestoreEntryValues(bool);
+
+ bool isExplicit() const;
+ void setIsExplicit(bool);
+
+ virtual ActionList actions();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlPropertyChanges)
+
+QT_END_HEADER
+
+#endif // QMLPROPERTYCHANGES_H
diff --git a/src/declarative/util/qmlpropertymap.cpp b/src/declarative/util/qmlpropertymap.cpp
new file mode 100644
index 0000000..226f82e
--- /dev/null
+++ b/src/declarative/util/qmlpropertymap.cpp
@@ -0,0 +1,278 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlpropertymap.h"
+
+#include "qmlopenmetaobject_p.h"
+
+#include <QDebug>
+
+QT_BEGIN_NAMESPACE
+
+//QmlPropertyMapMetaObject lets us listen for changes coming from QML
+//so we can emit the changed signal.
+class QmlPropertyMapMetaObject : public QmlOpenMetaObject
+{
+public:
+ QmlPropertyMapMetaObject(QmlPropertyMap *obj, QmlPropertyMapPrivate *objPriv);
+
+protected:
+ virtual void propertyWrite(int index);
+
+private:
+ QmlPropertyMap *map;
+ QmlPropertyMapPrivate *priv;
+};
+
+class QmlPropertyMapPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlPropertyMap)
+public:
+ QmlPropertyMapMetaObject *mo;
+ QStringList keys;
+ void emitChanged(const QString &key);
+};
+
+void QmlPropertyMapPrivate::emitChanged(const QString &key)
+{
+ Q_Q(QmlPropertyMap);
+ emit q->valueChanged(key);
+}
+
+QmlPropertyMapMetaObject::QmlPropertyMapMetaObject(QmlPropertyMap *obj, QmlPropertyMapPrivate *objPriv) : QmlOpenMetaObject(obj)
+{
+ map = obj;
+ priv = objPriv;
+}
+
+void QmlPropertyMapMetaObject::propertyWrite(int index)
+{
+ priv->emitChanged(QString::fromUtf8(name(index)));
+}
+
+/*!
+ \class QmlPropertyMap
+ \brief The QmlPropertyMap class allows you to set key-value pairs that can be used in bindings.
+
+ QmlPropertyMap provides a convenient way to expose domain data to the UI layer.
+ The following example shows how you might declare data in C++ and then
+ access it in QML.
+
+ Setup in C++:
+ \code
+ //create our data
+ QmlPropertyMap ownerData;
+ ownerData.insert("name", QVariant(QString("John Smith")));
+ ownerData.insert("phone", QVariant(QString("555-5555")));
+
+ //expose it to the UI layer
+ QmlContext *ctxt = view->bindContext();
+ ctxt->setProperty("owner", &data);
+ \endcode
+
+ Then, in QML:
+ \code
+ Text { text: owner.name }
+ Text { text: owner.phone }
+ \endcode
+
+ The binding is dynamic - whenever a key's value is updated, anything bound to that
+ key will be updated as well.
+
+ To detect value changes made in the UI layer you can connect to the valueChanged() signal.
+ However, note that valueChanged() is \bold NOT emitted when changes are made by calling insert()
+ or clear() - it is only emitted when a value is updated from QML.
+
+ \note It is not possible to remove keys from the map; once a key has been added, you can only
+ modify or clear its associated value.
+*/
+
+/*!
+ Constructs a bindable map with parent object \a parent.
+*/
+QmlPropertyMap::QmlPropertyMap(QObject *parent)
+: QObject(*(new QmlPropertyMapPrivate), parent)
+{
+ Q_D(QmlPropertyMap);
+ d->mo = new QmlPropertyMapMetaObject(this, d);
+}
+
+/*!
+ Destroys the bindable map.
+*/
+QmlPropertyMap::~QmlPropertyMap()
+{
+}
+
+/*!
+ Clears the value (if any) associated with \a key.
+*/
+void QmlPropertyMap::clear(const QString &key)
+{
+ Q_D(QmlPropertyMap);
+ d->mo->setValue(key.toUtf8(), QVariant());
+}
+
+/*!
+ Returns the value associated with \a key.
+
+ If no value has been set for this key (or if the value has been cleared),
+ an invalid QVariant is returned.
+*/
+QVariant QmlPropertyMap::value(const QString &key) const
+{
+ Q_D(const QmlPropertyMap);
+ return d->mo->value(key.toUtf8());
+}
+
+/*!
+ Sets the value associated with \a key to \a value.
+
+ If the key doesn't exist, it is automatically created.
+*/
+void QmlPropertyMap::insert(const QString &key, const QVariant &value)
+{
+ Q_D(QmlPropertyMap);
+ if (!d->keys.contains(key))
+ d->keys.append(key);
+ d->mo->setValue(key.toUtf8(), value);
+}
+
+/*!
+ Returns the list of keys.
+
+ Keys that have been cleared will still appear in this list, even though their
+ associated values are invalid QVariants.
+*/
+QStringList QmlPropertyMap::keys() const
+{
+ Q_D(const QmlPropertyMap);
+ return d->keys;
+}
+
+/*!
+ \overload
+
+ Same as size().
+*/
+int QmlPropertyMap::count() const
+{
+ Q_D(const QmlPropertyMap);
+ return d->keys.count();
+}
+
+/*!
+ Returns the number of keys in the map.
+
+ \sa isEmpty(), count()
+*/
+int QmlPropertyMap::size() const
+{
+ Q_D(const QmlPropertyMap);
+ return d->keys.size();
+}
+
+/*!
+ Returns true if the map contains no keys; otherwise returns
+ false.
+
+ \sa size()
+*/
+bool QmlPropertyMap::isEmpty() const
+{
+ Q_D(const QmlPropertyMap);
+ return d->keys.isEmpty();
+}
+
+/*!
+ Returns true if the map contains \a key.
+
+ \sa size()
+*/
+bool QmlPropertyMap::contains(const QString &key) const
+{
+ Q_D(const QmlPropertyMap);
+ return d->keys.contains(key);
+}
+
+/*!
+ Returns the value associated with the key \a key as a modifiable
+ reference.
+
+ If the map contains no item with key \a key, the function inserts
+ an invalid QVariant into the map with key \a key, and
+ returns a reference to it.
+
+ \sa insert(), value()
+*/
+QVariant &QmlPropertyMap::operator[](const QString &key)
+{
+ //### optimize
+ Q_D(QmlPropertyMap);
+ QByteArray utf8key = key.toUtf8();
+ if (!d->keys.contains(key)) {
+ d->keys.append(key);
+ d->mo->setValue(utf8key, QVariant()); //force creation -- needed below
+ }
+
+ return (*(d->mo))[utf8key];
+}
+
+/*!
+ \overload
+
+ Same as value().
+*/
+const QVariant QmlPropertyMap::operator[](const QString &key) const
+{
+ return value(key);
+}
+
+/*!
+ \fn void QmlPropertyMap::valueChanged(const QString &key)
+ This signal is emitted whenever one of the values in the map is changed. \a key
+ is the key corresponding to the value that was changed.
+
+ \note valueChanged() is \bold NOT emitted when changes are made by calling insert()
+ or clear() - it is only emitted when a value is updated from QML.
+*/
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlpropertymap.h b/src/declarative/util/qmlpropertymap.h
new file mode 100644
index 0000000..bb397fe
--- /dev/null
+++ b/src/declarative/util/qmlpropertymap.h
@@ -0,0 +1,90 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLPROPERTYMAP_H
+#define QMLPROPERTYMAP_H
+
+#include <QtCore/QObject>
+#include <QtCore/QHash>
+#include <QtCore/QStringList>
+#include <QtCore/QVariant>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlPropertyMapPrivate;
+class Q_DECLARATIVE_EXPORT QmlPropertyMap : public QObject
+{
+ Q_OBJECT
+public:
+ QmlPropertyMap(QObject *parent = 0);
+ virtual ~QmlPropertyMap();
+
+ QVariant value(const QString &key) const;
+ void insert(const QString &key, const QVariant &value);
+ void clear(const QString &key);
+
+ Q_INVOKABLE QStringList keys() const;
+
+ int count() const;
+ int size() const;
+ bool isEmpty() const;
+ bool contains(const QString &key) const;
+
+ QVariant &operator[](const QString &key);
+ const QVariant operator[](const QString &key) const;
+
+Q_SIGNALS:
+ void valueChanged(const QString &key);
+
+private:
+ Q_DECLARE_PRIVATE(QmlPropertyMap)
+ Q_DISABLE_COPY(QmlPropertyMap)
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/util/qmlspringfollow.cpp b/src/declarative/util/qmlspringfollow.cpp
new file mode 100644
index 0000000..764d7f9
--- /dev/null
+++ b/src/declarative/util/qmlspringfollow.cpp
@@ -0,0 +1,464 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlspringfollow_p.h"
+
+#include "qmlanimation_p_p.h"
+
+#include <QtCore/qdebug.h>
+
+#include <private/qobject_p.h>
+
+#include <limits.h>
+#include <math.h>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,SpringFollow,QmlSpringFollow)
+
+class QmlSpringFollowPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlSpringFollow)
+public:
+ QmlSpringFollowPrivate()
+ : currentValue(0), sourceValue(0), maxVelocity(0), lastTime(0)
+ , mass(1.0), spring(0.), damping(0.), velocity(0), epsilon(0.01)
+ , modulus(0.0), useMass(false), haveModulus(false), enabled(true), mode(Track), clock(this) {}
+
+ QmlMetaProperty property;
+ qreal currentValue;
+ qreal sourceValue;
+ qreal maxVelocity;
+ qreal velocityms;
+ int lastTime;
+ qreal mass;
+ qreal spring;
+ qreal damping;
+ qreal velocity;
+ qreal epsilon;
+ qreal modulus;
+
+ bool useMass : 1;
+ bool haveModulus : 1;
+ bool enabled : 1;
+
+ enum Mode {
+ Track,
+ Velocity,
+ Spring
+ };
+ Mode mode;
+
+ void tick(int);
+ void updateMode();
+ void start();
+ void stop();
+
+ QTickAnimationProxy<QmlSpringFollowPrivate, &QmlSpringFollowPrivate::tick> clock;
+};
+
+void QmlSpringFollowPrivate::tick(int time)
+{
+ Q_Q(QmlSpringFollow);
+
+ int elapsed = time - lastTime;
+ if (!elapsed)
+ return;
+ qreal srcVal = sourceValue;
+ if (haveModulus) {
+ currentValue = fmod(currentValue, modulus);
+ srcVal = fmod(srcVal, modulus);
+ }
+ if (mode == Spring) {
+ if (elapsed < 16) // capped at 62fps.
+ return;
+ // 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 - currentValue;
+ if (haveModulus && qAbs(diff) > modulus / 2) {
+ if (diff < 0)
+ diff += modulus;
+ else
+ diff -= modulus;
+ }
+ if (useMass)
+ velocity = velocity + (spring * diff - damping * velocity) / mass;
+ else
+ velocity = velocity + spring * diff - damping * velocity;
+ if (maxVelocity > 0.) {
+ // limit velocity
+ if (velocity > maxVelocity)
+ velocity = maxVelocity;
+ else if (velocity < -maxVelocity)
+ velocity = -maxVelocity;
+ }
+ currentValue += velocity * 16.0 / 1000.0;
+ if (haveModulus) {
+ currentValue = fmod(currentValue, modulus);
+ if (currentValue < 0.0)
+ currentValue += modulus;
+ }
+ }
+ if (qAbs(velocity) < epsilon && qAbs(srcVal - currentValue) < epsilon) {
+ velocity = 0.0;
+ currentValue = srcVal;
+ clock.stop();
+ }
+ lastTime = time - (elapsed - count * 16);
+ } else {
+ qreal moveBy = elapsed * velocityms;
+ qreal diff = srcVal - currentValue;
+ if (haveModulus && qAbs(diff) > modulus / 2) {
+ if (diff < 0)
+ diff += modulus;
+ else
+ diff -= modulus;
+ }
+ if (diff > 0) {
+ currentValue += moveBy;
+ if (haveModulus)
+ currentValue = fmod(currentValue, modulus);
+ if (currentValue > sourceValue) {
+ currentValue = sourceValue;
+ clock.stop();
+ }
+ } else {
+ currentValue -= moveBy;
+ if (haveModulus && currentValue < 0.0)
+ currentValue = fmod(currentValue, modulus) + modulus;
+ if (currentValue < sourceValue) {
+ currentValue = sourceValue;
+ clock.stop();
+ }
+ }
+ lastTime = time;
+ }
+ property.write(currentValue);
+ emit q->valueChanged(currentValue);
+ if (clock.state() != QAbstractAnimation::Running)
+ emit q->syncChanged();
+}
+
+void QmlSpringFollowPrivate::updateMode()
+{
+ if (spring == 0. && maxVelocity == 0.)
+ mode = Track;
+ else if (spring > 0.)
+ mode = Spring;
+ else
+ mode = Velocity;
+}
+
+void QmlSpringFollowPrivate::start()
+{
+ if (!enabled)
+ return;
+
+ Q_Q(QmlSpringFollow);
+ if (mode == QmlSpringFollowPrivate::Track) {
+ currentValue = sourceValue;
+ property.write(currentValue);
+ } else if (sourceValue != currentValue && clock.state() != QAbstractAnimation::Running) {
+ lastTime = 0;
+ currentValue = property.read().toReal();
+ clock.start(); // infinity??
+ emit q->syncChanged();
+ }
+}
+
+void QmlSpringFollowPrivate::stop()
+{
+ clock.stop();
+}
+
+/*!
+ \qmlclass SpringFollow QmlSpringFollow
+ \brief The SpringFollow element allows a property to track a value.
+
+ In example below, \e rect2 will follow \e rect1 moving with a velocity of up to 200:
+ \code
+ Rectangle {
+ id: rect1
+ width: 20; height: 20
+ color: "#00ff00"
+ y: 200 //initial value
+ y: SequentialAnimation {
+ running: true
+ repeat: true
+ NumberAnimation {
+ to: 200
+ easing: "easeOutBounce(amplitude:100)"
+ duration: 2000
+ }
+ PauseAnimation { duration: 1000 }
+ }
+ }
+ Rectangle {
+ id: rect2
+ x: rect1.width
+ width: 20; height: 20
+ color: "#ff0000"
+ y: SpringFollow { source: rect1.y; velocity: 200 }
+ }
+ \endcode
+
+ \sa EaseFollow
+*/
+
+QmlSpringFollow::QmlSpringFollow(QObject *parent)
+: QObject(*(new QmlSpringFollowPrivate),parent)
+{
+}
+
+QmlSpringFollow::~QmlSpringFollow()
+{
+}
+
+void QmlSpringFollow::setTarget(const QmlMetaProperty &property)
+{
+ Q_D(QmlSpringFollow);
+ d->property = property;
+ d->currentValue = property.read().toReal();
+}
+
+qreal QmlSpringFollow::sourceValue() const
+{
+ Q_D(const QmlSpringFollow);
+ return d->sourceValue;
+}
+
+/*!
+ \qmlproperty qreal SpringFollow::source
+ This property holds the source value which will be tracked.
+
+ Bind to a property in order to track its changes.
+*/
+
+void QmlSpringFollow::setSourceValue(qreal value)
+{
+ Q_D(QmlSpringFollow);
+ if (d->clock.state() == QAbstractAnimation::Running && d->sourceValue == value)
+ return;
+
+ d->sourceValue = value;
+ d->start();
+}
+
+/*!
+ \qmlproperty qreal SpringFollow::velocity
+ This property holds the maximum velocity allowed when tracking the source.
+*/
+
+qreal QmlSpringFollow::velocity() const
+{
+ Q_D(const QmlSpringFollow);
+ return d->maxVelocity;
+}
+
+void QmlSpringFollow::setVelocity(qreal velocity)
+{
+ Q_D(QmlSpringFollow);
+ d->maxVelocity = velocity;
+ d->velocityms = velocity / 1000.0;
+ d->updateMode();
+}
+
+/*!
+ \qmlproperty qreal SpringFollow::spring
+ This property holds the spring constant
+
+ The spring constant describes how strongly the target is pulled towards the
+ source. Setting spring to 0 turns off spring tracking. Useful values 0 - 5.0
+
+ When a spring constant is set and the velocity property is greater than 0,
+ velocity limits the maximum speed.
+*/
+qreal QmlSpringFollow::spring() const
+{
+ Q_D(const QmlSpringFollow);
+ return d->spring;
+}
+
+void QmlSpringFollow::setSpring(qreal spring)
+{
+ Q_D(QmlSpringFollow);
+ d->spring = spring;
+ d->updateMode();
+}
+
+/*!
+ \qmlproperty qreal SpringFollow::damping
+ This property holds the spring damping constant
+
+ The damping constant describes how quickly a sprung follower comes to rest.
+ Useful range is 0 - 1.0
+*/
+qreal QmlSpringFollow::damping() const
+{
+ Q_D(const QmlSpringFollow);
+ return d->damping;
+}
+
+void QmlSpringFollow::setDamping(qreal damping)
+{
+ Q_D(QmlSpringFollow);
+ if (damping > 1.)
+ damping = 1.;
+
+ d->damping = damping;
+}
+
+
+/*!
+ \qmlproperty qreal SpringFollow::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 QmlSpringFollow::epsilon() const
+{
+ Q_D(const QmlSpringFollow);
+ return d->epsilon;
+}
+
+void QmlSpringFollow::setEpsilon(qreal epsilon)
+{
+ Q_D(QmlSpringFollow);
+ d->epsilon = epsilon;
+}
+
+/*!
+ \qmlproperty qreal SpringFollow::modulus
+ This property holds the modulus value.
+
+ 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 QmlSpringFollow::modulus() const
+{
+ Q_D(const QmlSpringFollow);
+ return d->modulus;
+}
+
+void QmlSpringFollow::setModulus(qreal modulus)
+{
+ Q_D(QmlSpringFollow);
+ if (d->modulus != modulus) {
+ d->haveModulus = modulus != 0.0;
+ d->modulus = modulus;
+ emit modulusChanged();
+ }
+}
+
+/*!
+ \qmlproperty qreal SpringFollow::mass
+ This property holds the "mass" of the property being moved.
+
+ mass is 1.0 by default. Setting a different mass changes the dynamics of
+ a \l spring follow.
+*/
+qreal QmlSpringFollow::mass() const
+{
+ Q_D(const QmlSpringFollow);
+ return d->mass;
+}
+
+void QmlSpringFollow::setMass(qreal mass)
+{
+ Q_D(QmlSpringFollow);
+ if (d->mass != mass && mass > 0.0) {
+ d->useMass = mass != 1.0;
+ d->mass = mass;
+ emit massChanged();
+ }
+}
+
+/*!
+ \qmlproperty qreal SpringFollow::value
+ The current value.
+*/
+
+/*!
+ \qmlproperty bool SpringFollow::enabled
+ This property holds whether the target will track the source.
+*/
+bool QmlSpringFollow::enabled() const
+{
+ Q_D(const QmlSpringFollow);
+ return d->enabled;
+}
+
+void QmlSpringFollow::setEnabled(bool enabled)
+{
+ Q_D(QmlSpringFollow);
+ d->enabled = enabled;
+ if (enabled)
+ d->start();
+ else
+ d->stop();
+}
+
+/*!
+ \qmlproperty bool SpringFollow::inSync
+ This property is true when target is equal to the source; otherwise
+ false. If inSync is true the target is not being animated.
+
+ If \l enabled is false then inSync will also be false.
+*/
+bool QmlSpringFollow::inSync() const
+{
+ Q_D(const QmlSpringFollow);
+ return d->enabled && d->clock.state() != QAbstractAnimation::Running;
+}
+
+qreal QmlSpringFollow::value() const
+{
+ Q_D(const QmlSpringFollow);
+ return d->currentValue;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlspringfollow_p.h b/src/declarative/util/qmlspringfollow_p.h
new file mode 100644
index 0000000..7731b9e
--- /dev/null
+++ b/src/declarative/util/qmlspringfollow_p.h
@@ -0,0 +1,112 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSMOOTHFOLLOW_H
+#define QMLSMOOTHFOLLOW_H
+
+#include <qmlpropertyvaluesource.h>
+#include <qml.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlSpringFollowPrivate;
+class Q_DECLARATIVE_EXPORT QmlSpringFollow : public QObject,
+ public QmlPropertyValueSource
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlSpringFollow)
+ Q_INTERFACES(QmlPropertyValueSource)
+
+ Q_PROPERTY(qreal source READ sourceValue WRITE setSourceValue)
+ Q_PROPERTY(qreal velocity READ velocity WRITE setVelocity)
+ Q_PROPERTY(qreal spring READ spring WRITE setSpring)
+ Q_PROPERTY(qreal damping READ damping WRITE setDamping)
+ Q_PROPERTY(qreal epsilon READ epsilon WRITE setEpsilon)
+ Q_PROPERTY(bool enabled READ enabled WRITE setEnabled)
+ Q_PROPERTY(qreal value READ value NOTIFY valueChanged)
+ Q_PROPERTY(qreal modulus READ modulus WRITE setModulus NOTIFY modulusChanged)
+ Q_PROPERTY(qreal mass READ mass WRITE setMass NOTIFY massChanged)
+ Q_PROPERTY(bool inSync READ inSync NOTIFY syncChanged)
+
+public:
+ QmlSpringFollow(QObject *parent=0);
+ ~QmlSpringFollow();
+
+ virtual void setTarget(const QmlMetaProperty &);
+
+ qreal sourceValue() const;
+ void setSourceValue(qreal value);
+ 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);
+ bool enabled() const;
+ void setEnabled(bool enabled);
+ bool inSync() const;
+
+ qreal value() const;
+
+Q_SIGNALS:
+ void valueChanged(qreal);
+ void modulusChanged();
+ void massChanged();
+ void syncChanged();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlSpringFollow)
+
+QT_END_HEADER
+
+#endif // QMLSMOOTHFOLLOW_H
diff --git a/src/declarative/util/qmlstate.cpp b/src/declarative/util/qmlstate.cpp
new file mode 100644
index 0000000..cae8054
--- /dev/null
+++ b/src/declarative/util/qmlstate.cpp
@@ -0,0 +1,468 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlstate_p_p.h"
+#include "qmlstate_p.h"
+
+#include "qmltransition_p.h"
+#include "qmlstategroup_p.h"
+#include "qmlstateoperations_p.h"
+#include "qmlanimation_p.h"
+#include "qmlanimation_p_p.h"
+
+#include <qmlbinding.h>
+#include <qmlglobal_p.h>
+
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG);
+
+QmlAction::QmlAction()
+: restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false), fromBinding(0), toBinding(0), event(0),
+ specifiedObject(0)
+{
+}
+
+QmlAction::QmlAction(QObject *target, const QString &propertyName,
+ const QVariant &value)
+: restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false), toValue(value), fromBinding(0),
+ toBinding(0), event(0), specifiedObject(target),
+ specifiedProperty(propertyName)
+{
+ property = QmlMetaProperty::createProperty(target, propertyName);
+ if (property.isValid())
+ fromValue = property.read();
+}
+
+QmlActionEvent::~QmlActionEvent()
+{
+}
+
+QString QmlActionEvent::typeName() const
+{
+ return QString();
+}
+
+void QmlActionEvent::execute()
+{
+}
+
+bool QmlActionEvent::isReversable()
+{
+ return false;
+}
+
+void QmlActionEvent::reverse()
+{
+}
+
+QList<QmlAction> QmlActionEvent::extraActions()
+{
+ return QList<QmlAction>();
+}
+
+bool QmlActionEvent::changesBindings()
+{
+ return false;
+}
+
+void QmlActionEvent::clearForwardBindings()
+{
+}
+
+void QmlActionEvent::clearReverseBindings()
+{
+}
+
+bool QmlActionEvent::override(QmlActionEvent *other)
+{
+ Q_UNUSED(other);
+ return false;
+}
+
+/*!
+ \internal
+*/
+QmlStateOperation::QmlStateOperation(QObjectPrivate &dd, QObject *parent)
+ : QObject(dd, parent)
+{
+}
+
+/*!
+ \qmlclass State QmlState
+ \brief The State element defines configurations of objects and properties.
+
+ A state is specified as a set of batched changes from the default configuration.
+
+ Note that setting the state of an object from within another state of the same object is
+ inadvisible. Not only would this have the same effect as going directly to the second state
+ it may cause the program to crash.
+
+ \sa {qmlstates}{States}, {state-transitions}{Transitions}
+*/
+
+/*!
+ \internal
+ \class QmlState
+ \brief The QmlState class allows you to define configurations of objects and properties.
+
+ \ingroup group_states
+
+ QmlState allows you to specify a state as a set of batched changes from the default
+ configuration.
+
+ \sa {states-transitions}{States and Transitions}
+*/
+
+QML_DEFINE_TYPE(Qt,4,6,State,QmlState)
+QmlState::QmlState(QObject *parent)
+: QObject(*(new QmlStatePrivate), parent)
+{
+ Q_D(QmlState);
+ d->transitionManager.setState(this);
+}
+
+QmlState::~QmlState()
+{
+ Q_D(QmlState);
+ if (d->group)
+ d->group->removeState(this);
+}
+
+/*!
+ \qmlproperty string State::name
+ This property holds the name of the state
+
+ Each state should have a unique name.
+*/
+QString QmlState::name() const
+{
+ Q_D(const QmlState);
+ return d->name;
+}
+
+void QmlState::setName(const QString &n)
+{
+ Q_D(QmlState);
+ d->name = n;
+}
+
+bool QmlState::isWhenKnown() const
+{
+ Q_D(const QmlState);
+ return d->when != 0;
+}
+
+/*!
+ \qmlproperty bool State::when
+ This property holds when the state should be applied
+
+ This should be set to an expression that evaluates to true when you want the state to
+ be applied.
+*/
+QmlBinding *QmlState::when() const
+{
+ Q_D(const QmlState);
+ return d->when;
+}
+
+void QmlState::setWhen(QmlBinding *when)
+{
+ Q_D(QmlState);
+ d->when = when;
+ if (d->group)
+ d->group->updateAutoState();
+}
+
+/*!
+ \qmlproperty string State::extend
+ This property holds the state that this state extends
+
+ The state being extended is treated as the base state in regards to
+ the changes specified by the extending state.
+*/
+QString QmlState::extends() const
+{
+ Q_D(const QmlState);
+ return d->extends;
+}
+
+void QmlState::setExtends(const QString &extends)
+{
+ Q_D(QmlState);
+ d->extends = extends;
+}
+
+/*!
+ \qmlproperty list<Change> 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.
+*/
+QmlList<QmlStateOperation *> *QmlState::changes()
+{
+ Q_D(QmlState);
+ return &d->operations;
+}
+
+QmlState &QmlState::operator<<(QmlStateOperation *op)
+{
+ Q_D(QmlState);
+ d->operations.append(op);
+ return *this;
+}
+
+void QmlStatePrivate::complete()
+{
+ Q_Q(QmlState);
+
+ for (int ii = 0; ii < reverting.count(); ++ii) {
+ for (int jj = 0; jj < revertList.count(); ++jj) {
+ if (revertList.at(jj).property == reverting.at(ii)) {
+ revertList.removeAt(jj);
+ break;
+ }
+ }
+ }
+ reverting.clear();
+
+ emit q->completed();
+}
+
+// Generate a list of actions for this state. This includes coelescing state
+// actions that this state "extends"
+QmlStateOperation::ActionList
+QmlStatePrivate::generateActionList(QmlStateGroup *group) const
+{
+ QmlStateOperation::ActionList applyList;
+ if (inState)
+ return applyList;
+
+ // Prevent "extends" recursion
+ inState = true;
+
+ if (!extends.isEmpty()) {
+ QList<QmlState *> states = group->states();
+ for (int ii = 0; ii < states.count(); ++ii)
+ if (states.at(ii)->name() == extends)
+ applyList = static_cast<QmlStatePrivate*>(states.at(ii)->d_func())->generateActionList(group);
+ }
+
+ foreach(QmlStateOperation *op, operations)
+ applyList << op->actions();
+
+ inState = false;
+ return applyList;
+}
+
+QmlStateGroup *QmlState::stateGroup() const
+{
+ Q_D(const QmlState);
+ return d->group;
+}
+
+void QmlState::setStateGroup(QmlStateGroup *group)
+{
+ Q_D(QmlState);
+ d->group = group;
+}
+
+void QmlState::cancel()
+{
+ Q_D(QmlState);
+ d->transitionManager.cancel();
+}
+
+void QmlAction::deleteFromBinding()
+{
+ if (fromBinding) {
+ property.setBinding(0);
+ fromBinding->destroy();
+ fromBinding = 0;
+ }
+}
+
+void QmlState::apply(QmlStateGroup *group, QmlTransition *trans, QmlState *revert)
+{
+ Q_D(QmlState);
+
+ qmlExecuteDeferred(this);
+
+ cancel();
+ if (revert)
+ revert->cancel();
+ d->revertList.clear();
+ d->reverting.clear();
+
+ if (revert) {
+ QmlStatePrivate *revertPrivate =
+ static_cast<QmlStatePrivate*>(revert->d_func());
+ d->revertList = revertPrivate->revertList;
+ revertPrivate->revertList.clear();
+ }
+
+ // List of actions caused by this state
+ QmlStateOperation::ActionList applyList = d->generateActionList(group);
+
+ // List of actions that need to be reverted to roll back (just) this state
+ QmlStatePrivate::SimpleActionList additionalReverts;
+ // First add the reverse of all the applyList actions
+ for (int ii = 0; ii < applyList.count(); ++ii) {
+ QmlAction &action = applyList[ii];
+
+ bool found = false;
+
+ int jj;
+ if (action.event) {
+ if (!action.event->isReversable())
+ continue;
+ for (jj = 0; jj < d->revertList.count(); ++jj) {
+ QmlActionEvent *event = d->revertList.at(jj).event;
+ if (event && event->typeName() == action.event->typeName()) {
+ if (action.event->override(event)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ if (!found || action.event != d->revertList.at(jj).event)
+ action.event->saveOriginals();
+ else if (action.event->isRewindable())
+ action.event->saveCurrentValues();
+ } else {
+ action.fromBinding = action.property.binding();
+
+ for (jj = 0; jj < d->revertList.count(); ++jj) {
+ if (d->revertList.at(jj).property == action.property) {
+ found = true;
+ 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
+ QmlSimpleAction r(action);
+ additionalReverts << r;
+ }
+ } else if (d->revertList.at(jj).binding != action.fromBinding) {
+ action.deleteFromBinding();
+ }
+ }
+
+ // 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) {
+ QmlActionEvent *event = d->revertList.at(ii).event;
+ if (!event->isReversable())
+ continue;
+ for (int jj = 0; !found && jj < applyList.count(); ++jj) {
+ const QmlAction &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 QmlAction &action = applyList.at(jj);
+ if (action.property == d->revertList.at(ii).property)
+ found = true;
+ }
+ }
+ if (!found) {
+ QVariant cur = d->revertList.at(ii).property.read();
+ QmlAbstractBinding *delBinding = d->revertList.at(ii).property.setBinding(0);
+ if (delBinding)
+ delBinding->destroy();
+
+ QmlAction a;
+ a.property = d->revertList.at(ii).property;
+ a.fromValue = cur;
+ a.toValue = d->revertList.at(ii).value;
+ a.toBinding = 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
+ d->reverting << d->revertList.at(ii).property;
+ }
+ }
+ // All the local reverts now become part of the ongoing revertList
+ d->revertList << additionalReverts;
+
+ // Output for debugging
+ if (stateChangeDebug()) {
+ foreach(const QmlAction &action, applyList) {
+ if (action.event)
+ qWarning() << " QmlAction event:" << action.event->typeName();
+ else
+ qWarning() << " QmlAction:" << action.property.object()
+ << action.property.name() << "From:" << action.fromValue
+ << "To:" << action.toValue;
+ }
+ }
+
+ d->transitionManager.transition(applyList, trans);
+}
+
+QML_DEFINE_NOCREATE_TYPE(QmlStateOperation)
+QmlStateOperation::ActionList QmlStateOperation::actions()
+{
+ return ActionList();
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlstate_p.h b/src/declarative/util/qmlstate_p.h
new file mode 100644
index 0000000..5862c02
--- /dev/null
+++ b/src/declarative/util/qmlstate_p.h
@@ -0,0 +1,178 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSTATE_H
+#define QMLSTATE_H
+
+#include <qml.h>
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlActionEvent;
+class QmlBinding;
+class Q_DECLARATIVE_EXPORT QmlAction
+{
+public:
+ QmlAction();
+ QmlAction(QObject *, const QString &, const QVariant &);
+
+ bool restore:1;
+ bool actionDone:1;
+ bool reverseEvent:1;
+ bool deletableToBinding:1;
+
+ QmlMetaProperty property;
+ QVariant fromValue;
+ QVariant toValue;
+
+ QmlAbstractBinding *fromBinding;
+ QmlAbstractBinding *toBinding;
+ QmlActionEvent *event;
+
+ //strictly for matching
+ QObject *specifiedObject;
+ QString specifiedProperty;
+
+ void deleteFromBinding();
+};
+
+class QmlActionEvent
+{
+public:
+ virtual ~QmlActionEvent();
+ virtual QString typeName() const;
+
+ virtual void execute();
+ virtual bool isReversable();
+ virtual void reverse();
+ virtual void saveOriginals() {}
+
+ virtual bool isRewindable() { return isReversable(); }
+ virtual void rewind() {}
+ virtual void saveCurrentValues() {}
+
+ //virtual bool hasExtraActions();
+ virtual QList<QmlAction> extraActions();
+
+ virtual bool changesBindings();
+ virtual void clearForwardBindings();
+ virtual void clearReverseBindings();
+ virtual bool override(QmlActionEvent*other);
+};
+
+//### rename to QmlStateChange?
+class QmlStateGroup;
+class Q_DECLARATIVE_EXPORT QmlStateOperation : public QObject
+{
+ Q_OBJECT
+public:
+ QmlStateOperation(QObject *parent = 0)
+ : QObject(parent) {}
+ typedef QList<QmlAction> ActionList;
+
+ virtual ActionList actions();
+
+protected:
+ QmlStateOperation(QObjectPrivate &dd, QObject *parent = 0);
+};
+
+typedef QmlStateOperation::ActionList QmlStateActions;
+
+class QmlTransition;
+class QmlStatePrivate;
+class Q_DECLARATIVE_EXPORT QmlState : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QString name READ name WRITE setName)
+ Q_PROPERTY(QmlBinding *when READ when WRITE setWhen)
+ Q_PROPERTY(QString extend READ extends WRITE setExtends)
+ Q_PROPERTY(QmlList<QmlStateOperation *>* changes READ changes)
+ Q_CLASSINFO("DefaultProperty", "changes")
+ Q_CLASSINFO("DeferredPropertyNames", "changes")
+
+public:
+ QmlState(QObject *parent=0);
+ virtual ~QmlState();
+
+ QString name() const;
+ void setName(const QString &);
+
+ /*'when' is a QmlBinding to limit state changes oscillation
+ due to the unpredictable order of evaluation of bound expressions*/
+ bool isWhenKnown() const;
+ QmlBinding *when() const;
+ void setWhen(QmlBinding *);
+
+ QString extends() const;
+ void setExtends(const QString &);
+
+ QmlList<QmlStateOperation *> *changes();
+ QmlState &operator<<(QmlStateOperation *);
+
+ void apply(QmlStateGroup *, QmlTransition *, QmlState *revert);
+ void cancel();
+
+ QmlStateGroup *stateGroup() const;
+ void setStateGroup(QmlStateGroup *);
+
+Q_SIGNALS:
+ void completed();
+
+private:
+ Q_DECLARE_PRIVATE(QmlState)
+ Q_DISABLE_COPY(QmlState)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlStateOperation)
+QML_DECLARE_TYPE(QmlState)
+
+QT_END_HEADER
+
+#endif // QMLSTATE_H
diff --git a/src/declarative/util/qmlstate_p_p.h b/src/declarative/util/qmlstate_p_p.h
new file mode 100644
index 0000000..235fe62
--- /dev/null
+++ b/src/declarative/util/qmlstate_p_p.h
@@ -0,0 +1,147 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSTATE_P_H
+#define QMLSTATE_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 "qmlstate_p.h"
+
+#include "qmlanimation_p_p.h"
+#include "qmltransitionmanager_p_p.h"
+
+#include <qmlguard_p.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlSimpleAction
+{
+public:
+ enum State { StartState, EndState };
+ QmlSimpleAction(const QmlAction &a, State state = StartState)
+ {
+ property = a.property;
+ specifiedObject = a.specifiedObject;
+ specifiedProperty = a.specifiedProperty;
+ event = a.event;
+ if (state == StartState) {
+ value = a.fromValue;
+ binding = property.binding();
+ reverseEvent = true;
+ } else {
+ value = a.toValue;
+ binding = a.toBinding;
+ reverseEvent = false;
+ }
+ }
+
+ QmlMetaProperty property;
+ QVariant value;
+ QmlAbstractBinding *binding;
+ QObject *specifiedObject;
+ QString specifiedProperty;
+ QmlActionEvent *event;
+ bool reverseEvent;
+};
+
+class QmlStatePrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlState)
+
+public:
+ QmlStatePrivate()
+ : when(0), inState(false), group(0) {}
+
+ typedef QList<QmlSimpleAction> SimpleActionList;
+
+ QString name;
+ QmlBinding *when;
+
+ class OperationList;
+ struct OperationGuard : public QmlGuard<QmlStateOperation>
+ {
+ OperationGuard(QObject *obj, OperationList *l) : list(l) { (QmlGuard<QObject>&)*this = obj; }
+ OperationList *list;
+ void objectDestroyed(QmlStateOperation *) {
+ // we assume priv will always be destroyed after objectDestroyed calls
+ list->removeOne(*this);
+ }
+ };
+
+ class OperationList : public QList<OperationGuard>, public QmlList<QmlStateOperation*>
+ {
+ public:
+ virtual void append(QmlStateOperation* v) { QList<OperationGuard>::append(OperationGuard(v, this)); }
+ virtual void insert(int i, QmlStateOperation* v) { QList<OperationGuard>::insert(i, OperationGuard(v, this)); }
+ virtual void clear() { QList<OperationGuard>::clear(); }
+ virtual QmlStateOperation* at(int i) const { return QList<OperationGuard>::at(i); }
+ virtual void removeAt(int i) { QList<OperationGuard>::removeAt(i); }
+ virtual int count() const { return QList<OperationGuard>::count(); }
+ };
+ OperationList operations;
+
+ QmlTransitionManager transitionManager;
+
+ SimpleActionList revertList;
+ QList<QmlMetaProperty> reverting;
+ QString extends;
+ mutable bool inState;
+ QmlStateGroup *group;
+
+ QmlStateOperation::ActionList generateActionList(QmlStateGroup *) const;
+ void complete();
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLSTATE_P_H
diff --git a/src/declarative/util/qmlstategroup.cpp b/src/declarative/util/qmlstategroup.cpp
new file mode 100644
index 0000000..d4db2b9
--- /dev/null
+++ b/src/declarative/util/qmlstategroup.cpp
@@ -0,0 +1,423 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlstategroup_p.h"
+
+#include "qmltransition_p.h"
+#include "qmlstate_p_p.h"
+
+#include <qmlbinding.h>
+#include <qmlglobal_p.h>
+
+#include <QtCore/qdebug.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG);
+
+QML_DEFINE_TYPE(Qt,4,6,StateGroup,QmlStateGroup)
+
+class QmlStateGroupPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlStateGroup)
+public:
+ QmlStateGroupPrivate(QmlStateGroup *p)
+ : nullState(0), states(p), componentComplete(true),
+ ignoreTrans(false), applyingState(false) {}
+
+ QString currentState;
+ QmlState *nullState;
+
+ struct StateList : public QmlConcreteList<QmlState *>
+ {
+ StateList(QmlStateGroup *g)
+ :group(g) {}
+ void append(QmlState *s) {
+ QmlConcreteList<QmlState *>::append(s);
+ if (s) s->setStateGroup(group);
+ }
+ private:
+ QmlStateGroup *group;
+ };
+ StateList states;
+
+ QmlConcreteList<QmlTransition *> transitions;
+ bool componentComplete;
+ bool ignoreTrans;
+ bool applyingState;
+
+ QmlTransition *findTransition(const QString &from, const QString &to);
+ void setCurrentStateInternal(const QString &state, bool = false);
+ bool updateAutoState();
+};
+
+/*!
+ \qmlclass StateGroup QmlStateGroup
+ \brief The StateGroup element provides state support for non-Item elements.
+
+ Item (and all dervied elements) provides built in support for states and transitions
+ via its state, states and 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} {state-transitions}{Transitions}
+*/
+
+QmlStateGroup::QmlStateGroup(QObject *parent)
+ : QObject(*(new QmlStateGroupPrivate(this)), parent)
+{
+}
+
+QmlStateGroup::~QmlStateGroup()
+{
+ Q_D(const QmlStateGroup);
+ for (int i = 0; i < d->states.count(); ++i)
+ d->states.at(i)->setStateGroup(0);
+}
+
+QList<QmlState *> QmlStateGroup::states() const
+{
+ Q_D(const QmlStateGroup);
+ return d->states;
+}
+
+/*!
+ \qmlproperty list<State> StateGroup::states
+ This property holds a list of states defined by the state group.
+
+ \qml
+ StateGroup {
+ states: [
+ State { ... },
+ State { ... }
+ ...
+ ]
+ }
+ \endqml
+
+ \sa {qmlstate}{States}
+*/
+QmlList<QmlState *>* QmlStateGroup::statesProperty()
+{
+ Q_D(QmlStateGroup);
+ return &(d->states);
+}
+
+/*!
+ \qmlproperty list<Transition> StateGroup::transitions
+ This property holds a list of transitions defined by the state group.
+
+ \qml
+ StateGroup {
+ transitions: [
+ Transition { ... },
+ Transition { ... }
+ ...
+ ]
+ }
+ \endqml
+
+ \sa {state-transitions}{Transitions}
+*/
+QmlList<QmlTransition *>* QmlStateGroup::transitionsProperty()
+{
+ Q_D(QmlStateGroup);
+ return &(d->transitions);
+}
+
+/*!
+ \qmlproperty string 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:
+
+ \qml
+ Script {
+ function toggle() {
+ if (button.state == 'On')
+ button.state = 'Off';
+ else
+ button.state = 'On';
+ }
+ }
+ \endqml
+
+ 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 QmlStateGroup::state() const
+{
+ Q_D(const QmlStateGroup);
+ return d->currentState;
+}
+
+void QmlStateGroup::setState(const QString &state)
+{
+ Q_D(QmlStateGroup);
+ if (d->currentState == state)
+ return;
+
+ d->setCurrentStateInternal(state);
+}
+
+void QmlStateGroup::classBegin()
+{
+ Q_D(QmlStateGroup);
+ d->componentComplete = false;
+}
+
+void QmlStateGroup::componentComplete()
+{
+ Q_D(QmlStateGroup);
+ d->componentComplete = true;
+
+ if (d->updateAutoState()) {
+ return;
+ } else if (!d->currentState.isEmpty()) {
+ QString cs = d->currentState;
+ d->currentState = QString();
+ d->setCurrentStateInternal(cs, true);
+ }
+}
+
+/*!
+ Returns true if the state was changed, otherwise false.
+*/
+bool QmlStateGroup::updateAutoState()
+{
+ Q_D(QmlStateGroup);
+ return d->updateAutoState();
+}
+
+bool QmlStateGroupPrivate::updateAutoState()
+{
+ Q_Q(QmlStateGroup);
+ if (!componentComplete)
+ return false;
+
+ bool revert = false;
+ for (int ii = 0; ii < states.count(); ++ii) {
+ QmlState *state = states.at(ii);
+ if (state->isWhenKnown()) {
+ if (!state->name().isEmpty()) {
+ if (state->when() && state->when()->value().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 != QString();
+ q->setState(QString());
+ return rv;
+ } else {
+ return false;
+ }
+}
+
+QmlTransition *QmlStateGroupPrivate::findTransition(const QString &from, const QString &to)
+{
+ QmlTransition *highest = 0;
+ int score = 0;
+ bool reversed = false;
+ bool done = false;
+
+ for (int ii = 0; !done && ii < transitions.count(); ++ii) {
+ QmlTransition *t = transitions.at(ii);
+ 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(','));
+ toState = t->toState().split(QLatin1Char(','));
+ 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 QmlStateGroupPrivate::setCurrentStateInternal(const QString &state,
+ bool ignoreTrans)
+{
+ Q_Q(QmlStateGroup);
+ if (!componentComplete) {
+ currentState = state;
+ return;
+ }
+
+ if (applyingState) {
+ qWarning() << "Can't apply a state change as part of a state definition.";
+ return;
+ }
+
+ applyingState = true;
+
+ QmlTransition *transition = (ignoreTrans || ignoreTrans) ? 0 : findTransition(currentState, state);
+ if (stateChangeDebug()) {
+ qWarning() << this << "Changing state. From" << currentState << ". To" << state;
+ if (transition)
+ qWarning() << " using transition" << transition->fromState()
+ << transition->toState();
+ }
+
+ QmlState *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);
+
+ QmlState *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 QmlState; QmlGraphics_setParent_noEvent(nullState, q); }
+ if (!oldState) oldState = nullState;
+ if (!newState) newState = nullState;
+ }
+
+ newState->apply(q, transition, oldState);
+ applyingState = false;
+ if (!transition)
+ static_cast<QmlStatePrivate*>(QObjectPrivate::get(newState))->complete();
+}
+
+QmlState *QmlStateGroup::findState(const QString &name) const
+{
+ Q_D(const QmlStateGroup);
+ for (int i = 0; i < d->states.count(); ++i) {
+ QmlState *state = d->states.at(i);
+ if (state->name() == name)
+ return state;
+ }
+
+ return 0;
+}
+
+void QmlStateGroup::removeState(QmlState *state)
+{
+ Q_D(QmlStateGroup);
+ d->states.removeOne(state);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlstategroup_p.h b/src/declarative/util/qmlstategroup_p.h
new file mode 100644
index 0000000..112c9eb
--- /dev/null
+++ b/src/declarative/util/qmlstategroup_p.h
@@ -0,0 +1,95 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSTATEGROUP_H
+#define QMLSTATEGROUP_H
+
+#include "qmlstate_p.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlStateGroupPrivate;
+class Q_DECLARATIVE_EXPORT QmlStateGroup : public QObject, public QmlParserStatus
+{
+ Q_OBJECT
+ Q_INTERFACES(QmlParserStatus)
+ Q_DECLARE_PRIVATE(QmlStateGroup)
+
+ Q_PROPERTY(QString state READ state WRITE setState NOTIFY stateChanged)
+ Q_PROPERTY(QmlList<QmlState *>* states READ statesProperty DESIGNABLE false)
+ Q_PROPERTY(QmlList<QmlTransition *>* transitions READ transitionsProperty DESIGNABLE false)
+
+public:
+ QmlStateGroup(QObject * = 0);
+ virtual ~QmlStateGroup();
+
+ QString state() const;
+ void setState(const QString &);
+
+ QmlList<QmlState *>* statesProperty();
+ QList<QmlState *> states() const;
+
+ QmlList<QmlTransition *>* transitionsProperty();
+
+ QmlState *findState(const QString &name) const;
+
+ virtual void classBegin();
+ virtual void componentComplete();
+Q_SIGNALS:
+ void stateChanged(const QString &);
+
+private:
+ friend class QmlState;
+ bool updateAutoState();
+ void removeState(QmlState *state);
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlStateGroup)
+
+QT_END_HEADER
+
+#endif // QMLSTATEGROUP_H
diff --git a/src/declarative/util/qmlstateoperations.cpp b/src/declarative/util/qmlstateoperations.cpp
new file mode 100644
index 0000000..35c8f7d
--- /dev/null
+++ b/src/declarative/util/qmlstateoperations.cpp
@@ -0,0 +1,834 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlstateoperations_p.h"
+
+#include <qml.h>
+#include <qmlcontext.h>
+#include <qmlexpression.h>
+#include <qmlinfo.h>
+#include <qmlgraphicsanchors_p_p.h>
+#include <qmlgraphicsitem_p.h>
+#include <qmlguard_p.h>
+
+#include <QtCore/qdebug.h>
+#include <QtGui/qgraphicsitem.h>
+#include <QtCore/qmath.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlParentChangePrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlParentChange)
+public:
+ QmlParentChangePrivate() : target(0), parent(0), origParent(0), origStackBefore(0),
+ rewindParent(0), rewindStackBefore(0) {}
+
+ QmlGraphicsItem *target;
+ QmlGraphicsItem *parent;
+ QmlGuard<QmlGraphicsItem> origParent;
+ QmlGuard<QmlGraphicsItem> origStackBefore;
+ QmlGraphicsItem *rewindParent;
+ QmlGraphicsItem *rewindStackBefore;
+
+ void doChange(QmlGraphicsItem *targetParent, QmlGraphicsItem *stackBefore = 0);
+};
+
+void QmlParentChangePrivate::doChange(QmlGraphicsItem *targetParent, QmlGraphicsItem *stackBefore)
+{
+ if (targetParent && target && target->parentItem()) {
+ //### for backwards direction, can we just restore original x, y, scale, rotation
+ Q_Q(QmlParentChange);
+ bool ok;
+ const QTransform &transform = target->itemTransform(targetParent, &ok);
+ if (transform.type() >= QTransform::TxShear || !ok) {
+ qmlInfo(q) << QObject::tr("Unable to preserve appearance under complex transform");
+ ok = false;
+ }
+
+ qreal scale = 1;
+ qreal rotation = 0;
+ if (ok && transform.type() != QTransform::TxRotate) {
+ if (transform.m11() == transform.m22())
+ scale = transform.m11();
+ else {
+ qmlInfo(q) << QObject::tr("Unable to preserve appearance under non-uniform scale");
+ ok = false;
+ }
+ } else if (ok && transform.type() == QTransform::TxRotate) {
+ if (transform.m11() == transform.m22())
+ scale = qSqrt(transform.m11()*transform.m11() + transform.m12()*transform.m12());
+ else {
+ qmlInfo(q) << QObject::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) << QObject::tr("Unable to preserve appearance under scale of 0");
+ ok = false;
+ }
+ }
+
+ qreal xt = transform.dx();
+ qreal yt = transform.dy();
+ if (ok && target->transformOrigin() != QmlGraphicsItem::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);
+ QPointF offset = t.map(QPointF(0,0));
+ xt += offset.x();
+ yt += offset.y();
+ }
+
+ target->setParentItem(targetParent);
+ if (ok) {
+ //qDebug() << xt << yt << rotation << scale;
+ target->setX(xt);
+ target->setY(yt);
+ target->setRotation(rotation);
+ target->setScale(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);
+}
+
+/*!
+ \preliminary
+ \qmlclass ParentChange QmlParentChange
+ \brief The ParentChange element allows you to reparent an Item in a state change.
+
+ ParentChange reparents an Item while preserving its visual appearance (position, rotation,
+ and scale) on screen. You can then specify a transition to move/rotate/scale the Item to
+ its final intended appearance.
+
+ ParentChange can only preserve visual appearance if no complex transforms are involved.
+ More specifically, it will not work if the transform property has been set for any
+ Items involved in the reparenting (defined as any Items in the common ancestor tree
+ for the original and new parent).
+
+ You can specify at which point in a transition you want a ParentChange to occur by
+ using a ParentAction.
+*/
+
+QML_DEFINE_TYPE(Qt,4,6,ParentChange,QmlParentChange)
+QmlParentChange::QmlParentChange(QObject *parent)
+ : QmlStateOperation(*(new QmlParentChangePrivate), parent)
+{
+}
+
+QmlParentChange::~QmlParentChange()
+{
+}
+
+/*!
+ \qmlproperty Item ParentChange::target
+ This property holds the item to be reparented
+*/
+
+QmlGraphicsItem *QmlParentChange::object() const
+{
+ Q_D(const QmlParentChange);
+ return d->target;
+}
+
+void QmlParentChange::setObject(QmlGraphicsItem *target)
+{
+ Q_D(QmlParentChange);
+ d->target = target;
+}
+
+/*!
+ \qmlproperty Item ParentChange::parent
+ This property holds the parent for the item in this state
+*/
+
+QmlGraphicsItem *QmlParentChange::parent() const
+{
+ Q_D(const QmlParentChange);
+ return d->parent;
+}
+
+void QmlParentChange::setParent(QmlGraphicsItem *parent)
+{
+ Q_D(QmlParentChange);
+ d->parent = parent;
+}
+
+QmlStateOperation::ActionList QmlParentChange::actions()
+{
+ Q_D(QmlParentChange);
+ if (!d->target || !d->parent)
+ return ActionList();
+
+ QmlAction a;
+ a.event = this;
+
+ return ActionList() << a;
+}
+
+class AccessibleFxItem : public QmlGraphicsItem
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QmlGraphicsItem)
+public:
+ int siblingIndex() {
+ Q_D(QmlGraphicsItem);
+ return d->siblingIndex;
+ }
+};
+
+void QmlParentChange::saveOriginals()
+{
+ Q_D(QmlParentChange);
+ saveCurrentValues();
+ d->origParent = d->rewindParent;
+ d->origStackBefore = d->rewindStackBefore;
+}
+
+void QmlParentChange::execute()
+{
+ Q_D(QmlParentChange);
+ d->doChange(d->parent);
+}
+
+bool QmlParentChange::isReversable()
+{
+ return true;
+}
+
+void QmlParentChange::reverse()
+{
+ Q_D(QmlParentChange);
+ d->doChange(d->origParent, d->origStackBefore);
+}
+
+QString QmlParentChange::typeName() const
+{
+ return QLatin1String("ParentChange");
+}
+
+bool QmlParentChange::override(QmlActionEvent*other)
+{
+ Q_D(QmlParentChange);
+ if (other->typeName() != QLatin1String("ParentChange"))
+ return false;
+ if (QmlParentChange *otherPC = static_cast<QmlParentChange*>(other))
+ return (d->target == otherPC->object());
+ return false;
+}
+
+void QmlParentChange::saveCurrentValues()
+{
+ Q_D(QmlParentChange);
+ if (!d->target) {
+ d->rewindParent = 0;
+ d->rewindStackBefore = 0;
+ return;
+ }
+
+ d->rewindParent = d->target->parentItem();
+
+ if (!d->rewindParent) {
+ d->rewindStackBefore = 0;
+ return;
+ }
+
+ //try to determine the item's original stack position so we can restore it
+ int siblingIndex = ((AccessibleFxItem*)d->target)->siblingIndex() + 1;
+ QList<QGraphicsItem*> children = d->rewindParent->childItems();
+ for (int i = 0; i < children.count(); ++i) {
+ QmlGraphicsItem *child = qobject_cast<QmlGraphicsItem*>(children.at(i));
+ if (!child)
+ continue;
+ if (((AccessibleFxItem*)child)->siblingIndex() == siblingIndex) {
+ d->rewindStackBefore = child;
+ break;
+ }
+ }
+}
+
+void QmlParentChange::rewind()
+{
+ Q_D(QmlParentChange);
+ d->doChange(d->rewindParent, d->rewindStackBefore);
+}
+
+class QmlStateChangeScriptPrivate : public QObjectPrivate
+{
+public:
+ QmlStateChangeScriptPrivate() {}
+
+ QmlScriptString script;
+ QString name;
+};
+
+/*!
+ \qmlclass StateChangeScript QmlStateChangeScript
+ \brief The StateChangeScript element allows you to run a script in a state.
+
+ The script specified will be run immediately when the state is made current.
+ Alternatively you can use a ScriptAction to specify at which point in the transition
+ you want the StateChangeScript to be run.
+*/
+QML_DEFINE_TYPE(Qt,4,6,StateChangeScript,QmlStateChangeScript)
+QmlStateChangeScript::QmlStateChangeScript(QObject *parent)
+: QmlStateOperation(*(new QmlStateChangeScriptPrivate), parent)
+{
+}
+
+QmlStateChangeScript::~QmlStateChangeScript()
+{
+}
+
+/*!
+ \qmlproperty script StateChangeScript::script
+ This property holds the script to run when the state is current.
+*/
+QmlScriptString QmlStateChangeScript::script() const
+{
+ Q_D(const QmlStateChangeScript);
+ return d->script;
+}
+
+void QmlStateChangeScript::setScript(const QmlScriptString &s)
+{
+ Q_D(QmlStateChangeScript);
+ d->script = s;
+}
+
+/*!
+ \qmlproperty script StateChangeScript::script
+ This property holds the name of the script. This name can be used by a
+ ScriptAction to target a specific script.
+
+ \sa ScriptAction::stateChangeScriptName
+*/
+QString QmlStateChangeScript::name() const
+{
+ Q_D(const QmlStateChangeScript);
+ return d->name;
+}
+
+void QmlStateChangeScript::setName(const QString &n)
+{
+ Q_D(QmlStateChangeScript);
+ d->name = n;
+}
+
+void QmlStateChangeScript::execute()
+{
+ Q_D(QmlStateChangeScript);
+ const QString &script = d->script.script();
+ if (!script.isEmpty()) {
+ QmlExpression expr(d->script.context(), script, d->script.scopeObject());
+ expr.setTrackChange(false);
+ expr.value();
+ }
+}
+
+QmlStateChangeScript::ActionList QmlStateChangeScript::actions()
+{
+ ActionList rv;
+ QmlAction a;
+ a.event = this;
+ rv << a;
+ return rv;
+}
+
+QString QmlStateChangeScript::typeName() const
+{
+ return QLatin1String("StateChangeScript");
+}
+
+/*!
+ \qmlclass AnchorChanges QmlAnchorChanges
+ \brief The AnchorChanges element allows you to change the anchors of an item in a state.
+
+ In the following example we change the top and bottom anchors of an item:
+ \snippet examples/declarative/anchors/anchor-changes.qml 0
+
+ AnchorChanges will 'inject' \c x, \c y, \c width, and \c height changes into the transition,
+ so you can animate them as you would normally changes to these properties:
+ \qml
+ //animate our anchor changes
+ NumberAnimation { matchTargets: content; matchProperties: "x,y,width,height" }
+ \endqml
+
+ For more information on anchors see \l {anchor-layout}{Anchor Layouts}.
+*/
+
+QML_DEFINE_TYPE(Qt,4,6,AnchorChanges,QmlAnchorChanges)
+
+class QmlAnchorChangesPrivate : public QObjectPrivate
+{
+public:
+ QmlAnchorChangesPrivate() : target(0) {}
+
+ QString name;
+ QmlGraphicsItem *target;
+ QString resetString;
+ QStringList resetList;
+ QmlGraphicsAnchorLine left;
+ QmlGraphicsAnchorLine right;
+ QmlGraphicsAnchorLine horizontalCenter;
+ QmlGraphicsAnchorLine top;
+ QmlGraphicsAnchorLine bottom;
+ QmlGraphicsAnchorLine verticalCenter;
+ QmlGraphicsAnchorLine baseline;
+
+ QmlGraphicsAnchorLine origLeft;
+ QmlGraphicsAnchorLine origRight;
+ QmlGraphicsAnchorLine origHCenter;
+ QmlGraphicsAnchorLine origTop;
+ QmlGraphicsAnchorLine origBottom;
+ QmlGraphicsAnchorLine origVCenter;
+ QmlGraphicsAnchorLine origBaseline;
+
+ QmlGraphicsAnchorLine rewindLeft;
+ QmlGraphicsAnchorLine rewindRight;
+ QmlGraphicsAnchorLine rewindHCenter;
+ QmlGraphicsAnchorLine rewindTop;
+ QmlGraphicsAnchorLine rewindBottom;
+ QmlGraphicsAnchorLine rewindVCenter;
+ QmlGraphicsAnchorLine rewindBaseline;
+
+ qreal fromX;
+ qreal fromY;
+ qreal fromWidth;
+ qreal fromHeight;
+};
+
+/*!
+ \qmlproperty Item AnchorChanges::target
+ This property holds the Item whose anchors will change
+*/
+
+QmlAnchorChanges::QmlAnchorChanges(QObject *parent)
+ : QmlStateOperation(*(new QmlAnchorChangesPrivate), parent)
+{
+}
+
+QmlAnchorChanges::~QmlAnchorChanges()
+{
+}
+
+QmlAnchorChanges::ActionList QmlAnchorChanges::actions()
+{
+ QmlAction a;
+ a.event = this;
+ return ActionList() << a;
+}
+
+QmlGraphicsItem *QmlAnchorChanges::object() const
+{
+ Q_D(const QmlAnchorChanges);
+ return d->target;
+}
+
+void QmlAnchorChanges::setObject(QmlGraphicsItem *target)
+{
+ Q_D(QmlAnchorChanges);
+ d->target = target;
+}
+
+QString QmlAnchorChanges::reset() const
+{
+ Q_D(const QmlAnchorChanges);
+ return d->resetString;
+}
+
+void QmlAnchorChanges::setReset(const QString &reset)
+{
+ Q_D(QmlAnchorChanges);
+ d->resetString = reset;
+ d->resetList = d->resetString.split(QLatin1Char(','));
+ for (int i = 0; i < d->resetList.count(); ++i)
+ d->resetList[i] = d->resetList.at(i).trimmed();
+}
+
+/*!
+ \qmlproperty AnchorLine AnchorChanges::left
+ \qmlproperty AnchorLine AnchorChanges::right
+ \qmlproperty AnchorLine AnchorChanges::horizontalCenter
+ \qmlproperty AnchorLine AnchorChanges::top
+ \qmlproperty AnchorLine AnchorChanges::bottom
+ \qmlproperty AnchorLine AnchorChanges::verticalCenter
+ \qmlproperty AnchorLine AnchorChanges::baseline
+
+ These properties change the respective anchors of the item.
+*/
+
+QmlGraphicsAnchorLine QmlAnchorChanges::left() const
+{
+ Q_D(const QmlAnchorChanges);
+ return d->left;
+}
+
+void QmlAnchorChanges::setLeft(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlAnchorChanges);
+ d->left = edge;
+}
+
+QmlGraphicsAnchorLine QmlAnchorChanges::right() const
+{
+ Q_D(const QmlAnchorChanges);
+ return d->right;
+}
+
+void QmlAnchorChanges::setRight(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlAnchorChanges);
+ d->right = edge;
+}
+
+QmlGraphicsAnchorLine QmlAnchorChanges::horizontalCenter() const
+{
+ Q_D(const QmlAnchorChanges);
+ return d->horizontalCenter;
+}
+
+void QmlAnchorChanges::setHorizontalCenter(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlAnchorChanges);
+ d->horizontalCenter = edge;
+}
+
+QmlGraphicsAnchorLine QmlAnchorChanges::top() const
+{
+ Q_D(const QmlAnchorChanges);
+ return d->top;
+}
+
+void QmlAnchorChanges::setTop(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlAnchorChanges);
+ d->top = edge;
+}
+
+QmlGraphicsAnchorLine QmlAnchorChanges::bottom() const
+{
+ Q_D(const QmlAnchorChanges);
+ return d->bottom;
+}
+
+void QmlAnchorChanges::setBottom(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlAnchorChanges);
+ d->bottom = edge;
+}
+
+QmlGraphicsAnchorLine QmlAnchorChanges::verticalCenter() const
+{
+ Q_D(const QmlAnchorChanges);
+ return d->verticalCenter;
+}
+
+void QmlAnchorChanges::setVerticalCenter(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlAnchorChanges);
+ d->verticalCenter = edge;
+}
+
+QmlGraphicsAnchorLine QmlAnchorChanges::baseline() const
+{
+ Q_D(const QmlAnchorChanges);
+ return d->baseline;
+}
+
+void QmlAnchorChanges::setBaseline(const QmlGraphicsAnchorLine &edge)
+{
+ Q_D(QmlAnchorChanges);
+ d->baseline = edge;
+}
+
+void QmlAnchorChanges::execute()
+{
+ Q_D(QmlAnchorChanges);
+ if (!d->target)
+ return;
+
+ //set any anchors that have been specified
+ if (d->left.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setLeft(d->left);
+ if (d->right.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setRight(d->right);
+ if (d->horizontalCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setHorizontalCenter(d->horizontalCenter);
+ if (d->top.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setTop(d->top);
+ if (d->bottom.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setBottom(d->bottom);
+ if (d->verticalCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setVerticalCenter(d->verticalCenter);
+ if (d->baseline.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setBaseline(d->baseline);
+}
+
+bool QmlAnchorChanges::isReversable()
+{
+ return true;
+}
+
+void QmlAnchorChanges::reverse()
+{
+ Q_D(QmlAnchorChanges);
+ if (!d->target)
+ return;
+
+ //restore previous anchors
+ if (d->origLeft.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setLeft(d->origLeft);
+ if (d->origRight.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setRight(d->origRight);
+ if (d->origHCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setHorizontalCenter(d->origHCenter);
+ if (d->origTop.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setTop(d->origTop);
+ if (d->origBottom.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setBottom(d->origBottom);
+ if (d->origVCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setVerticalCenter(d->origVCenter);
+ if (d->origBaseline.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setBaseline(d->origBaseline);
+}
+
+QString QmlAnchorChanges::typeName() const
+{
+ return QLatin1String("AnchorChanges");
+}
+
+QList<QmlAction> QmlAnchorChanges::extraActions()
+{
+ Q_D(QmlAnchorChanges);
+ QList<QmlAction> extra;
+
+ //### try to be smarter about which ones we add.
+ // or short-circuit later on if they haven't actually changed.
+ // we shouldn't set explicit width if there wasn't one before.
+ if (d->target) {
+ QmlAction a;
+ a.fromValue = d->fromX;
+ a.property = QmlMetaProperty(d->target, QLatin1String("x"));
+ extra << a;
+
+ a.fromValue = d->fromY;
+ a.property = QmlMetaProperty(d->target, QLatin1String("y"));
+ extra << a;
+
+ a.fromValue = d->fromWidth;
+ a.property = QmlMetaProperty(d->target, QLatin1String("width"));
+ extra << a;
+
+ a.fromValue = d->fromHeight;
+ a.property = QmlMetaProperty(d->target, QLatin1String("height"));
+ extra << a;
+ }
+
+ return extra;
+}
+
+bool QmlAnchorChanges::changesBindings()
+{
+ return true;
+}
+
+void QmlAnchorChanges::saveOriginals()
+{
+ Q_D(QmlAnchorChanges);
+ d->origLeft = d->target->anchors()->left();
+ d->origRight = d->target->anchors()->right();
+ d->origHCenter = d->target->anchors()->horizontalCenter();
+ d->origTop = d->target->anchors()->top();
+ d->origBottom = d->target->anchors()->bottom();
+ d->origVCenter = d->target->anchors()->verticalCenter();
+ d->origBaseline = d->target->anchors()->baseline();
+
+ saveCurrentValues();
+}
+
+void QmlAnchorChanges::clearForwardBindings()
+{
+ Q_D(QmlAnchorChanges);
+ d->fromX = d->target->x();
+ d->fromY = d->target->y();
+ d->fromWidth = d->target->width();
+ d->fromHeight = d->target->height();
+
+ //reset any anchors that have been specified
+ if (d->resetList.contains(QLatin1String("left")))
+ d->target->anchors()->resetLeft();
+ if (d->resetList.contains(QLatin1String("right")))
+ d->target->anchors()->resetRight();
+ if (d->resetList.contains(QLatin1String("horizontalCenter")))
+ d->target->anchors()->resetHorizontalCenter();
+ if (d->resetList.contains(QLatin1String("top")))
+ d->target->anchors()->resetTop();
+ if (d->resetList.contains(QLatin1String("bottom")))
+ d->target->anchors()->resetBottom();
+ if (d->resetList.contains(QLatin1String("verticalCenter")))
+ d->target->anchors()->resetVerticalCenter();
+ if (d->resetList.contains(QLatin1String("baseline")))
+ d->target->anchors()->resetBaseline();
+
+ //reset any anchors that we'll be setting in the state
+ if (d->left.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetLeft();
+ if (d->right.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetRight();
+ if (d->horizontalCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetHorizontalCenter();
+ if (d->top.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetTop();
+ if (d->bottom.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetBottom();
+ if (d->verticalCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetVerticalCenter();
+ if (d->baseline.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetBaseline();
+}
+
+void QmlAnchorChanges::clearReverseBindings()
+{
+ Q_D(QmlAnchorChanges);
+ d->fromX = d->target->x();
+ d->fromY = d->target->y();
+ d->fromWidth = d->target->width();
+ d->fromHeight = d->target->height();
+
+ //reset any anchors that were set in the state
+ if (d->left.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetLeft();
+ if (d->right.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetRight();
+ if (d->horizontalCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetHorizontalCenter();
+ if (d->top.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetTop();
+ if (d->bottom.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetBottom();
+ if (d->verticalCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetVerticalCenter();
+ if (d->baseline.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetBaseline();
+
+ //reset any anchors that were set in the original state
+ if (d->origLeft.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetLeft();
+ if (d->origRight.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetRight();
+ if (d->origHCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetHorizontalCenter();
+ if (d->origTop.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetTop();
+ if (d->origBottom.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetBottom();
+ if (d->origVCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetVerticalCenter();
+ if (d->origBaseline.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->resetBaseline();
+}
+
+bool QmlAnchorChanges::override(QmlActionEvent*other)
+{
+ if (other->typeName() != QLatin1String("AnchorChanges"))
+ return false;
+ if (static_cast<QmlActionEvent*>(this) == other)
+ return true;
+ if (static_cast<QmlAnchorChanges*>(other)->object() == object())
+ return true;
+ return false;
+}
+
+void QmlAnchorChanges::rewind()
+{
+ Q_D(QmlAnchorChanges);
+ if (!d->target)
+ return;
+
+ //restore previous anchors
+ if (d->rewindLeft.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setLeft(d->rewindLeft);
+ if (d->rewindRight.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setRight(d->rewindRight);
+ if (d->rewindHCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setHorizontalCenter(d->rewindHCenter);
+ if (d->rewindTop.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setTop(d->rewindTop);
+ if (d->rewindBottom.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setBottom(d->rewindBottom);
+ if (d->rewindVCenter.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setVerticalCenter(d->rewindVCenter);
+ if (d->rewindBaseline.anchorLine != QmlGraphicsAnchorLine::Invalid)
+ d->target->anchors()->setBaseline(d->rewindBaseline);
+}
+
+void QmlAnchorChanges::saveCurrentValues()
+{
+ Q_D(QmlAnchorChanges);
+ d->rewindLeft = d->target->anchors()->left();
+ d->rewindRight = d->target->anchors()->right();
+ d->rewindHCenter = d->target->anchors()->horizontalCenter();
+ d->rewindTop = d->target->anchors()->top();
+ d->rewindBottom = d->target->anchors()->bottom();
+ d->rewindVCenter = d->target->anchors()->verticalCenter();
+ d->rewindBaseline = d->target->anchors()->baseline();
+}
+
+#include <qmlstateoperations.moc>
+#include <moc_qmlstateoperations_p.cpp>
+
+QT_END_NAMESPACE
+
diff --git a/src/declarative/util/qmlstateoperations_p.h b/src/declarative/util/qmlstateoperations_p.h
new file mode 100644
index 0000000..1a9f76f
--- /dev/null
+++ b/src/declarative/util/qmlstateoperations_p.h
@@ -0,0 +1,184 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSTATEOPERATIONS_H
+#define QMLSTATEOPERATIONS_H
+
+#include "qmlstate_p.h"
+
+#include <qmlgraphicsitem.h>
+#include "private/qmlgraphicsanchors_p.h"
+#include <qmlscriptstring.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlParentChangePrivate;
+class Q_DECLARATIVE_EXPORT QmlParentChange : public QmlStateOperation, public QmlActionEvent
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlParentChange)
+
+ Q_PROPERTY(QmlGraphicsItem *target READ object WRITE setObject)
+ Q_PROPERTY(QmlGraphicsItem *parent READ parent WRITE setParent)
+public:
+ QmlParentChange(QObject *parent=0);
+ ~QmlParentChange();
+
+ QmlGraphicsItem *object() const;
+ void setObject(QmlGraphicsItem *);
+
+ QmlGraphicsItem *parent() const;
+ void setParent(QmlGraphicsItem *);
+
+ virtual ActionList actions();
+
+ virtual void saveOriginals();
+ virtual void execute();
+ virtual bool isReversable();
+ virtual void reverse();
+ virtual QString typeName() const;
+ virtual bool override(QmlActionEvent*other);
+ virtual void rewind();
+ virtual void saveCurrentValues();
+};
+
+class QmlStateChangeScriptPrivate;
+class Q_DECLARATIVE_EXPORT QmlStateChangeScript : public QmlStateOperation, public QmlActionEvent
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlStateChangeScript)
+
+ Q_PROPERTY(QmlScriptString script READ script WRITE setScript)
+ Q_PROPERTY(QString name READ name WRITE setName)
+
+public:
+ QmlStateChangeScript(QObject *parent=0);
+ ~QmlStateChangeScript();
+
+ virtual ActionList actions();
+
+ virtual QString typeName() const;
+
+ QmlScriptString script() const;
+ void setScript(const QmlScriptString &);
+
+ QString name() const;
+ void setName(const QString &);
+
+ virtual void execute();
+};
+
+class QmlAnchorChangesPrivate;
+class Q_DECLARATIVE_EXPORT QmlAnchorChanges : public QmlStateOperation, public QmlActionEvent
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlAnchorChanges)
+
+ Q_PROPERTY(QmlGraphicsItem *target READ object WRITE setObject)
+ Q_PROPERTY(QString reset READ reset WRITE setReset)
+ Q_PROPERTY(QmlGraphicsAnchorLine left READ left WRITE setLeft)
+ Q_PROPERTY(QmlGraphicsAnchorLine right READ right WRITE setRight)
+ Q_PROPERTY(QmlGraphicsAnchorLine horizontalCenter READ horizontalCenter WRITE setHorizontalCenter)
+ Q_PROPERTY(QmlGraphicsAnchorLine top READ top WRITE setTop)
+ Q_PROPERTY(QmlGraphicsAnchorLine bottom READ bottom WRITE setBottom)
+ Q_PROPERTY(QmlGraphicsAnchorLine verticalCenter READ verticalCenter WRITE setVerticalCenter)
+ Q_PROPERTY(QmlGraphicsAnchorLine baseline READ baseline WRITE setBaseline)
+
+public:
+ QmlAnchorChanges(QObject *parent=0);
+ ~QmlAnchorChanges();
+
+ virtual ActionList actions();
+
+ QmlGraphicsItem *object() const;
+ void setObject(QmlGraphicsItem *);
+
+ QString reset() const;
+ void setReset(const QString &);
+
+ QmlGraphicsAnchorLine left() const;
+ void setLeft(const QmlGraphicsAnchorLine &edge);
+
+ QmlGraphicsAnchorLine right() const;
+ void setRight(const QmlGraphicsAnchorLine &edge);
+
+ QmlGraphicsAnchorLine horizontalCenter() const;
+ void setHorizontalCenter(const QmlGraphicsAnchorLine &edge);
+
+ QmlGraphicsAnchorLine top() const;
+ void setTop(const QmlGraphicsAnchorLine &edge);
+
+ QmlGraphicsAnchorLine bottom() const;
+ void setBottom(const QmlGraphicsAnchorLine &edge);
+
+ QmlGraphicsAnchorLine verticalCenter() const;
+ void setVerticalCenter(const QmlGraphicsAnchorLine &edge);
+
+ QmlGraphicsAnchorLine baseline() const;
+ void setBaseline(const QmlGraphicsAnchorLine &edge);
+
+ virtual void execute();
+ virtual bool isReversable();
+ virtual void reverse();
+ virtual QString typeName() const;
+ virtual bool override(QmlActionEvent*other);
+ virtual QList<QmlAction> extraActions();
+ virtual bool changesBindings();
+ virtual void saveOriginals();
+ virtual void clearForwardBindings();
+ virtual void clearReverseBindings();
+ virtual void rewind();
+ virtual void saveCurrentValues();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlParentChange)
+QML_DECLARE_TYPE(QmlStateChangeScript)
+QML_DECLARE_TYPE(QmlAnchorChanges)
+
+QT_END_HEADER
+
+#endif // QMLSTATEOPERATIONS_H
diff --git a/src/declarative/util/qmlstyledtext.cpp b/src/declarative/util/qmlstyledtext.cpp
new file mode 100644
index 0000000..36b5e49
--- /dev/null
+++ b/src/declarative/util/qmlstyledtext.cpp
@@ -0,0 +1,343 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QStack>
+#include <QVector>
+#include <QPainter>
+#include <QTextLayout>
+#include <QDebug>
+#include <qmath.h>
+#include "qmlstyledtext_p.h"
+
+/*
+ QmlStyledText supports few tags:
+
+ <b></b> - bold
+ <i></i> - italic
+ <br> - new line
+ <font color="color_name" size="1-7"></font>
+
+ The opening and closing tags must be correctly nested.
+*/
+
+class QmlStyledTextPrivate
+{
+public:
+ QmlStyledTextPrivate(const QString &t, QTextLayout &l) : text(t), layout(l), baseFont(layout.font()) {}
+
+ void parse();
+ bool parseTag(const QChar *&ch, const QString &textIn, QString &textOut, QTextCharFormat &format);
+ bool parseCloseTag(const QChar *&ch, const QString &textIn);
+ void parseEntity(const QChar *&ch, const QString &textIn, QString &textOut);
+ bool parseFontAttributes(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;
+ }
+
+ QString text;
+ QTextLayout &layout;
+ QFont baseFont;
+
+ 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;
+};
+
+const QChar QmlStyledTextPrivate::lessThan(QLatin1Char('<'));
+const QChar QmlStyledTextPrivate::greaterThan(QLatin1Char('>'));
+const QChar QmlStyledTextPrivate::equals(QLatin1Char('='));
+const QChar QmlStyledTextPrivate::singleQuote(QLatin1Char('\''));
+const QChar QmlStyledTextPrivate::doubleQuote(QLatin1Char('\"'));
+const QChar QmlStyledTextPrivate::slash(QLatin1Char('/'));
+const QChar QmlStyledTextPrivate::ampersand(QLatin1Char('&'));
+
+QmlStyledText::QmlStyledText(const QString &string, QTextLayout &layout)
+: d(new QmlStyledTextPrivate(string, layout))
+{
+}
+
+QmlStyledText::~QmlStyledText()
+{
+ delete d;
+}
+
+void QmlStyledText::parse(const QString &string, QTextLayout &layout)
+{
+ QmlStyledText styledText(string, layout);
+ styledText.d->parse();
+}
+
+void QmlStyledTextPrivate::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)
+ 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);
+ }
+ rangeStart = drawText.length();
+ ++ch;
+ if (*ch == slash) {
+ ++ch;
+ if (parseCloseTag(ch, text))
+ formatStack.pop();
+ } else {
+ QTextCharFormat format;
+ if (formatStack.count())
+ format = formatStack.top();
+ else
+ format.setFont(baseFont);
+ 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;
+ }
+ ++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 QmlStyledTextPrivate::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) {
+ QStringRef tag(&textIn, tagStart, tagLength);
+ const QChar char0 = tag.at(0);
+ if (char0 == QLatin1Char('b')) {
+ if (tagLength == 1) {
+ format.setFontWeight(QFont::Bold);
+ return true;
+ } else if (tagLength == 2 && tag.at(1) == QLatin1Char('r')) {
+ textOut.append(QChar(QChar::LineSeparator));
+ return true;
+ }
+ } else if (char0 == QLatin1Char('i')) {
+ if (tagLength == 1) {
+ format.setFontItalic(true);
+ return true;
+ }
+ }
+ return false;
+ } else if (ch->isSpace()) {
+ // may have params.
+ QStringRef tag(&textIn, tagStart, tagLength);
+ if (tag == QLatin1String("font"))
+ return parseFontAttributes(ch, textIn, format);
+ if (*ch == greaterThan || ch->isNull())
+ continue;
+ } else if (*ch != slash){
+ tagLength++;
+ }
+ ++ch;
+ }
+
+ return false;
+}
+
+bool QmlStyledTextPrivate::parseCloseTag(const QChar *&ch, const QString &textIn)
+{
+ skipSpace(ch);
+
+ int tagStart = ch - textIn.constData();
+ int tagLength = 0;
+ while (!ch->isNull()) {
+ if (*ch == greaterThan) {
+ QStringRef tag(&textIn, tagStart, tagLength);
+ const QChar char0 = tag.at(0);
+ 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 (tag == QLatin1String("font")) {
+ return true;
+ }
+ return false;
+ } else if (!ch->isSpace()){
+ tagLength++;
+ }
+ ++ch;
+ }
+
+ return false;
+}
+
+void QmlStyledTextPrivate::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 QmlStyledTextPrivate::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;
+}
+
+QPair<QStringRef,QStringRef> QmlStyledTextPrivate::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 QmlStyledTextPrivate::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);
+}
diff --git a/src/declarative/util/qmlstyledtext_p.h b/src/declarative/util/qmlstyledtext_p.h
new file mode 100644
index 0000000..0cfb43e
--- /dev/null
+++ b/src/declarative/util/qmlstyledtext_p.h
@@ -0,0 +1,63 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSTYLEDTEXT_H
+#define QMLSTYLEDTEXT_H
+
+#include <QSizeF>
+
+class QPainter;
+class QPointF;
+class QString;
+class QmlStyledTextPrivate;
+class Q_DECLARATIVE_EXPORT QmlStyledText
+{
+public:
+ static void parse(const QString &string, QTextLayout &layout);
+
+private:
+ QmlStyledText(const QString &string, QTextLayout &layout);
+ ~QmlStyledText();
+
+ QmlStyledTextPrivate *d;
+};
+
+#endif
diff --git a/src/declarative/util/qmlsystempalette.cpp b/src/declarative/util/qmlsystempalette.cpp
new file mode 100644
index 0000000..39d8f3e
--- /dev/null
+++ b/src/declarative/util/qmlsystempalette.cpp
@@ -0,0 +1,303 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlsystempalette_p.h"
+
+#include <QApplication>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QmlSystemPalettePrivate : public QObjectPrivate
+{
+public:
+ QPalette palette;
+ QPalette::ColorGroup group;
+};
+
+QML_DEFINE_TYPE(Qt,4,6,SystemPalette,QmlSystemPalette)
+
+/*!
+ \qmlclass SystemPalette QmlSystemPalette
+ \ingroup group_utility
+ \brief The SystemPalette item gives access to the Qt palettes.
+ \sa QPalette
+
+ Example:
+ \qml
+ SystemPalette { id: myPalette; colorGroup: Qt.Active }
+
+ Rectangle {
+ width: 640; height: 480
+ color: myPalette.window
+ Text {
+ anchors.fill: parent
+ text: "Hello!"; color: myPalette.windowText
+ }
+ }
+ \endqml
+*/
+QmlSystemPalette::QmlSystemPalette(QObject *parent)
+ : QObject(*(new QmlSystemPalettePrivate), parent)
+{
+ Q_D(QmlSystemPalette);
+ d->palette = QApplication::palette();
+ d->group = QPalette::Active;
+ qApp->installEventFilter(this);
+}
+
+QmlSystemPalette::~QmlSystemPalette()
+{
+}
+
+/*!
+ \qmlproperty color SystemPalette::window
+ The window (general background) color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::window() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::Window);
+}
+
+/*!
+ \qmlproperty color SystemPalette::windowText
+ The window text (general foreground) color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::windowText() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::WindowText);
+}
+
+/*!
+ \qmlproperty color SystemPalette::base
+ The base color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::base() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::Base);
+}
+
+/*!
+ \qmlproperty color SystemPalette::text
+ The text color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::text() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::Text);
+}
+
+/*!
+ \qmlproperty color SystemPalette::alternateBase
+ The alternate base color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::alternateBase() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::AlternateBase);
+}
+
+/*!
+ \qmlproperty color SystemPalette::button
+ The button color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::button() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::Button);
+}
+
+/*!
+ \qmlproperty color SystemPalette::buttonText
+ The button text foreground color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::buttonText() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::ButtonText);
+}
+
+/*!
+ \qmlproperty color SystemPalette::light
+ The light color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::light() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::Light);
+}
+
+/*!
+ \qmlproperty color SystemPalette::midlight
+ The midlight color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::midlight() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::Midlight);
+}
+
+/*!
+ \qmlproperty color SystemPalette::dark
+ The dark color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::dark() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::Dark);
+}
+
+/*!
+ \qmlproperty color SystemPalette::mid
+ The mid color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::mid() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::Mid);
+}
+
+/*!
+ \qmlproperty color SystemPalette::shadow
+ The shadow color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::shadow() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::Shadow);
+}
+
+/*!
+ \qmlproperty color SystemPalette::highlight
+ The highlight color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::highlight() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::Highlight);
+}
+
+/*!
+ \qmlproperty color SystemPalette::highlightedText
+ The highlighted text color of the current color group.
+
+ \sa QPalette::ColorRole
+*/
+QColor QmlSystemPalette::highlightedText() const
+{
+ Q_D(const QmlSystemPalette);
+ return d->palette.color(d->group, QPalette::HighlightedText);
+}
+
+/*!
+ \qmlproperty QmlSystemPalette::ColorGroup SystemPalette::colorGroup
+
+ The color group of the palette. It can be Active, Inactive or Disabled.
+ Active is the default.
+
+ \sa QPalette::ColorGroup
+*/
+QmlSystemPalette::ColorGroup QmlSystemPalette::colorGroup() const
+{
+ Q_D(const QmlSystemPalette);
+ return (QmlSystemPalette::ColorGroup)d->group;
+}
+
+void QmlSystemPalette::setColorGroup(QmlSystemPalette::ColorGroup colorGroup)
+{
+ Q_D(QmlSystemPalette);
+ d->group = (QPalette::ColorGroup)colorGroup;
+ emit paletteChanged();
+}
+
+bool QmlSystemPalette::eventFilter(QObject *watched, QEvent *event)
+{
+ if (watched == qApp) {
+ if (event->type() == QEvent::ApplicationPaletteChange) {
+ QApplication::postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
+ return false;
+ }
+ }
+ return QObject::eventFilter(watched, event);
+}
+
+bool QmlSystemPalette::event(QEvent *event)
+{
+ Q_D(QmlSystemPalette);
+ if (event->type() == QEvent::ApplicationPaletteChange) {
+ d->palette = QApplication::palette();
+ emit paletteChanged();
+ return true;
+ }
+ return QObject::event(event);
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlsystempalette_p.h b/src/declarative/util/qmlsystempalette_p.h
new file mode 100644
index 0000000..7c39d4a
--- /dev/null
+++ b/src/declarative/util/qmlsystempalette_p.h
@@ -0,0 +1,122 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLSYSTEMPALETTE_H
+#define QMLSYSTEMPALETTE_H
+
+#include <qml.h>
+
+#include <QtCore/qobject.h>
+#include <QPalette>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlSystemPalettePrivate;
+class Q_DECLARATIVE_EXPORT QmlSystemPalette : public QObject
+{
+ Q_OBJECT
+ Q_ENUMS(ColorGroup)
+ Q_DECLARE_PRIVATE(QmlSystemPalette)
+
+ Q_PROPERTY(QmlSystemPalette::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:
+ QmlSystemPalette(QObject *parent=0);
+ ~QmlSystemPalette();
+
+ 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;
+
+ QmlSystemPalette::ColorGroup colorGroup() const;
+ void setColorGroup(QmlSystemPalette::ColorGroup);
+
+Q_SIGNALS:
+ void paletteChanged();
+
+private:
+ bool eventFilter(QObject *watched, QEvent *event);
+ bool event(QEvent *event);
+
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlSystemPalette)
+
+QT_END_HEADER
+
+#endif // QMLSYSTEMPALETTE_H
diff --git a/src/declarative/util/qmltimeline.cpp b/src/declarative/util/qmltimeline.cpp
new file mode 100644
index 0000000..130e02d
--- /dev/null
+++ b/src/declarative/util/qmltimeline.cpp
@@ -0,0 +1,941 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmltimeline_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(QmlTimeLineValue *_g, qreal _v)
+ : g(_g), v(_v) {}
+ Update(const QmlTimeLineEvent &_e)
+ : g(0), v(0), e(_e) {}
+
+ QmlTimeLineValue *g;
+ qreal v;
+ QmlTimeLineEvent e;
+};
+
+struct QmlTimeLinePrivate
+{
+ QmlTimeLinePrivate(QmlTimeLine *);
+
+ struct Op {
+ enum Type {
+ Pause,
+ Set,
+ Move,
+ MoveBy,
+ Accel,
+ AccelDistance,
+ Execute
+ };
+ Op() {}
+ Op(Type t, int l, qreal v, qreal v2, int o,
+ const QmlTimeLineEvent &ev = QmlTimeLineEvent(), 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;
+ QmlTimeLineEvent 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<QmlTimeLineObject *, TimeLine> Ops;
+ Ops ops;
+ QmlTimeLine *q;
+
+ void add(QmlTimeLineObject &, const Op &);
+ qreal value(const Op &op, int time, qreal base, bool *) const;
+
+ int advance(int);
+
+ bool clockRunning;
+ int prevTime;
+
+ int order;
+
+ QmlTimeLine::SyncMode syncMode;
+ int syncAdj;
+ QList<QPair<int, Update> > *updateQueue;
+};
+
+QmlTimeLinePrivate::QmlTimeLinePrivate(QmlTimeLine *parent)
+: length(0), syncPoint(0), q(parent), clockRunning(false), prevTime(0), order(0), syncMode(QmlTimeLine::LocalSync), syncAdj(0), updateQueue(0)
+{
+}
+
+void QmlTimeLinePrivate::add(QmlTimeLineObject &g, const Op &o)
+{
+ if (g._t && g._t != q) {
+ qWarning() << "QmlTimeLine: Cannot modify a QmlTimeLineValue 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 == QmlTimeLine::LocalSync) {
+ syncAdj = -1;
+ } else {
+ syncAdj = 0;
+ }
+ q->start();
+/* q->tick(0);
+ if (syncMode == QmlTimeLine::LocalSync) {
+ syncAdj = -1;
+ } else {
+ syncAdj = 0;
+ }
+ */
+ }
+}
+
+qreal QmlTimeLinePrivate::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.execute();
+ *changed = false;
+ return -1;
+ }
+
+ return base;
+}
+
+/*!
+ \internal
+ \class QmlTimeLine
+ \ingroup group_animation
+ \brief The QmlTimeLine class provides a timeline for controlling animations.
+
+ QmlTimeLine is similar to QTimeLine except:
+ \list
+ \i It updates QmlTimeLineValue instances directly, rather than maintaining a single
+ current value.
+
+ For example, the following animates a simple value over 200 milliseconds:
+ \code
+ QmlTimeLineValue v(<starting value>);
+ QmlTimeLine 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 QmlTimeLine's updated() signal, or inherit from QmlTimeLineValue
+ and reimplement the QmlTimeLineValue::setValue() method.
+
+ \i Supports multiple QmlTimeLineValue, 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
+ QmlTimeLineValue x(<starting value>);
+ QmlTimeLineValue y(<starting value>);
+
+ QmlTimeLine tl;
+ tl.start();
+
+ tl.move(x, 100., 50);
+ tl.move(y, 100., 50);
+ tl.move(y, 200., 50);
+ \endcode
+
+ \i All QmlTimeLine 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
+ QmlTimeLine and across separate QmlTimeLine's within the same process.
+
+ \endlist
+
+ Currently easing functions are not supported.
+*/
+
+
+/*!
+ Construct a new QmlTimeLine with the specified \a parent.
+*/
+QmlTimeLine::QmlTimeLine(QObject *parent)
+: QAbstractAnimation(parent)
+{
+ d = new QmlTimeLinePrivate(this);
+}
+
+/*!
+ Destroys the time line. Any inprogress animations are canceled, but not
+ completed.
+*/
+QmlTimeLine::~QmlTimeLine()
+{
+ for (QmlTimeLinePrivate::Ops::Iterator iter = d->ops.begin();
+ iter != d->ops.end();
+ ++iter)
+ iter.key()->_t = 0;
+
+ delete d; d = 0;
+}
+
+/*!
+ \enum QmlTimeLine::SyncMode
+ */
+
+/*!
+ Return the timeline's synchronization mode.
+ */
+QmlTimeLine::SyncMode QmlTimeLine::syncMode() const
+{
+ return d->syncMode;
+}
+
+/*!
+ Set the timeline's synchronization mode to \a syncMode.
+ */
+void QmlTimeLine::setSyncMode(SyncMode syncMode)
+{
+ d->syncMode = syncMode;
+}
+
+/*!
+ Pause \a obj for \a time milliseconds.
+*/
+void QmlTimeLine::pause(QmlTimeLineObject &obj, int time)
+{
+ if (time <= 0) return;
+ QmlTimeLinePrivate::Op op(QmlTimeLinePrivate::Op::Pause, time, 0., 0., d->order++);
+ d->add(obj, op);
+}
+
+/*!
+ Execute the \a event.
+ */
+void QmlTimeLine::execute(const QmlTimeLineEvent &event)
+{
+ QmlTimeLinePrivate::Op op(QmlTimeLinePrivate::Op::Execute, 0, 0, 0., d->order++, event);
+ d->add(*event.eventObject(), op);
+}
+
+/*!
+ Set the \a value of \a timeLineValue.
+*/
+void QmlTimeLine::set(QmlTimeLineValue &timeLineValue, qreal value)
+{
+ QmlTimeLinePrivate::Op op(QmlTimeLinePrivate::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 QmlTimeLine will ensure
+ that the deceleration is in the opposite direction to the initial velocity.
+*/
+int QmlTimeLine::accel(QmlTimeLineValue &timeLineValue, qreal velocity, qreal acceleration)
+{
+ if ((velocity > 0.0f) == (acceleration > 0.0f))
+ acceleration = acceleration * -1.0f;
+
+ int time = static_cast<int>(-1000 * velocity / acceleration);
+
+ QmlTimeLinePrivate::Op op(QmlTimeLinePrivate::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, QmlTimeLine 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 QmlTimeLine::accel(QmlTimeLineValue &timeLineValue, qreal velocity, qreal acceleration, qreal maxDistance)
+{
+ 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);
+
+ QmlTimeLinePrivate::Op op(QmlTimeLinePrivate::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 QmlTimeLine calculates the exact
+ deceleration to use.
+
+ \a distance should be positive.
+*/
+int QmlTimeLine::accelDistance(QmlTimeLineValue &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);
+
+ QmlTimeLinePrivate::Op op(QmlTimeLinePrivate::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 QmlTimeLine::move(QmlTimeLineValue &timeLineValue, qreal destination, int time)
+{
+ if (time <= 0) return;
+ QmlTimeLinePrivate::Op op(QmlTimeLinePrivate::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 QmlTimeLine::move(QmlTimeLineValue &timeLineValue, qreal destination, const QEasingCurve &easing, int time)
+{
+ if (time <= 0) return;
+ QmlTimeLinePrivate::Op op(QmlTimeLinePrivate::Op::Move, time, destination, 0.0f, d->order++, QmlTimeLineEvent(), easing);
+ d->add(timeLineValue, op);
+}
+
+/*!
+ Linearly change the \a timeLineValue from its current value by the \a change amount
+ over \a time milliseconds.
+*/
+void QmlTimeLine::moveBy(QmlTimeLineValue &timeLineValue, qreal change, int time)
+{
+ if (time <= 0) return;
+ QmlTimeLinePrivate::Op op(QmlTimeLinePrivate::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 QmlTimeLine::moveBy(QmlTimeLineValue &timeLineValue, qreal change, const QEasingCurve &easing, int time)
+{
+ if (time <= 0) return;
+ QmlTimeLinePrivate::Op op(QmlTimeLinePrivate::Op::MoveBy, time, change, 0.0f, d->order++, QmlTimeLineEvent(), easing);
+ d->add(timeLineValue, op);
+}
+
+/*!
+ Cancel (but don't complete) all scheduled actions for \a timeLineValue.
+*/
+void QmlTimeLine::reset(QmlTimeLineValue &timeLineValue)
+{
+ if (!timeLineValue._t)
+ return;
+ if (timeLineValue._t != this) {
+ qWarning() << "QmlTimeLine: Cannot reset a QmlTimeLineValue owned by another timeline.";
+ return;
+ }
+ remove(&timeLineValue);
+ timeLineValue._t = 0;
+}
+
+int QmlTimeLine::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
+ psuedo-code this is equivalent to:
+ \code
+ QmlTimeLine::pause(timeLineValue, min(0, length_of(syncTo) - length_of(timeLineValue)))
+ \endcode
+*/
+void QmlTimeLine::sync(QmlTimeLineValue &timeLineValue, QmlTimeLineValue &syncTo)
+{
+ QmlTimeLinePrivate::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 psuedo-code, this is equivalent to:
+ \code
+ QmlTimeLine::pause(timeLineValue, length_of(timeline) - length_of(timeLineValue))
+ \endcode
+*/
+void QmlTimeLine::sync(QmlTimeLineValue &timeLineValue)
+{
+ QmlTimeLinePrivate::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.);
+ QmlTimeLine 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 QmlTimeLine::sync()
+{
+ for (QmlTimeLinePrivate::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 QmlTimeLine::setSyncPoint(int sp)
+{
+ d->syncPoint = sp;
+}
+
+/*!
+ \internal
+
+ Temporary hack.
+ */
+int QmlTimeLine::syncPoint() const
+{
+ return d->syncPoint;
+}
+
+/*!
+ Returns true if the timeline is active. An active timeline is one where
+ QmlTimeLineValue actions are still pending.
+*/
+bool QmlTimeLine::isActive() const
+{
+ return !d->ops.isEmpty();
+}
+
+/*!
+ Completes the timeline. All queued actions are played to completion, and then discarded. For example,
+ \code
+ QmlTimeLineValue v(0.);
+ QmlTimeLine tl;
+ tl.move(v, 100., 1000.);
+ // 500 ms passes
+ // v.value() == 50.
+ tl.complete();
+ // v.value() == 100.
+ \endcode
+*/
+void QmlTimeLine::complete()
+{
+ d->advance(d->length);
+}
+
+/*!
+ Resets the timeline. All queued actions are discarded and QmlTimeLineValue's retain their current value. For example,
+ \code
+ QmlTimeLineValue v(0.);
+ QmlTimeLine tl;
+ tl.move(v, 100., 1000.);
+ // 500 ms passes
+ // v.value() == 50.
+ tl.clear();
+ // v.value() == 50.
+ \endcode
+*/
+void QmlTimeLine::clear()
+{
+ for (QmlTimeLinePrivate::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 QmlTimeLine::time() const
+{
+ return d->prevTime;
+}
+
+/*!
+ \fn void QmlTimeLine::updated()
+
+ Emitted each time the timeline modifies QmlTimeLineValues. Even if multiple
+ QmlTimeLineValues are changed, this signal is only emitted once for each clock tick.
+*/
+
+void QmlTimeLine::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 QmlTimeLinePrivate::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(); ) {
+ QmlTimeLineValue *v = static_cast<QmlTimeLineValue *>(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.execute();
+ }
+ updateQueue = 0;
+ } while(t);
+
+ return pauseTime;
+}
+
+void QmlTimeLine::remove(QmlTimeLineObject *v)
+{
+ QmlTimeLinePrivate::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 (QmlTimeLinePrivate::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 == QmlTimeLine::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.eventObject() == v) {
+ d->updateQueue->removeAt(ii);
+ --ii;
+ }
+ }
+ }
+
+
+}
+
+/*!
+ \internal
+ \class QmlTimeLineValue
+ \ingroup group_animation
+ \brief The QmlTimeLineValue class provides a value that can be modified by QmlTimeLine.
+*/
+
+/*!
+ \fn QmlTimeLineValue::QmlTimeLineValue(qreal value = 0)
+
+ Construct a new QmlTimeLineValue with an initial \a value.
+*/
+
+/*!
+ \fn qreal QmlTimeLineValue::value() const
+
+ Return the current value.
+*/
+
+/*!
+ \fn void QmlTimeLineValue::setValue(qreal value)
+
+ Set the current \a value.
+*/
+
+/*!
+ \fn QmlTimeLine *QmlTimeLineValue::timeLine() const
+
+ If a QmlTimeLine is operating on this value, return a pointer to it,
+ otherwise return null.
+*/
+
+
+QmlTimeLineObject::QmlTimeLineObject()
+: _t(0)
+{
+}
+
+QmlTimeLineObject::~QmlTimeLineObject()
+{
+ if (_t) {
+ _t->remove(this);
+ _t = 0;
+ }
+}
+
+QmlTimeLineEvent::QmlTimeLineEvent()
+: d0(0), d1(0), d2(0)
+{
+}
+
+QmlTimeLineEvent::QmlTimeLineEvent(const QmlTimeLineEvent &o)
+: d0(o.d0), d1(o.d1), d2(o.d2)
+{
+}
+
+QmlTimeLineEvent &QmlTimeLineEvent::operator=(const QmlTimeLineEvent &o)
+{
+ d0 = o.d0;
+ d1 = o.d1;
+ d2 = o.d2;
+ return *this;
+}
+
+void QmlTimeLineEvent::execute() const
+{
+ d0(d1);
+}
+
+QmlTimeLineObject *QmlTimeLineEvent::eventObject() const
+{
+ return d2;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmltimeline_p_p.h b/src/declarative/util/qmltimeline_p_p.h
new file mode 100644
index 0000000..09d46ba
--- /dev/null
+++ b/src/declarative/util/qmltimeline_p_p.h
@@ -0,0 +1,223 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLTIMELINE_H
+#define QMLTIMELINE_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 QmlTimeLineValue;
+class QmlTimeLineEvent;
+struct QmlTimeLinePrivate;
+class QmlTimeLineObject;
+class Q_DECLARATIVE_EXPORT QmlTimeLine : public QAbstractAnimation
+{
+Q_OBJECT
+public:
+ QmlTimeLine(QObject *parent = 0);
+ ~QmlTimeLine();
+
+ enum SyncMode { LocalSync, GlobalSync };
+ SyncMode syncMode() const;
+ void setSyncMode(SyncMode);
+
+ void pause(QmlTimeLineObject &, int);
+ void execute(const QmlTimeLineEvent &);
+ void set(QmlTimeLineValue &, qreal);
+
+ int accel(QmlTimeLineValue &, qreal velocity, qreal accel);
+ int accel(QmlTimeLineValue &, qreal velocity, qreal accel, qreal maxDistance);
+ int accelDistance(QmlTimeLineValue &, qreal velocity, qreal distance);
+
+ void move(QmlTimeLineValue &, qreal destination, int time = 500);
+ void move(QmlTimeLineValue &, qreal destination, const QEasingCurve &, int time = 500);
+ void moveBy(QmlTimeLineValue &, qreal change, int time = 500);
+ void moveBy(QmlTimeLineValue &, qreal change, const QEasingCurve &, int time = 500);
+
+ void sync();
+ void setSyncPoint(int);
+ int syncPoint() const;
+
+ void sync(QmlTimeLineValue &);
+ void sync(QmlTimeLineValue &, QmlTimeLineValue &);
+
+ void reset(QmlTimeLineValue &);
+
+ 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(QmlTimeLineObject *);
+ friend class QmlTimeLineObject;
+ friend struct QmlTimeLinePrivate;
+ QmlTimeLinePrivate *d;
+};
+
+class Q_DECLARATIVE_EXPORT QmlTimeLineObject
+{
+public:
+ QmlTimeLineObject();
+ virtual ~QmlTimeLineObject();
+
+protected:
+ friend class QmlTimeLine;
+ friend struct QmlTimeLinePrivate;
+ QmlTimeLine *_t;
+};
+
+class Q_DECLARATIVE_EXPORT QmlTimeLineValue : public QmlTimeLineObject
+{
+public:
+ QmlTimeLineValue(qreal v = 0.) : _v(v) {}
+
+ virtual qreal value() const { return _v; }
+ virtual void setValue(qreal v) { _v = v; }
+
+ QmlTimeLine *timeLine() const { return _t; }
+
+ operator qreal() const { return _v; }
+ QmlTimeLineValue &operator=(qreal v) { setValue(v); return *this; }
+private:
+ friend class QmlTimeLine;
+ friend struct QmlTimeLinePrivate;
+ qreal _v;
+};
+
+class Q_DECLARATIVE_EXPORT QmlTimeLineEvent
+{
+public:
+ QmlTimeLineEvent();
+ QmlTimeLineEvent(const QmlTimeLineEvent &o);
+
+ template<class T, void (T::*method)()>
+ QmlTimeLineEvent(QmlTimeLineObject *b, T *c)
+ {
+ d0 = &callFunc<T, method>;
+ d1 = (void *)c;
+ d2 = b;
+ }
+
+ template<class T, void (T::*method)()>
+ static QmlTimeLineEvent timeLineEvent(QmlTimeLineObject *b, T *c)
+ {
+ QmlTimeLineEvent rv;
+ rv.d0 = &callFunc<T, method>;
+ rv.d1 = (void *)c;
+ rv.d2 = b;
+ return rv;
+ }
+
+ QmlTimeLineEvent &operator=(const QmlTimeLineEvent &o);
+ void execute() const;
+ QmlTimeLineObject *eventObject() const;
+
+private:
+ typedef void (*CallFunc)(void *c);
+
+ template <class T, void (T::*method)()>
+ static void callFunc(void *c)
+ {
+ T *cls = (T *)c;
+ (cls->*method)();
+ }
+ CallFunc d0;
+ void *d1;
+ QmlTimeLineObject *d2;
+};
+
+template<class T>
+class QmlTimeLineValueProxy : public QmlTimeLineValue
+{
+public:
+ QmlTimeLineValueProxy(T *cls, void (T::*func)(qreal), qreal v = 0.)
+ : QmlTimeLineValue(v), _class(cls), _setFunctionReal(func), _setFunctionInt(0)
+ {
+ Q_ASSERT(_class);
+ }
+
+ QmlTimeLineValueProxy(T *cls, void (T::*func)(int), qreal v = 0.)
+ : QmlTimeLineValue(v), _class(cls), _setFunctionReal(0), _setFunctionInt(func)
+ {
+ Q_ASSERT(_class);
+ }
+
+ virtual void setValue(qreal v)
+ {
+ QmlTimeLineValue::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/qmltimer.cpp b/src/declarative/util/qmltimer.cpp
new file mode 100644
index 0000000..046dfe9
--- /dev/null
+++ b/src/declarative/util/qmltimer.cpp
@@ -0,0 +1,313 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmltimer_p.h"
+
+#include <QtCore/qcoreapplication.h>
+#include <QtCore/qpauseanimation.h>
+#include <qdebug.h>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,Timer,QmlTimer)
+
+class QmlTimerPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlTimer)
+public:
+ QmlTimerPrivate()
+ : 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 QmlTimer
+ \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:
+
+ \qml
+ Timer {
+ interval: 500; running: true; repeat: true
+ onTriggered: time.text = Date().toString()
+ }
+ Text {
+ id: time
+ }
+ \endqml
+
+ QmlTimer is synchronized with the animation timer. Since the animation
+ timer is usually set to 60fps, the resolution of QmlTimer 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.
+*/
+
+QmlTimer::QmlTimer(QObject *parent)
+ : QObject(*(new QmlTimerPrivate), parent)
+{
+ Q_D(QmlTimer);
+ 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 Timer::interval
+
+ Sets the \a interval between triggers, in milliseconds.
+
+ The default interval is 1000 milliseconds.
+*/
+void QmlTimer::setInterval(int interval)
+{
+ Q_D(QmlTimer);
+ if (interval != d->interval) {
+ d->interval = interval;
+ update();
+ }
+}
+
+int QmlTimer::interval() const
+{
+ Q_D(const QmlTimer);
+ return d->interval;
+}
+
+/*!
+ \qmlproperty bool 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 QmlTimer::isRunning() const
+{
+ Q_D(const QmlTimer);
+ return d->running;
+}
+
+void QmlTimer::setRunning(bool running)
+{
+ Q_D(QmlTimer);
+ if (d->running != running) {
+ d->running = running;
+ d->firstTick = true;
+ emit runningChanged();
+ update();
+ }
+}
+
+/*!
+ \qmlproperty bool 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 QmlTimer::isRepeating() const
+{
+ Q_D(const QmlTimer);
+ return d->repeating;
+}
+
+void QmlTimer::setRepeating(bool repeating)
+{
+ Q_D(QmlTimer);
+ if (repeating != d->repeating) {
+ d->repeating = repeating;
+ update();
+ }
+}
+
+/*!
+ \qmlproperty bool 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 QmlTimer::triggeredOnStart() const
+{
+ Q_D(const QmlTimer);
+ return d->triggeredOnStart;
+}
+
+void QmlTimer::setTriggeredOnStart(bool triggeredOnStart)
+{
+ Q_D(QmlTimer);
+ if (d->triggeredOnStart != triggeredOnStart) {
+ d->triggeredOnStart = triggeredOnStart;
+ update();
+ }
+}
+
+/*!
+ \qmlmethod 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 QmlTimer::start()
+{
+ setRunning(true);
+}
+
+/*!
+ \qmlmethod 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 QmlTimer::stop()
+{
+ setRunning(false);
+}
+
+/*!
+ \qmlmethod 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 QmlTimer::restart()
+{
+ setRunning(false);
+ setRunning(true);
+}
+
+void QmlTimer::update()
+{
+ Q_D(QmlTimer);
+ 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 QmlTimer::classBegin()
+{
+ Q_D(QmlTimer);
+ d->classBegun = true;
+}
+
+void QmlTimer::componentComplete()
+{
+ Q_D(QmlTimer);
+ d->componentComplete = true;
+ update();
+}
+
+/*!
+ \qmlsignal Timer::onTriggered()
+
+ This handler is called when the Timer is triggered.
+*/
+void QmlTimer::ticked()
+{
+ Q_D(QmlTimer);
+ if (d->running && (d->pause.currentTime() > 0 || (d->triggeredOnStart && d->firstTick)))
+ emit triggered();
+ d->firstTick = false;
+}
+
+void QmlTimer::finished()
+{
+ Q_D(QmlTimer);
+ 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/qmltimer_p.h b/src/declarative/util/qmltimer_p.h
new file mode 100644
index 0000000..fcd6c84
--- /dev/null
+++ b/src/declarative/util/qmltimer_p.h
@@ -0,0 +1,109 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLTIMER_H
+#define QMLTIMER_H
+
+#include <qml.h>
+
+#include <QtCore/qobject.h>
+#include <QtCore/qabstractanimation.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlTimerPrivate;
+class Q_DECLARATIVE_EXPORT QmlTimer : public QObject, public QmlParserStatus
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlTimer)
+ Q_INTERFACES(QmlParserStatus)
+ Q_PROPERTY(int interval READ interval WRITE setInterval)
+ Q_PROPERTY(bool running READ isRunning WRITE setRunning NOTIFY runningChanged)
+ Q_PROPERTY(bool repeat READ isRepeating WRITE setRepeating)
+ Q_PROPERTY(bool triggeredOnStart READ triggeredOnStart WRITE setTriggeredOnStart)
+
+public:
+ QmlTimer(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();
+
+private:
+ void update();
+
+private Q_SLOTS:
+ void ticked();
+ void finished();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlTimer)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/util/qmltransition.cpp b/src/declarative/util/qmltransition.cpp
new file mode 100644
index 0000000..215fc91
--- /dev/null
+++ b/src/declarative/util/qmltransition.cpp
@@ -0,0 +1,261 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlstate_p.h"
+#include "qmlstategroup_p.h"
+#include "qmlstate_p_p.h"
+#include "qmlstateoperations_p.h"
+#include "qmlanimation_p.h"
+#include "qmlanimation_p_p.h"
+#include "qmltransitionmanager_p_p.h"
+
+#include <QParallelAnimationGroup>
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \qmlclass Transition QmlTransition
+ \brief The Transition element defines animated transitions that occur on state changes.
+
+ \sa {qmlstates}{States}, {state-transitions}{Transitions}
+*/
+
+/*!
+ \internal
+ \class QmlTransition
+ \brief The QmlTransition class allows you to define animated transitions that occur on state changes.
+
+ \ingroup group_states
+*/
+
+//ParallelAnimationWrapperallows 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) {}
+ QmlTransitionPrivate *trans;
+protected:
+ virtual void updateState(QAbstractAnimation::State newState, QAbstractAnimation::State oldState);
+};
+
+class QmlTransitionPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlTransition)
+public:
+ QmlTransitionPrivate() : fromState(QLatin1String("*")), toState(QLatin1String("*"))
+ , reversed(false), reversible(false), endState(0)
+ {
+ animations.parent = this;
+ }
+
+ QString fromState;
+ QString toState;
+ bool reversed;
+ bool reversible;
+ ParallelAnimationWrapper group;
+ QmlTransitionManager *endState;
+
+ void init()
+ {
+ group.trans = this;
+ }
+
+ void complete()
+ {
+ endState->complete();
+ }
+
+ class AnimationList : public QmlConcreteList<QmlAbstractAnimation *>
+ {
+ public:
+ AnimationList() : parent(0) {}
+ virtual void append(QmlAbstractAnimation *a);
+ virtual void clear() { QmlConcreteList<QmlAbstractAnimation *>::clear(); } //###
+
+ QmlTransitionPrivate *parent;
+ };
+ AnimationList animations;
+};
+
+void QmlTransitionPrivate::AnimationList::append(QmlAbstractAnimation *a)
+{
+ QmlConcreteList<QmlAbstractAnimation *>::append(a);
+ parent->group.addAnimation(a->qtAnimation());
+}
+
+void ParallelAnimationWrapper::updateState(QAbstractAnimation::State newState, QAbstractAnimation::State oldState)
+{
+ QParallelAnimationGroup::updateState(newState, oldState);
+ if (newState == Stopped &&
+ ((direction() == QAbstractAnimation::Forward && currentLoopTime() == duration()) ||
+ (direction() == QAbstractAnimation::Backward && currentLoopTime() == 0)))
+ {
+ trans->complete();
+ }
+}
+
+
+QML_DEFINE_TYPE(Qt,4,6,Transition,QmlTransition)
+QmlTransition::QmlTransition(QObject *parent)
+ : QObject(*(new QmlTransitionPrivate), parent)
+{
+ Q_D(QmlTransition);
+ d->init();
+}
+
+QmlTransition::~QmlTransition()
+{
+}
+
+void QmlTransition::stop()
+{
+ Q_D(QmlTransition);
+ d->group.stop();
+}
+
+void QmlTransition::setReversed(bool r)
+{
+ Q_D(QmlTransition);
+ d->reversed = r;
+}
+
+void QmlTransition::prepare(QmlStateOperation::ActionList &actions,
+ QList<QmlMetaProperty> &after,
+ QmlTransitionManager *endState)
+{
+ Q_D(QmlTransition);
+
+ qmlExecuteDeferred(this);
+
+ if (d->reversed) {
+ for (int ii = d->animations.count() - 1; ii >= 0; --ii) {
+ d->animations.at(ii)->transition(actions, after, QmlAbstractAnimation::Backward);
+ }
+ } else {
+ for (int ii = 0; ii < d->animations.count(); ++ii) {
+ d->animations.at(ii)->transition(actions, after, QmlAbstractAnimation::Forward);
+ }
+ }
+
+ d->endState = endState;
+ d->group.setDirection(d->reversed ? QAbstractAnimation::Backward : QAbstractAnimation::Forward);
+ d->group.start();
+}
+
+/*!
+ \qmlproperty string Transition::from
+ \qmlproperty string Transition::to
+ These properties are selectors indicating which state changes should trigger the transition.
+
+ from is used in conjunction with to to determine when a transition should
+ be applied. By default from and to are both "*" (any state). In the following example,
+ the transition is applied when changing from state1 to state2.
+ \code
+ Transition {
+ from: "state1"
+ to: "state2"
+ ...
+ }
+ \endcode
+*/
+QString QmlTransition::fromState() const
+{
+ Q_D(const QmlTransition);
+ return d->fromState;
+}
+
+void QmlTransition::setFromState(const QString &f)
+{
+ Q_D(QmlTransition);
+ d->fromState = f;
+}
+
+/*!
+ \qmlproperty bool 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.
+*/
+bool QmlTransition::reversible() const
+{
+ Q_D(const QmlTransition);
+ return d->reversible;
+}
+
+void QmlTransition::setReversible(bool r)
+{
+ Q_D(QmlTransition);
+ d->reversible = r;
+}
+
+QString QmlTransition::toState() const
+{
+ Q_D(const QmlTransition);
+ return d->toState;
+}
+
+void QmlTransition::setToState(const QString &t)
+{
+ Q_D(QmlTransition);
+ d->toState = t;
+}
+
+/*!
+ \qmlproperty list<Animation> Transition::animations
+ \default
+ This property holds a list of the animations to be run for this transition.
+
+ The top-level animations are run in parallel. To run them sequentially,
+ you can create a single SequentialAnimation which contains all the animations,
+ and assign that to animations the animations property.
+ \default
+*/
+QmlList<QmlAbstractAnimation *>* QmlTransition::animations()
+{
+ Q_D(QmlTransition);
+ return &d->animations;
+}
+
+QT_END_NAMESPACE
+
+#include <qmltransition.moc>
diff --git a/src/declarative/util/qmltransition_p.h b/src/declarative/util/qmltransition_p.h
new file mode 100644
index 0000000..c1a6f66
--- /dev/null
+++ b/src/declarative/util/qmltransition_p.h
@@ -0,0 +1,101 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLTRANSITION_H
+#define QMLTRANSITION_H
+
+#include "qmlstate_p.h"
+
+#include <qml.h>
+
+#include <QtCore/qobject.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlAbstractAnimation;
+class QmlTransitionPrivate;
+class QmlTransitionManager;
+class Q_DECLARATIVE_EXPORT QmlTransition : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QmlTransition)
+
+ Q_PROPERTY(QString from READ fromState WRITE setFromState)
+ Q_PROPERTY(QString to READ toState WRITE setToState)
+ Q_PROPERTY(bool reversible READ reversible WRITE setReversible)
+ Q_PROPERTY(QmlList<QmlAbstractAnimation *>* animations READ animations)
+ Q_CLASSINFO("DefaultProperty", "animations")
+ Q_CLASSINFO("DeferredPropertyNames", "animations")
+
+public:
+ QmlTransition(QObject *parent=0);
+ ~QmlTransition();
+
+ QString fromState() const;
+ void setFromState(const QString &);
+
+ QString toState() const;
+ void setToState(const QString &);
+
+ bool reversible() const;
+ void setReversible(bool);
+
+ QmlList<QmlAbstractAnimation *>* animations();
+
+ void prepare(QmlStateOperation::ActionList &actions,
+ QList<QmlMetaProperty> &after,
+ QmlTransitionManager *end);
+
+ void setReversed(bool r);
+ void stop();
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlTransition)
+
+QT_END_HEADER
+
+#endif // QMLTRANSITION_H
diff --git a/src/declarative/util/qmltransitionmanager.cpp b/src/declarative/util/qmltransitionmanager.cpp
new file mode 100644
index 0000000..a3a16ca
--- /dev/null
+++ b/src/declarative/util/qmltransitionmanager.cpp
@@ -0,0 +1,282 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmltransitionmanager_p_p.h"
+
+#include "qmlstate_p_p.h"
+
+#include <qmlbinding.h>
+#include <qmlglobal_p.h>
+
+QT_BEGIN_NAMESPACE
+
+DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG);
+
+class QmlTransitionManagerPrivate
+{
+public:
+ QmlTransitionManagerPrivate()
+ : state(0), transition(0) {}
+
+ void applyBindings();
+ typedef QList<QmlSimpleAction> SimpleActionList;
+ QmlState *state;
+ QmlTransition *transition;
+ QmlStateOperation::ActionList bindingsList;
+ SimpleActionList completeList;
+};
+
+QmlTransitionManager::QmlTransitionManager()
+: d(new QmlTransitionManagerPrivate)
+{
+}
+
+void QmlTransitionManager::setState(QmlState *s)
+{
+ d->state = s;
+}
+
+QmlTransitionManager::~QmlTransitionManager()
+{
+ delete d; d = 0;
+}
+
+void QmlTransitionManager::complete()
+{
+ d->applyBindings();
+
+ for (int ii = 0; ii < d->completeList.count(); ++ii) {
+ const QmlMetaProperty &prop = d->completeList.at(ii).property;
+ prop.write(d->completeList.at(ii).value);
+ }
+
+ d->completeList.clear();
+
+ if (d->state)
+ static_cast<QmlStatePrivate*>(QObjectPrivate::get(d->state))->complete();
+}
+
+void QmlTransitionManagerPrivate::applyBindings()
+{
+ foreach(const QmlAction &action, bindingsList) {
+ if (action.toBinding) {
+ action.property.setBinding(action.toBinding);
+ } else if (action.event) {
+ if (action.reverseEvent)
+ action.event->reverse();
+ else
+ action.event->execute();
+ }
+
+ }
+
+ bindingsList.clear();
+}
+
+void QmlTransitionManager::transition(const QList<QmlAction> &list,
+ QmlTransition *transition)
+{
+ cancel();
+
+ QmlStateOperation::ActionList applyList = list;
+ // Determine which actions are binding changes.
+ foreach(const QmlAction &action, applyList) {
+ if (action.toBinding)
+ d->bindingsList << action;
+ if (action.fromBinding)
+ action.property.setBinding(0); // Disable current binding
+ if (action.event && action.event->changesBindings()) { //### assume isReversable()?
+ d->bindingsList << action;
+ if (action.reverseEvent)
+ action.event->clearReverseBindings();
+ else
+ action.event->clearForwardBindings();
+ }
+ }
+
+ // 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?
+
+ if (!d->bindingsList.isEmpty()) {
+
+ //### do extra actions here?
+
+ // Apply all the property and binding changes
+ for (int ii = 0; ii < applyList.size(); ++ii) {
+ const QmlAction &action = applyList.at(ii);
+ if (action.toBinding) {
+ action.property.setBinding(action.toBinding, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding);
+ } else if (!action.event) {
+ action.property.write(action.toValue, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding);
+ } else if (action.event->isReversable()) {
+ if (action.reverseEvent)
+ action.event->reverse();
+ else
+ action.event->execute();
+ applyList << action.event->extraActions();
+ }
+ }
+
+ // Read all the end values for binding changes
+ for (int ii = 0; ii < applyList.size(); ++ii) {
+ QmlAction *action = &applyList[ii];
+ if (action->event)
+ continue;
+ const QmlMetaProperty &prop = action->property;
+ if (action->toBinding || !action->toValue.isValid()) { //### is this always right (used for exta actions)
+ action->toValue = prop.read();
+ }
+ }
+
+ // Revert back to the original values
+ foreach(const QmlAction &action, applyList) {
+ if (action.event) {
+ if (action.event->isReversable()) {
+ if (action.reverseEvent) { //reverse the reverse
+ action.event->clearForwardBindings();
+ action.event->rewind();
+ action.event->clearReverseBindings();
+ } else {
+ action.event->clearReverseBindings();
+ action.event->rewind();
+ action.event->clearForwardBindings();
+ }
+ }
+ continue;
+ }
+
+ if (action.toBinding)
+ action.property.setBinding(0); // Make sure this is disabled during the transition
+
+ action.property.write(action.fromValue, QmlMetaProperty::BypassInterceptor | QmlMetaProperty::DontRemoveBinding);
+ }
+ }
+
+ if (transition) {
+ QList<QmlMetaProperty> 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 QmlAction &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 <<
+ QmlSimpleAction(action, QmlSimpleAction::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 QmlAction &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);
+ }
+ }
+ if (stateChangeDebug()) {
+ foreach(const QmlAction &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;
+ }
+ }
+ if (!transition)
+ d->applyBindings();
+}
+
+void QmlTransitionManager::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) {
+ QmlAction action = d->bindingsList[i];
+ if (action.toBinding && action.deletableToBinding) {
+ action.property.setBinding(0);
+ action.toBinding->destroy();
+ action.toBinding = 0;
+ 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/qmltransitionmanager_p_p.h b/src/declarative/util/qmltransitionmanager_p_p.h
new file mode 100644
index 0000000..cb4111c
--- /dev/null
+++ b/src/declarative/util/qmltransitionmanager_p_p.h
@@ -0,0 +1,85 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLTRANSITIONMANAGER_P_H
+#define QMLTRANSITIONMANAGER_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 "qmlstateoperations_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QmlStatePrivate;
+class QmlTransitionManagerPrivate;
+class QmlTransitionManager
+{
+public:
+ QmlTransitionManager();
+ ~QmlTransitionManager();
+
+ void transition(const QList<QmlAction> &, QmlTransition *transition);
+
+ void cancel();
+
+private:
+ Q_DISABLE_COPY(QmlTransitionManager);
+ QmlTransitionManagerPrivate *d;
+
+ void complete();
+ void setState(QmlState *);
+
+ friend class QmlState;
+ friend class QmlTransitionPrivate;
+};
+
+QT_END_NAMESPACE
+
+#endif // QMLTRANSITIONMANAGER_P_H
diff --git a/src/declarative/util/qmlview.cpp b/src/declarative/util/qmlview.cpp
new file mode 100644
index 0000000..690924f
--- /dev/null
+++ b/src/declarative/util/qmlview.cpp
@@ -0,0 +1,586 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlview.h"
+
+#include "qperformancelog_p_p.h"
+#include "qfxperf_p_p.h"
+
+#include <qml.h>
+#include <qmlgraphicsitem.h>
+#include <qmlengine.h>
+#include <qmlcontext.h>
+#include <qmldebug_p.h>
+#include <qmldebugservice_p.h>
+#include <qmlglobal_p.h>
+
+#include <qscriptvalueiterator.h>
+#include <qdebug.h>
+#include <qtimer.h>
+#include <qevent.h>
+#include <qdir.h>
+#include <qcoreapplication.h>
+#include <qfontdatabase.h>
+#include <qicon.h>
+#include <qurl.h>
+#include <qboxlayout.h>
+#include <qbasictimer.h>
+#include <QtCore/qabstractanimation.h>
+
+QT_BEGIN_NAMESPACE
+
+DEFINE_BOOL_CONFIG_OPTION(frameRateDebug, QML_SHOW_FRAMERATE)
+
+class QmlViewDebugServer;
+class FrameBreakAnimation : public QAbstractAnimation
+{
+public:
+ FrameBreakAnimation(QmlViewDebugServer *s)
+ : QAbstractAnimation((QObject*)s), server(s)
+ {
+ start();
+ }
+
+ virtual int duration() const { return -1; }
+ virtual void updateCurrentTime(int msecs);
+
+private:
+ QmlViewDebugServer *server;
+};
+
+class QmlViewDebugServer : public QmlDebugService
+{
+public:
+ QmlViewDebugServer(QObject *parent = 0) : QmlDebugService(QLatin1String("CanvasFrameRate"), parent), breaks(0)
+ {
+ timer.start();
+ new FrameBreakAnimation(this);
+ }
+
+ void addTiming(int pe, int tbf)
+ {
+ if (!isEnabled())
+ return;
+
+ bool isFrameBreak = breaks > 1;
+ breaks = 0;
+ int e = timer.elapsed();
+ QByteArray data;
+ QDataStream ds(&data, QIODevice::WriteOnly);
+ ds << (int)pe << (int)tbf << (int)e
+ << (bool)isFrameBreak;
+ sendMessage(data);
+ }
+
+ void frameBreak() { ++breaks; }
+
+private:
+ QTime timer;
+ int breaks;
+};
+
+Q_GLOBAL_STATIC(QmlViewDebugServer, qfxViewDebugServer);
+
+void FrameBreakAnimation::updateCurrentTime(int msecs)
+{
+ Q_UNUSED(msecs);
+ server->frameBreak();
+}
+
+class QmlViewPrivate
+{
+public:
+ QmlViewPrivate(QmlView *w)
+ : q(w), root(0), component(0), resizable(false) {}
+
+ QmlView *q;
+ QmlGraphicsItem *root;
+
+ QUrl source;
+ QString qml;
+
+ QmlEngine engine;
+ QmlComponent *component;
+ QBasicTimer resizetimer;
+
+ QSize initialSize;
+ bool resizable;
+ QTime frameTimer;
+
+ void init();
+
+ QGraphicsScene scene;
+};
+
+/*!
+ \class QmlView
+ \brief The QmlView class provides a widget for displaying a Qt Declarative user interface.
+
+ QmlView currently provides a minimal interface for displaying QML
+ files, and connecting between QML and C++ Qt objects.
+
+ Typical usage:
+ \code
+ ...
+ QmlView *view = new QmlView(this);
+ vbox->addWidget(view);
+
+ QUrl url(fileName);
+ view->setUrl(url);
+ ...
+ view->execute();
+ ...
+ view->show();
+ \endcode
+
+ To receive errors related to loading and executing QML with QmlView,
+ you can connect to the errors() signal.
+*/
+
+/*!
+ \fn QmlView::QmlView(QWidget *parent)
+
+ Constructs a QmlView with the given \a parent.
+*/
+QmlView::QmlView(QWidget *parent)
+: QGraphicsView(parent), d(new QmlViewPrivate(this))
+{
+ setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
+ d->init();
+}
+
+void QmlViewPrivate::init()
+{
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ {
+ QmlPerfTimer<QmlPerf::FontDatabase> perf;
+ QFontDatabase database;
+ }
+#endif
+
+ q->setScene(&scene);
+
+ q->setOptimizationFlags(QGraphicsView::DontSavePainterState);
+ q->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ q->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ q->setFrameStyle(0);
+
+ // These seem to give the best performance
+ q->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
+ scene.setItemIndexMethod(QGraphicsScene::NoIndex);
+ q->viewport()->setFocusPolicy(Qt::NoFocus);
+
+ scene.setStickyFocus(true); //### needed for correct focus handling
+}
+
+/*!
+ The destructor clears the view's \l {QmlGraphicsItem} {items} and
+ deletes the internal representation.
+
+ \sa clearItems()
+ */
+QmlView::~QmlView()
+{
+ clearItems();
+ delete d; d = 0;
+}
+
+/*!
+ Sets the source to the \a url. The QML string is set to
+ empty.
+ */
+void QmlView::setUrl(const QUrl& url)
+{
+ d->source = url;
+ d->qml = QString();
+}
+
+/*!
+ Returns the source URL, if set.
+
+ \sa setUrl()
+ */
+QUrl QmlView::url() const
+{
+ return d->source;
+}
+
+/*!
+ Sets the source to the URL from the \a filename, and sets
+ the QML string to \a qml.
+ */
+void QmlView::setQml(const QString &qml, const QString &filename)
+{
+ d->source = QUrl::fromLocalFile(filename);
+ d->qml = qml;
+}
+
+/*!
+ Returns the QML string.
+ */
+QString QmlView::qml() const
+{
+ return d->qml;
+}
+
+/*!
+ Returns a pointer to the QmlEngine used for instantiating
+ QML Components.
+ */
+QmlEngine* QmlView::engine()
+{
+ return &d->engine;
+}
+
+/*!
+ This function returns the root of the context hierarchy. Each QML
+ component is instantiated in a QmlContext. QmlContext's are
+ essential for passing data to QML components. In QML, contexts are
+ arranged hierarchically and this hierarchy is managed by the
+ QmlEngine.
+ */
+QmlContext* QmlView::rootContext()
+{
+ return d->engine.rootContext();
+}
+
+/*!
+ Displays the Qt Declarative user interface.
+*/
+void QmlView::execute()
+{
+ if (d->qml.isEmpty()) {
+ d->component = new QmlComponent(&d->engine, d->source, this);
+ } else {
+ d->component = new QmlComponent(&d->engine, this);
+ d->component->setData(d->qml.toUtf8(), d->source);
+ }
+ connect (&d->engine, SIGNAL (quit ()), this, SIGNAL (quit ()));
+
+ if (!d->component->isLoading()) {
+ continueExecute();
+ } else {
+ connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(continueExecute()));
+ }
+}
+
+
+/*!
+ \internal
+ */
+void QmlView::continueExecute()
+{
+ disconnect(d->component, SIGNAL(statusChanged(QmlComponent::Status)), this, SLOT(continueExecute()));
+
+ if (!d->component) {
+ qWarning() << "Error in loading" << d->source;
+ return;
+ }
+
+ if(d->component->isError()) {
+ QList<QmlError> errorList = d->component->errors();
+ foreach (const QmlError &error, errorList) {
+ qWarning() << error;
+ }
+ emit errors(errorList);
+
+ return;
+ }
+
+ QObject *obj = d->component->create();
+
+ if(d->component->isError()) {
+ QList<QmlError> errorList = d->component->errors();
+ foreach (const QmlError &error, errorList) {
+ qWarning() << error;
+ }
+ emit errors(errorList);
+
+ return;
+ }
+
+ if (obj) {
+ if (QmlGraphicsItem *item = qobject_cast<QmlGraphicsItem *>(obj)) {
+
+ d->scene.addItem(item);
+
+ QPerformanceLog::displayData();
+ QPerformanceLog::clear();
+ d->root = item;
+ connect(item, SIGNAL(widthChanged()), this, SLOT(sizeChanged()));
+ connect(item, SIGNAL(heightChanged()), this, SLOT(sizeChanged()));
+ if (d->initialSize.height() <= 0 && d->root->width() > 0)
+ d->initialSize.setWidth(d->root->width());
+ if (d->initialSize.height() <= 0 && d->root->height() > 0)
+ d->initialSize.setHeight(d->root->height());
+ resize(d->initialSize);
+
+ if (d->resizable) {
+ d->root->setWidth(width());
+ d->root->setHeight(height());
+ } else {
+ QSize sz(d->root->width(),d->root->height());
+ emit sceneResized(sz);
+ resize(sz);
+ }
+ updateGeometry();
+ emit initialSize(d->initialSize);
+ } else if (QWidget *wid = qobject_cast<QWidget *>(obj)) {
+ window()->setAttribute(Qt::WA_OpaquePaintEvent, false);
+ window()->setAttribute(Qt::WA_NoSystemBackground, false);
+ if (!layout()) {
+ setLayout(new QVBoxLayout);
+ layout()->setContentsMargins(0, 0, 0, 0);
+ } else if (layout()->count()) {
+ // Hide the QGraphicsView in GV mode.
+ QLayoutItem *item = layout()->itemAt(0);
+ if (item->widget())
+ item->widget()->hide();
+ }
+ layout()->addWidget(wid);
+ emit sceneResized(wid->size());
+ emit initialSize(wid->size());
+ }
+ }
+}
+
+/*! \fn void QmlView::sceneResized(QSize size)
+ This signal is emitted when the view is resized to \a size.
+ */
+
+/*! \fn void QmlView::initialSize(QSize size)
+ This signal is emitted when the initial \a size of the root item is known.
+ */
+
+/*! \fn void QmlView::errors(const QList<QmlError> &errors)
+ This signal is emitted when the qml loaded contains \a errors.
+ */
+
+/*!
+ \internal
+ */
+void QmlView::sizeChanged()
+{
+ // delay, so we catch both width and height changing.
+ d->resizetimer.start(0,this);
+}
+
+/*!
+ If the \l {QTimerEvent} {timer event} \a e is this
+ view's resize timer, sceneResized() is emitted.
+ */
+void QmlView::timerEvent(QTimerEvent* e)
+{
+ if (!e || e->timerId() == d->resizetimer.timerId()) {
+ if (d->root) {
+ QSize sz(d->root->width(),d->root->height());
+ emit sceneResized(sz);
+ //if (!d->resizable)
+ //resize(sz);
+ }
+ d->resizetimer.stop();
+ updateGeometry();
+ }
+}
+
+// modelled on QScrollArea::widgetResizable
+/*!
+ \property QmlView::contentResizable
+ \brief whether the view should resize the canvas contents
+
+ If this property is set to false (the default), the view
+ resizes with the root item in the QML.
+
+ If this property is set to true, 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.
+
+ \sa initialSize()
+*/
+
+void QmlView::setContentResizable(bool on)
+{
+ if (d->resizable != on) {
+ d->resizable = on;
+ if (d->root) {
+ if (on) {
+ d->root->setWidth(width());
+ d->root->setHeight(height());
+ } else {
+ d->root->setWidth(d->initialSize.width());
+ d->root->setHeight(d->initialSize.height());
+ }
+ }
+ }
+}
+
+bool QmlView::contentResizable() const
+{
+ return d->resizable;
+}
+
+
+/*!
+ The size hint is the size of the root item.
+*/
+QSize QmlView::sizeHint() const
+{
+ if (d->root) {
+ if (d->initialSize.width() <= 0)
+ d->initialSize.setWidth(d->root->width());
+ if (d->initialSize.height() <= 0)
+ d->initialSize.setHeight(d->root->height());
+ }
+ return d->initialSize;
+}
+
+/*!
+ Creates a \l{QmlComponent} {component} from the \a qml
+ string, and returns it as an \l {QmlGraphicsItem} {item}. If the
+ \a parent item is provided, it becomes the new item's
+ parent. \a parent should be in this view's item hierarchy.
+ */
+QmlGraphicsItem* QmlView::addItem(const QString &qml, QmlGraphicsItem* parent)
+{
+ if (!d->root)
+ return 0;
+
+ QmlComponent component(&d->engine);
+ component.setData(qml.toUtf8(), QUrl());
+ if(d->component->isError()) {
+ QList<QmlError> errorList = d->component->errors();
+ foreach (const QmlError &error, errorList) {
+ qWarning() << error;
+ }
+ emit errors(errorList);
+
+ return 0;
+ }
+
+ QObject *obj = component.create();
+ if(d->component->isError()) {
+ QList<QmlError> errorList = d->component->errors();
+ foreach (const QmlError &error, errorList) {
+ qWarning() << error;
+ }
+ emit errors(errorList);
+
+ return 0;
+ }
+
+ if (obj){
+ QmlGraphicsItem *item = static_cast<QmlGraphicsItem *>(obj);
+ if (!parent)
+ parent = d->root;
+
+ item->setParentItem(parent);
+ return item;
+ }
+ return 0;
+}
+
+/*!
+ Deletes the view's \l {QmlGraphicsItem} {items} and clears the \l {QmlEngine}
+ {QML engine's} Component cache.
+ */
+void QmlView::reset()
+{
+ clearItems();
+ d->engine.clearComponentCache();
+ d->initialSize = QSize();
+}
+
+/*!
+ Deletes the view's \l {QmlGraphicsItem} {items}.
+ */
+void QmlView::clearItems()
+{
+ if (!d->root)
+ return;
+ delete d->root;
+ d->root = 0;
+}
+
+/*!
+ Returns the view's root \l {QmlGraphicsItem} {item}.
+ */
+QmlGraphicsItem *QmlView::root() const
+{
+ return d->root;
+}
+
+/*!
+ This function handles the \l {QResizeEvent} {resize event}
+ \a e.
+ */
+void QmlView::resizeEvent(QResizeEvent *e)
+{
+ if (d->resizable && d->root) {
+ d->root->setWidth(width());
+ d->root->setHeight(height());
+ }
+ if (d->root) {
+ setSceneRect(QRectF(0, 0, d->root->width(), d->root->height()));
+ } else {
+ setSceneRect(rect());
+ }
+ QGraphicsView::resizeEvent(e);
+}
+
+/*!
+ \reimp
+*/
+void QmlView::paintEvent(QPaintEvent *event)
+{
+ int time = 0;
+ if (frameRateDebug() || QmlViewDebugServer::isDebuggingEnabled())
+ time = d->frameTimer.restart();
+ QGraphicsView::paintEvent(event);
+ if (QmlViewDebugServer::isDebuggingEnabled())
+ qfxViewDebugServer()->addTiming(d->frameTimer.elapsed(), time);
+ if (frameRateDebug())
+ qDebug() << "paintEvent:" << d->frameTimer.elapsed() << "time since last frame:" << time;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qmlview.h b/src/declarative/util/qmlview.h
new file mode 100644
index 0000000..f4f58fd
--- /dev/null
+++ b/src/declarative/util/qmlview.h
@@ -0,0 +1,113 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QFXVIEW_H
+#define QFXVIEW_H
+
+#include <QtCore/qdatetime.h>
+#include <QtGui/qgraphicssceneevent.h>
+#include <QtGui/qgraphicsview.h>
+#include <QtGui/qwidget.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlGraphicsItem;
+class QmlEngine;
+class QmlContext;
+class QmlError;
+
+class QmlViewPrivate;
+class Q_DECLARATIVE_EXPORT QmlView : public QGraphicsView
+{
+ Q_OBJECT
+ Q_PROPERTY(bool contentResizable READ contentResizable WRITE setContentResizable)
+public:
+ explicit QmlView(QWidget *parent = 0);
+
+ virtual ~QmlView();
+
+ void setUrl(const QUrl&);
+ QUrl url() const;
+ void setQml(const QString &qml, const QString &filename=QString());
+ QString qml() const;
+ QmlEngine* engine();
+ QmlContext* rootContext();
+ virtual void execute();
+ virtual void reset();
+
+ virtual QmlGraphicsItem* addItem(const QString &qml, QmlGraphicsItem* parent=0);
+ virtual void clearItems();
+
+ virtual QmlGraphicsItem *root() const;
+
+ void setContentResizable(bool);
+ bool contentResizable() const;
+ QSize sizeHint() const;
+
+Q_SIGNALS:
+ void initialSize(QSize size);
+ void sceneResized(QSize size);
+ void errors(const QList<QmlError> &error);
+ void quit ();
+
+private Q_SLOTS:
+ void continueExecute();
+ void sizeChanged();
+
+protected:
+ virtual void resizeEvent(QResizeEvent *);
+ virtual void paintEvent(QPaintEvent *event);
+ void timerEvent(QTimerEvent*);
+
+private:
+ friend class QmlViewPrivate;
+ QmlViewPrivate *d;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QFXVIEW_H
diff --git a/src/declarative/util/qmlxmllistmodel.cpp b/src/declarative/util/qmlxmllistmodel.cpp
new file mode 100644
index 0000000..d31fadf
--- /dev/null
+++ b/src/declarative/util/qmlxmllistmodel.cpp
@@ -0,0 +1,728 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qmlxmllistmodel_p.h"
+
+#include <qmlcontext.h>
+#include <qmlengine.h>
+
+#include <QDebug>
+#include <QApplication>
+#include <QThread>
+#include <QMutex>
+#include <QWaitCondition>
+#include <QXmlQuery>
+#include <QXmlResultItems>
+#include <QXmlNodeModelIndex>
+#include <QBuffer>
+#include <QNetworkRequest>
+#include <QNetworkReply>
+
+#include <private/qobject_p.h>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_TYPE(Qt,4,6,XmlRole,QmlXmlListModelRole)
+QML_DEFINE_TYPE(Qt,4,6,XmlListModel,QmlXmlListModel)
+
+/*!
+ \qmlclass XmlRole QmlXmlListModelRole
+ \brief The XmlRole element allows you to specify a role for an XmlListModel.
+*/
+
+/*!
+ \qmlproperty string XmlRole::name
+ The name for the role. This name is used to access the model data for this role from Qml.
+
+ \qml
+ XmlRole { name: "title"; query: "title/string()" }
+
+ ...
+
+ Component {
+ id: myDelegate
+ Text { text: title }
+ }
+ \endqml
+*/
+
+/*!
+ \qmlproperty string XmlRole::query
+ The relative XPath query for this role. The query should not start with a '/' (i.e. it must be
+ relative).
+
+ \qml
+ XmlRole { name: "title"; query: "title/string()" }
+ \endqml
+*/
+
+class Q_DECLARATIVE_EXPORT QmlXmlListModelRole : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(QString name READ name WRITE setName)
+ Q_PROPERTY(QString query READ query WRITE setQuery)
+
+public:
+ QmlXmlListModelRole() {}
+ ~QmlXmlListModelRole() {}
+
+ QString name() const { return m_name; }
+ void setName(const QString &name) { m_name = name; }
+
+ QString query() const { return m_query; }
+ void setQuery(const QString &query)
+ {
+ if (query.startsWith(QLatin1Char('/'))) {
+ qmlInfo(this) << tr("An XmlRole query must not start with '/'");
+ return;
+ }
+ m_query = query;
+ }
+
+ bool isValid() {
+ return !m_name.isEmpty() && !m_query.isEmpty();
+ }
+
+private:
+ QString m_name;
+ QString m_query;
+};
+
+QML_DECLARE_TYPE(QmlXmlListModelRole)
+
+class QmlXmlListModelPrivate;
+struct QmlXmlRoleList : public QmlConcreteList<QmlXmlListModelRole *>
+{
+ QmlXmlRoleList(QmlXmlListModelPrivate *p)
+ : model(p) {}
+ virtual void append(QmlXmlListModelRole *role);
+ virtual void clear();
+ virtual void removeAt(int i);
+ virtual void insert(int i, QmlXmlListModelRole *role);
+
+ QmlXmlListModelPrivate *model;
+};
+
+class QmlXmlQuery : public QThread
+{
+ Q_OBJECT
+public:
+ QmlXmlQuery(QObject *parent=0)
+ : QThread(parent), m_quit(false), m_restart(false), m_abort(false), m_queryId(0) {
+ }
+ ~QmlXmlQuery() {
+ m_mutex.lock();
+ m_quit = true;
+ m_condition.wakeOne();
+ m_mutex.unlock();
+
+ wait();
+ }
+
+ void abort() {
+ QMutexLocker locker(&m_mutex);
+ m_abort = true;
+ }
+
+ int doQuery(QString query, QString namespaces, QByteArray data, QmlXmlRoleList *roleObjects) {
+ QMutexLocker locker(&m_mutex);
+ m_modelData.clear();
+ m_size = 0;
+ m_data = data;
+ m_query = QLatin1String("doc($src)") + query;
+ m_namespaces = namespaces;
+ m_roleObjects = roleObjects;
+ if (!isRunning()) {
+ m_abort = false;
+ start();
+ } else {
+ m_restart = true;
+ m_condition.wakeOne();
+ }
+ m_queryId++;
+ return m_queryId;
+ }
+
+ QList<QList<QVariant> > modelData() {
+ QMutexLocker locker(&m_mutex);
+ return m_modelData;
+ }
+
+Q_SIGNALS:
+ void queryCompleted(int queryId, int size);
+
+protected:
+ void run() {
+ while (!m_quit) {
+ m_mutex.lock();
+ int queryId = m_queryId;
+ doQueryJob();
+ if (m_size > 0)
+ doSubQueryJob();
+ m_data.clear(); // no longer needed
+ m_mutex.unlock();
+
+ m_mutex.lock();
+ if (!m_abort && m_size > 0)
+ emit queryCompleted(queryId, m_size);
+ if (!m_restart)
+ m_condition.wait(&m_mutex);
+ m_abort = false;
+ m_restart = false;
+ m_mutex.unlock();
+ }
+ }
+
+private:
+ void doQueryJob();
+ void doSubQueryJob();
+
+private:
+ QMutex m_mutex;
+ QWaitCondition m_condition;
+ bool m_quit;
+ bool m_restart;
+ bool m_abort;
+ QByteArray m_data;
+ QString m_query;
+ QString m_namespaces;
+ QString m_prefix;
+ int m_size;
+ int m_queryId;
+ const QmlXmlRoleList *m_roleObjects;
+ QList<QList<QVariant> > m_modelData;
+};
+
+void QmlXmlQuery::doQueryJob()
+{
+ QString r;
+ QXmlQuery query;
+ QBuffer buffer(&m_data);
+ buffer.open(QIODevice::ReadOnly);
+ query.bindVariable(QLatin1String("src"), &buffer);
+ query.setQuery(m_namespaces + m_query);
+ query.evaluateTo(&r);
+
+ //qDebug() << r;
+
+ //always need a single root element
+ QByteArray xml = "<dummy:items xmlns:dummy=\"http://qtsotware.com/dummy\">\n" + r.toUtf8() + "</dummy:items>";
+ QBuffer b(&xml);
+ b.open(QIODevice::ReadOnly);
+ //qDebug() << xml;
+
+ QString namespaces = QLatin1String("declare namespace dummy=\"http://qtsotware.com/dummy\";\n") + m_namespaces;
+ QString prefix = QLatin1String("doc($inputDocument)/dummy:items") +
+ m_query.mid(m_query.lastIndexOf(QLatin1Char('/')));
+
+ //figure out how many items we are dealing with
+ int count = -1;
+ {
+ QXmlResultItems result;
+ QXmlQuery countquery;
+ countquery.bindVariable(QLatin1String("inputDocument"), &b);
+ countquery.setQuery(namespaces + QLatin1String("count(") + prefix + QLatin1Char(')'));
+ countquery.evaluateTo(&result);
+ QXmlItem item(result.next());
+ if (item.isAtomicValue())
+ count = item.toAtomicValue().toInt();
+ }
+ //qDebug() << count;
+
+ m_prefix = namespaces + prefix + QLatin1Char('/');
+ m_data = xml;
+ if (count > 0)
+ m_size = count;
+}
+
+void QmlXmlQuery::doSubQueryJob()
+{
+ m_modelData.clear();
+
+ QBuffer b(&m_data);
+ b.open(QIODevice::ReadOnly);
+
+ QXmlQuery subquery;
+ subquery.bindVariable(QLatin1String("inputDocument"), &b);
+
+ //### we might be able to condense even further (query for everything in one go)
+ for (int i = 0; i < m_roleObjects->size(); ++i) {
+ QmlXmlListModelRole *role = m_roleObjects->at(i);
+ if (!role->isValid()) {
+ QList<QVariant> resultList;
+ for (int j = 0; j < m_size; ++j)
+ resultList << QVariant();
+ m_modelData << resultList;
+ continue;
+ }
+ subquery.setQuery(m_prefix + QLatin1String("(let $v := ") + role->query() + QLatin1String(" return if ($v) then ") + role->query() + QLatin1String(" else \"\")"));
+ QXmlResultItems output3;
+ subquery.evaluateTo(&output3);
+ QXmlItem item(output3.next());
+ QList<QVariant> resultList;
+ while (!item.isNull()) {
+ resultList << item.toAtomicValue(); //### we used to trim strings
+ item = output3.next();
+ }
+ //### should warn here if things have gone wrong.
+ while (resultList.count() < m_size)
+ resultList << QVariant();
+ m_modelData << resultList;
+ b.seek(0);
+ }
+
+ //this method is much slower, but works better for incremental loading
+ /*for (int j = 0; j < m_size; ++j) {
+ QList<QVariant> resultList;
+ for (int i = 0; i < m_roleObjects->size(); ++i) {
+ QmlXmlListModelRole *role = m_roleObjects->at(i);
+ subquery.setQuery(m_prefix.arg(j+1) + role->query());
+ if (role->isStringList()) {
+ QStringList data;
+ subquery.evaluateTo(&data);
+ resultList << QVariant(data);
+ //qDebug() << data;
+ } else {
+ QString s;
+ subquery.evaluateTo(&s);
+ if (role->isCData()) {
+ //un-escape
+ s.replace(QLatin1String("&lt;"), QLatin1String("<"));
+ s.replace(QLatin1String("&gt;"), QLatin1String(">"));
+ s.replace(QLatin1String("&amp;"), QLatin1String("&"));
+ }
+ resultList << s.trimmed();
+ //qDebug() << s;
+ }
+ b.seek(0);
+ }
+ m_modelData << resultList;
+ }*/
+}
+
+class QmlXmlListModelPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QmlXmlListModel)
+public:
+ QmlXmlListModelPrivate()
+ : isComponentComplete(true), size(-1), highestRole(Qt::UserRole)
+ , reply(0), status(QmlXmlListModel::Null), progress(0.0)
+ , queryId(-1), roleObjects(this) {}
+
+ bool isComponentComplete;
+ QUrl src;
+ QString xml;
+ QString query;
+ QString namespaces;
+ int size;
+ QList<int> roles;
+ QStringList roleNames;
+ int highestRole;
+ QNetworkReply *reply;
+ QmlXmlListModel::Status status;
+ qreal progress;
+ QmlXmlQuery qmlXmlQuery;
+ int queryId;
+ QmlXmlRoleList roleObjects;
+ QList<QList<QVariant> > data;
+};
+
+
+void QmlXmlRoleList::append(QmlXmlListModelRole *role)
+{
+ insert(size(), role);
+}
+
+//### clear, removeAt, and insert need to invalidate any cached data (in data table) as well
+// (and the model should emit the appropriate signals)
+void QmlXmlRoleList::clear()
+{
+ model->roles.clear();
+ model->roleNames.clear();
+ QmlConcreteList<QmlXmlListModelRole *>::clear();
+}
+
+void QmlXmlRoleList::removeAt(int i)
+{
+ model->roles.removeAt(i);
+ model->roleNames.removeAt(i);
+ QmlConcreteList<QmlXmlListModelRole *>::removeAt(i);
+}
+
+void QmlXmlRoleList::insert(int i, QmlXmlListModelRole *role)
+{
+ QmlConcreteList<QmlXmlListModelRole *>::insert(i, role);
+ if (model->roleNames.contains(role->name())) {
+ qmlInfo(role) << QObject::tr("\"%1\" duplicates a previous role name and will be disabled.").arg(role->name());
+ return;
+ }
+ model->roles.insert(i, model->highestRole);
+ model->roleNames.insert(i, role->name());
+ ++model->highestRole;
+}
+
+/*!
+ \class QmlXmlListModel
+ \internal
+*/
+
+/*!
+ \qmlclass XmlListModel QmlXmlListModel
+ \brief The XmlListModel element allows you to specify a model using XPath expressions.
+
+ XmlListModel allows you to construct a model from XML data that can then be used as a data source
+ for the view classes (ListView, PathView, GridView) and any other classes that interact with model
+ data (like Repeater).
+
+ The following is an example of a model containing news from a Yahoo RSS feed:
+ \qml
+ XmlListModel {
+ id: feedModel
+ source: "http://rss.news.yahoo.com/rss/oceania"
+ query: "/rss/channel/item"
+ XmlRole { name: "title"; query: "title/string()" }
+ XmlRole { name: "link"; query: "link/string()" }
+ XmlRole { name: "description"; query: "description/string()" }
+ }
+ \endqml
+ \note The model is currently static, so the above is really just a snapshot of an RSS feed. To force a
+ reload of the entire model, you can call the reload function.
+*/
+
+QmlXmlListModel::QmlXmlListModel(QObject *parent)
+ : QListModelInterface(*(new QmlXmlListModelPrivate), parent)
+{
+ Q_D(QmlXmlListModel);
+ connect(&d->qmlXmlQuery, SIGNAL(queryCompleted(int,int)),
+ this, SLOT(queryCompleted(int,int)));
+}
+
+QmlXmlListModel::~QmlXmlListModel()
+{
+}
+
+/*!
+ \qmlproperty list<XmlRole> XmlListModel::roles
+
+ The roles to make available for this model.
+*/
+QmlList<QmlXmlListModelRole *> *QmlXmlListModel::roleObjects()
+{
+ Q_D(QmlXmlListModel);
+ return &d->roleObjects;
+}
+
+QHash<int,QVariant> QmlXmlListModel::data(int index, const QList<int> &roles) const
+{
+ Q_D(const QmlXmlListModel);
+ QHash<int, QVariant> rv;
+ for (int i = 0; i < roles.size(); ++i) {
+ int role = roles.at(i);
+ int roleIndex = d->roles.indexOf(role);
+ rv.insert(role, roleIndex == -1 ? QVariant() : d->data.at(roleIndex).at(index));
+ }
+ return rv;
+}
+
+QVariant QmlXmlListModel::data(int index, int role) const
+{
+ Q_D(const QmlXmlListModel);
+ int roleIndex = d->roles.indexOf(role);
+ return (roleIndex == -1) ? QVariant() : d->data.at(roleIndex).at(index);
+}
+
+/*!
+ \qmlproperty int XmlListModel::count
+ The number of data entries in the model.
+*/
+int QmlXmlListModel::count() const
+{
+ Q_D(const QmlXmlListModel);
+ return d->size;
+}
+
+QList<int> QmlXmlListModel::roles() const
+{
+ Q_D(const QmlXmlListModel);
+ return d->roles;
+}
+
+QString QmlXmlListModel::toString(int role) const
+{
+ Q_D(const QmlXmlListModel);
+ int index = d->roles.indexOf(role);
+ if (index == -1)
+ return QString();
+ return d->roleNames.at(index);
+}
+
+/*!
+ \qmlproperty url XmlListModel::source
+ The location of the XML data source.
+
+ If both source and xml are set, xml will be used.
+*/
+QUrl QmlXmlListModel::source() const
+{
+ Q_D(const QmlXmlListModel);
+ return d->src;
+}
+
+void QmlXmlListModel::setSource(const QUrl &src)
+{
+ Q_D(QmlXmlListModel);
+ if (d->src != src) {
+ d->src = src;
+ reload();
+ }
+}
+
+/*!
+ \qmlproperty string XmlListModel::xml
+ This property holds XML text set directly.
+
+ The text is assumed to be UTF-8 encoded.
+
+ If both source and xml are set, xml will be used.
+*/
+QString QmlXmlListModel::xml() const
+{
+ Q_D(const QmlXmlListModel);
+ return d->xml;
+}
+
+void QmlXmlListModel::setXml(const QString &xml)
+{
+ Q_D(QmlXmlListModel);
+ d->xml = xml;
+ reload();
+}
+
+/*!
+ \qmlproperty url XmlListModel::query
+ An absolute XPath query representing the base query for the model items. The query should start with
+ a '/' or '//'.
+*/
+QString QmlXmlListModel::query() const
+{
+ Q_D(const QmlXmlListModel);
+ return d->query;
+}
+
+void QmlXmlListModel::setQuery(const QString &query)
+{
+ Q_D(QmlXmlListModel);
+ if (!query.startsWith(QLatin1Char('/'))) {
+ qmlInfo(this) << tr("An XmlListModel query must start with '/' or \"//\"");
+ return;
+ }
+
+ if (d->query != query) {
+ d->query = query;
+ reload();
+ }
+}
+
+/*!
+ \qmlproperty string XmlListModel::namespaceDeclarations
+ A set of declarations for the namespaces used in the query.
+*/
+QString QmlXmlListModel::namespaceDeclarations() const
+{
+ Q_D(const QmlXmlListModel);
+ return d->namespaces;
+}
+
+void QmlXmlListModel::setNamespaceDeclarations(const QString &declarations)
+{
+ Q_D(QmlXmlListModel);
+ if (d->namespaces != declarations) {
+ d->namespaces = declarations;
+ reload();
+ }
+}
+
+/*!
+ \qmlproperty enum XmlListModel::status
+
+ This property holds the status of data source loading. It can be one of:
+ \list
+ \o Null - no data source has been set
+ \o Ready - nthe data source has been loaded
+ \o Loading - the data source is currently being loaded
+ \o Error - an error occurred while loading the data source
+ \endlist
+
+ \sa progress
+
+*/
+QmlXmlListModel::Status QmlXmlListModel::status() const
+{
+ Q_D(const QmlXmlListModel);
+ return d->status;
+}
+
+/*!
+ \qmlproperty real XmlListModel::progress
+
+ This property holds the progress of data source loading, from 0.0 (nothing loaded)
+ to 1.0 (finished).
+
+ \sa status
+*/
+qreal QmlXmlListModel::progress() const
+{
+ Q_D(const QmlXmlListModel);
+ return d->progress;
+}
+
+void QmlXmlListModel::classBegin()
+{
+ Q_D(QmlXmlListModel);
+ d->isComponentComplete = false;
+}
+
+void QmlXmlListModel::componentComplete()
+{
+ Q_D(QmlXmlListModel);
+ d->isComponentComplete = true;
+ reload();
+}
+
+/*!
+ \qmlmethod XmlListModel::reload()
+
+ Reloads the model. All the existing model data will be removed, and the model
+ will be rebuilt from scratch.
+*/
+void QmlXmlListModel::reload()
+{
+ Q_D(QmlXmlListModel);
+
+ if (!d->isComponentComplete)
+ return;
+
+ d->qmlXmlQuery.abort();
+ d->queryId = -1;
+
+ //clear existing data
+ int count = d->size;
+ d->size = 0;
+ d->data.clear();
+ if (count > 0)
+ emit itemsRemoved(0, count);
+
+ if (d->src.isEmpty() && d->xml.isEmpty())
+ return;
+
+ if (d->reply) {
+ d->reply->abort();
+ d->reply->deleteLater();
+ d->reply = 0;
+ }
+
+ if (!d->xml.isEmpty()) {
+ d->queryId = d->qmlXmlQuery.doQuery(d->query, d->namespaces, d->xml.toUtf8(), &d->roleObjects);
+ d->progress = 1.0;
+ d->status = Ready;
+ emit progressChanged(d->progress);
+ emit statusChanged(d->status);
+ return;
+ }
+
+ d->progress = 0.0;
+ d->status = Loading;
+ emit progressChanged(d->progress);
+ emit statusChanged(d->status);
+
+ QNetworkRequest req(d->src);
+ d->reply = qmlContext(this)->engine()->networkAccessManager()->get(req);
+ QObject::connect(d->reply, SIGNAL(finished()), this, SLOT(requestFinished()));
+ QObject::connect(d->reply, SIGNAL(downloadProgress(qint64,qint64)),
+ this, SLOT(requestProgress(qint64,qint64)));
+}
+
+void QmlXmlListModel::requestFinished()
+{
+ Q_D(QmlXmlListModel);
+ if (d->reply->error() != QNetworkReply::NoError) {
+ disconnect(d->reply, 0, this, 0);
+ d->reply->deleteLater();
+ d->reply = 0;
+ d->status = Error;
+ } else {
+ d->status = Ready;
+ QByteArray data = d->reply->readAll();
+ d->queryId = d->qmlXmlQuery.doQuery(d->query, d->namespaces, data, &d->roleObjects);
+ disconnect(d->reply, 0, this, 0);
+ d->reply->deleteLater();
+ d->reply = 0;
+ }
+ d->progress = 1.0;
+ emit progressChanged(d->progress);
+ emit statusChanged(d->status);
+}
+
+void QmlXmlListModel::requestProgress(qint64 received, qint64 total)
+{
+ Q_D(QmlXmlListModel);
+ if (d->status == Loading && total > 0) {
+ d->progress = qreal(received)/total;
+ emit progressChanged(d->progress);
+ }
+}
+
+void QmlXmlListModel::queryCompleted(int id, int size)
+{
+ Q_D(QmlXmlListModel);
+ if (id != d->queryId)
+ return;
+ d->size = size;
+ if (size > 0) {
+ d->data = d->qmlXmlQuery.modelData();
+ emit itemsInserted(0, d->size);
+ emit countChanged();
+ }
+}
+
+QT_END_NAMESPACE
+
+#include <qmlxmllistmodel.moc>
diff --git a/src/declarative/util/qmlxmllistmodel_p.h b/src/declarative/util/qmlxmllistmodel_p.h
new file mode 100644
index 0000000..e4b8cab
--- /dev/null
+++ b/src/declarative/util/qmlxmllistmodel_p.h
@@ -0,0 +1,136 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QMLXMLLISTMODEL_H
+#define QMLXMLLISTMODEL_H
+
+#include <qml.h>
+#include <qmlinfo.h>
+
+#include "../3rdparty/qlistmodelinterface_p.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QmlContext;
+
+class QmlXmlListModelRole;
+
+class QmlXmlListModelPrivate;
+class Q_DECLARATIVE_EXPORT QmlXmlListModel : public QListModelInterface, public QmlParserStatus
+{
+ Q_OBJECT
+ Q_INTERFACES(QmlParserStatus)
+ Q_ENUMS(Status)
+
+ Q_PROPERTY(Status status READ status NOTIFY statusChanged)
+ Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged)
+ Q_PROPERTY(QUrl source READ source WRITE setSource)
+ Q_PROPERTY(QString xml READ xml WRITE setXml)
+ Q_PROPERTY(QString query READ query WRITE setQuery)
+ Q_PROPERTY(QString namespaceDeclarations READ namespaceDeclarations WRITE setNamespaceDeclarations)
+ Q_PROPERTY(QmlList<QmlXmlListModelRole *> *roles READ roleObjects)
+ Q_PROPERTY(int count READ count NOTIFY countChanged)
+ Q_CLASSINFO("DefaultProperty", "roles")
+
+public:
+ QmlXmlListModel(QObject *parent = 0);
+ ~QmlXmlListModel();
+
+ virtual QHash<int,QVariant> data(int index, const QList<int> &roles = (QList<int>())) const;
+ virtual QVariant data(int index, int role) const;
+ virtual int count() const;
+ virtual QList<int> roles() const;
+ virtual QString toString(int role) const;
+
+ QmlList<QmlXmlListModelRole *> *roleObjects();
+
+ QUrl source() const;
+ void setSource(const QUrl&);
+
+ QString xml() const;
+ void setXml(const QString&);
+
+ QString query() const;
+ void setQuery(const QString&);
+
+ QString namespaceDeclarations() const;
+ void setNamespaceDeclarations(const QString&);
+
+ enum Status { Null, Ready, Loading, Error };
+ Status status() const;
+ qreal progress() const;
+
+ virtual void classBegin();
+ virtual void componentComplete();
+
+Q_SIGNALS:
+ void statusChanged(Status);
+ void progressChanged(qreal progress);
+ void countChanged();
+
+public Q_SLOTS:
+ // ### need to use/expose Expiry to guess when to call this?
+ // ### property to auto-call this on reasonable Expiry?
+ // ### LastModified/Age also useful to guess.
+ // ### Probably also applies to other network-requesting types.
+ void reload();
+
+private Q_SLOTS:
+ void requestFinished();
+ void requestProgress(qint64,qint64);
+ void queryCompleted(int,int);
+
+private:
+ Q_DECLARE_PRIVATE(QmlXmlListModel)
+ Q_DISABLE_COPY(QmlXmlListModel)
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QmlXmlListModel)
+
+QT_END_HEADER
+
+#endif // QMLXMLLISTMODEL_H
diff --git a/src/declarative/util/qnumberformat.cpp b/src/declarative/util/qnumberformat.cpp
new file mode 100644
index 0000000..fd44db1
--- /dev/null
+++ b/src/declarative/util/qnumberformat.cpp
@@ -0,0 +1,225 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qnumberformat_p.h"
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_NOCREATE_TYPE(QNumberFormat)
+
+QNumberFormat::QNumberFormat(QObject *parent) : QObject(parent), _number(0), _type(Decimal),
+ _groupingSize(0)
+{
+ _locale = QLocale::system();
+ _groupingSeparator = _locale.groupSeparator();
+ _decimalSeparator = _locale.decimalPoint();
+ _currencySymbol = QLatin1Char('$');
+}
+
+QNumberFormat::~QNumberFormat()
+{
+
+}
+
+void QNumberFormat::updateText()
+{
+ QTime t;
+ t.start();
+ static int totalTime;
+
+ handleFormat();
+
+ totalTime += t.elapsed();
+ emit textChanged();
+}
+
+void QNumberFormat::handleFormat()
+{
+ // ### is extremely messy
+ if (_format.isEmpty()) {
+ _text = QString::number(_number, 'f', -1);
+ return;
+ }
+
+ QString inputString;
+
+ // ### possible to use the following parsed data in the future
+
+ int remainingLength = _format.size();
+ int currentIndex = _format.size()-1;
+
+ int maxDigits = 0;
+ int minDigits = 0;
+ int decimalLength = 0;
+
+ while (remainingLength > 0) {
+ switch(_format.at(currentIndex).unicode()) {
+ case ',':
+ if (decimalLength && !_groupingSize)
+ setGroupingSize(maxDigits - decimalLength);
+ else if (!_groupingSize)
+ setGroupingSize(maxDigits);
+ break;
+ case '.':
+ if (!decimalLength)
+ decimalLength = maxDigits;
+ break;
+ case '0':
+ minDigits++;
+ case '#':
+ maxDigits++;
+ break;
+ default:
+ break;
+ }
+ currentIndex--;
+ remainingLength--;
+ }
+
+ // round given the decimal length/precision
+ inputString = QString::number(_number, 'f', decimalLength);
+
+ QStringList parts = inputString.split(QLatin1Char('.'));
+ QStringList formatParts = _format.split(QLatin1Char('.'));
+
+ if (formatParts.size() > 2 || parts.size() > 2 )
+ return;
+
+ QString formatInt = formatParts.at(0);
+
+ QString formatDec;
+ if (formatParts.size() == 2)
+ formatDec = formatParts.at(1);
+
+ QString integer = parts.at(0);
+
+ QString decimal;
+ if (parts.size() == 2)
+ decimal = parts.at(1);
+
+ QString outputDecimal = formatDecimal(formatDec, decimal);
+ QString outputInteger = formatInteger(formatInt, integer);
+
+ // insert separators
+ if (_groupingSize) {
+ unsigned int count = 0;
+ for (int i = outputInteger.size()-1; i > 0; i--) {
+ if (outputInteger.at(i).digitValue() >= 0) {
+ if (count == _groupingSize - 1) {
+ count = 0;
+ outputInteger.insert(i, _groupingSeparator);
+ }
+ else
+ count++;
+ }
+ }
+ }
+ if (!outputDecimal.isEmpty())
+ _text = outputInteger + _decimalSeparator + outputDecimal;
+ else
+ _text = outputInteger;
+}
+
+QString QNumberFormat::formatInteger(const QString &formatInt, const QString &integer)
+{
+ if (formatInt.isEmpty() || integer.isEmpty())
+ return QString();
+
+ QString outputInteger;
+ int formatIndex = formatInt.size()-1;
+
+ //easier for carry?
+ for (int index= integer.size()-1; index >= 0; index--) {
+ if (formatIndex < 0) {
+ outputInteger.push_front(integer.at(index));
+ }
+ else {
+ switch(formatInt.at(formatIndex).unicode()) {
+ case '0':
+ if (index > integer.size()-1) {
+ outputInteger.push_front(QLatin1Char('0'));
+ break;
+ }
+ case '#':
+ outputInteger.push_front(integer.at(index));
+ break;
+ case ',':
+ index++;
+ break;
+ default:
+ outputInteger.push_front(formatInt.at(formatIndex));
+ index++;
+ break;
+ }
+ formatIndex--;
+ }
+ }
+ while (formatIndex >= 0) {
+ if (formatInt.at(formatIndex).unicode() != '#' && formatInt.at(formatIndex).unicode() != ',')
+ outputInteger.push_front(formatInt.at(formatIndex));
+ formatIndex--;
+ }
+ return outputInteger;
+}
+
+QString QNumberFormat::formatDecimal(const QString &formatDec, const QString &decimal)
+{
+ QString outputDecimal;
+
+ // up to max 6 decimal places
+ for (int index=formatDec.size()-1; index >= 0; index--) {
+ switch(formatDec.at(index).unicode()) {
+ case '0':
+ outputDecimal.push_front(decimal.at(index));
+ break;
+ case '#':
+ if (decimal.at(index) != QLatin1Char('0') || outputDecimal.size() > 0)
+ outputDecimal.push_front(decimal.at(index));
+ break;
+ default:
+ outputDecimal.push_front(formatDec.at(index));
+ break;
+ }
+ }
+ return outputDecimal;
+}
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qnumberformat_p.h b/src/declarative/util/qnumberformat_p.h
new file mode 100644
index 0000000..c73ef8a
--- /dev/null
+++ b/src/declarative/util/qnumberformat_p.h
@@ -0,0 +1,174 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef NUMBERFORMAT_H
+#define NUMBERFORMAT_H
+
+#include <qml.h>
+
+#include <QtCore/QLocale>
+#include <QtCore/QTime>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+// TODO
+// be able to set Locale, instead of default system for dynamic formatting
+// add currency support
+// add additional syntax, extend to format scientific, percentiles, significant digits etc
+
+
+class QNumberFormat : public QObject
+{
+ Q_OBJECT
+ Q_ENUMS(NumberType)
+public:
+ QNumberFormat(QObject *parent=0);
+ ~QNumberFormat();
+
+ enum NumberType {
+ Percent,
+ Scientific,
+ Currency,
+ Decimal
+ };
+
+ //external property, only visible
+ Q_PROPERTY(QString text READ text NOTIFY textChanged)
+
+ //mutatable properties to modify the output (text)
+ Q_PROPERTY(qreal number READ number WRITE setNumber)
+ Q_PROPERTY(QString format READ format WRITE setFormat)
+ Q_PROPERTY(QLocale locale READ locale WRITE setLocale)
+
+ //Format specific settings
+ Q_PROPERTY(unsigned short groupingSeparator READ groupingSeparator WRITE setGroupingSeparator)
+ Q_PROPERTY(unsigned short decimalSeperator READ decimalSeparator WRITE setDecimalSeparator)
+ Q_PROPERTY(unsigned int groupingSize READ groupingSize WRITE setGroupingSize)
+ Q_PROPERTY(unsigned short currencySymbol READ currencySymbol WRITE setCurrencySymbol)
+
+
+ QString text() const { return _text; }
+
+ qreal number() const { return _number; }
+ void setNumber(qreal n) {
+ if (_number == n)
+ return;
+ _number = n;
+ updateText();
+ }
+
+ QString format() const { return _format; }
+ void setFormat(const QString &format) {
+ if (format.isEmpty())
+ _format = QString::null;
+ else if (_format == format)
+ return;
+
+ _format = format;
+ updateText();
+ }
+
+ QLocale locale() const { return _locale; }
+ void setLocale(const QLocale &locale) { _locale = locale; updateText(); }
+
+ //Do we deal with unicode standard? or create our own
+ // ### since this is the backend for the number conversions, we will use the unicode
+ // the front-end will handle the QChar/QString -> short int
+
+ unsigned short groupingSeparator() { return _groupingSeparator.unicode(); }
+ void setGroupingSeparator(unsigned short unicodeSymbol)
+ {
+ _groupingSeparator = QChar(unicodeSymbol);
+ }
+
+ unsigned short decimalSeparator() { return _decimalSeparator.unicode(); }
+ void setDecimalSeparator(unsigned short unicodeSymbol)
+ {
+ _decimalSeparator = QChar(unicodeSymbol);
+ }
+
+ unsigned short currencySymbol() { return _currencySymbol.unicode(); }
+ void setCurrencySymbol(unsigned short unicodeSymbol)
+ {
+ _currencySymbol = QChar(unicodeSymbol);
+ }
+
+ unsigned int groupingSize() { return _groupingSize; }
+ void setGroupingSize(unsigned int size)
+ {
+ _groupingSize = size;
+ }
+
+Q_SIGNALS:
+ void textChanged();
+
+private:
+ void updateText();
+ void handleFormat();
+ QString formatInteger(const QString &formatInt, const QString &integer);
+ QString formatDecimal(const QString &formatDec, const QString &decimal);
+
+ qreal _number;
+ NumberType _type;
+ QChar _groupingSeparator;
+ QChar _decimalSeparator;
+ QChar _currencySymbol;
+ unsigned int _groupingSize;
+
+ QLocale _locale;
+ QString _format;
+
+ // only hooked member at the moment
+ QString _text;
+
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QNumberFormat)
+
+QT_END_HEADER
+
+#endif
diff --git a/src/declarative/util/qperformancelog.cpp b/src/declarative/util/qperformancelog.cpp
new file mode 100644
index 0000000..2f91dfb
--- /dev/null
+++ b/src/declarative/util/qperformancelog.cpp
@@ -0,0 +1,181 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qperformancelog_p_p.h"
+
+#include <QHash>
+#include <QDebug>
+
+QT_BEGIN_NAMESPACE
+
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+
+struct QPerformanceLogData
+{
+ struct Log
+ {
+ Log()
+ : logDescription(0), maxId(-1) {}
+
+ QHash<int, const char *> descriptions;
+ const char *logDescription;
+ int maxId;
+ };
+
+ typedef QHash<QPerformanceLog::LogData *, Log> Logs;
+ Logs logs;
+};
+Q_GLOBAL_STATIC(QPerformanceLogData, performanceLogData);
+
+QPerformanceLog::LogData::LogData(const char *desc)
+: sumTime(0), data(0)
+{
+ QPerformanceLogData *logData = performanceLogData();
+
+ QPerformanceLogData::Log log;
+ log.logDescription = desc;
+ logData->logs.insert(this, log);
+
+ timer.start();
+}
+
+QPerformanceLog::LogMetric::LogMetric(LogData *l, int id, const char *desc)
+{
+ if (id < 0)
+ qFatal("QPerformanceLog: Invalid log id %d ('%s')", id, desc);
+
+ QPerformanceLogData *logData = performanceLogData();
+
+ QPerformanceLogData::Logs::Iterator logIter = logData->logs.find(l);
+ if (logIter == logData->logs.end())
+ qFatal("QPerformanceLog: Unable to locate log for metric '%s'", desc);
+ QPerformanceLogData::Log &log = *logIter;
+ if (log.descriptions.contains(id))
+ qFatal("QPerformanceLog: Duplicate log metric %d ('%s')", id, desc);
+ log.descriptions.insert(id, desc);
+
+ if (log.maxId < id) {
+ log.maxId = id;
+ if (l->data) delete [] l->data;
+ l->data = new unsigned int[2 * (log.maxId + 1)];
+ ::memset(l->data, 0, 2 * (log.maxId + 1) * sizeof(unsigned int));
+ }
+}
+
+static void QPerformanceLog_clear(QPerformanceLog::LogData *l, const QPerformanceLogData::Log *pl)
+{
+ ::memset(l->data, 0, 2 * (pl->maxId + 1) * sizeof(unsigned int));
+}
+
+static void QPerformanceLog_displayData(const QPerformanceLog::LogData *l, const QPerformanceLogData::Log *pl)
+{
+ qWarning() << pl->logDescription << "performance data";
+ unsigned int total = 0;
+ for (QHash<int, const char *>::ConstIterator iter = pl->descriptions.begin();
+ iter != pl->descriptions.end();
+ ++iter) {
+
+ int id = iter.key();
+ unsigned int ms = l->data[id * 2];
+ total += ms;
+ unsigned int inst = l->data[id * 2 + 1];
+ float pi = float(ms) / float(inst);
+ qWarning().nospace() << " " << *iter << ": " << ms << " ms over "
+ << inst << " instances (" << pi << " ms/instance)";
+ }
+ qWarning().nospace() << " TOTAL: " << total;
+}
+
+void QPerformanceLog::displayData()
+{
+ QPerformanceLogData *logData = performanceLogData();
+
+ for (QPerformanceLogData::Logs::ConstIterator iter = logData->logs.begin();
+ iter != logData->logs.end();
+ ++iter) {
+ QPerformanceLog_displayData(iter.key(), &(*iter));
+ }
+}
+
+void QPerformanceLog::clear()
+{
+ QPerformanceLogData *logData = performanceLogData();
+
+ for (QPerformanceLogData::Logs::ConstIterator iter = logData->logs.begin();
+ iter != logData->logs.end();
+ ++iter) {
+ QPerformanceLog_clear(iter.key(), &(*iter));
+ }
+}
+
+void QPerformanceLog::displayData(LogData *l)
+{
+ QPerformanceLogData *logData = performanceLogData();
+ QPerformanceLogData::Logs::ConstIterator iter = logData->logs.find(l);
+ if (iter == logData->logs.end())
+ qFatal("QPerformanceLog: Internal corruption - unable to locate log");
+
+ QPerformanceLog_displayData(iter.key(), &(*iter));
+}
+
+void QPerformanceLog::clear(LogData *l)
+{
+ QPerformanceLogData *logData = performanceLogData();
+ QPerformanceLogData::Logs::ConstIterator iter = logData->logs.find(l);
+ if (iter == logData->logs.end())
+ qFatal("QPerformanceLog: Internal corruption - unable to locate log");
+
+ QPerformanceLog_clear(iter.key(), &(*iter));
+}
+
+#else // Q_ENABLE_PERFORMANCE_LOG
+
+void QPerformanceLog::displayData()
+{
+}
+
+void QPerformanceLog::clear()
+{
+}
+
+#endif // Q_ENABLE_PERFORMANCE_LOG
+
+QT_END_NAMESPACE
diff --git a/src/declarative/util/qperformancelog_p_p.h b/src/declarative/util/qperformancelog_p_p.h
new file mode 100644
index 0000000..e7a3b5e
--- /dev/null
+++ b/src/declarative/util/qperformancelog_p_p.h
@@ -0,0 +1,141 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QPERFORMANCELOG_H
+#define QPERFORMANCELOG_H
+
+#include <QtCore/qdatetime.h>
+
+QT_BEGIN_NAMESPACE
+
+namespace QPerformanceLog
+{
+ Q_DECLARATIVE_EXPORT void displayData();
+ Q_DECLARATIVE_EXPORT void clear();
+
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+ struct LogData {
+ LogData(const char *);
+ QTime timer;
+ int sumTime;
+ unsigned int *data;
+ };
+
+ struct LogMetric {
+ LogMetric(LogData *, int, const char *);
+ };
+
+ // Internal
+ void displayData(LogData *);
+ void clear(LogData *);
+#endif
+}
+
+#ifdef Q_ENABLE_PERFORMANCE_LOG
+
+#define Q_DECLARE_PERFORMANCE_METRIC(name) \
+ enum { name = ValueChoice<0, ValueTracker<0, __LINE__>::value, __LINE__>::value }; \
+ template<int L> \
+ struct ValueTracker<name, L> \
+ { \
+ enum { value = name }; \
+ }; \
+ extern QPerformanceLog::LogMetric metric ## name;
+
+#define Q_DECLARE_PERFORMANCE_LOG(name) \
+ namespace name { \
+ extern QPerformanceLog::LogData log; \
+ inline void displayData() { QPerformanceLog::displayData(&log); } \
+ inline void clear() { QPerformanceLog::clear(&log); } \
+ } \
+ template<int N> \
+ class name ## Timer { \
+ public: \
+ name ## Timer() { \
+ lastSum = name::log.sumTime + name::log.timer.restart(); \
+ name::log.sumTime = 0; \
+ } \
+ ~ name ## Timer() { \
+ name::log.data[2 * N] += name::log.sumTime + name::log.timer.restart(); \
+ ++name::log.data[2 * N + 1]; \
+ name::log.sumTime = lastSum; \
+ } \
+ private: \
+ int lastSum; \
+ }; \
+ namespace name { \
+ template<int N, int L> \
+ struct ValueTracker \
+ { \
+ enum { value = -1 }; \
+ }; \
+ template<int DefNextValue, int NextValue, int L> \
+ struct ValueChoice \
+ { \
+ enum { value = ValueChoice<DefNextValue + 1, ValueTracker<DefNextValue + 1, L>::value, L>::value }; \
+ }; \
+ template<int DefNextValue, int L> \
+ struct ValueChoice<DefNextValue, -1, L> \
+ { \
+ enum { value = DefNextValue }; \
+ }; \
+ } \
+ namespace name
+
+#define Q_DEFINE_PERFORMANCE_LOG(name, desc) \
+ QPerformanceLog::LogData name::log(desc); \
+ namespace name
+
+#define Q_DEFINE_PERFORMANCE_METRIC(name, desc) \
+ QPerformanceLog::LogMetric metrix ## name(&log, name, desc);
+
+#else // Q_ENABLE_PERFORMANCE_LOG
+
+#define Q_DECLARE_PERFORMANCE_METRIC(name)
+#define Q_DECLARE_PERFORMANCE_LOG(name) namespace name
+#define Q_DEFINE_PERFORMANCE_LOG(name, desc) namespace name
+#define Q_DEFINE_PERFORMANCE_METRIC(name, desc)
+
+#endif // Q_ENABLE_PERFORMANCE_LOG
+
+QT_END_NAMESPACE
+
+#endif // QPERFORMANCELOG_H
diff --git a/src/declarative/util/util.pri b/src/declarative/util/util.pri
new file mode 100644
index 0000000..b6a5c90
--- /dev/null
+++ b/src/declarative/util/util.pri
@@ -0,0 +1,72 @@
+INCLUDEPATH += $$PWD
+
+SOURCES += \
+ $$PWD/qmlview.cpp \
+ $$PWD/qfxperf.cpp \
+ $$PWD/qperformancelog.cpp \
+ $$PWD/qmlconnection.cpp \
+ $$PWD/qmlpackage.cpp \
+ $$PWD/qmlanimation.cpp \
+ $$PWD/qmlsystempalette.cpp \
+ $$PWD/qmlspringfollow.cpp \
+ $$PWD/qmleasefollow.cpp \
+ $$PWD/qmlstate.cpp\
+ $$PWD/qmltransitionmanager.cpp \
+ $$PWD/qmlstateoperations.cpp \
+ $$PWD/qmlpropertychanges.cpp \
+ $$PWD/qmlstategroup.cpp \
+ $$PWD/qmltransition.cpp \
+ $$PWD/qmllistmodel.cpp\
+ $$PWD/qmllistaccessor.cpp \
+ $$PWD/qmlopenmetaobject.cpp \
+ $$PWD/qmltimeline.cpp \
+ $$PWD/qmltimer.cpp \
+ $$PWD/qmlbind.cpp \
+ $$PWD/qmlpropertymap.cpp \
+ $$PWD/qmlpixmapcache.cpp \
+ $$PWD/qnumberformat.cpp \
+ $$PWD/qmlnumberformatter.cpp \
+ $$PWD/qmldatetimeformatter.cpp \
+ $$PWD/qmlbehavior.cpp \
+ $$PWD/qmlfontloader.cpp \
+ $$PWD/qmlstyledtext.cpp
+
+HEADERS += \
+ $$PWD/qmlview.h \
+ $$PWD/qfxperf_p_p.h \
+ $$PWD/qperformancelog_p_p.h \
+ $$PWD/qmlconnection_p.h \
+ $$PWD/qmlpackage_p.h \
+ $$PWD/qmlanimation_p.h \
+ $$PWD/qmlanimation_p_p.h \
+ $$PWD/qmlsystempalette_p.h \
+ $$PWD/qmlspringfollow_p.h \
+ $$PWD/qmleasefollow_p.h \
+ $$PWD/qmlstate_p.h\
+ $$PWD/qmlstateoperations_p.h \
+ $$PWD/qmlpropertychanges_p.h \
+ $$PWD/qmlstate_p_p.h\
+ $$PWD/qmltransitionmanager_p_p.h \
+ $$PWD/qmlstategroup_p.h \
+ $$PWD/qmltransition_p.h \
+ $$PWD/qmllistmodel_p.h\
+ $$PWD/qmllistaccessor_p.h \
+ $$PWD/qmlopenmetaobject_p.h \
+ $$PWD/qmlnullablevalue_p_p.h \
+ $$PWD/qmltimeline_p_p.h \
+ $$PWD/qmltimer_p.h \
+ $$PWD/qmlbind_p.h \
+ $$PWD/qmlpropertymap.h \
+ $$PWD/qmlpixmapcache_p.h \
+ $$PWD/qnumberformat_p.h \
+ $$PWD/qmlnumberformatter_p.h \
+ $$PWD/qmldatetimeformatter_p.h \
+ $$PWD/qmlbehavior_p.h \
+ $$PWD/qmlfontloader_p.h \
+ $$PWD/qmlstyledtext_p.h
+
+contains(QT_CONFIG, xmlpatterns) {
+ QT+=xmlpatterns
+ SOURCES += $$PWD/qmlxmllistmodel.cpp
+ HEADERS += $$PWD/qmlxmllistmodel_p.h
+}
diff --git a/src/declarative/widgets/graphicslayouts.cpp b/src/declarative/widgets/graphicslayouts.cpp
new file mode 100644
index 0000000..065040f
--- /dev/null
+++ b/src/declarative/widgets/graphicslayouts.cpp
@@ -0,0 +1,319 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "graphicslayouts_p.h"
+
+#include <QtGui/qgraphicswidget.h>
+#include <QtCore/qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+QML_DEFINE_INTERFACE(QGraphicsLayoutItem)
+QML_DEFINE_INTERFACE(QGraphicsLayout)
+
+QML_DEFINE_TYPE(Qt,4,6,QGraphicsLinearLayoutStretchItem,QGraphicsLinearLayoutStretchItemObject)
+QML_DEFINE_TYPE(Qt,4,6,QGraphicsLinearLayout,QGraphicsLinearLayoutObject)
+QML_DEFINE_TYPE(Qt,4,6,QGraphicsGridLayout,QGraphicsGridLayoutObject)
+
+class LinearLayoutAttached : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(int stretchFactor READ stretchFactor WRITE setStretchFactor NOTIFY stretchChanged)
+ Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged)
+public:
+ LinearLayoutAttached(QObject *parent)
+ : QObject(parent), _stretch(1), _alignment(Qt::AlignCenter)
+ {
+ }
+
+ int stretchFactor() const { return _stretch; }
+ void setStretchFactor(int f)
+ {
+ if (_stretch == f)
+ return;
+
+ _stretch = f;
+ emit stretchChanged(reinterpret_cast<QGraphicsLayoutItem*>(parent()), _stretch);
+ }
+
+ Qt::Alignment alignment() const { return _alignment; }
+ void setAlignment(Qt::Alignment a)
+ {
+ if (_alignment == a)
+ return;
+
+ _alignment = a;
+ emit alignmentChanged(reinterpret_cast<QGraphicsLayoutItem*>(parent()), _alignment);
+ }
+
+Q_SIGNALS:
+ void stretchChanged(QGraphicsLayoutItem*,int);
+ void alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment);
+
+private:
+ int _stretch;
+ Qt::Alignment _alignment;
+};
+
+
+QGraphicsLinearLayoutStretchItemObject::QGraphicsLinearLayoutStretchItemObject(QObject *parent)
+ : QObject(parent)
+{
+}
+
+QSizeF QGraphicsLinearLayoutStretchItemObject::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
+{
+ Q_UNUSED(which);
+ Q_UNUSED(constraint);
+ return QSizeF();
+}
+
+
+QGraphicsLinearLayoutObject::QGraphicsLinearLayoutObject(QObject *parent)
+: QObject(parent), _children(this)
+{
+}
+
+QGraphicsLinearLayoutObject::~QGraphicsLinearLayoutObject()
+{
+}
+
+void QGraphicsLinearLayoutObject::insertLayoutItem(int index, QGraphicsLayoutItem *item)
+{
+ insertItem(index, item);
+
+ //connect attached properties
+ if (LinearLayoutAttached *obj = attachedProperties.value(item)) {
+ setStretchFactor(item, obj->stretchFactor());
+ setAlignment(item, obj->alignment());
+ QObject::connect(obj, SIGNAL(stretchChanged(QGraphicsLayoutItem*,int)),
+ this, SLOT(updateStretch(QGraphicsLayoutItem*,int)));
+ QObject::connect(obj, SIGNAL(alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment)),
+ this, SLOT(updateAlignment(QGraphicsLayoutItem*,Qt::Alignment)));
+ //### need to disconnect when widget is removed?
+ }
+}
+
+//### is there a better way to do this?
+void QGraphicsLinearLayoutObject::clearChildren()
+{
+ for (int i = 0; i < count(); ++i)
+ removeAt(i);
+}
+
+void QGraphicsLinearLayoutObject::updateStretch(QGraphicsLayoutItem *item, int stretch)
+{
+ QGraphicsLinearLayout::setStretchFactor(item, stretch);
+}
+
+void QGraphicsLinearLayoutObject::updateAlignment(QGraphicsLayoutItem *item, Qt::Alignment alignment)
+{
+ QGraphicsLinearLayout::setAlignment(item, alignment);
+}
+
+QHash<QGraphicsLayoutItem*, LinearLayoutAttached*> QGraphicsLinearLayoutObject::attachedProperties;
+LinearLayoutAttached *QGraphicsLinearLayoutObject::qmlAttachedProperties(QObject *obj)
+{
+ // ### This is not allowed - you must attach to any object
+ if (!qobject_cast<QGraphicsLayoutItem*>(obj))
+ return 0;
+ LinearLayoutAttached *rv = new LinearLayoutAttached(obj);
+ attachedProperties.insert(qobject_cast<QGraphicsLayoutItem*>(obj), rv);
+ return rv;
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+// QGraphicsGridLayout-related classes
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+class GridLayoutAttached : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(int row READ row WRITE setRow)
+ Q_PROPERTY(int column READ column WRITE setColumn)
+ Q_PROPERTY(int rowSpan READ rowSpan WRITE setRowSpan)
+ Q_PROPERTY(int columnSpan READ columnSpan WRITE setColumnSpan)
+ Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment)
+public:
+ GridLayoutAttached(QObject *parent)
+ : QObject(parent), _row(-1), _column(-1), _rowspan(1), _colspan(1), _alignment(-1)
+ {
+ }
+
+ int row() const { return _row; }
+ void setRow(int r)
+ {
+ if (_row == r)
+ return;
+
+ _row = r;
+ //emit rowChanged(reinterpret_cast<QGraphicsLayoutItem*>(parent()), _row);
+ }
+
+ int column() const { return _column; }
+ void setColumn(int c)
+ {
+ if (_column == c)
+ return;
+
+ _column = c;
+ //emit columnChanged(reinterpret_cast<QGraphicsLayoutItem*>(parent()), _column);
+ }
+
+ int rowSpan() const { return _rowspan; }
+ void setRowSpan(int rs)
+ {
+ if (_rowspan == rs)
+ return;
+
+ _rowspan = rs;
+ //emit rowSpanChanged(reinterpret_cast<QGraphicsLayoutItem*>(parent()), _rowSpan);
+ }
+
+ int columnSpan() const { return _colspan; }
+ void setColumnSpan(int cs)
+ {
+ if (_colspan == cs)
+ return;
+
+ _colspan = cs;
+ //emit columnSpanChanged(reinterpret_cast<QGraphicsLayoutItem*>(parent()), _columnSpan);
+ }
+
+ Qt::Alignment alignment() const { return _alignment; }
+ void setAlignment(Qt::Alignment a)
+ {
+ if (_alignment == a)
+ return;
+
+ _alignment = a;
+ //emit alignmentChanged(reinterpret_cast<QGraphicsLayoutItem*>(parent()), _alignment);
+ }
+
+Q_SIGNALS:
+ //void rowChanged(QGraphicsLayoutItem*,int);
+ //void columnSpanChanged(QGraphicsLayoutItem*,int);
+ //void rowSpanChanged(QGraphicsLayoutItem*,int);
+ //void columnChanged(QGraphicsLayoutItem*,int);
+ //void alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment);
+
+private:
+ int _row;
+ int _column;
+ int _rowspan;
+ int _colspan;
+ Qt::Alignment _alignment;
+};
+
+
+QGraphicsGridLayoutObject::QGraphicsGridLayoutObject(QObject *parent)
+: QObject(parent), _children(this)
+{
+}
+
+QGraphicsGridLayoutObject::~QGraphicsGridLayoutObject()
+{
+}
+
+void QGraphicsGridLayoutObject::addWidget(QGraphicsWidget *wid)
+{
+ //use attached properties
+ if (QObject *obj = attachedProperties.value(qobject_cast<QGraphicsLayoutItem*>(wid))) {
+ int row = static_cast<GridLayoutAttached *>(obj)->row();
+ int column = static_cast<GridLayoutAttached *>(obj)->column();
+ int rowSpan = static_cast<GridLayoutAttached *>(obj)->rowSpan();
+ int columnSpan = static_cast<GridLayoutAttached *>(obj)->columnSpan();
+ if (row == -1 || column == -1) {
+ qWarning() << "Must set row and column for an item in a grid layout";
+ return;
+ }
+ addItem(wid, row, column, rowSpan, columnSpan);
+ }
+}
+
+void QGraphicsGridLayoutObject::addLayoutItem(QGraphicsLayoutItem *item)
+{
+ //use attached properties
+ if (GridLayoutAttached *obj = attachedProperties.value(item)) {
+ int row = obj->row();
+ int column = obj->column();
+ int rowSpan = obj->rowSpan();
+ int columnSpan = obj->columnSpan();
+ Qt::Alignment alignment = obj->alignment();
+ if (row == -1 || column == -1) {
+ qWarning() << "Must set row and column for an item in a grid layout";
+ return;
+ }
+ addItem(item, row, column, rowSpan, columnSpan);
+ if (alignment != -1)
+ setAlignment(item,alignment);
+ }
+}
+
+//### is there a better way to do this?
+void QGraphicsGridLayoutObject::clearChildren()
+{
+ for (int i = 0; i < count(); ++i)
+ removeAt(i);
+}
+
+qreal QGraphicsGridLayoutObject::spacing() const
+{
+ if (verticalSpacing() == horizontalSpacing())
+ return verticalSpacing();
+ return -1; //###
+}
+
+QHash<QGraphicsLayoutItem*, GridLayoutAttached*> QGraphicsGridLayoutObject::attachedProperties;
+GridLayoutAttached *QGraphicsGridLayoutObject::qmlAttachedProperties(QObject *obj)
+{
+ // ### This is not allowed - you must attach to any object
+ if (!qobject_cast<QGraphicsLayoutItem*>(obj))
+ return 0;
+ GridLayoutAttached *rv = new GridLayoutAttached(obj);
+ attachedProperties.insert(qobject_cast<QGraphicsLayoutItem*>(obj), rv);
+ return rv;
+}
+
+QT_END_NAMESPACE
+
+#include <graphicslayouts.moc>
diff --git a/src/declarative/widgets/graphicslayouts_p.h b/src/declarative/widgets/graphicslayouts_p.h
new file mode 100644
index 0000000..34e2556
--- /dev/null
+++ b/src/declarative/widgets/graphicslayouts_p.h
@@ -0,0 +1,183 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef GRAPHICSLAYOUTS_H
+#define GRAPHICSLAYOUTS_H
+
+#include "graphicswidgets_p.h"
+
+#include <QtGui/QGraphicsLinearLayout>
+#include <QtGui/QGraphicsGridLayout>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+class QGraphicsLinearLayoutStretchItemObject : public QObject, public QGraphicsLayoutItem
+{
+ Q_OBJECT
+ Q_INTERFACES(QGraphicsLayoutItem)
+public:
+ QGraphicsLinearLayoutStretchItemObject(QObject *parent = 0);
+
+ virtual QSizeF sizeHint(Qt::SizeHint, const QSizeF &) const;
+};
+
+class LinearLayoutAttached;
+class QGraphicsLinearLayoutObject : public QObject, public QGraphicsLinearLayout
+{
+ Q_OBJECT
+ Q_INTERFACES(QGraphicsLayout QGraphicsLayoutItem)
+
+ Q_PROPERTY(QmlList<QGraphicsLayoutItem *> *children READ children)
+ Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation)
+ Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing)
+ Q_CLASSINFO("DefaultProperty", "children")
+public:
+ QGraphicsLinearLayoutObject(QObject * = 0);
+ ~QGraphicsLinearLayoutObject();
+
+ QmlList<QGraphicsLayoutItem *> *children() { return &_children; }
+
+ static LinearLayoutAttached *qmlAttachedProperties(QObject *);
+
+private Q_SLOTS:
+ void updateStretch(QGraphicsLayoutItem*,int);
+ void updateAlignment(QGraphicsLayoutItem*,Qt::Alignment);
+
+private:
+ friend class LinearLayoutAttached;
+ void clearChildren();
+ void insertLayoutItem(int, QGraphicsLayoutItem *);
+ static QHash<QGraphicsLayoutItem*, LinearLayoutAttached*> attachedProperties;
+
+ class ChildList : public QmlList<QGraphicsLayoutItem *>
+ {
+ public:
+ ChildList(QGraphicsLinearLayoutObject *o)
+ : obj(o) {}
+
+ virtual void append(QGraphicsLayoutItem *item)
+ {
+ insert(-1, item);
+ }
+ virtual void clear() { obj->clearChildren(); }
+ virtual int count() const { return obj->count(); }
+ virtual void removeAt(int i) { obj->removeAt(i); }
+ virtual QGraphicsLayoutItem *at(int i) const { return obj->itemAt(i); }
+ virtual void insert(int i, QGraphicsLayoutItem *item) { obj->insertLayoutItem(i, item); }
+
+ private:
+ QGraphicsLinearLayoutObject *obj;
+ };
+
+ ChildList _children;
+};
+
+class GridLayoutAttached;
+class QGraphicsGridLayoutObject : public QObject, public QGraphicsGridLayout
+{
+ Q_OBJECT
+ Q_INTERFACES(QGraphicsLayout QGraphicsLayoutItem)
+
+ Q_PROPERTY(QmlList<QGraphicsLayoutItem *> *children READ children)
+ Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing)
+ Q_PROPERTY(qreal verticalSpacing READ verticalSpacing WRITE setVerticalSpacing)
+ Q_PROPERTY(qreal horizontalSpacing READ horizontalSpacing WRITE setHorizontalSpacing)
+ Q_CLASSINFO("DefaultProperty", "children")
+public:
+ QGraphicsGridLayoutObject(QObject * = 0);
+ ~QGraphicsGridLayoutObject();
+
+ QmlList<QGraphicsLayoutItem *> *children() { return &_children; }
+
+ qreal spacing() const;
+
+ static GridLayoutAttached *qmlAttachedProperties(QObject *);
+
+private:
+ friend class GraphicsLayoutAttached;
+ void addWidget(QGraphicsWidget *);
+ void clearChildren();
+ void addLayoutItem(QGraphicsLayoutItem *);
+ static QHash<QGraphicsLayoutItem*, GridLayoutAttached*> attachedProperties;
+
+ class ChildList : public QmlList<QGraphicsLayoutItem *>
+ {
+ public:
+ ChildList(QGraphicsGridLayoutObject *o)
+ : obj(o) {}
+
+ virtual void append(QGraphicsLayoutItem *o)
+ {
+ obj->addLayoutItem(o);
+ }
+ virtual void clear() { obj->clearChildren(); }
+ virtual int count() const { return obj->count(); }
+ virtual void removeAt(int i) { obj->removeAt(i); }
+ virtual QGraphicsLayoutItem *at(int i) const { return obj->itemAt(i); }
+ //### GridLayout doesn't have an insert, so for now we treat it as an append.
+ // this is obviously potenitally dangerous -- perhaps should be a concrete
+ // list with no relation to layout index, etc at all.
+ virtual void insert(int, QGraphicsLayoutItem *item) { append(item); }
+
+ private:
+ QGraphicsGridLayoutObject *obj;
+ };
+
+ ChildList _children;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_INTERFACE(QGraphicsLayoutItem)
+QML_DECLARE_INTERFACE(QGraphicsLayout)
+QML_DECLARE_TYPE(QGraphicsLinearLayoutStretchItemObject)
+QML_DECLARE_TYPE(QGraphicsLinearLayoutObject)
+QML_DECLARE_TYPEINFO(QGraphicsLinearLayoutObject, QML_HAS_ATTACHED_PROPERTIES)
+QML_DECLARE_TYPE(QGraphicsGridLayoutObject)
+QML_DECLARE_TYPEINFO(QGraphicsGridLayoutObject, QML_HAS_ATTACHED_PROPERTIES)
+
+QT_END_HEADER
+
+#endif // GRAPHICSLAYOUTS_H
diff --git a/src/declarative/widgets/graphicswidgets.cpp b/src/declarative/widgets/graphicswidgets.cpp
new file mode 100644
index 0000000..4c13865
--- /dev/null
+++ b/src/declarative/widgets/graphicswidgets.cpp
@@ -0,0 +1,163 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "graphicswidgets_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QGraphicsViewDeclarativeUI : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QGraphicsScene *scene READ scene WRITE setScene)
+ Q_CLASSINFO("DefaultProperty", "scene")
+public:
+ QGraphicsViewDeclarativeUI(QObject *other) : QObject(other) {}
+
+ QGraphicsScene *scene() const { return static_cast<QGraphicsView *>(parent())->scene(); }
+ void setScene(QGraphicsScene *scene)
+ {
+ static_cast<QGraphicsView *>(parent())->setScene(scene);
+ }
+};
+
+class QGraphicsSceneDeclarativeUI : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QmlList<QObject *> *children READ children)
+ Q_CLASSINFO("DefaultProperty", "children")
+public:
+ QGraphicsSceneDeclarativeUI(QObject *other) : QObject(other), _children(other) {}
+
+ QmlList<QObject *> *children() { return &_children; }
+
+private:
+ class Children : public QmlConcreteList<QObject *>
+ {
+ public:
+ Children(QObject *scene) : q(scene) {}
+ virtual void append(QObject *o)
+ {
+ insert(-1, o);
+ }
+ virtual void clear()
+ {
+ for (int i = 0; i < count(); ++i)
+ if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(at(i)))
+ static_cast<QGraphicsScene *>(q)->removeItem(go);
+ QmlConcreteList<QObject *>::clear();
+ }
+ virtual void removeAt(int i)
+ {
+ if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(at(i)))
+ static_cast<QGraphicsScene *>(q)->removeItem(go);
+ QmlConcreteList<QObject *>::removeAt(i);
+ }
+ virtual void insert(int i, QObject *o)
+ {
+ QmlConcreteList<QObject *>::insert(i, o);
+ if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(o))
+ static_cast<QGraphicsScene *>(q)->addItem(go);
+ //else if (QWidget *w = qobject_cast<QWidget *>(o))
+ // static_cast<QGraphicsScene *>(q)->addWidget(w);
+ }
+ private:
+ QObject *q;
+ };
+ Children _children;
+};
+
+class QGraphicsWidgetDeclarativeUI : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QmlList<QObject *> *data READ data)
+ Q_PROPERTY(QmlList<QGraphicsItem *> *children READ children)
+ Q_PROPERTY(QGraphicsLayout *layout READ layout WRITE setLayout)
+ Q_CLASSINFO("DefaultProperty", "children")
+public:
+ QGraphicsWidgetDeclarativeUI(QObject *other) : QObject(other), _widgets(this) {}
+
+ QmlList<QObject *> *data() { return &_data; }
+
+ QmlList<QGraphicsItem *> *children() { return &_widgets; }
+
+ QGraphicsLayout *layout() const { return static_cast<QGraphicsWidget *>(parent())->layout(); }
+ void setLayout(QGraphicsLayout *lo)
+ {
+ static_cast<QGraphicsWidget *>(parent())->setLayout(lo);
+ }
+
+private:
+ friend class WidgetList;
+ void setItemParent(QGraphicsItem *wid)
+ {
+ wid->setParentItem(static_cast<QGraphicsWidget *>(parent()));
+ }
+
+ class WidgetList : public QmlConcreteList<QGraphicsItem *>
+ {
+ public:
+ WidgetList(QGraphicsWidgetDeclarativeUI *o)
+ : obj(o) {}
+
+ virtual void append(QGraphicsItem *w) { QmlConcreteList<QGraphicsItem *>::append(w); obj->setItemParent(w); }
+ virtual void clear() { QmlConcreteList<QGraphicsItem *>::clear(); } //###
+ virtual void removeAt(int i) { QmlConcreteList<QGraphicsItem *>::removeAt(i); } //###
+ virtual void insert(int i, QGraphicsItem *item) { QmlConcreteList<QGraphicsItem *>::insert(i, item); obj->setItemParent(item); }
+
+ private:
+ QGraphicsWidgetDeclarativeUI *obj;
+ };
+ WidgetList _widgets;
+ QmlConcreteList<QObject *> _data;
+};
+
+QML_DEFINE_EXTENDED_TYPE(Qt,4,6,QGraphicsView,QGraphicsView,QGraphicsViewDeclarativeUI)
+QML_DEFINE_EXTENDED_TYPE(Qt,4,6,QGraphicsScene,QGraphicsScene,QGraphicsSceneDeclarativeUI)
+QML_DEFINE_EXTENDED_TYPE(Qt,4,6,QGraphicsWidget,QGraphicsWidget,QGraphicsWidgetDeclarativeUI)
+
+QML_DEFINE_INTERFACE(QGraphicsItem)
+
+QT_END_NAMESPACE
+
+#include <graphicswidgets.moc>
diff --git a/src/declarative/widgets/graphicswidgets_p.h b/src/declarative/widgets/graphicswidgets_p.h
new file mode 100644
index 0000000..0de5c89
--- /dev/null
+++ b/src/declarative/widgets/graphicswidgets_p.h
@@ -0,0 +1,68 @@
+/****************************************************************************
+**
+** 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$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef GRAPHICSWIDGETS_H
+#define GRAPHICSWIDGETS_H
+
+#include <qml.h>
+
+#include <QtGui/QGraphicsScene>
+#include <QtGui/QGraphicsView>
+#include <QtGui/QGraphicsWidget>
+#include <QtGui/QGraphicsItem>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Declarative)
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QGraphicsView)
+QML_DECLARE_TYPE_HASMETATYPE(QGraphicsScene)
+QML_DECLARE_TYPE(QGraphicsWidget)
+QML_DECLARE_TYPE(QGraphicsObject)
+QML_DECLARE_INTERFACE_HASMETATYPE(QGraphicsItem)
+
+QT_END_HEADER
+
+#endif // GRAPHICSWIDGETS_H
diff --git a/src/declarative/widgets/widgets.pri b/src/declarative/widgets/widgets.pri
new file mode 100644
index 0000000..4cae3ff
--- /dev/null
+++ b/src/declarative/widgets/widgets.pri
@@ -0,0 +1,9 @@
+INCLUDEPATH += $$PWD
+
+SOURCES += \
+ $$PWD/graphicswidgets.cpp \
+ $$PWD/graphicslayouts.cpp
+
+HEADERS += \
+ $$PWD/graphicswidgets_p.h \
+ $$PWD/graphicslayouts_p.h
diff --git a/src/gui/dialogs/dialogs.pri b/src/gui/dialogs/dialogs.pri
index 63f64a2..4e1b9a7 100644
--- a/src/gui/dialogs/dialogs.pri
+++ b/src/gui/dialogs/dialogs.pri
@@ -50,7 +50,8 @@ HEADERS += \
}
win32 {
- HEADERS += dialogs/qwizard_win_p.h
+ HEADERS += dialogs/qwizard_win_p.h \
+ dialogs/qfiledialog_win_p.h
SOURCES += dialogs/qdialogsbinarycompat_win.cpp \
dialogs/qfiledialog_win.cpp \
dialogs/qpagesetupdialog_win.cpp \
diff --git a/src/gui/dialogs/qdialog.cpp b/src/gui/dialogs/qdialog.cpp
index 9ff2ad8..fb0dba4 100644
--- a/src/gui/dialogs/qdialog.cpp
+++ b/src/gui/dialogs/qdialog.cpp
@@ -648,13 +648,14 @@ void QDialog::contextMenuEvent(QContextMenuEvent *e)
while (w && w->whatsThis().size() == 0 && !w->testAttribute(Qt::WA_CustomWhatsThis))
w = w->isWindow() ? 0 : w->parentWidget();
if (w) {
- QMenu p(this);
- QAction *wt = p.addAction(tr("What's This?"));
- if (p.exec(e->globalPos()) == wt) {
+ QWeakPointer<QMenu> p = new QMenu(this);
+ QAction *wt = p.data()->addAction(tr("What's This?"));
+ if (p.data()->exec(e->globalPos()) == wt) {
QHelpEvent e(QEvent::WhatsThis, w->rect().center(),
w->mapToGlobal(w->rect().center()));
QApplication::sendEvent(w, &e);
}
+ delete p.data();
}
#endif
}
diff --git a/src/gui/dialogs/qfiledialog_win.cpp b/src/gui/dialogs/qfiledialog_win.cpp
index 5a7ace9..3120938 100644
--- a/src/gui/dialogs/qfiledialog_win.cpp
+++ b/src/gui/dialogs/qfiledialog_win.cpp
@@ -53,53 +53,27 @@
#include <qdir.h>
#include <qstringlist.h>
#include <qlibrary.h>
+#include "qfiledialog_win_p.h"
#ifndef QT_NO_THREAD
# include <private/qmutexpool_p.h>
#endif
-#include <shlobj.h>
-//At some point we can hope that mingw will support that interface
-#if !defined(Q_WS_WINCE) && !defined(Q_CC_MINGW)
-#include <shobjidl.h>
-#endif
-
-#include <objbase.h>
-
-#if defined(__IFileDialog_INTERFACE_DEFINED__) \
- && defined(__IFileOpenDialog_INTERFACE_DEFINED__)
-#define USE_COMMON_ITEM_DIALOG
-#endif
-
#ifdef Q_WS_WINCE
+#include <shlobj.h>
#include <commdlg.h>
-# ifndef BFFM_SETSELECTION
-# define BFFM_SETSELECTION (WM_USER + 102)
-# endif
-// Windows Mobile has a broken definition for BROWSEINFO
-// Only compile fix
-typedef struct qt_priv_browseinfo {
- HWND hwndOwner;
- LPCITEMIDLIST pidlRoot;
- LPWSTR pszDisplayName;
- LPCWSTR lpszTitle;
- UINT ulFlags;
- BFFCALLBACK lpfn;
- LPARAM lParam;
- int iImage;
-} qt_BROWSEINFO;
bool qt_priv_ptr_valid = false;
+#else
+//we have to declare them here because they're not present for all SDK/compilers
+static const IID QT_IID_IFileOpenDialog = {0xd57c7288, 0xd4ad, 0x4768, {0xbe, 0x02, 0x9d, 0x96, 0x95, 0x32, 0xd9, 0x60} };
+static const IID QT_IID_IShellItem = {0x43826d1e, 0xe718, 0x42ee, {0xbc, 0x55, 0xa1, 0xe2, 0x61, 0xc3, 0x7b, 0xfe} };
+static const CLSID QT_CLSID_FileOpenDialog = {0xdc1c5a9c, 0xe88a, 0x4dde, {0xa5, 0xa1, 0x60, 0xf8, 0x2a, 0x20, 0xae, 0xf7} };
#endif
-// Don't remove the lines below!
-//
-// resolving the W methods manually is needed, because Windows 95 doesn't include
-// these methods in Shell32.lib (not even stubs!), so you'd get an unresolved symbol
-// when Qt calls getExistingDirectory(), etc.
-typedef LPITEMIDLIST (WINAPI *PtrSHBrowseForFolder)(BROWSEINFO*);
+typedef qt_LPITEMIDLIST (WINAPI *PtrSHBrowseForFolder)(qt_BROWSEINFO*);
static PtrSHBrowseForFolder ptrSHBrowseForFolder = 0;
-typedef BOOL (WINAPI *PtrSHGetPathFromIDList)(LPITEMIDLIST,LPWSTR);
+typedef BOOL (WINAPI *PtrSHGetPathFromIDList)(qt_LPITEMIDLIST, LPWSTR);
static PtrSHGetPathFromIDList ptrSHGetPathFromIDList = 0;
typedef HRESULT (WINAPI *PtrSHGetMalloc)(LPMALLOC *);
static PtrSHGetMalloc ptrSHGetMalloc = 0;
@@ -132,7 +106,7 @@ static void qt_win_resolve_libs()
ptrSHGetMalloc = (PtrSHGetMalloc) lib.resolve("SHGetMalloc");
#else
// CE stores them in a different lib and does not use unicode version
- HINSTANCE handle = LoadLibraryW(L"Ceshell");
+ HINSTANCE handle = LoadLibrary(L"Ceshell");
ptrSHBrowseForFolder = (PtrSHBrowseForFolder)GetProcAddress(handle, L"SHBrowseForFolder");
ptrSHGetPathFromIDList = (PtrSHGetPathFromIDList)GetProcAddress(handle, L"SHGetPathFromIDList");
ptrSHGetMalloc = (PtrSHGetMalloc)GetProcAddress(handle, L"SHGetMalloc");
@@ -421,7 +395,7 @@ QString qt_win_get_save_file_name(const QFileDialogArgs &args,
}
-#if defined(USE_COMMON_ITEM_DIALOG)
+#ifndef Q_WS_WINCE
typedef HRESULT (WINAPI *PtrSHCreateItemFromParsingName)(PCWSTR pszPath, IBindCtx *pbc, REFIID riid, void **ppv);
static PtrSHCreateItemFromParsingName pSHCreateItemFromParsingName = 0;
@@ -469,7 +443,7 @@ static bool qt_win_set_IFileDialogOptions(IFileDialog *pfd,
// Add the filters to the file dialog.
if (numFilters) {
wchar_t *szData = (wchar_t*)winfilters.utf16();
- COMDLG_FILTERSPEC *filterSpec = new COMDLG_FILTERSPEC[numFilters];
+ qt_COMDLG_FILTERSPEC *filterSpec = new qt_COMDLG_FILTERSPEC[numFilters];
for(int i = 0; i<numFilters; i++) {
filterSpec[i].pszName = szData+offsets[i*2];
filterSpec[i].pszSpec = szData+offsets[(i*2)+1];
@@ -481,9 +455,8 @@ static bool qt_win_set_IFileDialogOptions(IFileDialog *pfd,
tInitDir = QDir::toNativeSeparators(initialDirectory);
if (!tInitDir.isEmpty()) {
IShellItem *psiDefaultFolder;
- hr = pSHCreateItemFromParsingName((wchar_t*)tInitDir.utf16(),
- NULL,
- IID_PPV_ARGS(&psiDefaultFolder));
+ hr = pSHCreateItemFromParsingName((wchar_t*)tInitDir.utf16(), NULL, QT_IID_IShellItem,
+ reinterpret_cast<void**>(&psiDefaultFolder));
if (SUCCEEDED(hr)) {
hr = pfd->SetFolder(psiDefaultFolder);
@@ -522,7 +495,7 @@ static bool qt_win_set_IFileDialogOptions(IFileDialog *pfd,
return SUCCEEDED(hr);
}
-QStringList qt_win_CID_get_open_file_names(const QFileDialogArgs &args,
+static QStringList qt_win_CID_get_open_file_names(const QFileDialogArgs &args,
QString *initialDirectory,
const QStringList &filterList,
QString *selectedFilter,
@@ -535,10 +508,8 @@ QStringList qt_win_CID_get_open_file_names(const QFileDialogArgs &args,
QApplicationPrivate::enterModal(&modal_widget);
// Multiple selection is allowed only in IFileOpenDialog.
IFileOpenDialog *pfd = 0;
- HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog,
- NULL,
- CLSCTX_INPROC_SERVER,
- IID_PPV_ARGS(&pfd));
+ HRESULT hr = CoCreateInstance(QT_CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, QT_IID_IFileOpenDialog,
+ reinterpret_cast<void**>(&pfd));
if (SUCCEEDED(hr)) {
qt_win_set_IFileDialogOptions(pfd, args.selection,
@@ -643,7 +614,7 @@ QStringList qt_win_get_open_file_names(const QFileDialogArgs &args,
// multiple files belonging to different folders from these search results, the
// GetOpenFileName() will return only one folder name for all the files. To retrieve
// the correct path for all selected files, we have to use Common Item Dialog interfaces.
-#if defined(USE_COMMON_ITEM_DIALOG)
+#ifndef Q_WS_WINCE
if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)
return qt_win_CID_get_open_file_names(args, initialDirectory, filterLst, selectedFilter, idx);
#endif
@@ -716,7 +687,7 @@ static int __stdcall winGetExistDirCallbackProc(HWND hwnd,
qt_win_resolve_libs();
if (ptrSHGetPathFromIDList) {
wchar_t path[MAX_PATH];
- ptrSHGetPathFromIDList(LPITEMIDLIST(lParam), path);
+ ptrSHGetPathFromIDList(qt_LPITEMIDLIST(lParam), path);
QString tmpStr = QString::fromWCharArray(path);
if (!tmpStr.isEmpty())
SendMessage(hwnd, BFFM_ENABLEOK, 1, 1);
@@ -728,11 +699,6 @@ static int __stdcall winGetExistDirCallbackProc(HWND hwnd,
return 0;
}
-#ifndef BIF_NEWDIALOGSTYLE
-#define BIF_NEWDIALOGSTYLE 0x0040 // Use the new dialog layout with the ability to resize
-#endif
-
-
QString qt_win_get_existing_directory(const QFileDialogArgs &args)
{
QString currentDir = QDir::currentPath();
@@ -757,11 +723,7 @@ QString qt_win_get_existing_directory(const QFileDialogArgs &args)
path[0] = 0;
tTitle = args.caption;
-#if !defined(Q_WS_WINCE)
- BROWSEINFO bi;
-#else
qt_BROWSEINFO bi;
-#endif
Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created));
bi.hwndOwner = (parent ? parent->winId() : 0);
@@ -775,7 +737,7 @@ QString qt_win_get_existing_directory(const QFileDialogArgs &args)
qt_win_resolve_libs();
if (ptrSHBrowseForFolder) {
- LPITEMIDLIST pItemIDList = ptrSHBrowseForFolder((BROWSEINFO*)&bi);
+ qt_LPITEMIDLIST pItemIDList = ptrSHBrowseForFolder(&bi);
if (pItemIDList) {
ptrSHGetPathFromIDList(pItemIDList, path);
IMalloc *pMalloc;
diff --git a/src/gui/dialogs/qfiledialog_win_p.h b/src/gui/dialogs/qfiledialog_win_p.h
new file mode 100644
index 0000000..527ab3f
--- /dev/null
+++ b/src/gui/dialogs/qfiledialog_win_p.h
@@ -0,0 +1,243 @@
+/****************************************************************************
+**
+** 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 QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <objbase.h>
+#ifndef QFILEDIAG_WIN_P_H
+#define QFILEDIAG_WIN_P_H
+
+//these are the interface declarations needed for the file dialog on Vista and up
+
+//At some point we can hope that all compilers/sdk will support that interface
+//and we won't have to declare it ourselves
+
+//declarations
+#define FOS_OVERWRITEPROMPT 0x2
+#define FOS_STRICTFILETYPES 0x4
+#define FOS_NOCHANGEDIR 0x8
+#define FOS_PICKFOLDERS 0x20
+#define FOS_FORCEFILESYSTEM 0x40
+#define FOS_ALLNONSTORAGEITEMS 0x80
+#define FOS_NOVALIDATE 0x100
+#define FOS_ALLOWMULTISELECT 0x200
+#define FOS_PATHMUSTEXIST 0x800
+#define FOS_FILEMUSTEXIST 0x1000
+#define FOS_CREATEPROMPT 0x2000
+#define FOS_SHAREAWARE 0x4000
+#define FOS_NOREADONLYRETURN 0x8000
+#define FOS_NOTESTFILECREATE 0x10000
+#define FOS_HIDEMRUPLACES 0x20000
+#define FOS_HIDEPINNEDPLACES 0x40000
+#define FOS_NODEREFERENCELINKS 0x100000
+#define FOS_DONTADDTORECENT 0x2000000
+#define FOS_FORCESHOWHIDDEN 0x10000000
+#define FOS_DEFAULTNOMINIMODE 0x20000000
+#define FOS_FORCEPREVIEWPANEON 0x40000000
+
+typedef int GETPROPERTYSTOREFLAGS;
+#define GPS_DEFAULT 0x00000000
+#define GPS_HANDLERPROPERTIESONLY 0x00000001
+#define GPS_READWRITE 0x00000002
+#define GPS_TEMPORARY 0x00000004
+#define GPS_FASTPROPERTIESONLY 0x00000008
+#define GPS_OPENSLOWITEM 0x00000010
+#define GPS_DELAYCREATION 0x00000020
+#define GPS_BESTEFFORT 0x00000040
+#define GPS_MASK_VALID 0x0000007F
+
+typedef int (CALLBACK* BFFCALLBACK)(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData);
+// message from browser
+#define BFFM_INITIALIZED 1
+#define BFFM_SELCHANGED 2
+#define BFFM_ENABLEOK (WM_USER + 101)
+#define BFFM_SETSELECTION (WM_USER + 103)
+#define BFFM_SETSTATUSTEXT (WM_USER + 104)
+
+// Browsing for directory.
+#define BIF_RETURNONLYFSDIRS 0x0001
+#define BIF_DONTGOBELOWDOMAIN 0x0002
+#define BIF_STATUSTEXT 0x0004
+#define BIF_RETURNFSANCESTORS 0x0008
+#define BIF_EDITBOX 0x0010
+#define BIF_VALIDATE 0x0020
+#define BIF_NEWDIALOGSTYLE 0x0040
+#define BIF_BROWSEINCLUDEURLS 0x0080
+#define BIF_UAHINT 0x0100
+#define BIF_NONEWFOLDERBUTTON 0x0200
+#define BIF_NOTRANSLATETARGETS 0x0400
+#define BIF_BROWSEFORCOMPUTER 0x1000
+#define BIF_BROWSEFORPRINTER 0x2000
+#define BIF_BROWSEINCLUDEFILES 0x4000
+#define BIF_SHAREABLE 0x8000
+
+//the enums
+typedef enum {
+ SIATTRIBFLAGS_AND = 0x1,
+ SIATTRIBFLAGS_OR = 0x2,
+ SIATTRIBFLAGS_APPCOMPAT = 0x3,
+ SIATTRIBFLAGS_MASK = 0x3
+} SIATTRIBFLAGS;
+typedef enum {
+ SIGDN_NORMALDISPLAY = 0x00000000,
+ SIGDN_PARENTRELATIVEPARSING = 0x80018001,
+ SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
+ SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000,
+ SIGDN_PARENTRELATIVEEDITING = 0x80031001,
+ SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000,
+ SIGDN_FILESYSPATH = 0x80058000,
+ SIGDN_URL = 0x80068000
+} SIGDN;
+typedef enum {
+ FDAP_BOTTOM = 0x00000000,
+ FDAP_TOP = 0x00000001
+} FDAP;
+typedef enum {
+ FDESVR_DEFAULT = 0x00000000,
+ FDESVR_ACCEPT = 0x00000001,
+ FDESVR_REFUSE = 0x00000002
+} FDE_SHAREVIOLATION_RESPONSE;
+typedef FDE_SHAREVIOLATION_RESPONSE FDE_OVERWRITE_RESPONSE;
+
+//the structs
+typedef struct {
+ LPCWSTR pszName;
+ LPCWSTR pszSpec;
+} qt_COMDLG_FILTERSPEC;
+typedef struct {
+ GUID fmtid;
+ DWORD pid;
+} qt_PROPERTYKEY;
+
+typedef struct {
+ USHORT cb;
+ BYTE abID[1];
+} qt_SHITEMID, *qt_LPSHITEMID;
+typedef struct {
+ qt_SHITEMID mkid;
+} qt_ITEMIDLIST, *qt_LPITEMIDLIST;
+typedef const qt_ITEMIDLIST *qt_LPCITEMIDLIST;
+typedef struct {
+ HWND hwndOwner;
+ qt_LPCITEMIDLIST pidlRoot;
+ LPWSTR pszDisplayName;
+ LPCWSTR lpszTitle;
+ UINT ulFlags;
+ BFFCALLBACK lpfn;
+ LPARAM lParam;
+ int iImage;
+} qt_BROWSEINFO;
+
+DECLARE_INTERFACE(IFileDialogEvents);
+DECLARE_INTERFACE_(IShellItem, IUnknown)
+{
+ STDMETHOD(BindToHandler)(THIS_ IBindCtx *pbc, REFGUID bhid, REFIID riid, void **ppv) PURE;
+ STDMETHOD(GetParent)(THIS_ IShellItem **ppsi) PURE;
+ STDMETHOD(GetDisplayName)(THIS_ SIGDN sigdnName, LPWSTR *ppszName) PURE;
+ STDMETHOD(GetAttributes)(THIS_ ULONG sfgaoMask, ULONG *psfgaoAttribs) PURE;
+ STDMETHOD(Compare)(THIS_ IShellItem *psi, DWORD hint, int *piOrder) PURE;
+};
+DECLARE_INTERFACE_(IShellItemFilter, IUnknown)
+{
+ STDMETHOD(IncludeItem)(THIS_ IShellItem *psi) PURE;
+ STDMETHOD(GetEnumFlagsForItem)(THIS_ IShellItem *psi, DWORD *pgrfFlags) PURE;
+};
+DECLARE_INTERFACE_(IEnumShellItems, IUnknown)
+{
+ STDMETHOD(Next)(THIS_ ULONG celt, IShellItem **rgelt, ULONG *pceltFetched) PURE;
+ STDMETHOD(Skip)(THIS_ ULONG celt) PURE;
+ STDMETHOD(Reset)(THIS_) PURE;
+ STDMETHOD(Clone)(THIS_ IEnumShellItems **ppenum) PURE;
+};
+DECLARE_INTERFACE_(IShellItemArray, IUnknown)
+{
+ STDMETHOD(BindToHandler)(THIS_ IBindCtx *pbc, REFGUID rbhid, REFIID riid, void **ppvOut) PURE;
+ STDMETHOD(GetPropertyStore)(THIS_ GETPROPERTYSTOREFLAGS flags, REFIID riid, void **ppv) PURE;
+ STDMETHOD(GetPropertyDescriptionList)(THIS_ const qt_PROPERTYKEY *keyType, REFIID riid, void **ppv) PURE;
+ STDMETHOD(GetAttributes)(THIS_ SIATTRIBFLAGS dwAttribFlags, ULONG sfgaoMask, ULONG *psfgaoAttribs) PURE;
+ STDMETHOD(GetCount)(THIS_ DWORD *pdwNumItems) PURE;
+ STDMETHOD(GetItemAt)(THIS_ DWORD dwIndex, IShellItem **ppsi) PURE;
+ STDMETHOD(EnumItems)(THIS_ IEnumShellItems **ppenumShellItems) PURE;
+};
+DECLARE_INTERFACE_(IModalWindow, IUnknown)
+{
+ STDMETHOD(Show)(THIS_ HWND hwndParent) PURE;
+};
+DECLARE_INTERFACE_(IFileDialog, IModalWindow)
+{
+ STDMETHOD(SetFileTypes)(THIS_ UINT cFileTypes, const qt_COMDLG_FILTERSPEC *rgFilterSpec) PURE;
+ STDMETHOD(SetFileTypeIndex)(THIS_ UINT iFileType) PURE;
+ STDMETHOD(GetFileTypeIndex)(THIS_ UINT *piFileType) PURE;
+ STDMETHOD(Advise)(THIS_ IFileDialogEvents *pfde, DWORD *pdwCookie) PURE;
+ STDMETHOD(Unadvise)(THIS_ DWORD dwCookie) PURE;
+ STDMETHOD(SetOptions)(THIS_ DWORD fos) PURE;
+ STDMETHOD(GetOptions)(THIS_ DWORD *pfos) PURE;
+ STDMETHOD(SetDefaultFolder)(THIS_ IShellItem *psi) PURE;
+ STDMETHOD(SetFolder)(THIS_ IShellItem *psi) PURE;
+ STDMETHOD(GetFolder)(THIS_ IShellItem **ppsi) PURE;
+ STDMETHOD(GetCurrentSelection)(THIS_ IShellItem **ppsi) PURE;
+ STDMETHOD(SetFileName)(THIS_ LPCWSTR pszName) PURE;
+ STDMETHOD(GetFileName)(THIS_ LPWSTR *pszName) PURE;
+ STDMETHOD(SetTitle)(THIS_ LPCWSTR pszTitle) PURE;
+ STDMETHOD(SetOkButtonLabel)(THIS_ LPCWSTR pszText) PURE;
+ STDMETHOD(SetFileNameLabel)(THIS_ LPCWSTR pszLabel) PURE;
+ STDMETHOD(GetResult)(THIS_ IShellItem **ppsi) PURE;
+ STDMETHOD(AddPlace)(THIS_ IShellItem *psi, FDAP fdap) PURE;
+ STDMETHOD(SetDefaultExtension)(THIS_ LPCWSTR pszDefaultExtension) PURE;
+ STDMETHOD(Close)(THIS_ HRESULT hr) PURE;
+ STDMETHOD(SetClientGuid)(THIS_ REFGUID guid) PURE;
+ STDMETHOD(ClearClientData)(THIS_) PURE;
+ STDMETHOD(SetFilter)(THIS_ IShellItemFilter *pFilter) PURE;
+};
+DECLARE_INTERFACE_(IFileDialogEvents, IUnknown)
+{
+ STDMETHOD(OnFileOk)(THIS_ IFileDialog *pfd) PURE;
+ STDMETHOD(OnFolderChanging)(THIS_ IFileDialog *pfd, IShellItem *psiFolder) PURE;
+ STDMETHOD(OnFolderChange)(THIS_ IFileDialog *pfd) PURE;
+ STDMETHOD(OnSelectionChange)(THIS_ IFileDialog *pfd) PURE;
+ STDMETHOD(OnShareViolation)(THIS_ IFileDialog *pfd, IShellItem *psi, FDE_SHAREVIOLATION_RESPONSE *pResponse) PURE;
+ STDMETHOD(OnTypeChange)(THIS_ IFileDialog *pfd) PURE;
+ STDMETHOD(OnOverwrite)(THIS_ IFileDialog *pfd, IShellItem *psi, FDE_OVERWRITE_RESPONSE *pResponse) PURE;
+};
+DECLARE_INTERFACE_(IFileOpenDialog, IFileDialog)
+{
+ STDMETHOD(GetResults)(THIS_ IShellItemArray **ppenum) PURE;
+ STDMETHOD(GetSelectedItems)(THIS_ IShellItemArray **ppsai) PURE;
+};
+#endif \ No newline at end of file
diff --git a/src/gui/dialogs/qfileinfogatherer.cpp b/src/gui/dialogs/qfileinfogatherer.cpp
index 1f61957..c75cdfd 100644
--- a/src/gui/dialogs/qfileinfogatherer.cpp
+++ b/src/gui/dialogs/qfileinfogatherer.cpp
@@ -354,6 +354,7 @@ void QFileInfoGatherer::getFileInfos(const QString &path, const QStringList &fil
}
if (!updatedFiles.isEmpty())
emit updates(path, updatedFiles);
+ emit directoryLoaded(path);
}
void QFileInfoGatherer::fetch(const QFileInfo &fileInfo, QTime &base, bool &firstTime, QList<QPair<QString, QFileInfo> > &updatedFiles, const QString &path) {
diff --git a/src/gui/dialogs/qfileinfogatherer_p.h b/src/gui/dialogs/qfileinfogatherer_p.h
index 0242178..b8b58a2 100644
--- a/src/gui/dialogs/qfileinfogatherer_p.h
+++ b/src/gui/dialogs/qfileinfogatherer_p.h
@@ -155,6 +155,7 @@ Q_SIGNALS:
void updates(const QString &directory, const QList<QPair<QString, QFileInfo> > &updates);
void newListOfFiles(const QString &directory, const QStringList &listOfFiles) const;
void nameResolved(const QString &fileName, const QString &resolvedName) const;
+ void directoryLoaded(const QString &path);
public:
QFileInfoGatherer(QObject *parent = 0);
diff --git a/src/gui/dialogs/qfilesystemmodel.cpp b/src/gui/dialogs/qfilesystemmodel.cpp
index 6fd947c..ba0a560 100644
--- a/src/gui/dialogs/qfilesystemmodel.cpp
+++ b/src/gui/dialogs/qfilesystemmodel.cpp
@@ -51,6 +51,9 @@
#ifdef Q_OS_WIN
#include <qt_windows.h>
#endif
+#ifdef Q_OS_WIN32
+#include <QtCore/QVarLengthArray>
+#endif
QT_BEGIN_NAMESPACE
@@ -150,6 +153,14 @@ QT_BEGIN_NAMESPACE
*/
/*!
+ \since 4.7
+ \fn void QFileSystemModel::directoryLoaded(const QString &path)
+
+ This signal is emitted when the gatherer thread has finished to load the \a path.
+
+*/
+
+/*!
\fn bool QFileSystemModel::remove(const QModelIndex &index) const
Removes the model item \a index from the file system model and \bold{deletes the
@@ -270,53 +281,38 @@ QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QM
return indexNode;
}
-#ifdef Q_OS_WIN
+#ifdef Q_OS_WIN32
static QString qt_GetLongPathName(const QString &strShortPath)
{
- QString longPath;
- int i = 0;
- if (strShortPath == QLatin1String(".")
- || (strShortPath.startsWith(QLatin1String("//")))
- || (strShortPath.startsWith(QLatin1String("\\\\")))) // unc
+ if (strShortPath.isEmpty()
+ || strShortPath == QLatin1String(".") || strShortPath == QLatin1String(".."))
return strShortPath;
- QString::const_iterator it = strShortPath.constBegin();
- QString::const_iterator constEnd = strShortPath.constEnd();
- do {
- bool isSep = (*it == QLatin1Char('\\') || *it == QLatin1Char('/'));
- if (isSep || it == constEnd) {
- QString section = (it == constEnd ? strShortPath : strShortPath.left(i));
- // FindFirstFile does not handle volumes ("C:"), so we have to catch that ourselves.
- if (section.endsWith(QLatin1Char(':'))) {
- longPath.append(section.toUpper());
- } else {
- HANDLE h;
-#ifndef Q_OS_WINCE
- //We add the extend length prefix to handle long path
- QString longSection = QLatin1String("\\\\?\\")+QDir::toNativeSeparators(section);
-#else
- QString longSection = QDir::toNativeSeparators(section);
-#endif
- WIN32_FIND_DATA findData;
- h = ::FindFirstFile((wchar_t*)longSection.utf16(), &findData);
- if (h != INVALID_HANDLE_VALUE) {
- longPath.append(QString::fromWCharArray(findData.cFileName));
- ::FindClose(h);
- } else {
- longPath.append(section);
- break;
- }
- }
- if (it != constEnd)
- longPath.append(*it);
- else
- break;
- }
- ++it;
- if (isSep && it == constEnd) // break out if the last character is a separator
- break;
- ++i;
- } while (true);
- return longPath;
+ if (strShortPath.length() == 2 && strShortPath.endsWith(QLatin1Char(':')))
+ return strShortPath.toUpper();
+ const QString absPath = QDir(strShortPath).absolutePath();
+ if (absPath.startsWith(QLatin1String("//"))
+ || absPath.startsWith(QLatin1String("\\\\"))) // unc
+ return QDir::fromNativeSeparators(absPath);
+ if (absPath.startsWith(QLatin1Char('/')))
+ return QString();
+ const QString inputString = QLatin1String("\\\\?\\") + QDir::toNativeSeparators(absPath);
+ QVarLengthArray<TCHAR, MAX_PATH> buffer(MAX_PATH);
+ DWORD result = ::GetLongPathName((wchar_t*)inputString.utf16(),
+ buffer.data(),
+ buffer.size());
+ if (result > DWORD(buffer.size())) {
+ buffer.resize(result);
+ result = ::GetLongPathName((wchar_t*)inputString.utf16(),
+ buffer.data(),
+ buffer.size());
+ }
+ if (result > 4) {
+ QString longPath = QString::fromWCharArray(buffer.data() + 4); // ignoring prefix
+ longPath[0] = longPath.at(0).toUpper(); // capital drive letters
+ return QDir::fromNativeSeparators(longPath);
+ } else {
+ return QDir::fromNativeSeparators(strShortPath);
+ }
}
#endif
@@ -334,7 +330,7 @@ QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QS
// Construct the nodes up to the new root path if they need to be built
QString absolutePath;
-#ifdef Q_OS_WIN
+#ifdef Q_OS_WIN32
QString longPath = qt_GetLongPathName(path);
#else
QString longPath = path;
@@ -673,7 +669,7 @@ QVariant QFileSystemModel::data(const QModelIndex &index, int role) const
case Qt::EditRole:
case Qt::DisplayRole:
switch (index.column()) {
- case 0: return d->name(index);
+ case 0: return d->displayName(index);
case 1: return d->size(index);
case 2: return d->type(index);
case 3: return d->time(index);
@@ -789,13 +785,25 @@ QString QFileSystemModelPrivate::name(const QModelIndex &index) const
if (resolvedSymLinks.contains(fullPath))
return resolvedSymLinks[fullPath];
}
- // ### TODO it would be nice to grab the volume name if dirNode->parent == root
return dirNode->fileName;
}
/*!
\internal
*/
+QString QFileSystemModelPrivate::displayName(const QModelIndex &index) const
+{
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
+ QFileSystemNode *dirNode = node(index);
+ if (!dirNode->volumeName.isNull())
+ return dirNode->volumeName + QLatin1String(" (") + name(index) + QLatin1Char(')');
+#endif
+ return name(index);
+}
+
+/*!
+ \internal
+*/
QIcon QFileSystemModelPrivate::icon(const QModelIndex &index) const
{
if (!index.isValid())
@@ -1337,7 +1345,11 @@ QModelIndex QFileSystemModel::setRootPath(const QString &newPath)
{
Q_D(QFileSystemModel);
#ifdef Q_OS_WIN
- QString longNewPath = QDir::fromNativeSeparators(qt_GetLongPathName(newPath));
+#ifdef Q_OS_WIN32
+ QString longNewPath = qt_GetLongPathName(newPath);
+#else
+ QString longNewPath = QDir::fromNativeSeparators(newPath);
+#endif
#else
QString longNewPath = newPath;
#endif
@@ -1640,6 +1652,18 @@ QFileSystemModelPrivate::QFileSystemNode* QFileSystemModelPrivate::addNode(QFile
#ifndef QT_NO_FILESYSTEMWATCHER
node->populate(info);
#endif
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
+ //The parentNode is "" so we are listing the drives
+ if (parentNode->fileName.isEmpty()) {
+ wchar_t name[MAX_PATH + 1];
+ //GetVolumeInformation requires to add trailing backslash
+ const QString nodeName = fileName + QLatin1String("\\");
+ BOOL success = ::GetVolumeInformation((wchar_t *)(nodeName.utf16()),
+ name, MAX_PATH + 1, NULL, 0, NULL, NULL, 0);
+ if (success && name[0])
+ node->volumeName = QString::fromWCharArray(name);
+ }
+#endif
parentNode->children.insert(fileName, node);
return node;
}
@@ -1869,6 +1893,8 @@ void QFileSystemModelPrivate::init()
q, SLOT(_q_fileSystemChanged(QString,QList<QPair<QString,QFileInfo> >)));
q->connect(&fileInfoGatherer, SIGNAL(nameResolved(QString,QString)),
q, SLOT(_q_resolvedName(QString,QString)));
+ q->connect(&fileInfoGatherer, SIGNAL(directoryLoaded(QString)),
+ q, SIGNAL(directoryLoaded(QString)));
q->connect(&delayedSortTimer, SIGNAL(timeout()), q, SLOT(_q_performDelayedSort()), Qt::QueuedConnection);
}
diff --git a/src/gui/dialogs/qfilesystemmodel.h b/src/gui/dialogs/qfilesystemmodel.h
index 4dcfe26..d8178c7 100644
--- a/src/gui/dialogs/qfilesystemmodel.h
+++ b/src/gui/dialogs/qfilesystemmodel.h
@@ -70,6 +70,7 @@ class Q_GUI_EXPORT QFileSystemModel : public QAbstractItemModel
Q_SIGNALS:
void rootPathChanged(const QString &newPath);
void fileRenamed(const QString &path, const QString &oldName, const QString &newName);
+ void directoryLoaded(const QString &path);
public:
enum Roles {
diff --git a/src/gui/dialogs/qfilesystemmodel_p.h b/src/gui/dialogs/qfilesystemmodel_p.h
index 6c85a7c..03e0bfb 100644
--- a/src/gui/dialogs/qfilesystemmodel_p.h
+++ b/src/gui/dialogs/qfilesystemmodel_p.h
@@ -97,6 +97,9 @@ public:
}
QString fileName;
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
+ QString volumeName;
+#endif
inline qint64 size() const { if (info && !info->isDir()) return info->size(); return 0; }
inline QString type() const { if (info) return info->displayType; return QLatin1String(""); }
@@ -278,6 +281,7 @@ public:
QIcon icon(const QModelIndex &index) const;
QString name(const QModelIndex &index) const;
+ QString displayName(const QModelIndex &index) const;
QString filePath(const QModelIndex &index) const;
QString size(const QModelIndex &index) const;
static QString size(qint64 bytes);
diff --git a/src/gui/dialogs/qmessagebox.cpp b/src/gui/dialogs/qmessagebox.cpp
index d1b2e3f..ed437ff 100644
--- a/src/gui/dialogs/qmessagebox.cpp
+++ b/src/gui/dialogs/qmessagebox.cpp
@@ -92,8 +92,8 @@ public:
{
#ifndef QT_NO_CONTEXTMENU
QMenu *menu = createStandardContextMenu();
- menu->exec(e->globalPos());
- delete menu;
+ menu->setAttribute(Qt::WA_DeleteOnClose);
+ menu->popup(e->globalPos());
#else
Q_UNUSED(e);
#endif
diff --git a/src/gui/dialogs/qprintdialog_win.cpp b/src/gui/dialogs/qprintdialog_win.cpp
index 5ccd33d..fa0c99f 100644
--- a/src/gui/dialogs/qprintdialog_win.cpp
+++ b/src/gui/dialogs/qprintdialog_win.cpp
@@ -52,7 +52,7 @@
#include <private/qprintengine_win_p.h>
#include <private/qprinter_p.h>
-#if defined(Q_CC_MINGW) && !defined(PD_NOCURRENTPAGE)
+#if !defined(PD_NOCURRENTPAGE)
#define PD_NOCURRENTPAGE 0x00800000
#define PD_RESULT_PRINT 1
#define PD_RESULT_APPLY 2
diff --git a/src/gui/embedded/qscreen_qws.cpp b/src/gui/embedded/qscreen_qws.cpp
index 8eb8123..65a3fb5 100644
--- a/src/gui/embedded/qscreen_qws.cpp
+++ b/src/gui/embedded/qscreen_qws.cpp
@@ -39,6 +39,7 @@
**
****************************************************************************/
+#include "qplatformdefs.h"
#include "qscreen_qws.h"
#include "qcolormap.h"
@@ -3223,13 +3224,13 @@ QScreen * qt_probe_bus()
return qt_dodriver("unaccel.so",0,0);
}
- DIR * dirptr=opendir("/proc/bus/pci");
+ QT_DIR *dirptr = QT_OPENDIR("/proc/bus/pci");
if(!dirptr)
return qt_dodriver("unaccel.so",0,0);
- DIR * dirptr2;
- dirent * cards;
+ QT_DIR * dirptr2;
+ QT_DIRENT *cards;
- dirent * busses=readdir(dirptr);
+ QT_DIRENT *busses = QT_READDIR(dirptr);
while(busses) {
if(busses->d_name[0]!='.') {
@@ -3237,9 +3238,9 @@ QScreen * qt_probe_bus()
strcpy(buf,"/proc/bus/pci/");
qstrcpy(buf+14,busses->d_name);
int p=strlen(buf);
- dirptr2=opendir(buf);
+ dirptr2 = QT_OPENDIR(buf);
if(dirptr2) {
- cards=readdir(dirptr2);
+ cards = QT_READDIR(dirptr2);
while(cards) {
if(cards->d_name[0]!='.') {
buf[p]='/';
@@ -3248,14 +3249,14 @@ QScreen * qt_probe_bus()
if(ret)
return ret;
}
- cards=readdir(dirptr2);
+ cards = QT_READDIR(dirptr2);
}
- closedir(dirptr2);
+ QT_CLOSEDIR(dirptr2);
}
}
- busses=readdir(dirptr);
+ busses = QT_READDIR(dirptr);
}
- closedir(dirptr);
+ QT_CLOSEDIR(dirptr);
return qt_dodriver("unaccel.so",0,0);
}
diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp
index 39c41c4..63b0ec7 100644
--- a/src/gui/graphicsview/qgraphicsitem.cpp
+++ b/src/gui/graphicsview/qgraphicsitem.cpp
@@ -319,7 +319,7 @@
QGraphicsItem::keyPressEvent() and QGraphicsItem::keyReleaseEvent().
\value ItemClipsToShape The item clips to its own shape. The item cannot
- draw or receive mouse, tablet, drag and drop or hover events outside ts
+ draw or receive mouse, tablet, drag and drop or hover events outside its
shape. It is disabled by default. This behavior is enforced by
QGraphicsView::drawItems() or QGraphicsScene::drawItems(). This flag was
introduced in Qt 4.3.
@@ -668,6 +668,7 @@
#include <QtCore/qtimer.h>
#include <QtCore/qvariant.h>
#include <QtCore/qvarlengtharray.h>
+#include <QtCore/qnumeric.h>
#include <QtGui/qapplication.h>
#include <QtGui/qbitmap.h>
#include <QtGui/qpainter.h>
@@ -3442,6 +3443,9 @@ void QGraphicsItem::setX(qreal x)
if (d_ptr->inDestructor)
return;
+ if (qIsNaN(x))
+ return;
+
d_ptr->setPosHelper(QPointF(x, d_ptr->pos.y()));
}
@@ -3466,6 +3470,9 @@ void QGraphicsItem::setY(qreal y)
if (d_ptr->inDestructor)
return;
+ if (qIsNaN(y))
+ return;
+
d_ptr->setPosHelper(QPointF(d_ptr->pos.x(), y));
}
diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp
index 66707fc..9a36d46 100644
--- a/src/gui/graphicsview/qgraphicsscene.cpp
+++ b/src/gui/graphicsview/qgraphicsscene.cpp
@@ -4238,6 +4238,8 @@ static void _q_paintItem(QGraphicsItem *item, QPainter *painter,
widgetItem->paintWindowFrame(painter, option, widget);
if (painterStateProtection)
painter->restore();
+ } else if (widgetItem->autoFillBackground()) {
+ painter->fillRect(option->exposedRect, widgetItem->palette().window());
}
widgetItem->paint(painter, option, widget);
diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp
index 5e01785..87416b4 100644
--- a/src/gui/graphicsview/qgraphicswidget.cpp
+++ b/src/gui/graphicsview/qgraphicswidget.cpp
@@ -967,6 +967,36 @@ void QGraphicsWidget::setPalette(const QPalette &palette)
}
/*!
+ \property QGraphicsWidget::autoFillBackground
+ \brief whether the widget background is filled automatically
+ \since 4.7
+
+ If enabled, this property will cause Qt to fill the background of the
+ widget before invoking the paint() method. The color used is defined by the
+ QPalette::Window color role from the widget's \l{QPalette}{palette}.
+
+ In addition, Windows are always filled with QPalette::Window, unless the
+ WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
+
+ By default, this property is false.
+
+ \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
+*/
+bool QGraphicsWidget::autoFillBackground() const
+{
+ Q_D(const QGraphicsWidget);
+ return d->autoFillBackground;
+}
+void QGraphicsWidget::setAutoFillBackground(bool enabled)
+{
+ Q_D(QGraphicsWidget);
+ if (d->autoFillBackground != enabled) {
+ d->autoFillBackground = enabled;
+ update();
+ }
+}
+
+/*!
If this widget is currently managed by a layout, this function notifies
the layout that the widget's size hints have changed and the layout
may need to resize and reposition the widget accordingly.
diff --git a/src/gui/graphicsview/qgraphicswidget.h b/src/gui/graphicsview/qgraphicswidget.h
index f1d382b..4bea5be 100644
--- a/src/gui/graphicsview/qgraphicswidget.h
+++ b/src/gui/graphicsview/qgraphicswidget.h
@@ -82,6 +82,7 @@ class Q_GUI_EXPORT QGraphicsWidget : public QGraphicsObject, public QGraphicsLay
Q_PROPERTY(Qt::WindowFlags windowFlags READ windowFlags WRITE setWindowFlags)
Q_PROPERTY(QString windowTitle READ windowTitle WRITE setWindowTitle)
Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry)
+ Q_PROPERTY(bool autoFillBackground READ autoFillBackground WRITE setAutoFillBackground)
public:
QGraphicsWidget(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);
~QGraphicsWidget();
@@ -103,6 +104,9 @@ public:
QPalette palette() const;
void setPalette(const QPalette &palette);
+ bool autoFillBackground() const;
+ void setAutoFillBackground(bool enabled);
+
void resize(const QSizeF &size);
inline void resize(qreal w, qreal h) { resize(QSizeF(w, h)); }
QSizeF size() const;
diff --git a/src/gui/graphicsview/qgraphicswidget_p.h b/src/gui/graphicsview/qgraphicswidget_p.h
index 2c5b3bf..3ab8737 100644
--- a/src/gui/graphicsview/qgraphicswidget_p.h
+++ b/src/gui/graphicsview/qgraphicswidget_p.h
@@ -80,6 +80,7 @@ public:
inSetGeometry(0),
polished(0),
inSetPos(0),
+ autoFillBackground(0),
focusPolicy(Qt::NoFocus),
focusNext(0),
focusPrev(0),
@@ -172,6 +173,7 @@ public:
quint32 inSetGeometry : 1;
quint32 polished: 1;
quint32 inSetPos : 1;
+ quint32 autoFillBackground : 1;
// Focus
Qt::FocusPolicy focusPolicy;
diff --git a/src/gui/image/qimage.cpp b/src/gui/image/qimage.cpp
index 4f5efa1..6bcf72b 100644
--- a/src/gui/image/qimage.cpp
+++ b/src/gui/image/qimage.cpp
@@ -1835,7 +1835,7 @@ void QImage::setColor(int i, QRgb c)
qAlpha() to access the pixels.
\sa bytesPerLine(), bits(), {QImage#Pixel Manipulation}{Pixel
- Manipulation}
+ Manipulation}, constScanLine()
*/
uchar *QImage::scanLine(int i)
{
@@ -1865,6 +1865,28 @@ const uchar *QImage::scanLine(int i) const
/*!
+ Returns a pointer to the pixel data at the scanline with index \a
+ i. The first scanline is at index 0.
+
+ The scanline data is aligned on a 32-bit boundary.
+
+ Note that QImage uses \l{Implicit Data Sharing} {implicit data
+ sharing}, but this function does \e not perform a deep copy of the
+ shared pixel data, because the returned data is const.
+
+ \sa scanLine(), constBits()
+ \since 4.7
+*/
+const uchar *QImage::constScanLine(int i) const
+{
+ if (!d)
+ return 0;
+
+ Q_ASSERT(i >= 0 && i < height());
+ return d->data + i * d->bytes_per_line;
+}
+
+/*!
Returns a pointer to the first pixel data. This is equivalent to
scanLine(0).
@@ -1873,7 +1895,7 @@ const uchar *QImage::scanLine(int i) const
data, thus ensuring that this QImage is the only one using the
current return value.
- \sa scanLine(), byteCount()
+ \sa scanLine(), byteCount(), constBits()
*/
uchar *QImage::bits()
{
@@ -1901,6 +1923,20 @@ const uchar *QImage::bits() const
}
+/*!
+ Returns a pointer to the first pixel data.
+
+ Note that QImage uses \l{Implicit Data Sharing} {implicit data
+ sharing}, but this function does \e not perform a deep copy of the
+ shared pixel data, because the returned data is const.
+
+ \sa bits(), constScanLine()
+ \since 4.7
+*/
+const uchar *QImage::constBits() const
+{
+ return d ? d->data : 0;
+}
/*!
\fn void QImage::reset()
diff --git a/src/gui/image/qimage.h b/src/gui/image/qimage.h
index ac973a1..dd13782 100644
--- a/src/gui/image/qimage.h
+++ b/src/gui/image/qimage.h
@@ -182,6 +182,7 @@ public:
uchar *bits();
const uchar *bits() const;
+ const uchar *constBits() const;
#ifdef QT_DEPRECATED
QT_DEPRECATED int numBytes() const;
#endif
@@ -189,6 +190,7 @@ public:
uchar *scanLine(int);
const uchar *scanLine(int) const;
+ const uchar *constScanLine(int) const;
int bytesPerLine() const;
bool valid(int x, int y) const;
diff --git a/src/gui/image/qpicture.cpp b/src/gui/image/qpicture.cpp
index fb70e36..3220a67 100644
--- a/src/gui/image/qpicture.cpp
+++ b/src/gui/image/qpicture.cpp
@@ -440,36 +440,6 @@ bool QPicture::play(QPainter *painter)
return true; // no end-command
}
-
-//
-// QFakeDevice is used to create fonts with a custom DPI
-//
-class QFakeDevice : public QPaintDevice
-{
-public:
- QFakeDevice() { dpi_x = qt_defaultDpiX(); dpi_y = qt_defaultDpiY(); }
- void setDpiX(int dpi) { dpi_x = dpi; }
- void setDpiY(int dpi) { dpi_y = dpi; }
- QPaintEngine *paintEngine() const { return 0; }
- int metric(PaintDeviceMetric m) const
- {
- switch(m) {
- case PdmPhysicalDpiX:
- case PdmDpiX:
- return dpi_x;
- case PdmPhysicalDpiY:
- case PdmDpiY:
- return dpi_y;
- default:
- return QPaintDevice::metric(m);
- }
- }
-
-private:
- int dpi_x;
- int dpi_y;
-};
-
/*!
\internal
Iterates over the internal picture data and draws the picture using
@@ -679,30 +649,29 @@ bool QPicture::exec(QPainter *painter, QDataStream &s, int nrecords)
if (d->formatMajor >= 9) {
s >> dbl;
- QFont fnt(font);
- if (dbl != 1.0) {
- QFakeDevice fake;
- fake.setDpiX(qRound(dbl*qt_defaultDpiX()));
- fake.setDpiY(qRound(dbl*qt_defaultDpiY()));
- fnt = QFont(font, &fake);
- }
+ QFont fnt(font, painter->device());
+
+ qreal scale = painter->device()->logicalDpiY() / (dbl*qt_defaultDpiY());
+ painter->save();
+ painter->scale(1/scale, 1/scale);
qreal justificationWidth;
s >> justificationWidth;
int flags = Qt::TextSingleLine | Qt::TextDontClip | Qt::TextForceLeftToRight;
- QSizeF size(1, 1);
+ QSizeF size(scale, scale);
if (justificationWidth > 0) {
- size.setWidth(justificationWidth);
+ size.setWidth(justificationWidth*scale);
flags |= Qt::TextJustificationForced;
flags |= Qt::AlignJustify;
}
QFontMetrics fm(fnt);
- QPointF pt(p.x(), p.y() - fm.ascent());
+ QPointF pt(p.x()*scale, p.y()*scale - fm.ascent());
qt_format_text(fnt, QRectF(pt, size), flags, /*opt*/0,
str, /*brect=*/0, /*tabstops=*/0, /*...*/0, /*tabarraylen=*/0, painter);
+ painter->restore();
} else {
qt_format_text(font, QRectF(p, QSizeF(1, 1)), Qt::TextSingleLine | Qt::TextDontClip, /*opt*/0,
str, /*brect=*/0, /*tabstops=*/0, /*...*/0, /*tabarraylen=*/0, painter);
diff --git a/src/gui/image/qpixmap.cpp b/src/gui/image/qpixmap.cpp
index d1e5c40..7cafbd0 100644
--- a/src/gui/image/qpixmap.cpp
+++ b/src/gui/image/qpixmap.cpp
@@ -1078,6 +1078,9 @@ QPixmap QPixmap::grabWidget(QWidget * widget, const QRect &rect)
if (widget->testAttribute(Qt::WA_PendingResizeEvent) || !widget->testAttribute(Qt::WA_WState_Created))
sendResizeEvents(widget);
+ widget->d_func()->prepareToRender(QRegion(),
+ QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask);
+
QRect r(rect);
if (r.width() < 0)
r.setWidth(widget->width() - rect.x());
@@ -1088,8 +1091,8 @@ QPixmap QPixmap::grabWidget(QWidget * widget, const QRect &rect)
return QPixmap();
QPixmap res(r.size());
- widget->render(&res, QPoint(), r,
- QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask);
+ widget->d_func()->render(&res, QPoint(), r, QWidget::DrawWindowBackground
+ | QWidget::DrawChildren | QWidget::IgnoreMask, true);
return res;
}
@@ -1370,10 +1373,27 @@ void QPixmap::deref()
*/
/*!
- \fn bool QPixmap::convertFromImage(const QImage &image, Qt::ImageConversionFlags flags)
+ Replaces this pixmap's data with the given \a image using the
+ specified \a flags to control the conversion. The \a flags
+ argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
+ Passing 0 for \a flags sets all the default options. Returns true
+ if the result is that this pixmap is not null.
- Use the static fromImage() function instead.
+ Note: this function was part of Qt 3 support in Qt 4.6 and earlier.
+ It has been promoted to official API status in 4.7 to support updating
+ the pixmap's image without creating a new QPixmap as fromImage() would.
+
+ \sa fromImage()
+ \since 4.7
*/
+bool QPixmap::convertFromImage(const QImage &image, Qt::ImageConversionFlags flags)
+{
+ if (image.isNull() || !data)
+ *this = QPixmap::fromImage(image, flags);
+ else
+ data->fromImage(image, flags);
+ return !isNull();
+}
/*!
\fn QPixmap QPixmap::xForm(const QMatrix &matrix) const
diff --git a/src/gui/image/qpixmap.h b/src/gui/image/qpixmap.h
index 46363f0..180af3b 100644
--- a/src/gui/image/qpixmap.h
+++ b/src/gui/image/qpixmap.h
@@ -141,6 +141,8 @@ public:
bool save(const QString& fileName, const char* format = 0, int quality = -1) const;
bool save(QIODevice* device, const char* format = 0, int quality = -1) const;
+ bool convertFromImage(const QImage &img, Qt::ImageConversionFlags flags = Qt::AutoColor);
+
#if defined(Q_WS_WIN)
enum HBitmapFormat {
NoAlpha,
@@ -224,8 +226,6 @@ public:
QT3_SUPPORT QPixmap &operator=(const QImage &);
inline QT3_SUPPORT QImage convertToImage() const { return toImage(); }
QT3_SUPPORT bool convertFromImage(const QImage &, ColorMode mode);
- QT3_SUPPORT bool convertFromImage(const QImage &img, Qt::ImageConversionFlags flags = Qt::AutoColor)
- { (*this) = fromImage(img, flags); return !isNull(); }
inline QT3_SUPPORT operator QImage() const { return toImage(); }
inline QT3_SUPPORT QPixmap xForm(const QMatrix &matrix) const { return transformed(QTransform(matrix)); }
inline QT3_SUPPORT bool selfMask() const { return false; }
diff --git a/src/gui/image/qpixmap_x11.cpp b/src/gui/image/qpixmap_x11.cpp
index e1e8a0d..b976376 100644
--- a/src/gui/image/qpixmap_x11.cpp
+++ b/src/gui/image/qpixmap_x11.cpp
@@ -1142,7 +1142,7 @@ void QX11PixmapData::fromImage(const QImage &img,
}
}
-void QX11PixmapData::bitmapFromImage(const QImage &image)
+Qt::HANDLE QX11PixmapData::createBitmapFromImage(const QImage &image)
{
QImage img = image.convertToFormat(QImage::Format_MonoLSB);
const QRgb c0 = QColor(Qt::black).rgb();
@@ -1155,10 +1155,8 @@ void QX11PixmapData::bitmapFromImage(const QImage &image)
char *bits;
uchar *tmp_bits;
- w = img.width();
- h = img.height();
- d = 1;
- is_null = (w <= 0 || h <= 0);
+ int w = img.width();
+ int h = img.height();
int bpl = (w + 7) / 8;
int ibpl = img.bytesPerLine();
if (bpl != ibpl) {
@@ -1177,18 +1175,26 @@ void QX11PixmapData::bitmapFromImage(const QImage &image)
bits = (char *)img.bits();
tmp_bits = 0;
}
- hd = (Qt::HANDLE)XCreateBitmapFromData(xinfo.display(),
- RootWindow(xinfo.display(), xinfo.screen()),
+ Qt::HANDLE hd = (Qt::HANDLE)XCreateBitmapFromData(X11->display,
+ QX11Info::appRootWindow(),
bits, w, h);
+ if (tmp_bits) // Avoid purify complaint
+ delete [] tmp_bits;
+ return hd;
+}
+void QX11PixmapData::bitmapFromImage(const QImage &image)
+{
+ w = image.width();
+ h = image.height();
+ d = 1;
+ is_null = (w <= 0 || h <= 0);
+ hd = createBitmapFromImage(image);
#ifndef QT_NO_XRENDER
if (X11->use_xrender)
picture = XRenderCreatePicture(X11->display, hd,
XRenderFindStandardFormat(X11->display, PictStandardA1), 0, 0);
#endif // QT_NO_XRENDER
-
- if (tmp_bits) // Avoid purify complaint
- delete [] tmp_bits;
}
void QX11PixmapData::fill(const QColor &fillColor)
diff --git a/src/gui/image/qpixmap_x11_p.h b/src/gui/image/qpixmap_x11_p.h
index 20fb654..0c0a9bd 100644
--- a/src/gui/image/qpixmap_x11_p.h
+++ b/src/gui/image/qpixmap_x11_p.h
@@ -92,6 +92,8 @@ public:
Qt::HANDLE handle() const { return hd; }
Qt::HANDLE x11ConvertToDefaultDepth();
+ static Qt::HANDLE createBitmapFromImage(const QImage &image);
+
protected:
int metric(QPaintDevice::PaintDeviceMetric metric) const;
diff --git a/src/gui/image/qpnghandler.cpp b/src/gui/image/qpnghandler.cpp
index d5406cb..dd31834 100644
--- a/src/gui/image/qpnghandler.cpp
+++ b/src/gui/image/qpnghandler.cpp
@@ -50,8 +50,13 @@
#include <qvariant.h>
#include <qvector.h>
+#ifdef QT_USE_BUNDLED_LIBPNG
+#include <../../3rdparty/libpng/png.h>
+#include <../../3rdparty/libpng/pngconf.h>
+#else
#include <png.h>
#include <pngconf.h>
+#endif
#ifdef Q_OS_WINCE
#define CALLBACK_CALL_TYPE __cdecl
@@ -162,11 +167,16 @@ void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, float scre
png_uint_32 height;
int bit_depth;
int color_type;
+ png_bytep trans_alpha = 0;
+ png_color_16p trans_color_p = 0;
+ int num_trans;
+ png_colorp palette = 0;
+ int num_palette;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
if (color_type == PNG_COLOR_TYPE_GRAY) {
// Black & White or 8-bit grayscale
- if (bit_depth == 1 && info_ptr->channels == 1) {
+ if (bit_depth == 1 && png_get_channels(png_ptr, info_ptr) == 1) {
png_set_invert_mono(png_ptr);
png_read_update_info(png_ptr, info_ptr);
if (image.size() != QSize(width, height) || image.format() != QImage::Format_Mono) {
@@ -207,20 +217,16 @@ void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, float scre
int c = i*255/(ncols-1);
image.setColor(i, qRgba(c,c,c,0xff));
}
- if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
-#if PNG_LIBPNG_VER_MAJOR < 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR < 4)
- const int g = info_ptr->trans_values.gray;
-#else
- const int g = info_ptr->trans_color.gray;
-#endif
+ if (png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color_p) && trans_color_p) {
+ const int g = trans_color_p->gray;
if (g < ncols) {
image.setColor(g, 0);
}
}
}
} else if (color_type == PNG_COLOR_TYPE_PALETTE
- && png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE)
- && info_ptr->num_palette <= 256)
+ && png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette)
+ && num_palette <= 256)
{
// 1-bit and 8-bit color
if (bit_depth != 1)
@@ -233,29 +239,26 @@ void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, float scre
if (image.isNull())
return;
}
- image.setColorCount(info_ptr->num_palette);
+ png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
+ image.setColorCount(num_palette);
int i = 0;
- if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
- while (i < info_ptr->num_trans) {
+ if (png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color_p) && trans_alpha) {
+ while (i < num_trans) {
image.setColor(i, qRgba(
- info_ptr->palette[i].red,
- info_ptr->palette[i].green,
- info_ptr->palette[i].blue,
-#if PNG_LIBPNG_VER_MAJOR < 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR < 4)
- info_ptr->trans[i]
-#else
- info_ptr->trans_alpha[i]
-#endif
+ palette[i].red,
+ palette[i].green,
+ palette[i].blue,
+ trans_alpha[i]
)
);
i++;
}
}
- while (i < info_ptr->num_palette) {
+ while (i < num_palette) {
image.setColor(i, qRgba(
- info_ptr->palette[i].red,
- info_ptr->palette[i].green,
- info_ptr->palette[i].blue,
+ palette[i].red,
+ palette[i].green,
+ palette[i].blue,
0xff
)
);
@@ -531,33 +534,36 @@ QImage::Format QPngHandlerPrivate::readImageFormat()
QImage::Format format = QImage::Format_Invalid;
png_uint_32 width, height;
int bit_depth, color_type;
- if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY) {
+ png_colorp palette;
+ int num_palette;
+ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
+ if (color_type == PNG_COLOR_TYPE_GRAY) {
// Black & White or 8-bit grayscale
- if (info_ptr->bit_depth == 1 && info_ptr->channels == 1) {
+ if (bit_depth == 1 && png_get_channels(png_ptr, info_ptr) == 1) {
format = QImage::Format_Mono;
- } else if (info_ptr->bit_depth == 16 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
+ } else if (bit_depth == 16 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
format = QImage::Format_ARGB32;
} else {
format = QImage::Format_Indexed8;
}
- } else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE
- && png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE)
- && info_ptr->num_palette <= 256)
+ } else if (color_type == PNG_COLOR_TYPE_PALETTE
+ && png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette)
+ && num_palette <= 256)
{
// 1-bit and 8-bit color
- if (info_ptr->bit_depth != 1)
+ if (bit_depth != 1)
png_set_packing(png_ptr);
png_read_update_info(png_ptr, info_ptr);
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
format = bit_depth == 1 ? QImage::Format_Mono : QImage::Format_Indexed8;
} else {
// 32-bit
- if (info_ptr->bit_depth == 16)
+ if (bit_depth == 16)
png_set_strip_16(png_ptr);
format = QImage::Format_ARGB32;
// Only add filler if no alpha, or we can get 5 channel data.
- if (!(info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
+ if (!(color_type & PNG_COLOR_MASK_ALPHA)
&& !png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
// We want 4 bytes, but it isn't an alpha channel
format = QImage::Format_RGB32;
@@ -648,7 +654,7 @@ static void set_text(const QImage &image, png_structp png_ptr, png_infop info_pt
text_ptr[i].text = qstrdup(value.constData());
text_ptr[i].text_length = 0;
text_ptr[i].itxt_length = value.size();
- text_ptr[i].lang = "UTF-8";
+ text_ptr[i].lang = const_cast<char*>("UTF-8");
text_ptr[i].lang_key = qstrdup(it.key().toUtf8().constData());
#endif
++i;
@@ -735,64 +741,51 @@ bool Q_INTERNAL_WIN_NO_THROW QPNGImageWriter::writeImage(const QImage& image_in,
png_set_compression_level(png_ptr, quality);
}
- if (gamma != 0.0) {
- png_set_gAMA(png_ptr, info_ptr, 1.0/gamma);
- }
-
png_set_write_fn(png_ptr, (void*)this, qpiw_write_fn, qpiw_flush_fn);
- info_ptr->channels =
- (image.depth() == 32)
- ? (image.format() == QImage::Format_RGB32 ? 3 : 4)
- : 1;
-
png_set_IHDR(png_ptr, info_ptr, image.width(), image.height(),
image.depth() == 1 ? 1 : 8 /* per channel */,
image.depth() == 32
? image.format() == QImage::Format_RGB32
? PNG_COLOR_TYPE_RGB
: PNG_COLOR_TYPE_RGB_ALPHA
- : PNG_COLOR_TYPE_PALETTE, 0, 0, 0);
+ : PNG_COLOR_TYPE_PALETTE, 0, 0, 0); // also sets #channels
+ if (gamma != 0.0) {
+ png_set_gAMA(png_ptr, info_ptr, 1.0/gamma);
+ }
- //png_set_sBIT(png_ptr, info_ptr, 8);
- info_ptr->sig_bit.red = 8;
- info_ptr->sig_bit.green = 8;
- info_ptr->sig_bit.blue = 8;
+ png_color_8 sig_bit;
+ sig_bit.red = 8;
+ sig_bit.green = 8;
+ sig_bit.blue = 8;
+ sig_bit.alpha = image.hasAlphaChannel() ? 8 : 0;
+ png_set_sBIT(png_ptr, info_ptr, &sig_bit);
if (image.format() == QImage::Format_MonoLSB)
png_set_packswap(png_ptr);
- png_colorp palette = 0;
- png_bytep copy_trans = 0;
if (image.colorCount()) {
// Paletted
- int num_palette = image.colorCount();
- palette = new png_color[num_palette];
- png_set_PLTE(png_ptr, info_ptr, palette, num_palette);
- int* trans = new int[num_palette];
+ int num_palette = qMin(256, image.colorCount());
+ png_color palette[256];
+ png_byte trans[256];
int num_trans = 0;
for (int i=0; i<num_palette; i++) {
- QRgb rgb=image.color(i);
- info_ptr->palette[i].red = qRed(rgb);
- info_ptr->palette[i].green = qGreen(rgb);
- info_ptr->palette[i].blue = qBlue(rgb);
- trans[i] = rgb >> 24;
+ QRgb rgba=image.color(i);
+ palette[i].red = qRed(rgba);
+ palette[i].green = qGreen(rgba);
+ palette[i].blue = qBlue(rgba);
+ trans[i] = qAlpha(rgba);
if (trans[i] < 255) {
num_trans = i+1;
}
}
+ png_set_PLTE(png_ptr, info_ptr, palette, num_palette);
+
if (num_trans) {
- copy_trans = new png_byte[num_trans];
- for (int i=0; i<num_trans; i++)
- copy_trans[i] = trans[i];
- png_set_tRNS(png_ptr, info_ptr, copy_trans, num_trans, 0);
+ png_set_tRNS(png_ptr, info_ptr, trans, num_trans, 0);
}
- delete [] trans;
- }
-
- if (image.format() != QImage::Format_RGB32) {
- info_ptr->sig_bit.alpha = 8;
}
// Swap ARGB to RGBA (normal PNG format) before saving on
@@ -868,11 +861,6 @@ bool Q_INTERNAL_WIN_NO_THROW QPNGImageWriter::writeImage(const QImage& image_in,
png_write_end(png_ptr, info_ptr);
frames_written++;
- if (palette)
- delete [] palette;
- if (copy_trans)
- delete [] copy_trans;
-
png_destroy_write_struct(&png_ptr, &info_ptr);
return true;
@@ -958,7 +946,8 @@ QVariant QPngHandler::option(ImageOption option) const
else if (option == Description)
return d->description;
else if (option == Size)
- return QSize(d->info_ptr->width, d->info_ptr->height);
+ return QSize(png_get_image_width(d->png_ptr, d->info_ptr),
+ png_get_image_height(d->png_ptr, d->info_ptr));
else if (option == ImageFormat)
return d->readImageFormat();
return 0;
diff --git a/src/gui/inputmethod/qwininputcontext_p.h b/src/gui/inputmethod/qwininputcontext_p.h
index 08cc3d2..d5bedf4 100644
--- a/src/gui/inputmethod/qwininputcontext_p.h
+++ b/src/gui/inputmethod/qwininputcontext_p.h
@@ -56,7 +56,7 @@
#include "QtGui/qinputcontext.h"
#include "QtCore/qt_windows.h"
-#if defined(Q_CC_MINGW) && !defined(IMR_RECONVERTSTRING)
+#if !defined(IMR_RECONVERTSTRING)
typedef struct tagRECONVERTSTRING {
DWORD dwSize;
DWORD dwVersion;
diff --git a/src/gui/itemviews/qdirmodel.cpp b/src/gui/itemviews/qdirmodel.cpp
index ea608c1..378a238 100644
--- a/src/gui/itemviews/qdirmodel.cpp
+++ b/src/gui/itemviews/qdirmodel.cpp
@@ -185,12 +185,12 @@ void QDirModelPrivate::invalidate()
/*!
\class QDirModel
-
+ \obsolete
\brief The QDirModel class provides a data model for the local filesystem.
\ingroup model-view
- \note The usage of QDirModel is not recommended anymore. The
+ The usage of QDirModel is not recommended anymore. The
QFileSystemModel class is a more performant alternative.
This class provides access to the local filesystem, providing functions
diff --git a/src/gui/itemviews/qfileiconprovider.cpp b/src/gui/itemviews/qfileiconprovider.cpp
index fcc61e5..f321ab3 100644
--- a/src/gui/itemviews/qfileiconprovider.cpp
+++ b/src/gui/itemviews/qfileiconprovider.cpp
@@ -73,7 +73,7 @@ QT_BEGIN_NAMESPACE
/*!
\class QFileIconProvider
- \brief The QFileIconProvider class provides file icons for the QDirModel class.
+ \brief The QFileIconProvider class provides file icons for the QDirModel and the QFileSystemModel classes.
*/
/*!
diff --git a/src/gui/itemviews/qheaderview.cpp b/src/gui/itemviews/qheaderview.cpp
index 8a456e6..1c26e51 100644
--- a/src/gui/itemviews/qheaderview.cpp
+++ b/src/gui/itemviews/qheaderview.cpp
@@ -1853,11 +1853,9 @@ void QHeaderViewPrivate::_q_layoutChanged()
persistentHiddenSections.clear();
return;
}
+
+ QBitArray oldSectionHidden = sectionHidden;
bool sectionCountChanged = false;
- for (int i = 0; i < sectionHidden.count(); ++i) {
- if (sectionHidden.testBit(i))
- q->setSectionHidden(logicalIndex(i), false);
- }
for (int i = 0; i < persistentHiddenSections.count(); ++i) {
QModelIndex index = persistentHiddenSections.at(i);
@@ -1866,6 +1864,7 @@ void QHeaderViewPrivate::_q_layoutChanged()
? index.column()
: index.row());
q->setSectionHidden(logical, true);
+ oldSectionHidden.setBit(logical, false);
} else if (!sectionCountChanged && (modelSectionCount() != sectionCount)) {
sectionCountChanged = true;
break;
@@ -1873,6 +1872,11 @@ void QHeaderViewPrivate::_q_layoutChanged()
}
persistentHiddenSections.clear();
+ for (int i = 0; i < oldSectionHidden.count(); ++i) {
+ if (oldSectionHidden.testBit(i))
+ q->setSectionHidden(logicalIndex(i), false);
+ }
+
// the number of sections changed; we need to reread the state of the model
if (sectionCountChanged)
q->initializeSections();
@@ -2300,7 +2304,7 @@ void QHeaderView::mouseReleaseEvent(QMouseEvent *e)
int section = logicalIndexAt(pos);
if (section != -1 && section == d->pressed) {
d->flipSortIndicator(section);
- emit sectionClicked(logicalIndexAt(pos));
+ emit sectionClicked(section);
}
if (d->pressed != -1)
updateSection(d->pressed);
diff --git a/src/gui/itemviews/qsortfilterproxymodel.cpp b/src/gui/itemviews/qsortfilterproxymodel.cpp
index 41c984e..e73013c 100644
--- a/src/gui/itemviews/qsortfilterproxymodel.cpp
+++ b/src/gui/itemviews/qsortfilterproxymodel.cpp
@@ -270,6 +270,11 @@ void QSortFilterProxyModelPrivate::clear_mapping()
qDeleteAll(source_index_mapping);
source_index_mapping.clear();
+ if (dynamic_sortfilter && update_source_sort_column()) {
+ //update_source_sort_column might have created wrong mapping so we have to clear it again
+ qDeleteAll(source_index_mapping);
+ source_index_mapping.clear();
+ }
// update the persistent indexes
update_persistent_indexes(source_indexes);
@@ -1208,11 +1213,6 @@ void QSortFilterProxyModelPrivate::_q_sourceLayoutAboutToBeChanged()
void QSortFilterProxyModelPrivate::_q_sourceLayoutChanged()
{
Q_Q(QSortFilterProxyModel);
- if (saved_persistent_indexes.isEmpty()) {
- clear_mapping();
- emit q->layoutChanged();
- return;
- }
qDeleteAll(source_index_mapping);
source_index_mapping.clear();
@@ -1220,7 +1220,11 @@ void QSortFilterProxyModelPrivate::_q_sourceLayoutChanged()
update_persistent_indexes(saved_persistent_indexes);
saved_persistent_indexes.clear();
- update_source_sort_column();
+ if (dynamic_sortfilter && update_source_sort_column()) {
+ //update_source_sort_column might have created wrong mapping so we have to clear it again
+ qDeleteAll(source_index_mapping);
+ source_index_mapping.clear();
+ }
emit q->layoutChanged();
}
@@ -1481,7 +1485,6 @@ QSortFilterProxyModel::QSortFilterProxyModel(QObject *parent)
d->filter_column = 0;
d->filter_role = Qt::DisplayRole;
d->dynamic_sortfilter = false;
- connect(this, SIGNAL(modelReset()), this, SLOT(invalidate()));
}
/*!
diff --git a/src/gui/kernel/kernel.pri b/src/gui/kernel/kernel.pri
index 0993b86..6fd45ad 100644
--- a/src/gui/kernel/kernel.pri
+++ b/src/gui/kernel/kernel.pri
@@ -206,6 +206,7 @@ embedded {
OBJECTIVE_HEADERS += \
qcocoawindow_mac_p.h \
+ qcocoapanel_mac_p.h \
qcocoawindowdelegate_mac_p.h \
qcocoaview_mac_p.h \
qcocoaapplication_mac_p.h \
diff --git a/src/gui/kernel/qaction.h b/src/gui/kernel/qaction.h
index 4341367..538b04f 100644
--- a/src/gui/kernel/qaction.h
+++ b/src/gui/kernel/qaction.h
@@ -246,6 +246,9 @@ private:
friend class QMenuBar;
friend class QShortcutMap;
friend class QToolButton;
+#ifdef Q_WS_MAC
+ friend void qt_mac_clear_status_text(QAction *action);
+#endif
};
QT_BEGIN_INCLUDE_NAMESPACE
diff --git a/src/gui/kernel/qapplication.cpp b/src/gui/kernel/qapplication.cpp
index 4fe3900..336be91 100644
--- a/src/gui/kernel/qapplication.cpp
+++ b/src/gui/kernel/qapplication.cpp
@@ -182,6 +182,15 @@ QApplicationPrivate::QApplicationPrivate(int &argc, char **argv, QApplication::T
gestureManager = 0;
gestureWidget = 0;
+#if defined(Q_WS_X11) || defined(Q_WS_WIN)
+ move_cursor = 0;
+ copy_cursor = 0;
+ link_cursor = 0;
+#endif
+#if defined(Q_WS_WIN)
+ ignore_cursor = 0;
+#endif
+
if (!self)
self = this;
}
@@ -925,7 +934,7 @@ void QApplicationPrivate::initialize()
// Set up which span functions should be used in raster engine...
qInitDrawhelperAsm();
-
+
#if !defined(Q_WS_X11) && !defined(Q_WS_QWS)
// initialize the graphics system - on X11 this is initialized inside
// qt_init() in qapplication_x11.cpp because of several reasons.
@@ -1032,6 +1041,15 @@ QApplication::~QApplication()
qt_clipboard = 0;
#endif
+#if defined(Q_WS_X11) || defined(Q_WS_WIN)
+ delete d->move_cursor; d->move_cursor = 0;
+ delete d->copy_cursor; d->copy_cursor = 0;
+ delete d->link_cursor; d->link_cursor = 0;
+#endif
+#if defined(Q_WS_WIN)
+ delete d->ignore_cursor; d->ignore_cursor = 0;
+#endif
+
delete QWidgetPrivate::mapper;
QWidgetPrivate::mapper = 0;
@@ -5246,10 +5264,20 @@ QInputContext *QApplication::inputContext() const
qic = QInputContextFactory::create(QLatin1String("xim"), that);
that->d_func()->inputContext = qic;
}
-#elif defined(Q_WS_S60)
+#elif defined(Q_OS_SYMBIAN)
if (!d->inputContext) {
QApplication *that = const_cast<QApplication *>(this);
- that->d_func()->inputContext = QInputContextFactory::create(QString::fromLatin1("coefep"), that);
+ const QStringList keys = QInputContextFactory::keys();
+ // Try hbim and coefep first, then try others.
+ if (keys.contains("hbim")) {
+ that->d_func()->inputContext = QInputContextFactory::create(QLatin1String("hbim"), that);
+ } else if (keys.contains("coefep")) {
+ that->d_func()->inputContext = QInputContextFactory::create(QLatin1String("coefep"), that);
+ } else {
+ for (int c = 0; c < keys.size() && !d->inputContext; ++c) {
+ that->d_func()->inputContext = QInputContextFactory::create(keys[c], that);
+ }
+ }
}
#endif
return d->inputContext;
@@ -5689,6 +5717,228 @@ QGestureManager* QGestureManager::instance()
return qAppPriv->gestureManager;
}
+// These pixmaps approximate the images in the Windows User Interface Guidelines.
+
+// XPM
+
+static const char * const move_xpm[] = {
+"11 20 3 1",
+". c None",
+#if defined(Q_WS_WIN)
+"a c #000000",
+"X c #FFFFFF", // Windows cursor is traditionally white
+#else
+"a c #FFFFFF",
+"X c #000000", // X11 cursor is traditionally black
+#endif
+"aa.........",
+"aXa........",
+"aXXa.......",
+"aXXXa......",
+"aXXXXa.....",
+"aXXXXXa....",
+"aXXXXXXa...",
+"aXXXXXXXa..",
+"aXXXXXXXXa.",
+"aXXXXXXXXXa",
+"aXXXXXXaaaa",
+"aXXXaXXa...",
+"aXXaaXXa...",
+"aXa..aXXa..",
+"aa...aXXa..",
+"a.....aXXa.",
+"......aXXa.",
+".......aXXa",
+".......aXXa",
+"........aa."};
+
+#ifdef Q_WS_WIN
+/* XPM */
+static const char * const ignore_xpm[] = {
+"24 30 3 1",
+". c None",
+"a c #000000",
+"X c #FFFFFF",
+"aa......................",
+"aXa.....................",
+"aXXa....................",
+"aXXXa...................",
+"aXXXXa..................",
+"aXXXXXa.................",
+"aXXXXXXa................",
+"aXXXXXXXa...............",
+"aXXXXXXXXa..............",
+"aXXXXXXXXXa.............",
+"aXXXXXXaaaa.............",
+"aXXXaXXa................",
+"aXXaaXXa................",
+"aXa..aXXa...............",
+"aa...aXXa...............",
+"a.....aXXa..............",
+"......aXXa.....XXXX.....",
+".......aXXa..XXaaaaXX...",
+".......aXXa.XaaaaaaaaX..",
+"........aa.XaaaXXXXaaaX.",
+"...........XaaaaX..XaaX.",
+"..........XaaXaaaX..XaaX",
+"..........XaaXXaaaX.XaaX",
+"..........XaaX.XaaaXXaaX",
+"..........XaaX..XaaaXaaX",
+"...........XaaX..XaaaaX.",
+"...........XaaaXXXXaaaX.",
+"............XaaaaaaaaX..",
+".............XXaaaaXX...",
+"...............XXXX....."};
+#endif
+
+/* XPM */
+static const char * const copy_xpm[] = {
+"24 30 3 1",
+". c None",
+"a c #000000",
+"X c #FFFFFF",
+#if defined(Q_WS_WIN) // Windows cursor is traditionally white
+"aa......................",
+"aXa.....................",
+"aXXa....................",
+"aXXXa...................",
+"aXXXXa..................",
+"aXXXXXa.................",
+"aXXXXXXa................",
+"aXXXXXXXa...............",
+"aXXXXXXXXa..............",
+"aXXXXXXXXXa.............",
+"aXXXXXXaaaa.............",
+"aXXXaXXa................",
+"aXXaaXXa................",
+"aXa..aXXa...............",
+"aa...aXXa...............",
+"a.....aXXa..............",
+"......aXXa..............",
+".......aXXa.............",
+".......aXXa.............",
+"........aa...aaaaaaaaaaa",
+#else
+"XX......................",
+"XaX.....................",
+"XaaX....................",
+"XaaaX...................",
+"XaaaaX..................",
+"XaaaaaX.................",
+"XaaaaaaX................",
+"XaaaaaaaX...............",
+"XaaaaaaaaX..............",
+"XaaaaaaaaaX.............",
+"XaaaaaaXXXX.............",
+"XaaaXaaX................",
+"XaaXXaaX................",
+"XaX..XaaX...............",
+"XX...XaaX...............",
+"X.....XaaX..............",
+"......XaaX..............",
+".......XaaX.............",
+".......XaaX.............",
+"........XX...aaaaaaaaaaa",
+#endif
+".............aXXXXXXXXXa",
+".............aXXXXXXXXXa",
+".............aXXXXaXXXXa",
+".............aXXXXaXXXXa",
+".............aXXaaaaaXXa",
+".............aXXXXaXXXXa",
+".............aXXXXaXXXXa",
+".............aXXXXXXXXXa",
+".............aXXXXXXXXXa",
+".............aaaaaaaaaaa"};
+
+/* XPM */
+static const char * const link_xpm[] = {
+"24 30 3 1",
+". c None",
+"a c #000000",
+"X c #FFFFFF",
+#if defined(Q_WS_WIN) // Windows cursor is traditionally white
+"aa......................",
+"aXa.....................",
+"aXXa....................",
+"aXXXa...................",
+"aXXXXa..................",
+"aXXXXXa.................",
+"aXXXXXXa................",
+"aXXXXXXXa...............",
+"aXXXXXXXXa..............",
+"aXXXXXXXXXa.............",
+"aXXXXXXaaaa.............",
+"aXXXaXXa................",
+"aXXaaXXa................",
+"aXa..aXXa...............",
+"aa...aXXa...............",
+"a.....aXXa..............",
+"......aXXa..............",
+".......aXXa.............",
+".......aXXa.............",
+"........aa...aaaaaaaaaaa",
+#else
+"XX......................",
+"XaX.....................",
+"XaaX....................",
+"XaaaX...................",
+"XaaaaX..................",
+"XaaaaaX.................",
+"XaaaaaaX................",
+"XaaaaaaaX...............",
+"XaaaaaaaaX..............",
+"XaaaaaaaaaX.............",
+"XaaaaaaXXXX.............",
+"XaaaXaaX................",
+"XaaXXaaX................",
+"XaX..XaaX...............",
+"XX...XaaX...............",
+"X.....XaaX..............",
+"......XaaX..............",
+".......XaaX.............",
+".......XaaX.............",
+"........XX...aaaaaaaaaaa",
+#endif
+".............aXXXXXXXXXa",
+".............aXXXaaaaXXa",
+".............aXXXXaaaXXa",
+".............aXXXaaaaXXa",
+".............aXXaaaXaXXa",
+".............aXXaaXXXXXa",
+".............aXXaXXXXXXa",
+".............aXXXaXXXXXa",
+".............aXXXXXXXXXa",
+".............aaaaaaaaaaa"};
+
+QPixmap QApplicationPrivate::getPixmapCursor(Qt::CursorShape cshape)
+{
+ if (!move_cursor) {
+ move_cursor = new QPixmap((const char **)move_xpm);
+ copy_cursor = new QPixmap((const char **)copy_xpm);
+ link_cursor = new QPixmap((const char **)link_xpm);
+#ifdef Q_WS_WIN
+ ignore_cursor = new QPixmap((const char **)ignore_xpm);
+#endif
+ }
+
+ switch (cshape) {
+ case Qt::DragMoveCursor:
+ return *move_cursor;
+ case Qt::DragCopyCursor:
+ return *copy_cursor;
+ case Qt::DragLinkCursor:
+ return *link_cursor;
+#ifdef Q_WS_WIN
+ case Qt::ForbiddenCursor:
+ return *ignore_cursor;
+#endif
+ default:
+ break;
+ }
+ return QPixmap();
+}
+
QT_END_NAMESPACE
#include "moc_qapplication.cpp"
diff --git a/src/gui/kernel/qapplication_mac.mm b/src/gui/kernel/qapplication_mac.mm
index 54a4901..25c98c5 100644
--- a/src/gui/kernel/qapplication_mac.mm
+++ b/src/gui/kernel/qapplication_mac.mm
@@ -1258,10 +1258,6 @@ void qt_init(QApplicationPrivate *priv, int)
[cocoaApp setMenu:[qtMenuLoader menu]];
[newDelegate setMenuLoader:qtMenuLoader];
[qtMenuLoader release];
-
- NSAppleEventManager *eventManager = [NSAppleEventManager sharedAppleEventManager];
- [eventManager setEventHandler:newDelegate andSelector:@selector(getUrl:withReplyEvent:)
- forEventClass:kInternetEventClass andEventID:kAEGetURL];
}
#endif
// Register for Carbon tablet proximity events on the event monitor target.
@@ -1361,12 +1357,39 @@ void QApplication::setMainWidget(QWidget *mainWidget)
/*****************************************************************************
QApplication cursor stack
*****************************************************************************/
+#ifdef QT_MAC_USE_COCOA
+void QApplicationPrivate::disableUsageOfCursorRects(bool disable)
+{
+ // In Cocoa there are two competing ways of setting the cursor; either
+ // by using cursor rects (see qcocoaview_mac.mm), or by pushing/popping
+ // the cursor manually. When we use override cursors, it makes most sense
+ // to use the latter. But then we need to tell cocoa to stop using the
+ // first approach so it doesn't change the cursor back when hovering over
+ // a cursor rect:
+ QWidgetList topLevels = qApp->topLevelWidgets();
+ for (int i=0; i<topLevels.size(); ++i) {
+ if (NSWindow *window = qt_mac_window_for(topLevels.at(i)))
+ disable ? [window disableCursorRects] : [window enableCursorRects];
+ }
+}
+
+void QApplicationPrivate::updateOverrideCursor()
+{
+ // Sometimes Cocoa forgets that we have set a Cursor
+ // manually. In those cases, remind it again:
+ if (QCursor *override = qApp->overrideCursor())
+ [static_cast<NSCursor *>(qt_mac_nsCursorForQCursor(*override)) set];
+}
+#endif
+
void QApplication::setOverrideCursor(const QCursor &cursor)
{
qApp->d_func()->cursor_list.prepend(cursor);
#ifdef QT_MAC_USE_COCOA
QMacCocoaAutoReleasePool pool;
+ if (qApp->d_func()->cursor_list.size() == 1)
+ qApp->d_func()->disableUsageOfCursorRects(true);
[static_cast<NSCursor *>(qt_mac_nsCursorForQCursor(cursor)) push];
#else
if (qApp && qApp->activeWindow())
@@ -1383,6 +1406,8 @@ void QApplication::restoreOverrideCursor()
#ifdef QT_MAC_USE_COCOA
QMacCocoaAutoReleasePool pool;
[NSCursor pop];
+ if (qApp->d_func()->cursor_list.isEmpty())
+ qApp->d_func()->disableUsageOfCursorRects(false);
#else
if (qApp && qApp->activeWindow()) {
const QCursor def(Qt::ArrowCursor);
@@ -2457,6 +2482,28 @@ QApplicationPrivate::globalEventProcessor(EventHandlerCallRef er, EventRef event
#endif
}
+#ifdef QT_MAC_USE_COCOA
+void QApplicationPrivate::qt_initAfterNSAppStarted()
+{
+ setupAppleEvents();
+ updateOverrideCursor();
+}
+
+void QApplicationPrivate::setupAppleEvents()
+{
+ // This function is called from the event dispatcher when NSApplication has
+ // finished initialization, which appears to be just after [NSApplication run] has
+ // started to execute. By setting up our apple events handlers this late, we override
+ // the ones set up by NSApplication.
+ QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *newDelegate = [QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate];
+ NSAppleEventManager *eventManager = [NSAppleEventManager sharedAppleEventManager];
+ [eventManager setEventHandler:newDelegate andSelector:@selector(appleEventQuit:withReplyEvent:)
+ forEventClass:kCoreEventClass andEventID:kAEQuitApplication];
+ [eventManager setEventHandler:newDelegate andSelector:@selector(getUrl:withReplyEvent:)
+ forEventClass:kInternetEventClass andEventID:kAEGetURL];
+}
+#endif
+
// In Carbon this is your one stop for apple events.
// In Cocoa, it ISN'T. This is the catch-all Apple Event handler that exists
// for the time between instantiating the NSApplication, but before the
@@ -3008,7 +3055,7 @@ void onApplicationWindowChangedActivation(QWidget *widget, bool activated)
}
QMenuBar::macUpdateMenuBar();
-
+ QApplicationPrivate::updateOverrideCursor();
#else
Q_UNUSED(widget);
Q_UNUSED(activated);
diff --git a/src/gui/kernel/qapplication_p.h b/src/gui/kernel/qapplication_p.h
index b3ec732..e0a6103 100644
--- a/src/gui/kernel/qapplication_p.h
+++ b/src/gui/kernel/qapplication_p.h
@@ -459,6 +459,12 @@ public:
static OSStatus globalEventProcessor(EventHandlerCallRef, EventRef, void *);
static OSStatus globalAppleEventProcessor(const AppleEvent *, AppleEvent *, long);
static OSStatus tabletProximityCallback(EventHandlerCallRef, EventRef, void *);
+#ifdef QT_MAC_USE_COCOA
+ static void qt_initAfterNSAppStarted();
+ static void setupAppleEvents();
+ static void updateOverrideCursor();
+ static void disableUsageOfCursorRects(bool disable);
+#endif
static bool qt_mac_apply_settings();
#endif
@@ -514,6 +520,13 @@ public:
QGestureManager *gestureManager;
QWidget *gestureWidget;
+ QPixmap *move_cursor;
+ QPixmap *copy_cursor;
+ QPixmap *link_cursor;
+#if defined(Q_WS_WIN)
+ QPixmap *ignore_cursor;
+#endif
+ QPixmap getPixmapCursor(Qt::CursorShape cshape);
QMap<int, QWeakPointer<QWidget> > widgetForTouchPointId;
QMap<int, QTouchEvent::TouchPoint> appCurrentTouchPoints;
diff --git a/src/gui/kernel/qapplication_x11.cpp b/src/gui/kernel/qapplication_x11.cpp
index afd927b..34865b5 100644
--- a/src/gui/kernel/qapplication_x11.cpp
+++ b/src/gui/kernel/qapplication_x11.cpp
@@ -614,6 +614,11 @@ static int (*original_xio_errhandler)(Display *dpy);
static int qt_x_errhandler(Display *dpy, XErrorEvent *err)
{
+ if (X11->display != dpy) {
+ // only handle X errors for our display
+ return 0;
+ }
+
switch (err->error_code) {
case BadAtom:
if (err->request_code == 20 /* X_GetProperty */
diff --git a/src/gui/kernel/qcocoaapplicationdelegate_mac.mm b/src/gui/kernel/qcocoaapplicationdelegate_mac.mm
index 47a8026..ab71a05 100644
--- a/src/gui/kernel/qcocoaapplicationdelegate_mac.mm
+++ b/src/gui/kernel/qcocoaapplicationdelegate_mac.mm
@@ -317,5 +317,12 @@ static void cleanupCocoaApplicationDelegate()
qt_sendSpontaneousEvent(qAppInstance(), &qtEvent);
}
+- (void)appleEventQuit:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
+{
+ Q_UNUSED(event);
+ Q_UNUSED(replyEvent);
+ [NSApp terminate:self];
+}
+
@end
#endif
diff --git a/src/gui/kernel/qcocoapanel_mac.mm b/src/gui/kernel/qcocoapanel_mac.mm
index 5e24c84..0b48efd 100644
--- a/src/gui/kernel/qcocoapanel_mac.mm
+++ b/src/gui/kernel/qcocoapanel_mac.mm
@@ -46,6 +46,7 @@
#import <private/qcocoawindowdelegate_mac_p.h>
#import <private/qcocoaview_mac_p.h>
#import <private/qcocoawindowcustomthemeframe_mac_p.h>
+#import <private/qcocoaapplication_mac_p.h>
#include <private/qapplication_p.h>
#include <private/qbackingstore_p.h>
diff --git a/src/gui/kernel/qcocoapanel_mac_p.h b/src/gui/kernel/qcocoapanel_mac_p.h
index fc83bd8..3678f81 100644
--- a/src/gui/kernel/qcocoapanel_mac_p.h
+++ b/src/gui/kernel/qcocoapanel_mac_p.h
@@ -54,10 +54,16 @@
#ifdef QT_MAC_USE_COCOA
#import <Cocoa/Cocoa.h>
+QT_FORWARD_DECLARE_CLASS(QStringList);
+
@interface QT_MANGLE_NAMESPACE(QCocoaPanel) : NSPanel {
bool leftButtonIsRightButton;
+ QStringList *currentCustomDragTypes;
}
+ (Class)frameViewClassForStyleMask:(NSUInteger)styleMask;
+- (void)registerDragTypes;
+
@end
#endif
+
diff --git a/src/gui/kernel/qcocoasharedwindowmethods_mac_p.h b/src/gui/kernel/qcocoasharedwindowmethods_mac_p.h
index d2b74d7..a1d2c61 100644
--- a/src/gui/kernel/qcocoasharedwindowmethods_mac_p.h
+++ b/src/gui/kernel/qcocoasharedwindowmethods_mac_p.h
@@ -57,8 +57,32 @@
QT_BEGIN_NAMESPACE
extern Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum); // qcocoaview.mm
extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
+extern const QStringList& qEnabledDraggedTypes(); // qmime_mac.cpp
+extern bool qt_blockCocoaSettingModalWindowLevel; // qeventdispatcher_mac_p.h
+
+Q_GLOBAL_STATIC(QPointer<QWidget>, currentDragTarget);
+
QT_END_NAMESPACE
+- (id)initWithContentRect:(NSRect)contentRect
+ styleMask:(NSUInteger)windowStyle
+ backing:(NSBackingStoreType)bufferingType
+ defer:(BOOL)deferCreation
+{
+ self = [super initWithContentRect:contentRect styleMask:windowStyle
+ backing:bufferingType defer:deferCreation];
+ if (self) {
+ currentCustomDragTypes = 0;
+ }
+ return self;
+}
+
+- (void)dealloc
+{
+ delete currentCustomDragTypes;
+ [super dealloc];
+}
+
- (BOOL)canBecomeKeyWindow
{
QWidget *widget = [self QT_MANGLE_NAMESPACE(qt_qwidget)];
@@ -68,6 +92,40 @@ QT_END_NAMESPACE
return !(isPopup || isToolTip);
}
+- (BOOL)canBecomeMainWindow
+{
+ QWidget *widget = [self QT_MANGLE_NAMESPACE(qt_qwidget)];
+
+ bool isToolTip = (widget->windowType() == Qt::ToolTip);
+ bool isPopup = (widget->windowType() == Qt::Popup);
+ bool isTool = (widget->windowType() == Qt::Tool);
+ return !(isPopup || isToolTip || isTool);
+}
+
+- (void)orderWindow:(NSWindowOrderingMode)orderingMode relativeTo:(NSInteger)otherWindowNumber
+{
+ if (qt_blockCocoaSettingModalWindowLevel) {
+ // To avoid windows popping in front while restoring modal sessions
+ // in the event dispatcher, we block cocoa from ordering this window
+ // to front. The result of not doing this can be seen if executing
+ // a native color dialog on top of another executing dialog.
+ return;
+ }
+ [super orderWindow:orderingMode relativeTo:otherWindowNumber];
+}
+
+- (void)setLevel:(NSInteger)windowLevel
+{
+ if (qt_blockCocoaSettingModalWindowLevel) {
+ // To avoid windows popping in front while restoring modal sessions
+ // in the event dispatcher, we block cocoa from ordering this window
+ // to front. The result of not doing this can be seen if executing
+ // a native color dialog on top of another executing dialog.
+ return;
+ }
+ [super setLevel:windowLevel];
+}
+
- (void)toggleToolbarShown:(id)sender
{
macSendToolbarChangeEvent([self QT_MANGLE_NAMESPACE(qt_qwidget)]);
@@ -106,6 +164,23 @@ QT_END_NAMESPACE
qt_dispatchTabletProximityEvent(tabletEvent);
}
+- (void)qtDispatcherToQAction:(id)sender
+{
+ // If this window is modal, the menu bar will be modally shaddowed.
+ // In that case, since the window will be in the first responder chain,
+ // we can still catch the trigger here and forward it to the menu bar.
+ // This is needed as a single modal dialog on Qt should be able to access
+ // the application menu (e.g. quit).
+ [[NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)] qtDispatcherToQAction:sender];
+}
+
+- (void)terminate:(id)sender
+{
+ // This function is called from the quit item in the menubar when this window
+ // is in the first responder chain (see also qtDispatcherToQAction above)
+ [NSApp terminate:sender];
+}
+
- (void)sendEvent:(NSEvent *)event
{
QWidget *widget = [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] qt_qwidgetForWindow:self];
@@ -133,7 +208,7 @@ QT_END_NAMESPACE
qt_button_down = widget;
handled = qt_mac_handleMouseEvent(view, event, QEvent::MouseButtonPress, mouseButton);
// Don't call super here. This prevents us from getting the mouseUp event,
- // which we need to send even if the mouseDown event was not accepted.
+ // which we need to send even if the mouseDown event was not accepted.
// (this is standard Qt behavior.)
break;
case NSRightMouseDown:
@@ -188,6 +263,115 @@ QT_END_NAMESPACE
return [super frameViewClassForStyleMask:styleMask];
}
+-(void)registerDragTypes
+{
+ // Calling registerForDraggedTypes below is slow, so only do
+ // it once for each window, or when the custom types change.
+ QMacCocoaAutoReleasePool pool;
+ const QStringList& customTypes = qEnabledDraggedTypes();
+ if (currentCustomDragTypes == 0 || *currentCustomDragTypes != customTypes) {
+ if (currentCustomDragTypes == 0)
+ currentCustomDragTypes = new QStringList();
+ *currentCustomDragTypes = customTypes;
+ const NSString* mimeTypeGeneric = @"com.trolltech.qt.MimeTypeName";
+ NSMutableArray *supportedTypes = [NSMutableArray arrayWithObjects:NSColorPboardType,
+ NSFilenamesPboardType, NSStringPboardType,
+ NSFilenamesPboardType, NSPostScriptPboardType, NSTIFFPboardType,
+ NSRTFPboardType, NSTabularTextPboardType, NSFontPboardType,
+ NSRulerPboardType, NSFileContentsPboardType, NSColorPboardType,
+ NSRTFDPboardType, NSHTMLPboardType, NSPICTPboardType,
+ NSURLPboardType, NSPDFPboardType, NSVCardPboardType,
+ NSFilesPromisePboardType, NSInkTextPboardType,
+ NSMultipleTextSelectionPboardType, mimeTypeGeneric, nil];
+ // Add custom types supported by the application.
+ for (int i = 0; i < customTypes.size(); i++) {
+ [supportedTypes addObject:reinterpret_cast<const NSString *>(QCFString::toCFStringRef(customTypes[i]))];
+ }
+ [self registerForDraggedTypes:supportedTypes];
+ }
+}
+
+- (QWidget *)dragTargetHitTest:(id <NSDraggingInfo>)sender
+{
+ // Do a hittest to find the NSView under the
+ // mouse, and return the corresponding QWidget:
+ NSPoint windowPoint = [sender draggingLocation];
+ NSView *candidateView = [[self contentView] hitTest:windowPoint];
+ if (![candidateView isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]])
+ return 0;
+ return [static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(candidateView) qt_qwidget];
+}
+
+- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
+{
+ // The user dragged something into the window. Send a draggingEntered message
+ // to the QWidget under the mouse. As the drag moves over the window, and over
+ // different widgets, we will handle enter and leave events from within
+ // draggingUpdated below. The reason why we handle this ourselves rather than
+ // subscribing for drag events directly in QCocoaView is that calling
+ // registerForDraggedTypes on the views will severly degrade initialization time
+ // for an application that uses a lot of drag subscribing widgets.
+
+ QWidget *target = [self dragTargetHitTest:sender];
+ if (!target)
+ return [super draggingEntered:sender];
+ if (target->testAttribute(Qt::WA_DropSiteRegistered) == false)
+ return NSDragOperationNone;
+
+ *currentDragTarget() = target;
+ return [reinterpret_cast<NSView *>((*currentDragTarget())->winId()) draggingEntered:sender];
+ }
+
+- (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender
+{
+ QWidget *target = [self dragTargetHitTest:sender];
+ if (!target)
+ return [super draggingUpdated:sender];
+
+ if (target == *currentDragTarget()) {
+ // The drag continues to move over the widget that we have sendt
+ // a draggingEntered message to. So just update the view:
+ return [reinterpret_cast<NSView *>((*currentDragTarget())->winId()) draggingUpdated:sender];
+ } else {
+ // The widget under the mouse has changed.
+ // So we need to fake enter/leave events:
+ if (*currentDragTarget())
+ [reinterpret_cast<NSView *>((*currentDragTarget())->winId()) draggingExited:sender];
+ if (target->testAttribute(Qt::WA_DropSiteRegistered) == false) {
+ *currentDragTarget() = 0;
+ return NSDragOperationNone;
+ }
+ *currentDragTarget() = target;
+ return [reinterpret_cast<NSView *>((*currentDragTarget())->winId()) draggingEntered:sender];
+ }
+}
+
+- (void)draggingExited:(id < NSDraggingInfo >)sender
+{
+ QWidget *target = [self dragTargetHitTest:sender];
+ if (!target)
+ return [super draggingExited:sender];
+
+ if (*currentDragTarget()) {
+ [reinterpret_cast<NSView *>((*currentDragTarget())->winId()) draggingExited:sender];
+ *currentDragTarget() = 0;
+ }
+}
+
+- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender
+{
+ QWidget *target = [self dragTargetHitTest:sender];
+ if (!target)
+ return [super performDragOperation:sender];
+
+ BOOL dropResult = NO;
+ if (*currentDragTarget()) {
+ dropResult = [reinterpret_cast<NSView *>((*currentDragTarget())->winId()) performDragOperation:sender];
+ *currentDragTarget() = 0;
+ }
+ return dropResult;
+}
+
- (void)displayIfNeeded
{
@@ -203,5 +387,3 @@ QT_END_NAMESPACE
}
[super displayIfNeeded];
}
-
-
diff --git a/src/gui/kernel/qcocoaview_mac.mm b/src/gui/kernel/qcocoaview_mac.mm
index ad64a91..873fb7e 100644
--- a/src/gui/kernel/qcocoaview_mac.mm
+++ b/src/gui/kernel/qcocoaview_mac.mm
@@ -81,7 +81,6 @@ Q_GLOBAL_STATIC(DnDParams, qMacDnDParams);
extern void qt_mac_update_cursor_at_global_pos(const QPoint &globalPos); // qcursor_mac.mm
extern bool qt_sendSpontaneousEvent(QObject *, QEvent *); // qapplication.cpp
extern OSViewRef qt_mac_nativeview_for(const QWidget *w); // qwidget_mac.mm
-extern const QStringList& qEnabledDraggedTypes(); // qmime_mac.cpp
extern QPointer<QWidget> qt_mouseover; //qapplication_mac.mm
extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
@@ -212,7 +211,6 @@ extern "C" {
composingText = new QString();
composing = false;
sendKeyEvents = true;
- currentCustomTypes = 0;
[self setHidden:YES];
return self;
}
@@ -227,36 +225,12 @@ extern "C" {
object:self];
}
--(void)registerDragTypes
-{
- QMacCocoaAutoReleasePool pool;
- // Calling registerForDraggedTypes is slow, so only do it once for each widget
- // or when the custom types change.
- const QStringList& customTypes = qEnabledDraggedTypes();
- if (currentCustomTypes == 0 || *currentCustomTypes != customTypes) {
- if (currentCustomTypes == 0)
- currentCustomTypes = new QStringList();
- *currentCustomTypes = customTypes;
- const NSString* mimeTypeGeneric = @"com.trolltech.qt.MimeTypeName";
- NSMutableArray *supportedTypes = [NSMutableArray arrayWithObjects:NSColorPboardType,
- NSFilenamesPboardType, NSStringPboardType,
- NSFilenamesPboardType, NSPostScriptPboardType, NSTIFFPboardType,
- NSRTFPboardType, NSTabularTextPboardType, NSFontPboardType,
- NSRulerPboardType, NSFileContentsPboardType, NSColorPboardType,
- NSRTFDPboardType, NSHTMLPboardType, NSPICTPboardType,
- NSURLPboardType, NSPDFPboardType, NSVCardPboardType,
- NSFilesPromisePboardType, NSInkTextPboardType,
- NSMultipleTextSelectionPboardType, mimeTypeGeneric, nil];
- // Add custom types supported by the application.
- for (int i = 0; i < customTypes.size(); i++) {
- [supportedTypes addObject:reinterpret_cast<const NSString *>(QCFString::toCFStringRef(customTypes[i]))];
- }
- [self registerForDraggedTypes:supportedTypes];
- }
-}
-
- (void)resetCursorRects
{
+ // [NSView addCursorRect] is slow, so bail out early if we can:
+ if (NSIsEmptyRect([self visibleRect]))
+ return;
+
QWidget *cursorWidget = qwidget;
if (cursorWidget->testAttribute(Qt::WA_TransparentForMouseEvents))
@@ -300,15 +274,9 @@ extern "C" {
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
- if (qwidget->testAttribute(Qt::WA_DropSiteRegistered) == false)
- return NSDragOperationNone;
+ // NB: This function is called from QCoocaWindow/QCocoaPanel rather than directly
+ // from Cocoa. They modify the drag target, and might fake enter/leave events.
NSPoint windowPoint = [sender draggingLocation];
- if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
- // pass the drag enter event to the view underneath.
- NSView *candidateView = [[[self window] contentView] hitTest:windowPoint];
- if (candidateView && candidateView != self)
- return [candidateView draggingEntered:sender];
- }
dragEnterSequence = [sender draggingSequenceNumber];
[self addDropData:sender];
QMimeData *mimeData = dropData;
@@ -361,13 +329,9 @@ extern "C" {
}
- (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender
{
+ // NB: This function is called from QCoocaWindow/QCocoaPanel rather than directly
+ // from Cocoa. They modify the drag target, and might fake enter/leave events.
NSPoint windowPoint = [sender draggingLocation];
- if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
- // pass the drag move event to the view underneath.
- NSView *candidateView = [[[self window] contentView] hitTest:windowPoint];
- if (candidateView && candidateView != self)
- return [candidateView draggingUpdated:sender];
- }
// in cases like QFocusFrame, the view under the mouse might
// not have received the drag enter. Generate a synthetic
// drag enter event for that view.
@@ -417,14 +381,10 @@ extern "C" {
- (void)draggingExited:(id < NSDraggingInfo >)sender
{
+ // NB: This function is called from QCoocaWindow/QCocoaPanel rather than directly
+ // from Cocoa. They modify the drag target, and might fake enter/leave events.
+ Q_UNUSED(sender);
dragEnterSequence = -1;
- if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
- // try sending the leave event to the last view which accepted drag enter.
- DnDParams *dndParams = [QT_MANGLE_NAMESPACE(QCocoaView) currentMouseEvent];
- NSView *candidateView = [[[self window] contentView] hitTest:dndParams->activeDragEnterPos];
- if (candidateView && candidateView != self)
- return [candidateView draggingExited:sender];
- }
// drag enter event was rejected, so ignore the move event.
if (dropData) {
QDragLeaveEvent de;
@@ -435,14 +395,10 @@ extern "C" {
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
+ // NB: This function is called from QCoocaWindow/QCocoaPanel rather than directly
+ // from Cocoa. They modify the drag target, and might fake enter/leave events.
NSPoint windowPoint = [sender draggingLocation];
dragEnterSequence = -1;
- if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
- // pass the drop event to the view underneath.
- NSView *candidateView = [[[self window] contentView] hitTest:windowPoint];
- if (candidateView && candidateView != self)
- return [candidateView performDragOperation:sender];
- }
[self addDropData:sender];
NSPoint globalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:windowPoint];
@@ -472,8 +428,6 @@ extern "C" {
{
delete composingText;
[[NSNotificationCenter defaultCenter] removeObserver:self];
- delete currentCustomTypes;
- [self unregisterDraggedTypes];
[super dealloc];
}
@@ -616,6 +570,10 @@ extern "C" {
- (void)updateTrackingAreas
{
+ // [NSView addTrackingArea] is slow, so bail out early if we can:
+ if (NSIsEmptyRect([self visibleRect]))
+ return;
+
QMacCocoaAutoReleasePool pool;
if (NSArray *trackingArray = [self trackingAreas]) {
NSUInteger size = [trackingArray count];
diff --git a/src/gui/kernel/qcocoaview_mac_p.h b/src/gui/kernel/qcocoaview_mac_p.h
index 797b4d5..4bb10c5 100644
--- a/src/gui/kernel/qcocoaview_mac_p.h
+++ b/src/gui/kernel/qcocoaview_mac_p.h
@@ -87,7 +87,6 @@ Q_GUI_EXPORT
int composingLength;
bool sendKeyEvents;
QString *composingText;
- QStringList *currentCustomTypes;
NSInteger dragEnterSequence;
}
- (id)initWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate;
@@ -97,7 +96,6 @@ Q_GUI_EXPORT
- (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender;
- (void)draggingExited:(id < NSDraggingInfo >)sender;
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
-- (void)registerDragTypes;
- (void)removeDropData;
- (void)addDropData:(id <NSDraggingInfo>)sender;
- (void)setSupportedActions:(NSDragOperation)actions;
diff --git a/src/gui/kernel/qcocoawindow_mac.mm b/src/gui/kernel/qcocoawindow_mac.mm
index a644dfe..f1b642b 100644
--- a/src/gui/kernel/qcocoawindow_mac.mm
+++ b/src/gui/kernel/qcocoawindow_mac.mm
@@ -46,6 +46,7 @@
#import <private/qcocoaview_mac_p.h>
#import <private/qt_cocoa_helpers_mac_p.h>
#import <private/qcocoawindowcustomthemeframe_mac_p.h>
+#import <private/qcocoaapplication_mac_p.h>
#include <QtGui/QWidget>
diff --git a/src/gui/kernel/qcocoawindow_mac_p.h b/src/gui/kernel/qcocoawindow_mac_p.h
index 0474882..21f82df 100644
--- a/src/gui/kernel/qcocoawindow_mac_p.h
+++ b/src/gui/kernel/qcocoawindow_mac_p.h
@@ -73,9 +73,12 @@ QT_FORWARD_DECLARE_CLASS(QStringList);
@interface QT_MANGLE_NAMESPACE(QCocoaWindow) : NSWindow {
bool leftButtonIsRightButton;
+ QStringList *currentCustomDragTypes;
}
+ (Class)frameViewClassForStyleMask:(NSUInteger)styleMask;
+- (void)registerDragTypes;
+
@end
#endif
diff --git a/src/gui/kernel/qcocoawindowdelegate_mac.mm b/src/gui/kernel/qcocoawindowdelegate_mac.mm
index db87491..24498f8 100644
--- a/src/gui/kernel/qcocoawindowdelegate_mac.mm
+++ b/src/gui/kernel/qcocoawindowdelegate_mac.mm
@@ -269,9 +269,6 @@ static void cleanupCocoaWindowDelegate()
{
QWidget *qwidget = m_windowHash->value([notification object]);
Q_ASSERT(qwidget);
- if (qwidget->isActiveWindow())
- return; // Widget is already active, no need to go through re-activation.
-
onApplicationWindowChangedActivation(qwidget, true);
}
@@ -288,10 +285,6 @@ static void cleanupCocoaWindowDelegate()
{
QWidget *qwidget = m_windowHash->value([notification object]);
Q_ASSERT(qwidget);
- if (qwidget->isActiveWindow())
- return; // Widget is already active, no need to go through re-activation
-
-
onApplicationWindowChangedActivation(qwidget, true);
}
diff --git a/src/gui/kernel/qcursor.cpp b/src/gui/kernel/qcursor.cpp
index 0f0470c..f38e4f5 100644
--- a/src/gui/kernel/qcursor.cpp
+++ b/src/gui/kernel/qcursor.cpp
@@ -141,6 +141,12 @@ QT_BEGIN_NAMESPACE
\o Qt::WhatsThisCursor \o \c whats_this
\o \inlineimage cursor-closedhand.png
\o Qt::ClosedHandCursor \o \c closedhand
+ \row \o
+ \o Qt::DragMoveCursor \o \c dnd-move or \c move
+ \o
+ \o Qt::DragCopyCursor \o \c dnd-copy or \c copy
+ \row \o
+ \o Qt::DragLinkCursor \o \c dnd-link or \c link
\endtable
\sa QWidget, {fowler}{GUI Design Handbook: Cursors}
diff --git a/src/gui/kernel/qcursor_mac.mm b/src/gui/kernel/qcursor_mac.mm
index 48bb9cc..cfebf60 100644
--- a/src/gui/kernel/qcursor_mac.mm
+++ b/src/gui/kernel/qcursor_mac.mm
@@ -424,6 +424,18 @@ void QCursorData::update()
type = QCursorData::TYPE_ThemeCursor;
curs.cp.nscursor = [NSCursor closedHandCursor];
break;
+ case Qt::DragCopyCursor:
+ type = QCursorData::TYPE_ThemeCursor;
+ curs.cp.nscursor = [NSCursor dragCopyCursor];
+ break;
+ case Qt::DragMoveCursor:
+ type = QCursorData::TYPE_ThemeCursor;
+ curs.cp.nscursor = [NSCursor arrowCursor];
+ break;
+ case Qt::DragLinkCursor:
+ type = QCursorData::TYPE_ThemeCursor;
+ curs.cp.nscursor = [NSCursor dragLinkCursor];
+ break;
#define QT_USE_APPROXIMATE_CURSORS
#ifdef QT_USE_APPROXIMATE_CURSORS
case Qt::SizeVerCursor:
@@ -519,6 +531,18 @@ void QCursorData::update()
type = QCursorData::TYPE_ThemeCursor;
curs.tc.curs = kThemeClosedHandCursor;
break;
+ case Qt::DragMoveCursor:
+ type = QCursorData::TYPE_ThemeCursor;
+ curs.tc.curs = kThemeArrowCursor;
+ break;
+ case Qt::DragCopyCursor:
+ type = QCursorData::TYPE_ThemeCursor;
+ curs.tc.curs = kThemeCopyArrowCursor;
+ break;
+ case Qt::DragLinkCursor:
+ type = QCursorData::TYPE_ThemeCursor;
+ curs.tc.curs = kThemeAliasArrowCursor;
+ break;
#define QT_USE_APPROXIMATE_CURSORS
#ifdef QT_USE_APPROXIMATE_CURSORS
case Qt::SizeVerCursor:
diff --git a/src/gui/kernel/qcursor_win.cpp b/src/gui/kernel/qcursor_win.cpp
index 6f651d4..ae1c004 100644
--- a/src/gui/kernel/qcursor_win.cpp
+++ b/src/gui/kernel/qcursor_win.cpp
@@ -47,6 +47,7 @@
#include <qimage.h>
#include <qt_windows.h>
+#include <private/qapplication_p.h>
QT_BEGIN_NAMESPACE
@@ -470,6 +471,12 @@ void QCursorData::update()
#endif
return;
}
+ case Qt::DragCopyCursor:
+ case Qt::DragMoveCursor:
+ case Qt::DragLinkCursor: {
+ QPixmap pixmap = QApplicationPrivate::instance()->getPixmapCursor(cshape);
+ hcurs = create32BitCursor(pixmap, hx, hy);
+ }
default:
qWarning("QCursor::update: Invalid cursor shape %d", cshape);
return;
diff --git a/src/gui/kernel/qcursor_x11.cpp b/src/gui/kernel/qcursor_x11.cpp
index 3e83363..4e871a6 100644
--- a/src/gui/kernel/qcursor_x11.cpp
+++ b/src/gui/kernel/qcursor_x11.cpp
@@ -39,9 +39,11 @@
**
****************************************************************************/
+#include <qdebug.h>
#include <qdatastream.h>
#include <private/qcursor_p.h>
#include <private/qt_x11_p.h>
+#include <private/qapplication_p.h>
#include <qbitmap.h>
#include <qcursor.h>
#include <X11/cursorfont.h>
@@ -57,6 +59,7 @@
#endif // QT_NO_XFIXES
#include "qx11info_x11.h"
+#include <private/qpixmap_x11_p.h>
QT_BEGIN_NAMESPACE
@@ -262,12 +265,31 @@ void QCursorData::update()
"whats_this",
"left_ptr_watch",
"openhand",
- "closedhand"
+ "closedhand",
+ "copy",
+ "move",
+ "link"
};
#ifndef QT_NO_XCURSOR
- if (X11->ptrXcursorLibraryLoadCursor)
- hcurs = X11->ptrXcursorLibraryLoadCursor(dpy, cursorNames[cshape]);
+ if (X11->ptrXcursorLibraryLoadCursor) {
+ // special case for non-standard dnd-* cursors
+ switch (cshape) {
+ case Qt::DragCopyCursor:
+ hcurs = X11->ptrXcursorLibraryLoadCursor(dpy, "dnd-copy");
+ break;
+ case Qt::DragMoveCursor:
+ hcurs = X11->ptrXcursorLibraryLoadCursor(dpy, "dnd-move");
+ break;
+ case Qt::DragLinkCursor:
+ hcurs = X11->ptrXcursorLibraryLoadCursor(dpy, "dnd-link");
+ break;
+ default:
+ break;
+ }
+ if (!hcurs)
+ hcurs = X11->ptrXcursorLibraryLoadCursor(dpy, cursorNames[cshape]);
+ }
if (hcurs)
return;
#endif // QT_NO_XCURSOR
@@ -504,6 +526,19 @@ void QCursorData::update()
pm = XCreateBitmapFromData(dpy, rootwin, open ? openhand_bits : closedhand_bits, 16, 16);
pmm = XCreateBitmapFromData(dpy, rootwin, open ? openhandm_bits : closedhandm_bits, 16, 16);
hcurs = XCreatePixmapCursor(dpy, pm, pmm, &fg, &bg, 8, 8);
+ } else if (cshape == Qt::DragCopyCursor || cshape == Qt::DragMoveCursor
+ || cshape == Qt::DragLinkCursor) {
+ XColor bg, fg;
+ bg.red = 255 << 8;
+ bg.green = 255 << 8;
+ bg.blue = 255 << 8;
+ fg.red = 0;
+ fg.green = 0;
+ fg.blue = 0;
+ QImage image = QApplicationPrivate::instance()->getPixmapCursor(cshape).toImage();
+ pm = QX11PixmapData::createBitmapFromImage(image);
+ pmm = QX11PixmapData::createBitmapFromImage(image.createAlphaMask().convertToFormat(QImage::Format_MonoLSB));
+ hcurs = XCreatePixmapCursor(dpy, pm, pmm, &fg, &bg, 8, 8);
}
if (hcurs)
@@ -577,6 +612,15 @@ void QCursorData::update()
case Qt::BusyCursor:
sh = XC_watch;
break;
+ case Qt::DragCopyCursor:
+ sh = XC_tcross;
+ break;
+ case Qt::DragLinkCursor:
+ sh = XC_center_ptr;
+ break;
+ case Qt::DragMoveCursor:
+ sh = XC_top_left_arrow;
+ break;
#endif /* QT_USE_APPROXIMATE_CURSORS */
default:
qWarning("QCursor::update: Invalid cursor shape %d", cshape);
diff --git a/src/gui/kernel/qdnd.cpp b/src/gui/kernel/qdnd.cpp
index 21438a8..2b3a3d0 100644
--- a/src/gui/kernel/qdnd.cpp
+++ b/src/gui/kernel/qdnd.cpp
@@ -60,204 +60,12 @@
#include "qdebug.h"
#include <ctype.h>
+#include <private/qapplication_p.h>
+
#ifndef QT_NO_DRAGANDDROP
QT_BEGIN_NAMESPACE
-// These pixmaps approximate the images in the Windows User Interface Guidelines.
-
-// XPM
-
-static const char * const move_xpm[] = {
-"11 20 3 1",
-". c None",
-#if defined(Q_WS_WIN)
-"a c #000000",
-"X c #FFFFFF", // Windows cursor is traditionally white
-#else
-"a c #FFFFFF",
-"X c #000000", // X11 cursor is traditionally black
-#endif
-"aa.........",
-"aXa........",
-"aXXa.......",
-"aXXXa......",
-"aXXXXa.....",
-"aXXXXXa....",
-"aXXXXXXa...",
-"aXXXXXXXa..",
-"aXXXXXXXXa.",
-"aXXXXXXXXXa",
-"aXXXXXXaaaa",
-"aXXXaXXa...",
-"aXXaaXXa...",
-"aXa..aXXa..",
-"aa...aXXa..",
-"a.....aXXa.",
-"......aXXa.",
-".......aXXa",
-".......aXXa",
-"........aa."};
-
-#ifdef Q_WS_WIN
-/* XPM */
-static const char * const ignore_xpm[] = {
-"24 30 3 1",
-". c None",
-"a c #000000",
-"X c #FFFFFF",
-"aa......................",
-"aXa.....................",
-"aXXa....................",
-"aXXXa...................",
-"aXXXXa..................",
-"aXXXXXa.................",
-"aXXXXXXa................",
-"aXXXXXXXa...............",
-"aXXXXXXXXa..............",
-"aXXXXXXXXXa.............",
-"aXXXXXXaaaa.............",
-"aXXXaXXa................",
-"aXXaaXXa................",
-"aXa..aXXa...............",
-"aa...aXXa...............",
-"a.....aXXa..............",
-"......aXXa.....XXXX.....",
-".......aXXa..XXaaaaXX...",
-".......aXXa.XaaaaaaaaX..",
-"........aa.XaaaXXXXaaaX.",
-"...........XaaaaX..XaaX.",
-"..........XaaXaaaX..XaaX",
-"..........XaaXXaaaX.XaaX",
-"..........XaaX.XaaaXXaaX",
-"..........XaaX..XaaaXaaX",
-"...........XaaX..XaaaaX.",
-"...........XaaaXXXXaaaX.",
-"............XaaaaaaaaX..",
-".............XXaaaaXX...",
-"...............XXXX....."};
-#endif
-
-/* XPM */
-static const char * const copy_xpm[] = {
-"24 30 3 1",
-". c None",
-"a c #000000",
-"X c #FFFFFF",
-#if defined(Q_WS_WIN) // Windows cursor is traditionally white
-"aa......................",
-"aXa.....................",
-"aXXa....................",
-"aXXXa...................",
-"aXXXXa..................",
-"aXXXXXa.................",
-"aXXXXXXa................",
-"aXXXXXXXa...............",
-"aXXXXXXXXa..............",
-"aXXXXXXXXXa.............",
-"aXXXXXXaaaa.............",
-"aXXXaXXa................",
-"aXXaaXXa................",
-"aXa..aXXa...............",
-"aa...aXXa...............",
-"a.....aXXa..............",
-"......aXXa..............",
-".......aXXa.............",
-".......aXXa.............",
-"........aa...aaaaaaaaaaa",
-#else
-"XX......................",
-"XaX.....................",
-"XaaX....................",
-"XaaaX...................",
-"XaaaaX..................",
-"XaaaaaX.................",
-"XaaaaaaX................",
-"XaaaaaaaX...............",
-"XaaaaaaaaX..............",
-"XaaaaaaaaaX.............",
-"XaaaaaaXXXX.............",
-"XaaaXaaX................",
-"XaaXXaaX................",
-"XaX..XaaX...............",
-"XX...XaaX...............",
-"X.....XaaX..............",
-"......XaaX..............",
-".......XaaX.............",
-".......XaaX.............",
-"........XX...aaaaaaaaaaa",
-#endif
-".............aXXXXXXXXXa",
-".............aXXXXXXXXXa",
-".............aXXXXaXXXXa",
-".............aXXXXaXXXXa",
-".............aXXaaaaaXXa",
-".............aXXXXaXXXXa",
-".............aXXXXaXXXXa",
-".............aXXXXXXXXXa",
-".............aXXXXXXXXXa",
-".............aaaaaaaaaaa"};
-
-/* XPM */
-static const char * const link_xpm[] = {
-"24 30 3 1",
-". c None",
-"a c #000000",
-"X c #FFFFFF",
-#if defined(Q_WS_WIN) // Windows cursor is traditionally white
-"aa......................",
-"aXa.....................",
-"aXXa....................",
-"aXXXa...................",
-"aXXXXa..................",
-"aXXXXXa.................",
-"aXXXXXXa................",
-"aXXXXXXXa...............",
-"aXXXXXXXXa..............",
-"aXXXXXXXXXa.............",
-"aXXXXXXaaaa.............",
-"aXXXaXXa................",
-"aXXaaXXa................",
-"aXa..aXXa...............",
-"aa...aXXa...............",
-"a.....aXXa..............",
-"......aXXa..............",
-".......aXXa.............",
-".......aXXa.............",
-"........aa...aaaaaaaaaaa",
-#else
-"XX......................",
-"XaX.....................",
-"XaaX....................",
-"XaaaX...................",
-"XaaaaX..................",
-"XaaaaaX.................",
-"XaaaaaaX................",
-"XaaaaaaaX...............",
-"XaaaaaaaaX..............",
-"XaaaaaaaaaX.............",
-"XaaaaaaXXXX.............",
-"XaaaXaaX................",
-"XaaXXaaX................",
-"XaX..XaaX...............",
-"XX...XaaX...............",
-"X.....XaaX..............",
-"......XaaX..............",
-".......XaaX.............",
-".......XaaX.............",
-"........XX...aaaaaaaaaaa",
-#endif
-".............aXXXXXXXXXa",
-".............aXXXaaaaXXa",
-".............aXXXXaaaXXa",
-".............aXXXaaaaXXa",
-".............aXXaaaXaXXa",
-".............aXXaaXXXXXa",
-".............aXXaXXXXXXa",
-".............aXXXaXXXXXa",
-".............aXXXXXXXXXa",
-".............aaaaaaaaaaa"};
-
#ifndef QT_NO_DRAGANDDROP
//#define QDND_DEBUG
@@ -326,22 +134,9 @@ QDragManager::QDragManager()
{
Q_ASSERT(!instance);
-#ifdef Q_WS_WIN
- n_cursor = 4;
-#else
- n_cursor = 3;
-#endif
-
#ifdef Q_WS_QWS
currentActionForOverrideCursor = Qt::IgnoreAction;
#endif
- pm_cursor = new QPixmap[n_cursor];
- pm_cursor[0] = QPixmap((const char **)move_xpm);
- pm_cursor[1] = QPixmap((const char **)copy_xpm);
- pm_cursor[2] = QPixmap((const char **)link_xpm);
-#ifdef Q_WS_WIN
- pm_cursor[3] = QPixmap((const char **)ignore_xpm);
-#endif
object = 0;
beingCancelled = false;
restoreCursor = false;
@@ -362,7 +157,6 @@ QDragManager::~QDragManager()
QApplication::restoreOverrideCursor();
#endif
instance = 0;
- delete [] pm_cursor;
delete dropData;
}
@@ -379,14 +173,14 @@ QPixmap QDragManager::dragCursor(Qt::DropAction action) const
if (d && d->customCursors.contains(action))
return d->customCursors[action];
else if (action == Qt::MoveAction)
- return pm_cursor[0];
+ return QApplicationPrivate::instance()->getPixmapCursor(Qt::DragMoveCursor);
else if (action == Qt::CopyAction)
- return pm_cursor[1];
+ return QApplicationPrivate::instance()->getPixmapCursor(Qt::DragCopyCursor);
else if (action == Qt::LinkAction)
- return pm_cursor[2];
+ return QApplicationPrivate::instance()->getPixmapCursor(Qt::DragLinkCursor);
#ifdef Q_WS_WIN
else if (action == Qt::IgnoreAction)
- return pm_cursor[3];
+ return QApplicationPrivate::instance()->getPixmapCursor(Qt::ForbiddenCursor);
#endif
return QPixmap();
}
diff --git a/src/gui/kernel/qdnd_p.h b/src/gui/kernel/qdnd_p.h
index d70b983..033e6a6 100644
--- a/src/gui/kernel/qdnd_p.h
+++ b/src/gui/kernel/qdnd_p.h
@@ -261,8 +261,6 @@ public:
#endif
private:
- QPixmap *pm_cursor;
- int n_cursor;
#ifdef Q_WS_QWS
Qt::DropAction currentActionForOverrideCursor;
#endif
diff --git a/src/gui/kernel/qdnd_x11.cpp b/src/gui/kernel/qdnd_x11.cpp
index 33968bd..9591b9a 100644
--- a/src/gui/kernel/qdnd_x11.cpp
+++ b/src/gui/kernel/qdnd_x11.cpp
@@ -1340,9 +1340,9 @@ void QDragManager::updateCursor()
if (!noDropCursor) {
#ifndef QT_NO_CURSOR
noDropCursor = new QCursor(Qt::ForbiddenCursor);
- moveCursor = new QCursor(dragCursor(Qt::MoveAction), 0,0);
- copyCursor = new QCursor(dragCursor(Qt::CopyAction), 0,0);
- linkCursor = new QCursor(dragCursor(Qt::LinkAction), 0,0);
+ moveCursor = new QCursor(Qt::DragMoveCursor);
+ copyCursor = new QCursor(Qt::DragCopyCursor);
+ linkCursor = new QCursor(Qt::DragLinkCursor);
#endif
}
diff --git a/src/gui/kernel/qeventdispatcher_mac.mm b/src/gui/kernel/qeventdispatcher_mac.mm
index c7c7caf..c7d042d 100644
--- a/src/gui/kernel/qeventdispatcher_mac.mm
+++ b/src/gui/kernel/qeventdispatcher_mac.mm
@@ -90,11 +90,16 @@
#ifndef QT_NO_THREAD
# include "qmutex.h"
+#endif
QT_BEGIN_NAMESPACE
QT_USE_NAMESPACE
-#endif
+
+/*****************************************************************************
+ Internal variables and functions
+ *****************************************************************************/
+bool qt_blockCocoaSettingModalWindowLevel = false;
/*****************************************************************************
Externals
@@ -540,6 +545,12 @@ bool QEventDispatcherMac::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(QEventDispatcherMac);
d->interrupt = false;
+
+#ifdef QT_MAC_USE_COCOA
+ bool interruptLater = false;
+ QtMacInterruptDispatcherHelp::cancelInterruptLater();
+#endif
+
// In case we end up recursing while we now process events, make sure
// that we send remaining posted Qt events before this call returns:
wakeUp();
@@ -554,25 +565,25 @@ bool QEventDispatcherMac::processEvents(QEventLoop::ProcessEventsFlags flags)
QMacCocoaAutoReleasePool pool;
NSEvent* event = 0;
- // If Qt is used as a plugin, or just added into a native cocoa
- // application, we should not run or stop NSApplication;
- // This will be done from outside Qt.
- // And if processEvents is called manually (rather than from QEventLoop), we
- // cannot enter a tight loop and block the call, but instead return after one flush:
- bool canExec_3rdParty = d->nsAppRunCalledByQt || ![NSApp isRunning];
- bool canExec_Qt = flags & QEventLoop::DialogExec || flags & QEventLoop::EventLoopExec;
+ // If Qt is used as a plugin, or as an extension in a native cocoa
+ // application, we should not run or stop NSApplication; This will be
+ // done from the application itself. And if processEvents is called
+ // manually (rather than from a QEventLoop), we cannot enter a tight
+ // loop and block this call, but instead we need to return after one flush:
+ const bool canExec_3rdParty = d->nsAppRunCalledByQt || ![NSApp isRunning];
+ const bool canExec_Qt = flags & QEventLoop::DialogExec || flags & QEventLoop::EventLoopExec;
if (canExec_Qt && canExec_3rdParty) {
// We can use exec-mode, meaning that we can stay in a tight loop until
- // interrupted. This is mostly an optimization, but it also allow us
- // to use [NSApp run], which is the recommended way of running applications
- // in cocoa. [NSApp run] should be called at least once for any cocoa app.
+ // interrupted. This is mostly an optimization, but it allow us to use
+ // [NSApp run], which is the normal code path for cocoa applications.
if (NSModalSession session = d->currentModalSession()) {
QBoolBlocker execGuard(d->currentExecIsNSAppRun, false);
while ([NSApp runModalSession:session] == NSRunContinuesResponse && !d->interrupt)
qt_mac_waitForMoreModalSessionEvents();
+
if (!d->interrupt && session == d->currentModalSessionCached) {
- // INVARIANT: Someone called e.g. [NSApp stopModal:] from outside the event
+ // Someone called [NSApp stopModal:] from outside the event
// dispatcher (e.g to stop a native dialog). But that call wrongly stopped
// 'session' as well. As a result, we need to restart all internal sessions:
d->temporarilyStopAllModalSessions();
@@ -583,54 +594,63 @@ bool QEventDispatcherMac::processEvents(QEventLoop::ProcessEventsFlags flags)
[NSApp run];
}
retVal = true;
- } else do {
- // INVARIANT: We cannot block the thread (and run in a tight loop).
+ } else {
+ // We cannot block the thread (and run in a tight loop).
// Instead we will process all current pending events and return.
- bool mustRelease = false;
-
- if (!(flags & QEventLoop::ExcludeUserInputEvents) && !d->queuedUserInputEvents.isEmpty()) {
- // Process a pending user input event
- mustRelease = true;
- event = static_cast<NSEvent *>(d->queuedUserInputEvents.takeFirst());
- } else {
- if (NSModalSession session = d->currentModalSession()) {
- if (flags & QEventLoop::WaitForMoreEvents)
- qt_mac_waitForMoreModalSessionEvents();
- NSInteger status = [NSApp runModalSession:session];
- if (status != NSRunContinuesResponse && session == d->currentModalSessionCached) {
- // INVARIANT: Someone called e.g. [NSApp stopModal:] from outside the event
- // dispatcher (e.g to stop a native dialog). But that call wrongly stopped
- // 'session' as well. As a result, we need to restart all internal sessions:
- d->temporarilyStopAllModalSessions();
- }
- retVal = true;
- break;
+ d->ensureNSAppInitialized();
+ do {
+ bool releaseEvent = false;
+
+ if (!(flags & QEventLoop::ExcludeUserInputEvents)
+ && !d->queuedUserInputEvents.isEmpty()) {
+ // Process a pending user input event
+ releaseEvent = true;
+ event = static_cast<NSEvent *>(d->queuedUserInputEvents.takeFirst());
} else {
- event = [NSApp nextEventMatchingMask:NSAnyEventMask
- untilDate:nil
- inMode:NSDefaultRunLoopMode
- dequeue: YES];
-
- if (event != nil) {
- if (flags & QEventLoop::ExcludeUserInputEvents) {
- if (IsMouseOrKeyEvent(event)) {
- // retain event here?
- [event retain];
- d->queuedUserInputEvents.append(event);
- continue;
+ if (NSModalSession session = d->currentModalSession()) {
+ if (flags & QEventLoop::WaitForMoreEvents)
+ qt_mac_waitForMoreModalSessionEvents();
+ NSInteger status = [NSApp runModalSession:session];
+ if (status != NSRunContinuesResponse && session == d->currentModalSessionCached) {
+ // INVARIANT: Someone called [NSApp stopModal:] from outside the event
+ // dispatcher (e.g to stop a native dialog). But that call wrongly stopped
+ // 'session' as well. As a result, we need to restart all internal sessions:
+ d->temporarilyStopAllModalSessions();
+ }
+ retVal = true;
+ break;
+ } else {
+ event = [NSApp nextEventMatchingMask:NSAnyEventMask
+ untilDate:nil
+ inMode:NSDefaultRunLoopMode
+ dequeue: YES];
+
+ if (event != nil) {
+ if (flags & QEventLoop::ExcludeUserInputEvents) {
+ if (IsMouseOrKeyEvent(event)) {
+ [event retain];
+ d->queuedUserInputEvents.append(event);
+ continue;
+ }
}
}
}
}
- }
- if (event) {
- if (!filterEvent(event) && qt_mac_send_event(flags, event, 0))
- retVal = true;
- if (mustRelease)
- [event release];
- }
- } while(!d->interrupt && event != nil);
-
+ if (event) {
+ if (!filterEvent(event) && qt_mac_send_event(flags, event, 0))
+ retVal = true;
+ if (releaseEvent)
+ [event release];
+ }
+ } while (!d->interrupt && event != nil);
+
+ // Since the window that holds modality might have changed while processing
+ // events, we we need to interrupt when we return back the previous process
+ // event recursion to ensure that we spin the correct modal session.
+ // We do the interruptLater at the end of the function to ensure that we don't
+ // disturb the 'wait for more events' below (as deleteLater will post an event):
+ interruptLater = true;
+ }
#else
do {
EventRef event;
@@ -682,25 +702,19 @@ bool QEventDispatcherMac::processEvents(QEventLoop::ProcessEventsFlags flags)
}
}
+ // If we're interrupted, we need to interrupt the _current_
+ // recursion as well to check if it is still supposed to be
+ // executing. This way we wind down the stack until we land
+ // on a recursion that again calls processEvents (typically
+ // from QEventLoop), and set interrupt to false:
+ if (d->interrupt)
+ interrupt();
+
#ifdef QT_MAC_USE_COCOA
- // In case we _now_ process events using [NSApp run], we need to stop it to
- // ensure that:
- // 1. the QEventLoop that called us is still executing, or
- // 2. we have a modal session that needs to be spun instead.
- // In case this is a plain call to processEvents (perhaps from a loop)
- // from the application (rather than from a QEventLoop), we delay the
- // interrupting until we/ actually enter a lower loop level (hence the
- // deffered delete of the object below):
- QtMacInterruptDispatcherHelp::interruptLater();
+ if (interruptLater)
+ QtMacInterruptDispatcherHelp::interruptLater();
#endif
- if (d->interrupt) {
- // We should continue to leave all recursion to processEvents until
- // processEvents is called again (e.g. from a QEventLoop that
- // was not yet told to quit:
- interrupt();
- }
-
return retVal;
}
@@ -729,39 +743,60 @@ void QEventDispatcherMac::flush()
*****************************************************************************/
MacTimerHash QEventDispatcherMacPrivate::macTimerHash;
bool QEventDispatcherMacPrivate::blockSendPostedEvents = false;
+bool QEventDispatcherMacPrivate::interrupt = false;
#ifdef QT_MAC_USE_COCOA
QStack<QCocoaModalSessionInfo> QEventDispatcherMacPrivate::cocoaModalSessionStack;
bool QEventDispatcherMacPrivate::currentExecIsNSAppRun = false;
+bool QEventDispatcherMacPrivate::modalSessionsTemporarilyStopped = false;
bool QEventDispatcherMacPrivate::nsAppRunCalledByQt = false;
+bool QEventDispatcherMacPrivate::cleanupModalSessionsNeeded = false;
NSModalSession QEventDispatcherMacPrivate::currentModalSessionCached = 0;
-int QEventDispatcherMacPrivate::activeModalSessionCount()
+void QEventDispatcherMacPrivate::ensureNSAppInitialized()
{
- // Returns the number of modal sessions created
- // (and not just pushed onto the stack, pending to be created)
- int count = 0;
- for (int i=cocoaModalSessionStack.size()-1; i>=0; --i) {
- QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
- if (info.session)
- ++count;
- }
- return count;
+ // Some elements in Cocoa require NSApplication to be running before
+ // they get fully initialized, in particular the menu bar. This
+ // function is intended for cases where a dialog is told to execute before
+ // QApplication::exec is called, or the application spins the events loop
+ // manually rather than calling QApplication:exec.
+ // The function makes sure that NSApplication starts running, but stops
+ // it again as soon as the send posted events callback is called. That way
+ // we let Cocoa finish the initialization it seems to need. We'll only
+ // apply this trick at most once for any application, and we avoid doing it
+ // for the common case where main just starts QApplication::exec.
+ if (nsAppRunCalledByQt || [NSApp isRunning])
+ return;
+ nsAppRunCalledByQt = true;
+ QBoolBlocker block1(interrupt, true);
+ QBoolBlocker block2(currentExecIsNSAppRun, true);
+ [NSApp run];
}
void QEventDispatcherMacPrivate::temporarilyStopAllModalSessions()
{
- // Stop all created modal session, and as such, make then
- // pending again. The next call to currentModalSession will
- // recreate the session on top again:
+ // Flush, and Stop, all created modal session, and as
+ // such, make them pending again. The next call to
+ // currentModalSession will recreate them again. The
+ // reason to stop all session like this is that otherwise
+ // a call [NSApp stop] would not stop NSApp, but rather
+ // the current modal session. So if we need to stop NSApp
+ // we need to stop all the modal session first. To avoid changing
+ // the stacking order of the windows while doing so, we put
+ // up a block that is used in QCocoaWindow and QCocoaPanel:
+ QBoolBlocker block1(blockSendPostedEvents, true);
+ QBoolBlocker block2(qt_blockCocoaSettingModalWindowLevel, true);
+
int stackSize = cocoaModalSessionStack.size();
for (int i=stackSize-1; i>=0; --i) {
QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
if (info.session) {
+ [NSApp runModalSession:info.session];
[NSApp endModalSession:info.session];
info.session = 0;
}
}
+ modalSessionsTemporarilyStopped = true;
currentModalSessionCached = 0;
}
@@ -775,23 +810,6 @@ NSModalSession QEventDispatcherMacPrivate::currentModalSession()
if (cocoaModalSessionStack.isEmpty())
return 0;
- // Since this code will end up calling our Qt event handler
- // (also from beginModalSessionForWindow), we need to block
- // that to avoid side effects of events beeing delivered:
- QBoolBlocker block(blockSendPostedEvents, true);
-
- if (![NSApp isRunning]) {
- // Sadly, we need to introduce this little event flush
- // to stop dialogs from blinking/poping in front if a
- // modal session restart was needed:
- while (NSEvent *event = [NSApp nextEventMatchingMask:0
- untilDate:nil
- inMode:NSDefaultRunLoopMode
- dequeue: YES]) {
- qt_mac_send_event(0, event, 0);
- }
- }
-
int sessionCount = cocoaModalSessionStack.size();
for (int i=0; i<sessionCount; ++i) {
QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
@@ -804,11 +822,28 @@ NSModalSession QEventDispatcherMacPrivate::currentModalSession()
NSWindow *window = qt_mac_window_for(info.widget);
if (!window)
continue;
+
+ ensureNSAppInitialized();
+ QBoolBlocker block1(blockSendPostedEvents, true);
info.session = [NSApp beginModalSessionForWindow:window];
}
currentModalSessionCached = info.session;
}
+ if (modalSessionsTemporarilyStopped && currentModalSessionCached) {
+ // After a call to temporarilyStopAllModalSessions, cocoa have
+ // now posted events to restore ended modal session windows to
+ // the correct window level. Those events will be processed
+ // _after_ our new calls to beginModalSessionForWindow have
+ // taken effect, which will end up stacking the windows wrong on
+ // screen. To work around this, we block cocoa from changing the
+ // stacking order of the windows, and flush out the pending events
+ // (the block is used in QCocoaWindow and QCocoaPanel):
+ QBoolBlocker block1(blockSendPostedEvents, true);
+ QBoolBlocker block2(qt_blockCocoaSettingModalWindowLevel, true);
+ [NSApp runModalSession:currentModalSessionCached];
+ }
+ modalSessionsTemporarilyStopped = false;
return currentModalSessionCached;
}
@@ -844,6 +879,34 @@ void QEventDispatcherMacPrivate::updateChildrenWorksWhenModal()
}
}
+void QEventDispatcherMacPrivate::cleanupModalSessions()
+{
+ // Go through the list of modal sessions, and end those
+ // that no longer has a widget assosiated; no widget means
+ // the the session has logically ended. The reason we wait like
+ // this to actually end the sessions for real (rather than at the
+ // point they were marked as stopped), is that ending a session
+ // when no other session runs below it on the stack will make cocoa
+ // drop some events on the floor.
+ QMacCocoaAutoReleasePool pool;
+ int stackSize = cocoaModalSessionStack.size();
+
+ for (int i=stackSize-1; i>=0; --i) {
+ QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
+ if (info.widget) {
+ currentModalSessionCached = info.session;
+ break;
+ }
+ cocoaModalSessionStack.remove(i);
+ currentModalSessionCached = 0;
+ if (info.session)
+ [NSApp endModalSession:info.session];
+ }
+
+ updateChildrenWorksWhenModal();
+ cleanupModalSessionsNeeded = false;
+}
+
void QEventDispatcherMacPrivate::beginModalSession(QWidget *widget)
{
// Add a new, empty (null), NSModalSession to the stack.
@@ -852,7 +915,7 @@ void QEventDispatcherMacPrivate::beginModalSession(QWidget *widget)
// is non-zero, and the session pointer is zero (it will become active upon a call to
// currentModalSession). A QCocoaModalSessionInfo is considered pending to be stopped if
// the widget pointer is zero, and the session pointer is non-zero (it will be fully
- // stopped in endModalSession().
+ // stopped in cleanupModalSessions()).
QCocoaModalSessionInfo info = {widget, 0};
cocoaModalSessionStack.push(info);
updateChildrenWorksWhenModal();
@@ -869,38 +932,21 @@ void QEventDispatcherMacPrivate::endModalSession(QWidget *widget)
int stackSize = cocoaModalSessionStack.size();
for (int i=stackSize-1; i>=0; --i) {
QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
- if (info.widget == widget)
+ if (info.widget == widget) {
info.widget = 0;
- }
-
- // Now we stop, and remove, all sessions marked as pending
- // to be stopped on _top_ of the stack, if any:
- bool needToInterruptEventDispatcher = false;
- bool needToUpdateChildrenWorksWhenModal = false;
-
- for (int i=stackSize-1; i>=0; --i) {
- QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
- if (info.widget)
- break;
- cocoaModalSessionStack.remove(i);
- needToUpdateChildrenWorksWhenModal = true;
- currentModalSessionCached = 0;
- if (info.session) {
- [NSApp endModalSession:info.session];
- needToInterruptEventDispatcher = true;
+ if (i == stackSize-1) {
+ // The top sessions ended. Interrupt the event dispatcher
+ // to start spinning the correct session immidiatly:
+ cleanupModalSessionsNeeded = true;
+ QEventDispatcherMac::instance()->interrupt();
+ }
}
}
-
- if (needToUpdateChildrenWorksWhenModal)
- updateChildrenWorksWhenModal();
- if (needToInterruptEventDispatcher)
- QEventDispatcherMac::instance()->interrupt();
}
#endif
QEventDispatcherMacPrivate::QEventDispatcherMacPrivate()
- : interrupt(false)
{
}
@@ -959,13 +1005,39 @@ Boolean QEventDispatcherMacPrivate::postedEventSourceEqualCallback(const void *i
inline static void processPostedEvents(QEventDispatcherMacPrivate *const d, const bool blockSendPostedEvents)
{
- if (blockSendPostedEvents || d->interrupt) {
+ if (blockSendPostedEvents) {
+ // We're told to not send posted events (because the event dispatcher
+ // is currently working on setting up the correct session to run). But
+ // we still need to make sure that we don't fall asleep until pending events
+ // are sendt, so we just signal this need, and return:
CFRunLoopSourceSignal(d->postedEventsSource);
- } else {
- if (!d->threadData->canWait || (d->serialNumber != d->lastSerial)) {
- d->lastSerial = d->serialNumber;
- QApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
+ return;
+ }
+
+#ifdef QT_MAC_USE_COCOA
+ if (d->cleanupModalSessionsNeeded)
+ d->cleanupModalSessions();
+#endif
+
+ if (d->interrupt) {
+#ifdef QT_MAC_USE_COCOA
+ if (d->currentExecIsNSAppRun) {
+ // The event dispatcher has been interrupted. But since
+ // [NSApplication run] is running the event loop, we
+ // delayed stopping it until now (to let cocoa process
+ // pending cocoa events first).
+ if (d->currentModalSessionCached)
+ d->temporarilyStopAllModalSessions();
+ [NSApp stop:NSApp];
+ d->cancelWaitForMoreEvents();
}
+#endif
+ return;
+ }
+
+ if (!d->threadData->canWait || (d->serialNumber != d->lastSerial)) {
+ d->lastSerial = d->serialNumber;
+ QApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
}
}
@@ -975,6 +1047,9 @@ void QEventDispatcherMacPrivate::firstLoopEntry(CFRunLoopObserverRef ref,
{
Q_UNUSED(ref);
Q_UNUSED(activity);
+#ifdef QT_MAC_USE_COCOA
+ QApplicationPrivate::qt_initAfterNSAppStarted();
+#endif
processPostedEvents(static_cast<QEventDispatcherMacPrivate *>(info), blockSendPostedEvents);
}
@@ -983,6 +1058,19 @@ void QEventDispatcherMacPrivate::postedEventsSourcePerformCallback(void *info)
processPostedEvents(static_cast<QEventDispatcherMacPrivate *>(info), blockSendPostedEvents);
}
+#ifdef QT_MAC_USE_COCOA
+void QEventDispatcherMacPrivate::cancelWaitForMoreEvents()
+{
+ // In case the event dispatcher is waiting for more
+ // events somewhere, we post a dummy event to wake it up:
+ QMacCocoaAutoReleasePool pool;
+ static const short NSAppShouldStopForQt = SHRT_MAX;
+ [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined location:NSZeroPoint
+ modifierFlags:0 timestamp:0. windowNumber:0 context:0
+ subtype:NSAppShouldStopForQt data1:0 data2:0] atStart:NO];
+}
+#endif
+
void QEventDispatcherMac::interrupt()
{
Q_D(QEventDispatcherMac);
@@ -992,20 +1080,14 @@ void QEventDispatcherMac::interrupt()
#ifndef QT_MAC_USE_COCOA
CFRunLoopStop(mainRunLoop());
#else
- QMacCocoaAutoReleasePool pool;
- // In case we wait for more events inside
- // processEvents (or NSApp run), post a dummy to wake it up:
- static const short NSAppShouldStopForQt = SHRT_MAX;
- [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined location:NSZeroPoint
- modifierFlags:0 timestamp:0. windowNumber:0 context:0
- subtype:NSAppShouldStopForQt data1:0 data2:0] atStart:NO];
-
- if (d->activeModalSessionCount() == 0) {
- // We should only stop NSApp if we actually started it (and
- // not some 3rd party application, e.g. if we are a plugin).
- if (d->nsAppRunCalledByQt)
- [NSApp stop:NSApp];
- }
+ // We do nothing more here than setting d->interrupt = true, and
+ // poke the event loop if it is sleeping. Actually stopping
+ // NSApp, or the current modal session, is done inside the send
+ // posted events callback. We do this to ensure that all current pending
+ // cocoa events gets delivered before we stop. Otherwise, if we now stop
+ // the last event loop recursion, cocoa will just drop pending posted
+ // events on the floor before we get a chance to reestablish a new session.
+ d->cancelWaitForMoreEvents();
#endif
}
@@ -1046,17 +1128,18 @@ QEventDispatcherMac::~QEventDispatcherMac()
CFRelease(d->firstTimeObserver);
}
-/////////////////////////////////////////////////////////////////////////////
-
#ifdef QT_MAC_USE_COCOA
QtMacInterruptDispatcherHelp* QtMacInterruptDispatcherHelp::instance = 0;
QtMacInterruptDispatcherHelp::QtMacInterruptDispatcherHelp() : cancelled(false)
{
- // This is the whole point of encapsulation this code
- // inside a class; we can make the code (inside destructor)
- // execute on lower loop level:
+ // The whole point of this class is that we enable a way to interrupt
+ // the event dispatcher when returning back to a lower recursion level
+ // than where interruptLater was called. This is needed to detect if
+ // [NSApp run] should still be running at the recursion level it is at.
+ // Since the interrupt is canceled if processEvents is called before
+ // this object gets deleted, we also avoid interrupting unnecessary.
deleteLater();
}
@@ -1064,34 +1147,26 @@ QtMacInterruptDispatcherHelp::~QtMacInterruptDispatcherHelp()
{
if (cancelled)
return;
-
instance = 0;
-
- if (QEventDispatcherMacPrivate::currentExecIsNSAppRun) {
- int activeCount = QEventDispatcherMacPrivate::activeModalSessionCount();
- if (activeCount > 0) {
- // The problem we now have hit: [NSApp stop] will not stop NSApp
- // if a session is active; it will stop the session instead.
- // So to stop NSApp, we need to temporarily stop all the
- // sessions, then stop NSApp, then restart the session on top again.
- // We need to do this to ensure that we're not stuck inside
- // [NSApp run] when we really should be running a modal session:
- QEventDispatcherMacPrivate::temporarilyStopAllModalSessions();
- }
- }
- // Always interrupt once more in case the modal session stack changed
- // while processEvents was called manually from within the application:
QEventDispatcherMac::instance()->interrupt();
}
-void QtMacInterruptDispatcherHelp::interruptLater() {
- if (instance) {
- instance->cancelled = true;
- delete instance;
- }
+void QtMacInterruptDispatcherHelp::cancelInterruptLater()
+{
+ if (!instance)
+ return;
+ instance->cancelled = true;
+ delete instance;
+ instance = 0;
+}
+
+void QtMacInterruptDispatcherHelp::interruptLater()
+{
+ cancelInterruptLater();
instance = new QtMacInterruptDispatcherHelp;
}
#endif
QT_END_NAMESPACE
+
diff --git a/src/gui/kernel/qeventdispatcher_mac_p.h b/src/gui/kernel/qeventdispatcher_mac_p.h
index a335f16..e932532 100644
--- a/src/gui/kernel/qeventdispatcher_mac_p.h
+++ b/src/gui/kernel/qeventdispatcher_mac_p.h
@@ -174,13 +174,17 @@ public:
static QStack<QCocoaModalSessionInfo> cocoaModalSessionStack;
static bool currentExecIsNSAppRun;
static bool nsAppRunCalledByQt;
+ static bool cleanupModalSessionsNeeded;
+ static bool modalSessionsTemporarilyStopped;
static NSModalSession currentModalSessionCached;
- static void updateChildrenWorksWhenModal();
static NSModalSession currentModalSession();
- static int activeModalSessionCount();
+ static void updateChildrenWorksWhenModal();
static void temporarilyStopAllModalSessions();
static void beginModalSession(QWidget *widget);
static void endModalSession(QWidget *widget);
+ static void cancelWaitForMoreEvents();
+ static void cleanupModalSessions();
+ static void ensureNSAppInitialized();
#endif
MacSocketHash macSockets;
@@ -190,7 +194,7 @@ public:
CFRunLoopObserverRef firstTimeObserver;
QAtomicInt serialNumber;
int lastSerial;
- bool interrupt;
+ static bool interrupt;
private:
static Boolean postedEventSourceEqualCallback(const void *info1, const void *info2);
static void postedEventsSourcePerformCallback(void *info);
@@ -211,6 +215,7 @@ class QtMacInterruptDispatcherHelp : public QObject
public:
static void interruptLater();
+ static void cancelInterruptLater();
};
#endif
diff --git a/src/gui/kernel/qguieventdispatcher_glib.cpp b/src/gui/kernel/qguieventdispatcher_glib.cpp
index 7b30741..ac2b5f7 100644
--- a/src/gui/kernel/qguieventdispatcher_glib.cpp
+++ b/src/gui/kernel/qguieventdispatcher_glib.cpp
@@ -216,4 +216,9 @@ void QGuiEventDispatcherGlib::startingUp()
g_source_add_poll(&d->x11EventSource->source, &d->x11EventSource->pollfd);
}
+void QGuiEventDispatcherGlib::flush()
+{
+ XFlush(X11->display);
+}
+
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qguieventdispatcher_glib_p.h b/src/gui/kernel/qguieventdispatcher_glib_p.h
index ff778cc..758650b 100644
--- a/src/gui/kernel/qguieventdispatcher_glib_p.h
+++ b/src/gui/kernel/qguieventdispatcher_glib_p.h
@@ -71,6 +71,7 @@ public:
bool processEvents(QEventLoop::ProcessEventsFlags flags);
void startingUp();
+ void flush();
};
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qkeysequence.cpp b/src/gui/kernel/qkeysequence.cpp
index 2a13546..99bf971 100644
--- a/src/gui/kernel/qkeysequence.cpp
+++ b/src/gui/kernel/qkeysequence.cpp
@@ -861,6 +861,8 @@ QKeySequence::QKeySequence()
Up to four key codes may be entered by separating them with
commas, e.g. "Alt+X,Ctrl+S,Q".
+ \a key should be in NativeText format.
+
This constructor is typically used with \link QObject::tr() tr
\endlink(), so that shortcut keys can be replaced in
translations:
@@ -877,6 +879,16 @@ QKeySequence::QKeySequence(const QString &key)
}
/*!
+ \since 4.x
+ Creates a key sequence from the \a key string based on \a format.
+*/
+QKeySequence::QKeySequence(const QString &key, QKeySequence::SequenceFormat format)
+{
+ d = new QKeySequencePrivate();
+ assign(key, format);
+}
+
+/*!
Constructs a key sequence with up to 4 keys \a k1, \a k2,
\a k3 and \a k4.
@@ -1055,9 +1067,24 @@ QKeySequence QKeySequence::mnemonic(const QString &text)
contain up to four key codes, provided they are separated by a
comma; for example, "Alt+X,Ctrl+S,Z". The return value is the
number of key codes added.
+ \a keys should be in NativeText format.
*/
int QKeySequence::assign(const QString &ks)
{
+ return assign(ks, NativeText);
+}
+
+/*!
+ \fn int QKeySequence::assign(const QString &keys, QKeySequence::SequenceFormat format)
+ \since 4.x
+
+ Adds the given \a keys to the key sequence (based on \a format).
+ \a keys may contain up to four key codes, provided they are
+ separated by a comma; for example, "Alt+X,Ctrl+S,Z". The return
+ value is the number of key codes added.
+*/
+int QKeySequence::assign(const QString &ks, QKeySequence::SequenceFormat format)
+{
QString keyseq = ks;
QString part;
int n = 0;
@@ -1086,7 +1113,7 @@ int QKeySequence::assign(const QString &ks)
}
part = keyseq.left(-1 == p ? keyseq.length() : p - diff);
keyseq = keyseq.right(-1 == p ? 0 : keyseq.length() - (p + 1));
- d->key[n] = decodeString(part);
+ d->key[n] = QKeySequencePrivate::decodeString(part, format);
++n;
}
return n;
@@ -1557,12 +1584,7 @@ QString QKeySequence::toString(SequenceFormat format) const
*/
QKeySequence QKeySequence::fromString(const QString &str, SequenceFormat format)
{
- QStringList sl = str.split(QLatin1String(", "));
- int keys[4] = {0, 0, 0, 0};
- int total = qMin(sl.count(), 4);
- for (int i = 0; i < total; ++i)
- keys[i] = QKeySequencePrivate::decodeString(sl[i], format);
- return QKeySequence(keys[0], keys[1], keys[2], keys[3]);
+ return QKeySequence(str, format);
}
/*****************************************************************************
diff --git a/src/gui/kernel/qkeysequence.h b/src/gui/kernel/qkeysequence.h
index 1409e28..5a973e3 100644
--- a/src/gui/kernel/qkeysequence.h
+++ b/src/gui/kernel/qkeysequence.h
@@ -141,8 +141,14 @@ public:
Quit
};
+ enum SequenceFormat {
+ NativeText,
+ PortableText
+ };
+
QKeySequence();
QKeySequence(const QString &key);
+ QKeySequence(const QString &key, SequenceFormat format);
QKeySequence(int k1, int k2 = 0, int k3 = 0, int k4 = 0);
QKeySequence(const QKeySequence &ks);
QKeySequence(StandardKey key);
@@ -160,11 +166,6 @@ public:
#endif
};
- enum SequenceFormat {
- NativeText,
- PortableText
- };
-
QString toString(SequenceFormat format = PortableText) const;
static QKeySequence fromString(const QString &str, SequenceFormat format = PortableText);
@@ -194,6 +195,7 @@ private:
static int decodeString(const QString &ks);
static QString encodeString(int key);
int assign(const QString &str);
+ int assign(const QString &str, SequenceFormat format);
void setKey(int key, int index);
QKeySequencePrivate *d;
diff --git a/src/gui/kernel/qmime_mac.cpp b/src/gui/kernel/qmime_mac.cpp
index 071f80d..c6fd184 100644
--- a/src/gui/kernel/qmime_mac.cpp
+++ b/src/gui/kernel/qmime_mac.cpp
@@ -154,6 +154,7 @@ CFStringRef qt_mac_mime_typeUTI = CFSTR("com.pasteboard.trolltech.marker");
\i public.url - converts to "text/uri-list"
\i public.file-url - converts to "text/uri-list"
\i public.tiff - converts to "application/x-qt-image"
+ \i public.vcard - converts to "text/plain"
\i com.apple.traditional-mac-plain-text - converts to "text/plain"
\i com.apple.pict - converts to "application/x-qt-image"
\endlist
@@ -909,6 +910,61 @@ QList<QByteArray> QMacPasteboardMimeUrl::convertFromMime(const QString &mime, QV
return ret;
}
+class QMacPasteboardMimeVCard : public QMacPasteboardMime
+{
+public:
+ QMacPasteboardMimeVCard() : QMacPasteboardMime(MIME_ALL){ }
+ QString convertorName();
+
+ QString flavorFor(const QString &mime);
+ QString mimeFor(QString flav);
+ bool canConvert(const QString &mime, QString flav);
+ QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
+ QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
+};
+
+QString QMacPasteboardMimeVCard::convertorName()
+{
+ return QString("VCard");
+}
+
+bool QMacPasteboardMimeVCard::canConvert(const QString &mime, QString flav)
+{
+ return mimeFor(flav) == mime;
+}
+
+QString QMacPasteboardMimeVCard::flavorFor(const QString &mime)
+{
+ if(mime.startsWith(QLatin1String("text/plain")))
+ return QLatin1String("public.vcard");
+ return QString();
+}
+
+QString QMacPasteboardMimeVCard::mimeFor(QString flav)
+{
+ if (flav == QLatin1String("public.vcard"))
+ return QLatin1String("text/plain");
+ return QString();
+}
+
+QVariant QMacPasteboardMimeVCard::convertToMime(const QString &mime, QList<QByteArray> data, QString)
+{
+ QByteArray cards;
+ if (mime == QLatin1String("text/plain")) {
+ for (int i=0; i<data.size(); ++i)
+ cards += data[i];
+ }
+ return QVariant(cards);
+}
+
+QList<QByteArray> QMacPasteboardMimeVCard::convertFromMime(const QString &mime, QVariant data, QString)
+{
+ QList<QByteArray> ret;
+ if (mime == QLatin1String("text/plain"))
+ ret.append(data.toString().toUtf8());
+ return ret;
+}
+
#ifdef QT3_SUPPORT
class QMacPasteboardMimeQt3Any : public QMacPasteboardMime {
private:
@@ -1116,6 +1172,7 @@ void QMacPasteboardMime::initialize()
new QMacPasteboardMimeFileUri;
new QMacPasteboardMimeUrl;
new QMacPasteboardMimeTypeName;
+ new QMacPasteboardMimeVCard;
//make sure our "non-standard" types are always last! --Sam
new QMacPasteboardMimeAny;
#ifdef QT3_SUPPORT
diff --git a/src/gui/kernel/qnsthemeframe_mac_p.h b/src/gui/kernel/qnsthemeframe_mac_p.h
index 77a6963..d061b1b 100644
--- a/src/gui/kernel/qnsthemeframe_mac_p.h
+++ b/src/gui/kernel/qnsthemeframe_mac_p.h
@@ -157,7 +157,7 @@
- (void)resetCursorRects;
- (char)shouldBeTreatedAsInkEvent:fp8;
- (char)_shouldBeTreatedAsInkEventInInactiveWindow:fp8;
-- hitTest:(struct _NSPoint)fp8;
+//- hitTest:(struct _NSPoint)fp8; // collides with hittest in qcocoasharedwindowmethods_mac_p.h
- (NSRect)_leftGroupRect;
- (NSRect)_rightGroupRect;
- (void)_updateWidgets;
diff --git a/src/gui/kernel/qsoftkeymanager_s60.cpp b/src/gui/kernel/qsoftkeymanager_s60.cpp
index af84a8f..8ac1e31 100644
--- a/src/gui/kernel/qsoftkeymanager_s60.cpp
+++ b/src/gui/kernel/qsoftkeymanager_s60.cpp
@@ -66,17 +66,18 @@ QSoftKeyManagerPrivateS60::QSoftKeyManagerPrivateS60()
cachedCbaIconSize[1] = QSize(0,0);
cachedCbaIconSize[2] = QSize(0,0);
cachedCbaIconSize[3] = QSize(0,0);
- skipNextUpdate = false;
}
bool QSoftKeyManagerPrivateS60::skipCbaUpdate()
{
- // lets not update softkeys if
+ // Lets not update softkeys if
// 1. We don't have application panes, i.e. cba
- // 2. S60 native dialog or menu is shown
- if (QApplication::testAttribute(Qt::AA_S60DontConstructApplicationPanes) ||
- CCoeEnv::Static()->AppUi()->IsDisplayingMenuOrDialog() || skipNextUpdate) {
- skipNextUpdate = false;
+ // 2. Our CBA is not active, i.e. S60 native dialog or menu with custom CBA is shown
+ // Note: Cannot use IsDisplayingMenuOrDialog since CBA update can be triggered before
+ // menu/dialog CBA is actually displayed i.e. it is being costructed.
+ CEikButtonGroupContainer *appUiCba = S60->buttonGroupContainer();
+ CEikButtonGroupContainer *currentCba = CEikButtonGroupContainer::Current();
+ if (QApplication::testAttribute(Qt::AA_S60DontConstructApplicationPanes) || appUiCba != currentCba) {
return true;
}
return false;
@@ -384,9 +385,6 @@ bool QSoftKeyManagerPrivateS60::handleCommand(int command)
}
qt_symbian_next_menu_from_action(actionContainer);
QT_TRAP_THROWING(S60->menuBar()->TryDisplayMenuBarL());
- // TODO: hack remove, it can happen that IsDisplayingMenuOrDialog return false
- // in updateSoftKeys_sys, and we will override menu CBA with our own
- skipNextUpdate = true;
} else {
Q_ASSERT(action->softKeyRole() != QAction::NoSoftKey);
QWidget *actionParent = action->parentWidget();
diff --git a/src/gui/kernel/qsoftkeymanager_s60_p.h b/src/gui/kernel/qsoftkeymanager_s60_p.h
index f8bd6d9..823a2db 100644
--- a/src/gui/kernel/qsoftkeymanager_s60_p.h
+++ b/src/gui/kernel/qsoftkeymanager_s60_p.h
@@ -98,7 +98,6 @@ private:
private:
QHash<int, QAction*> realSoftKeyActions;
QSize cachedCbaIconSize[4];
- bool skipNextUpdate;
};
diff --git a/src/gui/kernel/qt_cocoa_helpers_mac.mm b/src/gui/kernel/qt_cocoa_helpers_mac.mm
index 65c04e5..4e51cf4 100644
--- a/src/gui/kernel/qt_cocoa_helpers_mac.mm
+++ b/src/gui/kernel/qt_cocoa_helpers_mac.mm
@@ -1281,6 +1281,21 @@ void qt_cocoaChangeOverrideCursor(const QCursor &cursor)
}
#endif
+@implementation DebugNSApplication {
+}
+- (void)sendEvent:(NSEvent *)event
+{
+ NSLog(@"NSAppDebug: sendEvent: %@", event);
+ return [super sendEvent:event];
+}
+
+- (BOOL)sendAction:(SEL)anAction to:(id)aTarget from:(id)sender
+{
+ NSLog(@"NSAppDebug: sendAction: %s to %@ from %@", anAction, aTarget, sender);
+ return [super sendAction:anAction to:aTarget from:sender];
+}
+@end
+
QMacCocoaAutoReleasePool::QMacCocoaAutoReleasePool()
{
#ifndef QT_MAC_USE_COCOA
diff --git a/src/gui/kernel/qt_cocoa_helpers_mac_p.h b/src/gui/kernel/qt_cocoa_helpers_mac_p.h
index 6f0c4ce..ace8255 100644
--- a/src/gui/kernel/qt_cocoa_helpers_mac_p.h
+++ b/src/gui/kernel/qt_cocoa_helpers_mac_p.h
@@ -181,6 +181,10 @@ inline QString qt_mac_NSStringToQString(const NSString *nsstr)
inline NSString *qt_mac_QStringToNSString(const QString &qstr)
{ return [reinterpret_cast<const NSString *>(QCFString::toCFStringRef(qstr)) autorelease]; }
+
+@interface DebugNSApplication : NSApplication {}
+@end
+
#endif
QT_END_NAMESPACE
diff --git a/src/gui/kernel/qt_x11_p.h b/src/gui/kernel/qt_x11_p.h
index d110084..b2ce754 100644
--- a/src/gui/kernel/qt_x11_p.h
+++ b/src/gui/kernel/qt_x11_p.h
@@ -331,7 +331,7 @@ struct QXdndDropTransaction
class QMimeData;
struct QX11Data;
-extern QX11Data *qt_x11Data;
+extern Q_GUI_EXPORT QX11Data *qt_x11Data;
enum DesktopEnvironment {
DE_UNKNOWN,
diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp
index 2a19d23..d433048 100644
--- a/src/gui/kernel/qwidget.cpp
+++ b/src/gui/kernel/qwidget.cpp
@@ -4876,90 +4876,7 @@ void QWidget::unsetCursor()
void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
const QRegion &sourceRegion, RenderFlags renderFlags)
{
- Q_D(QWidget);
- if (!target) {
- qWarning("QWidget::render: null pointer to paint device");
- return;
- }
-
- const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
- QRegion paintRegion = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
- : sourceRegion;
- if (paintRegion.isEmpty())
- return;
-
-#ifndef Q_WS_MAC
- QPainter *oldSharedPainter = inRenderWithPainter ? d->sharedPainter() : 0;
-
- // Use the target's shared painter if set (typically set when doing
- // "other->render(widget);" in the widget's paintEvent.
- if (target->devType() == QInternal::Widget) {
- QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
- if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
- QPainter *targetPainter = targetPrivate->sharedPainter();
- if (targetPainter && targetPainter->isActive())
- d->setSharedPainter(targetPainter);
- }
- }
-#endif
-
- // Use the target's redirected device if set and adjust offset and paint
- // region accordingly. This is typically the case when people call render
- // from the paintEvent.
- QPoint offset = targetOffset;
- offset -= paintRegion.boundingRect().topLeft();
- QPoint redirectionOffset;
- QPaintDevice *redirected = 0;
-
- if (target->devType() == QInternal::Widget)
- redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
- if (!redirected)
- redirected = QPainter::redirected(target, &redirectionOffset);
-
- if (redirected) {
- target = redirected;
- offset -= redirectionOffset;
- }
-
- if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
- if (QPaintEngine *targetEngine = target->paintEngine()) {
- const QRegion targetSystemClip = targetEngine->systemClip();
- if (!targetSystemClip.isEmpty())
- paintRegion &= targetSystemClip.translated(-offset);
- }
- }
-
- // Set backingstore flags.
- int flags = QWidgetPrivate::DrawPaintOnScreen | QWidgetPrivate::DrawInvisible;
- if (renderFlags & DrawWindowBackground)
- flags |= QWidgetPrivate::DrawAsRoot;
-
- if (renderFlags & DrawChildren)
- flags |= QWidgetPrivate::DrawRecursive;
- else
- flags |= QWidgetPrivate::DontSubtractOpaqueChildren;
-
-#ifdef Q_WS_QWS
- flags |= QWidgetPrivate::DontSetCompositionMode;
-#endif
-
- if (target->devType() == QInternal::Printer) {
- QPainter p(target);
- d->render_helper(&p, targetOffset, paintRegion, renderFlags);
- return;
- }
-
-#ifndef Q_WS_MAC
- // Render via backingstore.
- d->drawWidget(target, paintRegion, offset, flags, d->sharedPainter());
-
- // Restore shared painter.
- if (oldSharedPainter)
- d->setSharedPainter(oldSharedPainter);
-#else
- // Render via backingstore (no shared painter).
- d->drawWidget(target, paintRegion, offset, flags, 0);
-#endif
+ d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
}
/*!
@@ -5405,6 +5322,97 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
}
}
+void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
+ const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
+ bool readyToRender)
+{
+ Q_Q(QWidget);
+ if (!target) {
+ qWarning("QWidget::render: null pointer to paint device");
+ return;
+ }
+
+ const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
+ QRegion paintRegion = !inRenderWithPainter && !readyToRender
+ ? prepareToRender(sourceRegion, renderFlags)
+ : sourceRegion;
+ if (paintRegion.isEmpty())
+ return;
+
+#ifndef Q_WS_MAC
+ QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
+
+ // Use the target's shared painter if set (typically set when doing
+ // "other->render(widget);" in the widget's paintEvent.
+ if (target->devType() == QInternal::Widget) {
+ QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
+ if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
+ QPainter *targetPainter = targetPrivate->sharedPainter();
+ if (targetPainter && targetPainter->isActive())
+ setSharedPainter(targetPainter);
+ }
+ }
+#endif
+
+ // Use the target's redirected device if set and adjust offset and paint
+ // region accordingly. This is typically the case when people call render
+ // from the paintEvent.
+ QPoint offset = targetOffset;
+ offset -= paintRegion.boundingRect().topLeft();
+ QPoint redirectionOffset;
+ QPaintDevice *redirected = 0;
+
+ if (target->devType() == QInternal::Widget)
+ redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
+ if (!redirected)
+ redirected = QPainter::redirected(target, &redirectionOffset);
+
+ if (redirected) {
+ target = redirected;
+ offset -= redirectionOffset;
+ }
+
+ if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
+ if (QPaintEngine *targetEngine = target->paintEngine()) {
+ const QRegion targetSystemClip = targetEngine->systemClip();
+ if (!targetSystemClip.isEmpty())
+ paintRegion &= targetSystemClip.translated(-offset);
+ }
+ }
+
+ // Set backingstore flags.
+ int flags = DrawPaintOnScreen | DrawInvisible;
+ if (renderFlags & QWidget::DrawWindowBackground)
+ flags |= DrawAsRoot;
+
+ if (renderFlags & QWidget::DrawChildren)
+ flags |= DrawRecursive;
+ else
+ flags |= DontSubtractOpaqueChildren;
+
+#ifdef Q_WS_QWS
+ flags |= DontSetCompositionMode;
+#endif
+
+ if (target->devType() == QInternal::Printer) {
+ QPainter p(target);
+ render_helper(&p, targetOffset, paintRegion, renderFlags);
+ return;
+ }
+
+#ifndef Q_WS_MAC
+ // Render via backingstore.
+ drawWidget(target, paintRegion, offset, flags, sharedPainter());
+
+ // Restore shared painter.
+ if (oldSharedPainter)
+ setSharedPainter(oldSharedPainter);
+#else
+ // Render via backingstore (no shared painter).
+ drawWidget(target, paintRegion, offset, flags, 0);
+#endif
+}
+
void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
const QPoint &offset, int flags
#ifdef Q_BACKINGSTORE_SUBSURFACES
@@ -7592,23 +7600,21 @@ bool QWidgetPrivate::close_helper(CloseMode mode)
if (isMain)
QApplication::quit();
#endif
- // Attempt to close the application only if this widget has the
- // WA_QuitOnClose flag set set and has a non-visible parent
- quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible() || parentWidget->testAttribute(Qt::WA_DontShowOnScreen));
+ // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
+ quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
if (quitOnClose) {
- // If there is no non-withdrawn primary window left (except
- // the ones without QuitOnClose or with WA_DontShowOnScreen),
- // we emit the lastWindowClosed signal
+ /* if there is no non-withdrawn primary window left (except
+ the ones without QuitOnClose), we emit the lastWindowClosed
+ signal */
QWidgetList list = QApplication::topLevelWidgets();
bool lastWindowClosed = true;
for (int i = 0; i < list.size(); ++i) {
QWidget *w = list.at(i);
- if ((w->isVisible() && !w->testAttribute(Qt::WA_DontShowOnScreen))
- && !w->parentWidget() && w->testAttribute(Qt::WA_QuitOnClose)) {
- lastWindowClosed = false;
- break;
- }
+ if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
+ continue;
+ lastWindowClosed = false;
+ break;
}
if (lastWindowClosed)
QApplicationPrivate::emitLastWindowClosed();
@@ -8271,7 +8277,7 @@ bool QWidget::event(QEvent *event)
}
#ifdef QT_SOFTKEYS_ENABLED
- if (isWindow() && isActiveWindow())
+ if (isWindow())
QSoftKeyManager::updateSoftKeys();
#endif
diff --git a/src/gui/kernel/qwidget_mac.mm b/src/gui/kernel/qwidget_mac.mm
index 9e7517f..a5633d3 100644
--- a/src/gui/kernel/qwidget_mac.mm
+++ b/src/gui/kernel/qwidget_mac.mm
@@ -1917,13 +1917,15 @@ void QWidgetPrivate::determineWindowClass()
wclass = kDocumentWindowClass;
else if(popup || (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5 && type == Qt::SplashScreen))
wclass = kModalWindowClass;
- else if(q->testAttribute(Qt::WA_ShowModal) || type == Qt::Dialog)
+ else if(type == Qt::Dialog)
wclass = kMovableModalWindowClass;
else if(type == Qt::ToolTip)
wclass = kHelpWindowClass;
else if(type == Qt::Tool || (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5
&& type == Qt::SplashScreen))
wclass = kFloatingWindowClass;
+ else if(q->testAttribute(Qt::WA_ShowModal))
+ wclass = kMovableModalWindowClass;
else
wclass = kDocumentWindowClass;
@@ -2027,8 +2029,6 @@ void QWidgetPrivate::determineWindowClass()
for(int i = 0; tmp_wattr && known_attribs[i].name; i++) {
if((tmp_wattr & known_attribs[i].tag) == known_attribs[i].tag) {
tmp_wattr ^= known_attribs[i].tag;
- qDebug("Qt: internal: * %s %s", known_attribs[i].name,
- (GetAvailableWindowAttributes(wclass) & known_attribs[i].tag) ? "" : "(*)");
}
}
if(tmp_wattr)
@@ -2223,6 +2223,41 @@ void QWidgetPrivate::finishCreateWindow_sys_Carbon(OSWindowRef windowRef)
applyMaxAndMinSizeOnWindow();
}
#else // QT_MAC_USE_COCOA
+
+void QWidgetPrivate::setWindowLevel()
+{
+ Q_Q(QWidget);
+ const QWidget * const windowParent = q->window()->parentWidget();
+ const QWidget * const primaryWindow = windowParent ? windowParent->window() : 0;
+ NSInteger winLevel = -1;
+
+ if (q->windowType() == Qt::Popup) {
+ winLevel = NSPopUpMenuWindowLevel;
+ // Popup should be in at least the same level as its parent.
+ if (primaryWindow) {
+ OSWindowRef parentRef = qt_mac_window_for(primaryWindow);
+ winLevel = qMax([parentRef level], winLevel);
+ }
+ } else if (q->windowType() == Qt::Tool) {
+ winLevel = NSFloatingWindowLevel;
+ } else if (q->windowType() == Qt::Dialog) {
+ // Correct modality level (NSModalPanelWindowLevel) will be
+ // set by cocoa when creating a modal session later.
+ winLevel = NSNormalWindowLevel;
+ }
+
+ // StayOnTop window should appear above Tool windows.
+ if (data.window_flags & Qt::WindowStaysOnTopHint)
+ winLevel = NSPopUpMenuWindowLevel;
+ // Tooltips should appear above StayOnTop windows.
+ if (q->windowType() == Qt::ToolTip)
+ winLevel = NSScreenSaverWindowLevel;
+ // All other types are Normal level.
+ if (winLevel == -1)
+ winLevel = NSNormalWindowLevel;
+ [qt_mac_window_for(q) setLevel:winLevel];
+}
+
void QWidgetPrivate::finishCreateWindow_sys_Cocoa(void * /*NSWindow * */ voidWindowRef)
{
Q_Q(QWidget);
@@ -2295,6 +2330,10 @@ void QWidgetPrivate::finishCreateWindow_sys_Cocoa(void * /*NSWindow * */ voidWin
q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
}
+ if (qApp->overrideCursor())
+ [windowRef disableCursorRects];
+
+ setWindowLevel();
macUpdateHideOnSuspend();
macUpdateOpaqueSizeGrip();
macUpdateIgnoreMouseEvents();
@@ -2725,6 +2764,35 @@ void QWidgetPrivate::transferChildren()
}
}
+#ifdef QT_MAC_USE_COCOA
+void QWidgetPrivate::setSubWindowStacking(bool set)
+{
+ Q_Q(QWidget);
+ if (!q->isWindow() || !q->testAttribute(Qt::WA_WState_Created))
+ return;
+
+ if (QWidget *parent = q->parentWidget()) {
+ if (parent->testAttribute(Qt::WA_WState_Created)) {
+ if (set)
+ [qt_mac_window_for(parent) addChildWindow:qt_mac_window_for(q) ordered:NSWindowAbove];
+ else
+ [qt_mac_window_for(parent) removeChildWindow:qt_mac_window_for(q)];
+ }
+ }
+
+ QList<QWidget *> widgets = q->findChildren<QWidget *>();
+ for (int i=0; i<widgets.size(); ++i) {
+ QWidget *child = widgets.at(i);
+ if (child->isWindow() && child->testAttribute(Qt::WA_WState_Created)) {
+ if (set)
+ [qt_mac_window_for(q) addChildWindow:qt_mac_window_for(child) ordered:NSWindowAbove];
+ else
+ [qt_mac_window_for(q) removeChildWindow:qt_mac_window_for(child)];
+ }
+ }
+}
+#endif
+
void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f)
{
Q_Q(QWidget);
@@ -2879,7 +2947,6 @@ void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f)
current = current->parentWidget();
}
}
-
invalidateBuffer(q->rect());
qt_event_request_window_change(q);
}
@@ -3185,10 +3252,10 @@ void QWidget::activateWindow()
|| windowActive) {
#ifndef QT_MAC_USE_COCOA
ActivateWindow(win, true);
+ qApp->setActiveWindow(tlw);
#else
[win makeKeyWindow];
#endif
- qApp->setActiveWindow(tlw);
} else if(!isMinimized()) {
#ifndef QT_MAC_USE_COCOA
SelectWindow(win);
@@ -3341,13 +3408,23 @@ void QWidgetPrivate::show_sys()
#else
// sync the opacity value back (in case of a fade).
[window setAlphaValue:q->windowOpacity()];
- [window makeKeyAndOrderFront:window];
-
- // If this window is app modal, we need to start spinning
- // a modal session for it. Interrupting
- // the event dispatcher will make this happend:
- if (data.window_modality == Qt::ApplicationModal)
- QEventDispatcherMac::instance()->interrupt();
+ setSubWindowStacking(true);
+
+ QWidget *top = 0;
+ if (QApplicationPrivate::tryModalHelper(q, &top)) {
+ [window makeKeyAndOrderFront:window];
+ // If this window is app modal, we need to start spinning
+ // a modal session for it. Interrupting
+ // the event dispatcher will make this happend:
+ if (data.window_modality == Qt::ApplicationModal)
+ QEventDispatcherMac::instance()->interrupt();
+ } else {
+ // The window is modally shaddowed, so we need to make
+ // sure that we don't pop in front of the modal window:
+ [window orderFront:window];
+ if (NSWindow *modalWin = qt_mac_window_for(top))
+ [modalWin orderFront:window];
+ }
#endif
if (q->windowType() == Qt::Popup) {
if (q->focusWidget())
@@ -3366,8 +3443,6 @@ void QWidgetPrivate::show_sys()
} else if (!q->testAttribute(Qt::WA_ShowWithoutActivating)) {
#ifndef QT_MAC_USE_COCOA
qt_event_request_activate(q);
-#else
- [qt_mac_window_for(q) makeKeyWindow];
#endif
}
} else if(topData()->embedded || !q->parentWidget() || q->parentWidget()->isVisible()) {
@@ -3410,6 +3485,9 @@ void QWidgetPrivate::hide_sys()
QMacCocoaAutoReleasePool pool;
if(q->isWindow()) {
+#ifdef QT_MAC_USE_COCOA
+ setSubWindowStacking(false);
+#endif
OSWindowRef window = qt_mac_window_for(q);
if(qt_mac_is_macsheet(q)) {
#ifndef QT_MAC_USE_COCOA
@@ -3475,12 +3553,15 @@ void QWidgetPrivate::hide_sys()
}
#endif
}
- if(q->isActiveWindow() && !(q->windowType() == Qt::Popup)) {
+#ifndef QT_MAC_USE_COCOA
+ // If the window we now hide was the active window, we need
+ // to find, and activate another window on screen. NB: Cocoa takes care of this
+ // logic for us (and distinquishes between main windows and key windows)
+ if (q->isActiveWindow() && !(q->windowType() == Qt::Popup)) {
QWidget *w = 0;
if(q->parentWidget())
w = q->parentWidget()->window();
if(!w || (!w->isVisible() && !w->isMinimized())) {
-#ifndef QT_MAC_USE_COCOA
for (WindowPtr wp = GetFrontWindowOfClass(kMovableModalWindowClass, true);
wp; wp = GetNextWindowOfClass(wp, kMovableModalWindowClass, true)) {
if((w = qt_mac_find_window(wp)))
@@ -3500,24 +3581,12 @@ void QWidgetPrivate::hide_sys()
break;
}
}
-#else
- NSArray *windows = [NSApp windows];
- NSUInteger totalWindows = [windows count];
- for (NSUInteger i = 0; i < totalWindows; ++i) {
- OSWindowRef wp = [windows objectAtIndex:i];
- if ((w = qt_mac_find_window(wp)))
- break;
- }
-#endif
}
if(w && w->isVisible() && !w->isMinimized()) {
-#ifndef QT_MAC_USE_COCOA
- qt_event_request_activate(w);
-#else
- [qt_mac_window_for(w) makeKeyWindow];
-#endif
+ qt_event_request_activate(w);
}
}
+#endif
} else {
invalidateBuffer(q->rect());
#ifndef QT_MAC_USE_COCOA
@@ -4605,9 +4674,12 @@ void QWidgetPrivate::registerDropSite(bool on)
#ifndef QT_MAC_USE_COCOA
SetControlDragTrackingEnabled(qt_mac_nativeview_for(q), on);
#else
- NSView *view = qt_mac_nativeview_for(q);
- if (on && [view isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]]) {
- [static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view) registerDragTypes];
+ NSWindow *win = qt_mac_window_for(q);
+ if (on) {
+ if ([win isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaWindow) class]])
+ [static_cast<QT_MANGLE_NAMESPACE(QCocoaWindow) *>(win) registerDragTypes];
+ else if ([win isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaPanel) class]])
+ [static_cast<QT_MANGLE_NAMESPACE(QCocoaPanel) *>(win) registerDragTypes];
}
#endif
}
@@ -4761,7 +4833,7 @@ void QWidgetPrivate::setModal_sys()
bool alreadySheet = [windowRef styleMask] & NSDocModalWindowMask;
if (windowParent && q->windowModality() == Qt::WindowModal){
- // Window should be window-modal, which implies a sheet.
+ // INVARIANT: Window should be window-modal (which implies a sheet).
if (!alreadySheet) {
// NB: the following call will call setModal_sys recursivly:
recreateMacWindow();
@@ -4778,47 +4850,19 @@ void QWidgetPrivate::setModal_sys()
[static_cast<NSPanel *>(windowRef) setWorksWhenModal:YES];
}
} else {
- // Window shold not be window-modal, and as such, not a sheet.
+ // INVARIANT: Window shold _not_ be window-modal (and as such, not a sheet).
if (alreadySheet){
// NB: the following call will call setModal_sys recursivly:
recreateMacWindow();
windowRef = qt_mac_window_for(q);
}
- if (q->windowModality() == Qt::ApplicationModal) {
- [windowRef setLevel:NSModalPanelWindowLevel];
- } else if (primaryWindow && primaryWindow->windowModality() == Qt::ApplicationModal) {
- // INVARIANT: Our window is a dialog that has a dialog parent that is
- // application modal, or . This means that q is supposed to be on top of this
- // dialog and not be modally shaddowed:
- [windowRef setLevel:NSModalPanelWindowLevel];
+ if (q->windowModality() == Qt::NonModal
+ && primaryWindow && primaryWindow->windowModality() == Qt::ApplicationModal) {
+ // INVARIANT: Our window has a parent that is application modal.
+ // This means that q is supposed to be on top of this window and
+ // not be modally shaddowed:
if ([windowRef isKindOfClass:[NSPanel class]])
[static_cast<NSPanel *>(windowRef) setWorksWhenModal:YES];
- } else {
- // INVARIANT: q should not be modal.
- NSInteger winLevel = -1;
- if (q->windowType() == Qt::Popup) {
- winLevel = NSPopUpMenuWindowLevel;
- // Popup should be in at least the same level as its parent.
- if (primaryWindow) {
- OSWindowRef parentRef = qt_mac_window_for(primaryWindow);
- winLevel = qMax([parentRef level], winLevel);
- }
- } else if (q->windowType() == Qt::Tool) {
- winLevel = NSFloatingWindowLevel;
- } else if (q->windowType() == Qt::Dialog) {
- winLevel = NSModalPanelWindowLevel;
- }
-
- // StayOnTop window should appear above Tool windows.
- if (data.window_flags & Qt::WindowStaysOnTopHint)
- winLevel = NSPopUpMenuWindowLevel;
- // Tooltips should appear above StayOnTop windows.
- if (q->windowType() == Qt::ToolTip)
- winLevel = NSScreenSaverWindowLevel;
- // All other types are Normal level.
- if (winLevel == -1)
- winLevel = NSNormalWindowLevel;
- [windowRef setLevel:winLevel];
}
}
diff --git a/src/gui/kernel/qwidget_p.h b/src/gui/kernel/qwidget_p.h
index b421d30..75b4c12 100644
--- a/src/gui/kernel/qwidget_p.h
+++ b/src/gui/kernel/qwidget_p.h
@@ -158,6 +158,7 @@ struct QTLWExtra {
quint32 newCounterValueLo;
#endif
#elif defined(Q_WS_WIN) // <--------------------------------------------------------- WIN
+ uint hotkeyRegistered: 1; // Hot key from the STARTUPINFO has been registered.
HICON winIconBig; // internal big Windows icon
HICON winIconSmall; // internal small Windows icon
#elif defined(Q_WS_MAC) // <--------------------------------------------------------- MAC
@@ -385,6 +386,8 @@ public:
QRegion prepareToRender(const QRegion &region, QWidget::RenderFlags renderFlags);
void render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &sourceRegion,
QWidget::RenderFlags renderFlags);
+ void render(QPaintDevice *target, const QPoint &targetOffset, const QRegion &sourceRegion,
+ QWidget::RenderFlags renderFlags, bool readyToRender);
void drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
QPainter *sharedPainter = 0, QWidgetBackingStore *backingStore = 0);
@@ -761,6 +764,8 @@ public:
void initWindowPtr();
void finishCreateWindow_sys_Carbon(OSWindowRef windowRef);
#else
+ void setSubWindowStacking(bool set);
+ void setWindowLevel();
void finishCreateWindow_sys_Cocoa(void * /*NSWindow * */ windowRef);
void syncCocoaMask();
void finishCocoaMaskSetup();
diff --git a/src/gui/kernel/qwidget_win.cpp b/src/gui/kernel/qwidget_win.cpp
index 10522ed..8cab387 100644
--- a/src/gui/kernel/qwidget_win.cpp
+++ b/src/gui/kernel/qwidget_win.cpp
@@ -1094,6 +1094,21 @@ void QWidgetPrivate::show_sys()
return;
}
+ if (data.window_flags & Qt::Window) {
+ QTLWExtra *extra = topData();
+ if (!extra->hotkeyRegistered) {
+ // Try to set the hotkey using information from STARTUPINFO
+ STARTUPINFO startupInfo;
+ GetStartupInfo(&startupInfo);
+ // If STARTF_USEHOTKEY is set, hStdInput is the virtual keycode
+ if (startupInfo.dwFlags & 0x00000200) {
+ WPARAM hotKey = (WPARAM)startupInfo.hStdInput;
+ SendMessage(data.winid, WM_SETHOTKEY, hotKey, 0);
+ }
+ extra->hotkeyRegistered = 1;
+ }
+ }
+
int sm = SW_SHOWNORMAL;
bool fakedMaximize = false;
if (q->isWindow()) {
@@ -1141,6 +1156,11 @@ void QWidgetPrivate::show_sys()
data.window_state |= Qt::WindowMinimized;
if (IsZoomed(q->internalWinId()))
data.window_state |= Qt::WindowMaximized;
+ // This is to resolve the problem where popups are opened from the
+ // system tray and not being implicitly activated
+ if (q->windowType() == Qt::Popup &&
+ (!q->parentWidget() || !q->parentWidget()->isActiveWindow()))
+ q->activateWindow();
}
winSetupGestures();
@@ -1687,6 +1707,7 @@ void QWidgetPrivate::deleteSysExtra()
void QWidgetPrivate::createTLSysExtra()
{
+ extra->topextra->hotkeyRegistered = 0;
extra->topextra->savedFlags = 0;
extra->topextra->winIconBig = 0;
extra->topextra->winIconSmall = 0;
diff --git a/src/gui/mac/qt_menu.nib/classes.nib b/src/gui/mac/qt_menu.nib/classes.nib
index fed50a3..0031e0e 100644
--- a/src/gui/mac/qt_menu.nib/classes.nib
+++ b/src/gui/mac/qt_menu.nib/classes.nib
@@ -5,14 +5,6 @@
<key>IBClasses</key>
<array>
<dict>
- <key>CLASS</key>
- <string>FirstResponder</string>
- <key>LANGUAGE</key>
- <string>ObjC</string>
- <key>SUPERCLASS</key>
- <string>NSObject</string>
- </dict>
- <dict>
<key>ACTIONS</key>
<dict>
<key>hide</key>
@@ -52,6 +44,14 @@
<key>SUPERCLASS</key>
<string>NSResponder</string>
</dict>
+ <dict>
+ <key>CLASS</key>
+ <string>FirstResponder</string>
+ <key>LANGUAGE</key>
+ <string>ObjC</string>
+ <key>SUPERCLASS</key>
+ <string>NSObject</string>
+ </dict>
</array>
<key>IBVersion</key>
<string>1</string>
diff --git a/src/gui/mac/qt_menu.nib/info.nib b/src/gui/mac/qt_menu.nib/info.nib
index 768cb8b..02e5cca 100644
--- a/src/gui/mac/qt_menu.nib/info.nib
+++ b/src/gui/mac/qt_menu.nib/info.nib
@@ -3,7 +3,7 @@
<plist version="1.0">
<dict>
<key>IBFramework Version</key>
- <string>670</string>
+ <string>672</string>
<key>IBOldestOS</key>
<integer>5</integer>
<key>IBOpenObjects</key>
@@ -11,7 +11,7 @@
<integer>57</integer>
</array>
<key>IBSystem Version</key>
- <string>9G55</string>
+ <string>9L31a</string>
<key>targetFramework</key>
<string>IBCocoaFramework</string>
</dict>
diff --git a/src/gui/mac/qt_menu.nib/keyedobjects.nib b/src/gui/mac/qt_menu.nib/keyedobjects.nib
index 18a6648..3edb0ed 100644
--- a/src/gui/mac/qt_menu.nib/keyedobjects.nib
+++ b/src/gui/mac/qt_menu.nib/keyedobjects.nib
Binary files differ
diff --git a/src/gui/math3d/qmatrix4x4.h b/src/gui/math3d/qmatrix4x4.h
index f9902d7..0671fa8 100644
--- a/src/gui/math3d/qmatrix4x4.h
+++ b/src/gui/math3d/qmatrix4x4.h
@@ -208,6 +208,8 @@ private:
friend class QGraphicsRotation;
};
+Q_DECLARE_TYPEINFO(QMatrix4x4, Q_MOVABLE_TYPE);
+
inline QMatrix4x4::QMatrix4x4
(qreal m11, qreal m12, qreal m13, qreal m14,
qreal m21, qreal m22, qreal m23, qreal m24,
diff --git a/src/gui/math3d/qquaternion.h b/src/gui/math3d/qquaternion.h
index a446f28..16aa5d0 100644
--- a/src/gui/math3d/qquaternion.h
+++ b/src/gui/math3d/qquaternion.h
@@ -136,6 +136,8 @@ private:
qreal wp, xp, yp, zp;
};
+Q_DECLARE_TYPEINFO(QQuaternion, Q_MOVABLE_TYPE);
+
inline QQuaternion::QQuaternion() : wp(1.0f), xp(0.0f), yp(0.0f), zp(0.0f) {}
inline QQuaternion::QQuaternion(qreal aScalar, qreal xpos, qreal ypos, qreal zpos) : wp(aScalar), xp(xpos), yp(ypos), zp(zpos) {}
diff --git a/src/gui/math3d/qvector2d.h b/src/gui/math3d/qvector2d.h
index d76f35a..c92c5e0 100644
--- a/src/gui/math3d/qvector2d.h
+++ b/src/gui/math3d/qvector2d.h
@@ -126,6 +126,8 @@ private:
friend class QVector4D;
};
+Q_DECLARE_TYPEINFO(QVector2D, Q_MOVABLE_TYPE);
+
inline QVector2D::QVector2D() : xp(0.0f), yp(0.0f) {}
inline QVector2D::QVector2D(float xpos, float ypos, int) : xp(xpos), yp(ypos) {}
diff --git a/src/gui/math3d/qvector3d.h b/src/gui/math3d/qvector3d.h
index 80c7152..2fdd1d3 100644
--- a/src/gui/math3d/qvector3d.h
+++ b/src/gui/math3d/qvector3d.h
@@ -141,6 +141,8 @@ private:
#endif
};
+Q_DECLARE_TYPEINFO(QVector3D, Q_MOVABLE_TYPE);
+
inline QVector3D::QVector3D() : xp(0.0f), yp(0.0f), zp(0.0f) {}
inline QVector3D::QVector3D(qreal xpos, qreal ypos, qreal zpos) : xp(xpos), yp(ypos), zp(zpos) {}
diff --git a/src/gui/math3d/qvector4d.h b/src/gui/math3d/qvector4d.h
index 4af2961..a383fbb 100644
--- a/src/gui/math3d/qvector4d.h
+++ b/src/gui/math3d/qvector4d.h
@@ -138,6 +138,8 @@ private:
#endif
};
+Q_DECLARE_TYPEINFO(QVector4D, Q_MOVABLE_TYPE);
+
inline QVector4D::QVector4D() : xp(0.0f), yp(0.0f), zp(0.0f), wp(0.0f) {}
inline QVector4D::QVector4D(qreal xpos, qreal ypos, qreal zpos, qreal wpos) : xp(xpos), yp(ypos), zp(zpos), wp(wpos) {}
diff --git a/src/gui/painting/qbrush.cpp b/src/gui/painting/qbrush.cpp
index 1a83b1d..a82d0f9 100644
--- a/src/gui/painting/qbrush.cpp
+++ b/src/gui/painting/qbrush.cpp
@@ -912,7 +912,7 @@ void QBrush::setTransform(const QTransform &matrix)
otherwise returns false.
Two brushes are different if they have different styles, colors or
- pixmaps.
+ transforms or different pixmaps or gradients depending on the style.
\sa operator==()
*/
@@ -924,7 +924,7 @@ void QBrush::setTransform(const QTransform &matrix)
otherwise returns false.
Two brushes are equal if they have equal styles, colors and
- pixmaps.
+ transforms and equal pixmaps or gradients depending on the style.
\sa operator!=()
*/
@@ -933,26 +933,26 @@ bool QBrush::operator==(const QBrush &b) const
{
if (b.d == d)
return true;
- if (b.d->style == d->style && b.d->color == d->color) {
- switch (d->style) {
- case Qt::TexturePattern: {
- QPixmap &us = (static_cast<QTexturedBrushData *>(d.data()))->pixmap();
- QPixmap &them = (static_cast<QTexturedBrushData *>(b.d.data()))->pixmap();
+ if (b.d->style != d->style || b.d->color != d->color || b.d->transform != d->transform)
+ return false;
+ switch (d->style) {
+ case Qt::TexturePattern:
+ {
+ const QPixmap &us = (static_cast<QTexturedBrushData *>(d.data()))->pixmap();
+ const QPixmap &them = (static_cast<QTexturedBrushData *>(b.d.data()))->pixmap();
return ((us.isNull() && them.isNull()) || us.cacheKey() == them.cacheKey());
}
- case Qt::LinearGradientPattern:
- case Qt::RadialGradientPattern:
- case Qt::ConicalGradientPattern:
- {
- QGradientBrushData *d1 = static_cast<QGradientBrushData *>(d.data());
- QGradientBrushData *d2 = static_cast<QGradientBrushData *>(b.d.data());
- return d1->gradient == d2->gradient;
- }
- default:
- return true;
+ case Qt::LinearGradientPattern:
+ case Qt::RadialGradientPattern:
+ case Qt::ConicalGradientPattern:
+ {
+ const QGradientBrushData *d1 = static_cast<QGradientBrushData *>(d.data());
+ const QGradientBrushData *d2 = static_cast<QGradientBrushData *>(b.d.data());
+ return d1->gradient == d2->gradient;
}
+ default:
+ return true;
}
- return false;
}
/*!
diff --git a/src/gui/painting/qdatabuffer_p.h b/src/gui/painting/qdatabuffer_p.h
index a7834ea..bc5f1ef 100644
--- a/src/gui/painting/qdatabuffer_p.h
+++ b/src/gui/painting/qdatabuffer_p.h
@@ -81,7 +81,9 @@ public:
inline Type &at(int i) { Q_ASSERT(i >= 0 && i < siz); return buffer[i]; }
inline const Type &at(int i) const { Q_ASSERT(i >= 0 && i < siz); return buffer[i]; }
+ inline Type &last() { Q_ASSERT(!isEmpty()); return buffer[siz-1]; }
inline const Type &last() const { Q_ASSERT(!isEmpty()); return buffer[siz-1]; }
+ inline Type &first() { Q_ASSERT(!isEmpty()); return buffer[0]; }
inline const Type &first() const { Q_ASSERT(!isEmpty()); return buffer[0]; }
inline void add(const Type &t) {
@@ -90,6 +92,11 @@ public:
++siz;
}
+ inline void pop_back() {
+ Q_ASSERT(siz > 0);
+ --siz;
+ }
+
inline void resize(int size) {
reserve(size);
siz = size;
diff --git a/src/gui/painting/qemulationpaintengine.cpp b/src/gui/painting/qemulationpaintengine.cpp
index f2f0c73..fd42736 100644
--- a/src/gui/painting/qemulationpaintengine.cpp
+++ b/src/gui/painting/qemulationpaintengine.cpp
@@ -172,6 +172,36 @@ void QEmulationPaintEngine::drawTextItem(const QPointF &p, const QTextItem &text
QRectF rect(p.x(), p.y() - ti.ascent.toReal(), ti.width.toReal(), (ti.ascent + ti.descent + 1).toReal());
fillBGRect(rect);
}
+
+ QPainterState *s = state();
+ Qt::BrushStyle style = qbrush_style(s->pen.brush());
+ if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern)
+ {
+ QPen savedPen = s->pen;
+ QGradient g = *s->pen.brush().gradient();
+
+ if (g.coordinateMode() > QGradient::LogicalMode) {
+ QTransform mat = s->pen.brush().transform();
+ if (g.coordinateMode() == QGradient::StretchToDeviceMode) {
+ mat.scale(real_engine->painter()->device()->width(), real_engine->painter()->device()->height());
+ } else if (g.coordinateMode() == QGradient::ObjectBoundingMode) {
+ const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
+ QRectF r(p.x(), p.y() - ti.ascent.toReal(), ti.width.toReal(), (ti.ascent + ti.descent + 1).toReal());
+ mat.translate(r.x(), r.y());
+ mat.scale(r.width(), r.height());
+ }
+ g.setCoordinateMode(QGradient::LogicalMode);
+ QBrush brush(g);
+ brush.setTransform(mat);
+ s->pen.setBrush(brush);
+ penChanged();
+ real_engine->drawTextItem(p, textItem);
+ s->pen = savedPen;
+ penChanged();
+ return;
+ }
+ }
+
real_engine->drawTextItem(p, textItem);
}
diff --git a/src/gui/painting/qpainterpath.cpp b/src/gui/painting/qpainterpath.cpp
index fba3595..f78de34 100644
--- a/src/gui/painting/qpainterpath.cpp
+++ b/src/gui/painting/qpainterpath.cpp
@@ -1257,6 +1257,8 @@ Qt::FillRule QPainterPath::fillRule() const
void QPainterPath::setFillRule(Qt::FillRule fillRule)
{
ensureData();
+ if (d_func()->fillRule == fillRule)
+ return;
detach();
d_func()->fillRule = fillRule;
diff --git a/src/gui/painting/qwindowsurface_s60.cpp b/src/gui/painting/qwindowsurface_s60.cpp
index b01a515..949b338 100644
--- a/src/gui/painting/qwindowsurface_s60.cpp
+++ b/src/gui/painting/qwindowsurface_s60.cpp
@@ -149,11 +149,19 @@ void QS60WindowSurface::flush(QWidget *widget, const QRegion &region, const QPoi
Q_ASSERT(window);
QTLWExtra *topExtra = window->d_func()->maybeTopData();
Q_ASSERT(topExtra);
+ QRect qr = region.boundingRect();
if (!topExtra->inExpose) {
topExtra->inExpose = true; // Prevent DrawNow() from calling syncBackingStore() again
- TRect tr = qt_QRect2TRect(region.boundingRect());
+ TRect tr = qt_QRect2TRect(qr);
widget->winId()->DrawNow(tr);
topExtra->inExpose = false;
+ } else {
+ // This handles the case when syncBackingStore updates content outside of the
+ // original drawing rectangle. This might happen if there are pending update()
+ // events at the same time as we get a Draw() from Symbian.
+ QRect drawRect = qt_TRect2QRect(widget->winId()->DrawableWindow()->GetDrawRect());
+ if (!drawRect.contains(qr))
+ widget->winId()->DrawDeferred();
}
}
diff --git a/src/gui/statemachine/qguistatemachine.cpp b/src/gui/statemachine/qguistatemachine.cpp
index 70f152d..63ad94e 100644
--- a/src/gui/statemachine/qguistatemachine.cpp
+++ b/src/gui/statemachine/qguistatemachine.cpp
@@ -469,12 +469,6 @@ static QEvent *cloneEvent(QEvent *e)
case QEvent::UngrabKeyboard:
return new QEvent(*e);
-#ifdef QT_MAC_USE_COCOA
- case QEvent::CocoaRequestModal:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
-#endif
-
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd:
diff --git a/src/gui/styles/qcommonstyle.cpp b/src/gui/styles/qcommonstyle.cpp
index b1924e7..f8464cc 100644
--- a/src/gui/styles/qcommonstyle.cpp
+++ b/src/gui/styles/qcommonstyle.cpp
@@ -5662,10 +5662,16 @@ QIcon QCommonStyle::standardIconImplementation(StandardPixmap standardIcon, cons
OSType iconType = 0;
switch (standardIcon) {
case QStyle::SP_MessageBoxQuestion:
+ iconType = kQuestionMarkIcon;
+ break;
case QStyle::SP_MessageBoxInformation:
+ iconType = kAlertNoteIcon;
+ break;
case QStyle::SP_MessageBoxWarning:
+ iconType = kAlertCautionIcon;
+ break;
case QStyle::SP_MessageBoxCritical:
- iconType = kGenericApplicationIcon;
+ iconType = kAlertStopIcon;
break;
case SP_DesktopIcon:
iconType = kDesktopIcon;
@@ -5755,88 +5761,88 @@ QIcon QCommonStyle::standardIconImplementation(StandardPixmap standardIcon, cons
switch (standardIcon) {
#ifndef QT_NO_IMAGEFORMAT_PNG
case SP_FileDialogNewFolder:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/newdirectory-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/newdirectory-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/newdirectory-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/newdirectory-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/newdirectory-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/newdirectory-128.png"), QSize(128, 128));
break;
case SP_FileDialogBack:
return standardIconImplementation(SP_ArrowBack, option, widget);
case SP_FileDialogToParent:
return standardIconImplementation(SP_ArrowUp, option, widget);
case SP_FileDialogDetailedView:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewdetailed-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewdetailed-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewdetailed-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewdetailed-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewdetailed-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewdetailed-128.png"), QSize(128, 128));
break;
case SP_FileDialogInfoView:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/fileinfo-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/fileinfo-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/fileinfo-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/fileinfo-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/fileinfo-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/fileinfo-128.png"), QSize(128, 128));
break;
case SP_FileDialogContentsView:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filecontents-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filecontents-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filecontents-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filecontents-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filecontents-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filecontents-128.png"), QSize(128, 128));
break;
case SP_FileDialogListView:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewlist-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewlist-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewlist-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewlist-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewlist-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewlist-128.png"), QSize(128, 128));
break;
case SP_DialogOkButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-ok-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-ok-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-ok-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-ok-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-ok-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-ok-128.png"), QSize(128, 128));
break;
case SP_DialogCancelButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-cancel-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-cancel-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-cancel-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-cancel-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-cancel-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-cancel-128.png"), QSize(128, 128));
break;
case SP_DialogHelpButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-help-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-help-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-help-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-help-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-help-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-help-128.png"), QSize(128, 128));
break;
case SP_DialogOpenButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-open-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-open-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-open-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-open-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-open-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-open-128.png"), QSize(128, 128));
break;
case SP_DialogSaveButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-save-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-save-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-save-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-save-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-save-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-save-128.png"), QSize(128, 128));
break;
case SP_DialogCloseButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-close-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-close-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-close-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-close-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-close-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-close-128.png"), QSize(128, 128));
break;
case SP_DialogApplyButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-apply-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-apply-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-apply-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-apply-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-apply-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-apply-128.png"), QSize(128, 128));
break;
case SP_DialogResetButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-clear-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-clear-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-clear-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-clear-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-clear-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-clear-128.png"), QSize(128, 128));
break;
case SP_DialogDiscardButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-delete-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-delete-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-delete-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-delete-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-delete-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-delete-128.png"), QSize(128, 128));
break;
case SP_DialogYesButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-yes-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-yes-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-yes-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-yes-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-yes-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-yes-128.png"), QSize(128, 128));
break;
case SP_DialogNoButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-no-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-no-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-no-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-no-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-no-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-no-128.png"), QSize(128, 128));
break;
case SP_ArrowForward:
if (rtl)
@@ -5847,24 +5853,24 @@ QIcon QCommonStyle::standardIconImplementation(StandardPixmap standardIcon, cons
return standardIconImplementation(SP_ArrowRight, option, widget);
return standardIconImplementation(SP_ArrowLeft, option, widget);
case SP_ArrowLeft:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/left-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/left-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/left-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/left-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/left-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/left-128.png"), QSize(128, 128));
break;
case SP_ArrowRight:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/right-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/right-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/right-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/right-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/right-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/right-128.png"), QSize(128, 128));
break;
case SP_ArrowUp:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/up-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/up-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/up-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/up-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/up-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/up-128.png"), QSize(128, 128));
break;
case SP_ArrowDown:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/down-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/down-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/down-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/down-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/down-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/down-128.png"), QSize(128, 128));
break;
case SP_DirHomeIcon:
case SP_DirIcon:
@@ -5882,71 +5888,71 @@ QIcon QCommonStyle::standardIconImplementation(StandardPixmap standardIcon, cons
QSize(128, 128), QIcon::Normal, QIcon::On);
break;
case SP_DriveCDIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/cdr-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/cdr-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/cdr-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/cdr-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/cdr-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/cdr-128.png"), QSize(128, 128));
break;
case SP_DriveDVDIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dvd-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dvd-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dvd-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dvd-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dvd-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dvd-128.png"), QSize(128, 128));
break;
case SP_FileIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/file-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/file-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/file-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/file-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/file-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/file-128.png"), QSize(128, 128));
break;
case SP_FileLinkIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filelink-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filelink-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filelink-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filelink-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filelink-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filelink-128.png"), QSize(128, 128));
break;
case SP_TrashIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/trash-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/trash-32.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/trash-128.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/trash-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/trash-32.png"), QSize(32, 32));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/trash-128.png"), QSize(128, 128));
break;
case SP_BrowserReload:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/refresh-24.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/refresh-32.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/refresh-24.png"), QSize(24, 24));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/refresh-32.png"), QSize(32, 32));
break;
case SP_BrowserStop:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/stop-24.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/stop-32.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/stop-24.png"), QSize(24, 24));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/stop-32.png"), QSize(32, 32));
break;
case SP_MediaPlay:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-play-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-play-32.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-play-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-play-32.png"), QSize(32, 32));
break;
case SP_MediaPause:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-pause-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-pause-32.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-pause-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-pause-32.png"), QSize(32, 32));
break;
case SP_MediaStop:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-stop-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-stop-32.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-stop-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-stop-32.png"), QSize(32, 32));
break;
case SP_MediaSeekForward:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-forward-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-forward-32.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-forward-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-forward-32.png"), QSize(32, 32));
break;
case SP_MediaSeekBackward:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-backward-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-backward-32.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-backward-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-backward-32.png"), QSize(32, 32));
break;
case SP_MediaSkipForward:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-forward-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-forward-32.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-forward-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-forward-32.png"), QSize(32, 32));
break;
case SP_MediaSkipBackward:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-backward-16.png"));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-backward-32.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-backward-16.png"), QSize(16, 16));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-backward-32.png"), QSize(32, 32));
break;
case SP_MediaVolume:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-volume-16.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-volume-16.png"), QSize(16, 16));
break;
case SP_MediaVolumeMuted:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-volume-muted-16.png"));
+ icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-volume-muted-16.png"), QSize(16, 16));
break;
#endif // QT_NO_IMAGEFORMAT_PNG
default:
diff --git a/src/gui/styles/qmacstyle_mac.mm b/src/gui/styles/qmacstyle_mac.mm
index 78074c7..40ee31d 100644
--- a/src/gui/styles/qmacstyle_mac.mm
+++ b/src/gui/styles/qmacstyle_mac.mm
@@ -3146,6 +3146,18 @@ void QMacStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPai
break;
case PE_PanelLineEdit:
QWindowsStyle::drawPrimitive(pe, opt, p, w);
+ // Draw the focus frame for widgets other than QLineEdit (e.g. for line edits in Webkit).
+ // Focus frame is drawn outside the rectangle passed in the option-rect.
+ if (const QStyleOptionFrame *panel = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
+ if ((opt->state & State_HasFocus) && !qobject_cast<const QLineEdit*>(w)) {
+ int vmargin = pixelMetric(QStyle::PM_FocusFrameVMargin);
+ int hmargin = pixelMetric(QStyle::PM_FocusFrameHMargin);
+ QStyleOptionFrame focusFrame = *panel;
+ focusFrame.rect = panel->rect.adjusted(-hmargin, -vmargin, hmargin, vmargin);
+ drawControl(CE_FocusFrame, &focusFrame, p, w);
+ }
+ }
+
break;
case PE_FrameTabWidget:
if (const QStyleOptionTabWidgetFrame *twf
@@ -3169,7 +3181,6 @@ void QMacStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPai
p->drawLine(opt->rect.topLeft(), opt->rect.bottomLeft());
} break;
case PE_FrameStatusBarItem:
- QCommonStyle::drawPrimitive(pe, opt, p, w);
break;
case PE_IndicatorTabClose: {
bool hover = (opt->state & State_MouseOver);
diff --git a/src/gui/styles/qs60style.cpp b/src/gui/styles/qs60style.cpp
index 9025e5b..ea7399f 100644
--- a/src/gui/styles/qs60style.cpp
+++ b/src/gui/styles/qs60style.cpp
@@ -289,6 +289,9 @@ void QS60StylePrivate::drawSkinElement(SkinElements element, QPainter *painter,
case SE_Editor:
drawFrame(SF_FrameLineEdit, painter, rect, flags | SF_PointNorth);
break;
+ case SE_DropArea:
+ drawPart(QS60StyleEnums::SP_QgnGrafOrgBgGrid, painter, rect, flags | SF_PointNorth);
+ break;
default:
break;
}
@@ -844,15 +847,18 @@ QSize QS60StylePrivate::partSize(QS60StyleEnums::SkinParts part, SkinElementFlag
result.setWidth(pixelMetric(PM_Custom_FrameCornerWidth));
break;
- case QS60StyleEnums::SP_QsnCpScrollHandleBottomPressed:
case QS60StyleEnums::SP_QsnCpScrollHandleTopPressed:
- case QS60StyleEnums::SP_QsnCpScrollHandleMiddlePressed:
case QS60StyleEnums::SP_QsnCpScrollBgBottom:
- case QS60StyleEnums::SP_QsnCpScrollBgMiddle:
case QS60StyleEnums::SP_QsnCpScrollBgTop:
case QS60StyleEnums::SP_QsnCpScrollHandleBottom:
- case QS60StyleEnums::SP_QsnCpScrollHandleMiddle:
case QS60StyleEnums::SP_QsnCpScrollHandleTop:
+ case QS60StyleEnums::SP_QsnCpScrollHandleBottomPressed:
+ result.setHeight(pixelMetric(QStyle::PM_ScrollBarExtent));
+ result.setWidth(pixelMetric(QStyle::PM_ScrollBarExtent));
+ break;
+ case QS60StyleEnums::SP_QsnCpScrollHandleMiddlePressed:
+ case QS60StyleEnums::SP_QsnCpScrollBgMiddle:
+ case QS60StyleEnums::SP_QsnCpScrollHandleMiddle:
result.setHeight(pixelMetric(QStyle::PM_ScrollBarExtent));
result.setWidth(pixelMetric(QStyle::PM_ScrollBarSliderMin));
break;
@@ -2271,14 +2277,16 @@ void QS60Style::drawPrimitive(PrimitiveElement element, const QStyleOption *opti
QS60StyleEnums::SkinParts skinPart =
(option->state & State_Open) ? QS60StyleEnums::SP_QgnIndiHlColSuper : QS60StyleEnums::SP_QgnIndiHlExpSuper;
int minDimension = qMin(option->rect.width(), option->rect.height());
- const int resizeValue = minDimension >> 1;
- minDimension += resizeValue; // Adjust the icon bigger because of empty space in svg icon.
QRect iconRect(option->rect.topLeft(), QSize(minDimension, minDimension));
- int verticalMagic(0);
- // magic values for positioning svg icon.
- if (option->rect.width() <= option->rect.height())
- verticalMagic = 3;
- iconRect.translate(3, verticalMagic - resizeValue);
+ const int magicTweak = 3;
+ int resizeValue = minDimension >> 1;
+ if (!QS60StylePrivate::isTouchSupported()) {
+ minDimension += resizeValue; // Adjust the icon bigger because of empty space in svg icon.
+ iconRect.setSize(QSize(minDimension, minDimension));
+ const int verticalMagic = (option->rect.width() <= option->rect.height()) ? magicTweak : 0;
+ resizeValue = verticalMagic - resizeValue;
+ }
+ iconRect.translate(magicTweak, resizeValue);
QS60StylePrivate::drawSkinPart(skinPart, painter, iconRect, flags);
}
}
@@ -2302,7 +2310,12 @@ void QS60Style::drawPrimitive(PrimitiveElement element, const QStyleOption *opti
break;
case PE_PanelScrollAreaCorner:
break;
-
+ case PE_IndicatorItemViewItemDrop:
+ if (QS60StylePrivate::isTouchSupported())
+ QS60StylePrivate::drawSkinElement(QS60StylePrivate::SE_DropArea, painter, option->rect, flags);
+ else
+ commonStyleDraws = true;
+ break;
// todo: items are below with #ifdefs "just in case". in final version, remove all non-required cases
case PE_FrameLineEdit:
case PE_IndicatorDockWidgetResizeHandle:
@@ -2323,7 +2336,6 @@ void QS60Style::drawPrimitive(PrimitiveElement element, const QStyleOption *opti
#endif //QT_NO_TOOLBAR
#ifndef QT_NO_COLUMNVIEW
case PE_IndicatorColumnViewArrow:
- case PE_IndicatorItemViewItemDrop:
#endif //QT_NO_COLUMNVIEW
case PE_FrameTabBarBase: // since tabs are in S60 always in navipane, let's use common style for tab base in Qt.
default:
@@ -2481,6 +2493,9 @@ int QS60Style::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *w
case SH_FormLayoutWrapPolicy:
retValue = QFormLayout::WrapLongRows;
break;
+ case SH_ScrollBar_ContextMenu:
+ retValue = false;
+ break;
default:
retValue = QCommonStyle::styleHint(sh, opt, widget, hret);
break;
@@ -2559,11 +2574,11 @@ QRect QS60Style::subControlRect(ComplexControl control, const QStyleOptionComple
if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
const int frameThickness = spinbox->frame ? pixelMetric(PM_SpinBoxFrameWidth, spinbox, widget) : 0;
const int buttonMargin = spinbox->frame ? 2 : 0;
- const int buttonWidth = QS60StylePrivate::pixelMetric(PM_ButtonIconSize) + 2 * buttonMargin;
+ const int buttonContentWidth = QS60StylePrivate::pixelMetric(PM_ButtonIconSize) + 2 * buttonMargin;
QSize buttonSize;
buttonSize.setHeight(qMax(8, spinbox->rect.height() - frameThickness));
//width should at least be equal to height
- buttonSize.setWidth(qMax(buttonSize.height(), buttonWidth));
+ buttonSize.setWidth(qMax(buttonSize.height(), buttonContentWidth));
buttonSize = buttonSize.expandedTo(QApplication::globalStrut());
const int y = frameThickness + spinbox->rect.y();
diff --git a/src/gui/styles/qs60style_p.h b/src/gui/styles/qs60style_p.h
index eae2291..ea30b81 100644
--- a/src/gui/styles/qs60style_p.h
+++ b/src/gui/styles/qs60style_p.h
@@ -131,6 +131,7 @@ public:
SP_QgnGrafBarFrameSideL,
SP_QgnGrafBarFrameSideR,
SP_QgnGrafBarProgress,
+ SP_QgnGrafOrgBgGrid,
SP_QgnGrafScrollArrowDown,
SP_QgnGrafScrollArrowLeft,
SP_QgnGrafScrollArrowRight,
@@ -428,6 +429,7 @@ public:
SE_ScrollBarHandlePressedVertical,
SE_ButtonInactive,
SE_Editor,
+ SE_DropArea
};
enum SkinFrameElements {
diff --git a/src/gui/styles/qs60style_s60.cpp b/src/gui/styles/qs60style_s60.cpp
index 872bc2b..cb49fbc 100644
--- a/src/gui/styles/qs60style_s60.cpp
+++ b/src/gui/styles/qs60style_s60.cpp
@@ -58,8 +58,8 @@
#include <aknsskininstance.h>
#include <aknsbasicbackgroundcontrolcontext.h>
#include <avkon.mbg>
-#include <AknFontAccess.h>
-#include <AknLayoutFont.h>
+#include <aknfontaccess.h>
+#include <aknlayoutfont.h>
#include <aknutils.h>
#include <aknnavi.h>
#include <gulicon.h>
@@ -178,6 +178,8 @@ const partMapEntry QS60StyleModeSpecifics::m_partMap[] = {
/* SP_QgnGrafBarFrameSideL */ {KAknsIIDQgnGrafBarFrameSideL, EDrawIcon, ES60_All, -1,-1},
/* SP_QgnGrafBarFrameSideR */ {KAknsIIDQgnGrafBarFrameSideR, EDrawIcon, ES60_All, -1,-1},
/* SP_QgnGrafBarProgress */ {KAknsIIDQgnGrafBarProgress, EDrawIcon, ES60_All, -1,-1},
+ // No drop area for 3.x non-touch devices
+ /* SP_QgnGrafOrgBgGrid */ {KAknsIIDNone, EDrawIcon, ES60_3_X, EAknsMajorGeneric ,0x1eba}, //KAknsIIDQgnGrafOrgBgGrid
/* SP_QgnGrafScrollArrowDown */ {KAknsIIDQgnGrafScrollArrowDown, EDrawGulIcon, ES60_All, -1,-1},
/* SP_QgnGrafScrollArrowLeft */ {KAknsIIDQgnGrafScrollArrowLeft, EDrawGulIcon, ES60_All, -1,-1},
/* SP_QgnGrafScrollArrowRight */ {KAknsIIDQgnGrafScrollArrowRight, EDrawGulIcon, ES60_All, -1,-1},
diff --git a/src/gui/styles/qs60style_simulated.cpp b/src/gui/styles/qs60style_simulated.cpp
index f87cf28..3f09ebc 100644
--- a/src/gui/styles/qs60style_simulated.cpp
+++ b/src/gui/styles/qs60style_simulated.cpp
@@ -94,12 +94,12 @@ bool saveThemeToBlob(const QString &themeBlob,
dataOut << color;
}
- const int picturesCount = partPictures.count();
- dataOut << picturesCount;
- foreach (const QString &key, partPictures.keys()) {
- const QPicture picture = partPictures.value(key);
- dataOut << key;
- dataOut << picture;
+ dataOut << partPictures.count();
+ QHashIterator<QString, QPicture> i(partPictures);
+ while (i.hasNext()) {
+ i.next();
+ dataOut << i.key();
+ dataOut << i.value(); // the QPicture
}
QDataStream blobOut(&blob);
diff --git a/src/gui/styles/qstylesheetstyle.cpp b/src/gui/styles/qstylesheetstyle.cpp
index b36294a..1f9fc32 100644
--- a/src/gui/styles/qstylesheetstyle.cpp
+++ b/src/gui/styles/qstylesheetstyle.cpp
@@ -1065,7 +1065,7 @@ QRect QRenderRule::boxRect(const QRect& cr, int flags) const
r.adjust(-p[LeftEdge], -p[TopEdge], p[RightEdge], p[BottomEdge]);
}
}
- if (!hasNativeBorder() && (flags & Border)) {
+ if (hasBorder() && (flags & Border)) {
const int *b = border()->borders;
r.adjust(-b[LeftEdge], -b[TopEdge], b[RightEdge], b[BottomEdge]);
}
@@ -1352,6 +1352,12 @@ void QRenderRule::configurePalette(QPalette *p, QPalette::ColorRole fr, QPalette
if (br != QPalette::NoRole)
p->setBrush(br, bg->brush);
p->setBrush(QPalette::Window, bg->brush);
+ if (bg->brush.style() == Qt::SolidPattern) {
+ p->setBrush(QPalette::Light, bg->brush.color().lighter(115));
+ p->setBrush(QPalette::Midlight, bg->brush.color().lighter(107));
+ p->setBrush(QPalette::Dark, bg->brush.color().darker(150));
+ p->setBrush(QPalette::Shadow, bg->brush.color().darker(300));
+ }
}
if (!hasPalette())
diff --git a/src/gui/text/qfontdatabase_win.cpp b/src/gui/text/qfontdatabase_win.cpp
index 05c8f08..b30a6c3 100644
--- a/src/gui/text/qfontdatabase_win.cpp
+++ b/src/gui/text/qfontdatabase_win.cpp
@@ -1101,7 +1101,6 @@ static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
if (AddFontResource((LPCWSTR)fnt->fileName.utf16()) == 0)
return;
#else
- // supported from 2000 on, so no need to deal with the *A variant
PtrAddFontResourceExW ptrAddFontResourceExW = (PtrAddFontResourceExW)QLibrary::resolve(QLatin1String("gdi32"),
"AddFontResourceExW");
if (!ptrAddFontResourceExW
diff --git a/src/gui/text/qtextcontrol.cpp b/src/gui/text/qtextcontrol.cpp
index aaaa3ca..f345cd1 100644
--- a/src/gui/text/qtextcontrol.cpp
+++ b/src/gui/text/qtextcontrol.cpp
@@ -441,7 +441,6 @@ void QTextControlPrivate::setContent(Qt::TextFormat format, const QString &text,
QObject::connect(doc, SIGNAL(documentLayoutChanged()), q, SLOT(_q_documentLayoutChanged()));
// convenience signal forwards
- QObject::connect(doc, SIGNAL(contentsChanged()), q, SIGNAL(textChanged()));
QObject::connect(doc, SIGNAL(undoAvailable(bool)), q, SIGNAL(undoAvailable(bool)));
QObject::connect(doc, SIGNAL(redoAvailable(bool)), q, SIGNAL(redoAvailable(bool)));
QObject::connect(doc, SIGNAL(modificationChanged(bool)), q, SIGNAL(modificationChanged(bool)));
@@ -452,8 +451,11 @@ void QTextControlPrivate::setContent(Qt::TextFormat format, const QString &text,
if (!document)
doc->setUndoRedoEnabled(false);
+ //Saving the index save some time.
+ static int contentsChangedIndex = QTextDocument::staticMetaObject.indexOfSignal("contentsChanged()");
+ static int textChangedIndex = QTextControl::staticMetaObject.indexOfSignal("textChanged()");
// avoid multiple textChanged() signals being emitted
- QObject::disconnect(doc, SIGNAL(contentsChanged()), q, SIGNAL(textChanged()));
+ QMetaObject::disconnect(doc, contentsChangedIndex, q, textChangedIndex);
if (!text.isEmpty()) {
// clear 'our' cursor for insertion to prevent
@@ -488,7 +490,7 @@ void QTextControlPrivate::setContent(Qt::TextFormat format, const QString &text,
}
cursor.setCharFormat(charFormatForInsertion);
- QObject::connect(doc, SIGNAL(contentsChanged()), q, SIGNAL(textChanged()));
+ QMetaObject::connect(doc, contentsChangedIndex, q, textChangedIndex);
emit q->textChanged();
if (!document)
doc->setUndoRedoEnabled(previousUndoRedoState);
@@ -1762,8 +1764,8 @@ void QTextControlPrivate::contextMenuEvent(const QPoint &screenPos, const QPoint
QMenu *menu = q->createStandardContextMenu(docPos, contextWidget);
if (!menu)
return;
- menu->exec(screenPos);
- delete menu;
+ menu->setAttribute(Qt::WA_DeleteOnClose);
+ menu->popup(screenPos);
#endif
}
diff --git a/src/gui/text/qtextdocument.cpp b/src/gui/text/qtextdocument.cpp
index 21f3189..80931c9 100644
--- a/src/gui/text/qtextdocument.cpp
+++ b/src/gui/text/qtextdocument.cpp
@@ -61,6 +61,7 @@
#include <qapplication.h>
#include "qtextcontrol_p.h"
#include "private/qtextedit_p.h"
+#include "private/qdataurl_p.h"
#include "qtextdocument_p.h"
#include <private/qprinter_p.h>
@@ -435,6 +436,23 @@ void QTextDocument::redo(QTextCursor *cursor)
}
/*!
+ \since 4.7
+ Clears the specified stacks.
+
+ This method clears any commands on the undo stack, the redo stack, or both (the
+ default). If any commands got cleared, the appropriate signals
+ (\a QTextDocument::undoAvailable or \a QTextDocument::redoAvailable) get
+ emitted.
+
+ \sa QTextDocument::undoAvailable QTextDocument::redoAvailable
+*/
+void QTextDocument::clearUndoRedoStacks(Stacks stacksToClear)
+{
+ Q_D(QTextDocument);
+ d->clearUndoRedoStacks(stacksToClear, true);
+}
+
+/*!
\overload
*/
@@ -1924,6 +1942,10 @@ QVariant QTextDocument::loadResource(int type, const QUrl &name)
}
#endif
+ // handle data: URLs
+ if (r.isNull() && name.scheme() == QLatin1String("data"))
+ r = qDecodeDataUrl(name).second;
+
// if resource was not loaded try to load it here
if (!doc && r.isNull() && name.isRelative()) {
QUrl currentURL = d->url;
diff --git a/src/gui/text/qtextdocument.h b/src/gui/text/qtextdocument.h
index b5bcb41..0140772 100644
--- a/src/gui/text/qtextdocument.h
+++ b/src/gui/text/qtextdocument.h
@@ -256,6 +256,13 @@ public:
void undo(QTextCursor *cursor);
void redo(QTextCursor *cursor);
+ enum Stacks {
+ UndoStack = 0x01,
+ RedoStack = 0x02,
+ UndoAndRedoStacks = UndoStack | RedoStack
+ };
+ void clearUndoRedoStacks(Stacks historyToClear = UndoAndRedoStacks);
+
int maximumBlockCount() const;
void setMaximumBlockCount(int maximum);
diff --git a/src/gui/text/qtextdocument_p.cpp b/src/gui/text/qtextdocument_p.cpp
index 372b9dc..969d5b4 100644
--- a/src/gui/text/qtextdocument_p.cpp
+++ b/src/gui/text/qtextdocument_p.cpp
@@ -259,8 +259,7 @@ void QTextDocumentPrivate::clear()
objects.clear();
title.clear();
- undoState = 0;
- truncateUndoStack();
+ clearUndoRedoStacks(QTextDocument::UndoAndRedoStacks);
text = QString();
unreachableCharacterCount = 0;
modifiedState = 0;
@@ -292,7 +291,7 @@ QTextDocumentPrivate::~QTextDocumentPrivate()
cursors.clear();
undoState = 0;
undoEnabled = true;
- truncateUndoStack();
+ clearUndoRedoStacks(QTextDocument::RedoStack);
}
void QTextDocumentPrivate::setLayout(QAbstractTextDocumentLayout *layout)
@@ -1027,7 +1026,7 @@ void QTextDocumentPrivate::appendUndoItem(const QTextUndoCommand &c)
if (!undoEnabled)
return;
if (undoState < undoStack.size())
- truncateUndoStack();
+ clearUndoRedoStacks(QTextDocument::RedoStack);
if (!undoStack.isEmpty() && modified) {
QTextUndoCommand &last = undoStack[undoState - 1];
@@ -1050,26 +1049,46 @@ void QTextDocumentPrivate::appendUndoItem(const QTextUndoCommand &c)
emit document()->undoCommandAdded();
}
-void QTextDocumentPrivate::truncateUndoStack()
+void QTextDocumentPrivate::clearUndoRedoStacks(QTextDocument::Stacks stacksToClear,
+ bool emitSignals)
{
- if (undoState == undoStack.size())
- return;
-
- for (int i = undoState; i < undoStack.size(); ++i) {
- QTextUndoCommand c = undoStack[i];
- if (c.command & QTextUndoCommand::Removed) {
- // ########
-// QTextFragment *f = c.fragment_list;
-// while (f) {
-// QTextFragment *n = f->right;
-// delete f;
-// f = n;
-// }
- } else if (c.command & QTextUndoCommand::Custom) {
- delete c.custom;
+ bool undoCommandsAvailable = undoState != 0;
+ bool redoCommandsAvailable = undoState != undoStack.size();
+ if (stacksToClear == QTextDocument::UndoStack && undoCommandsAvailable) {
+ for (int i = 0; i < undoState; ++i) {
+ QTextUndoCommand c = undoStack[undoState];
+ if (c.command & QTextUndoCommand::Custom)
+ delete c.custom;
}
+ undoStack.remove(0, undoState);
+ undoStack.resize(undoStack.size() - undoState);
+ undoState = 0;
+ if (emitSignals)
+ emitUndoAvailable(false);
+ } else if (stacksToClear == QTextDocument::RedoStack
+ && redoCommandsAvailable) {
+ for (int i = undoState; i < undoStack.size(); ++i) {
+ QTextUndoCommand c = undoStack[i];
+ if (c.command & QTextUndoCommand::Custom)
+ delete c.custom;
+ }
+ undoStack.resize(undoState);
+ if (emitSignals)
+ emitRedoAvailable(false);
+ } else if (stacksToClear == QTextDocument::UndoAndRedoStacks
+ && !undoStack.isEmpty()) {
+ for (int i = 0; i < undoStack.size(); ++i) {
+ QTextUndoCommand c = undoStack[i];
+ if (c.command & QTextUndoCommand::Custom)
+ delete c.custom;
+ }
+ undoState = 0;
+ undoStack.resize(0);
+ if (emitSignals && undoCommandsAvailable)
+ emitUndoAvailable(false);
+ if (emitSignals && redoCommandsAvailable)
+ emitRedoAvailable(false);
}
- undoStack.resize(undoState);
}
void QTextDocumentPrivate::emitUndoAvailable(bool available)
@@ -1097,7 +1116,7 @@ void QTextDocumentPrivate::enableUndoRedo(bool enable)
if (!enable) {
undoState = 0;
- truncateUndoStack();
+ clearUndoRedoStacks(QTextDocument::RedoStack);
emitUndoAvailable(false);
emitRedoAvailable(false);
}
diff --git a/src/gui/text/qtextdocument_p.h b/src/gui/text/qtextdocument_p.h
index 4ecc2fa..ac5ed3c 100644
--- a/src/gui/text/qtextdocument_p.h
+++ b/src/gui/text/qtextdocument_p.h
@@ -252,10 +252,11 @@ public:
inline QFont defaultFont() const { return formats.defaultFont(); }
inline void setDefaultFont(const QFont &f) { formats.setDefaultFont(f); }
+ void clearUndoRedoStacks(QTextDocument::Stacks stacksToClear, bool emitSignals = false);
+
private:
bool split(int pos);
bool unite(uint f);
- void truncateUndoStack();
void insert_string(int pos, uint strPos, uint length, int format, QTextUndoCommand::Operation op);
int insert_block(int pos, uint strPos, int format, int blockformat, QTextUndoCommand::Operation op, int command);
diff --git a/src/gui/text/qzipreader_p.h b/src/gui/text/qzipreader_p.h
index 67a2ace..9b73373 100644
--- a/src/gui/text/qzipreader_p.h
+++ b/src/gui/text/qzipreader_p.h
@@ -62,7 +62,7 @@ QT_BEGIN_NAMESPACE
class QZipReaderPrivate;
-class Q_AUTOTEST_EXPORT QZipReader
+class Q_GUI_EXPORT QZipReader
{
public:
QZipReader(const QString &fileName, QIODevice::OpenMode mode = QIODevice::ReadOnly );
@@ -73,7 +73,7 @@ public:
bool isReadable() const;
bool exists() const;
- struct Q_AUTOTEST_EXPORT FileInfo
+ struct Q_GUI_EXPORT FileInfo
{
FileInfo();
FileInfo(const FileInfo &other);
diff --git a/src/gui/util/qcompleter.cpp b/src/gui/util/qcompleter.cpp
index cefdb27..b7be967 100644
--- a/src/gui/util/qcompleter.cpp
+++ b/src/gui/util/qcompleter.cpp
@@ -62,7 +62,7 @@
\snippet doc/src/snippets/code/src_gui_util_qcompleter.cpp 0
- A QDirModel can be used to provide auto completion of file names.
+ A QFileSystemModel can be used to provide auto completion of file names.
For example:
\snippet doc/src/snippets/code/src_gui_util_qcompleter.cpp 1
@@ -120,7 +120,7 @@
completion is then performed one level at a time.
Let's take the example of a user typing in a file system path.
- The model is a (hierarchical) QDirModel. The completion
+ The model is a (hierarchical) QFileSystemModel. The completion
occurs for every element in the path. For example, if the current
text is \c C:\Wind, QCompleter might suggest \c Windows to
complete the current path element. Similarly, if the current text
@@ -130,12 +130,12 @@
split the path into a list of strings that are matched at each level.
For \c C:\Windows\Sy, it needs to be split as "C:", "Windows" and "Sy".
The default implementation of splitPath(), splits the completionPrefix
- using QDir::separator() if the model is a QDirModel.
+ using QDir::separator() if the model is a QFileSystemModel.
To provide completions, QCompleter needs to know the path from an index.
This is provided by pathFromIndex(). The default implementation of
pathFromIndex(), returns the data for the \l{Qt::EditRole}{edit role}
- for list models and the absolute file path if the mode is a QDirModel.
+ for list models and the absolute file path if the mode is a QFileSystemModel.
\sa QAbstractItemModel, QLineEdit, QComboBox, {Completer Example}
*/
@@ -147,6 +147,7 @@
#include "QtGui/qscrollbar.h"
#include "QtGui/qstringlistmodel.h"
#include "QtGui/qdirmodel.h"
+#include "QtGui/qfilesystemmodel.h"
#include "QtGui/qheaderview.h"
#include "QtGui/qlistview.h"
#include "QtGui/qapplication.h"
@@ -470,9 +471,13 @@ QMatchData QCompletionEngine::filterHistory()
QAbstractItemModel *source = c->proxy->sourceModel();
if (curParts.count() <= 1 || c->proxy->showAll || !source)
return QMatchData();
- bool dirModel = false;
+ bool isDirModel = false;
+ bool isFsModel = false;
#ifndef QT_NO_DIRMODEL
- dirModel = (qobject_cast<QDirModel *>(source) != 0);
+ isDirModel = (qobject_cast<QDirModel *>(source) != 0);
+#endif
+#ifndef QT_NO_FILESYSTEMMODEL
+ isFsModel = (qobject_cast<QFileSystemModel *>(source) != 0);
#endif
QVector<int> v;
QIndexMapper im(v);
@@ -482,7 +487,7 @@ QMatchData QCompletionEngine::filterHistory()
QString str = source->index(i, c->column).data().toString();
if (str.startsWith(c->prefix, c->cs)
#if (!defined(Q_OS_WIN) || defined(Q_OS_WINCE)) && !defined(Q_OS_SYMBIAN)
- && (!dirModel || QDir::toNativeSeparators(str) != QDir::separator())
+ && ((!isFsModel && !isDirModel) || QDir::toNativeSeparators(str) != QDir::separator())
#endif
)
m.indices.append(i);
@@ -838,6 +843,13 @@ void QCompleterPrivate::_q_complete(QModelIndex index, bool highlighted)
completion += QDir::separator();
}
#endif
+#ifndef QT_NO_FILESYSTEMMODEL
+ // add a trailing separator in inline
+ if (mode == QCompleter::InlineCompletion) {
+ if (qobject_cast<QFileSystemModel *>(proxy->sourceModel()) && QFileInfo(completion).isDir())
+ completion += QDir::separator();
+ }
+#endif
}
if (highlighted) {
@@ -891,6 +903,14 @@ void QCompleterPrivate::showPopup(const QRect& rect)
popup->show();
}
+void QCompleterPrivate::_q_fileSystemModelDirectoryLoaded(const QString &path)
+{
+ Q_Q(QCompleter);
+ //the path given by QFileSystemModel does not end with /
+ if (q->completionPrefix() != path + QLatin1Char('/'))
+ q->complete();
+}
+
/*!
Constructs a completer object with the given \a parent.
*/
@@ -971,7 +991,7 @@ QWidget *QCompleter::widget() const
be list model or a tree model. If a model has been already previously set
and it has the QCompleter as its parent, it is deleted.
- For convenience, if \a model is a QDirModel, QCompleter switches its
+ For convenience, if \a model is a QFileSystemModel, QCompleter switches its
caseSensitivity to Qt::CaseInsensitive on Windows and Qt::CaseSensitive
on other platforms.
@@ -995,6 +1015,18 @@ void QCompleter::setModel(QAbstractItemModel *model)
#endif
}
#endif // QT_NO_DIRMODEL
+#ifndef QT_NO_FILESYSTEMMODEL
+ QFileSystemModel *fsModel = qobject_cast<QFileSystemModel *>(model);
+ if (fsModel) {
+#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) || defined(Q_OS_SYMBIAN)
+ setCaseSensitivity(Qt::CaseInsensitive);
+#else
+ setCaseSensitivity(Qt::CaseSensitive);
+#endif
+ setCompletionRole(QFileSystemModel::FileNameRole);
+ connect(fsModel, SIGNAL(directoryLoaded(QString)), this, SLOT(_q_fileSystemModelDirectoryLoaded(QString)));
+ }
+#endif // QT_NO_FILESYSTEMMODEL
}
/*!
@@ -1626,10 +1658,11 @@ QAbstractItemModel *QCompleter::completionModel() const
The default implementation returns the \l{Qt::EditRole}{edit role} of the
item for list models. It returns the absolute file path if the model is a
- QDirModel.
+ QFileSystemModel.
\sa splitPath()
*/
+
QString QCompleter::pathFromIndex(const QModelIndex& index) const
{
Q_D(const QCompleter);
@@ -1639,16 +1672,25 @@ QString QCompleter::pathFromIndex(const QModelIndex& index) const
QAbstractItemModel *sourceModel = d->proxy->sourceModel();
if (!sourceModel)
return QString();
+ bool isDirModel = false;
+ bool isFsModel = false;
#ifndef QT_NO_DIRMODEL
- QDirModel *dirModel = qobject_cast<QDirModel *>(sourceModel);
- if (!dirModel)
+ isDirModel = qobject_cast<QDirModel *>(d->proxy->sourceModel()) != 0;
+#endif
+#ifndef QT_NO_FILESYSTEMMODEL
+ isFsModel = qobject_cast<QFileSystemModel *>(d->proxy->sourceModel()) != 0;
#endif
+ if (!isDirModel && !isFsModel)
return sourceModel->data(index, d->role).toString();
QModelIndex idx = index;
QStringList list;
do {
- QString t = sourceModel->data(idx, Qt::EditRole).toString();
+ QString t;
+ if (isDirModel)
+ t = sourceModel->data(idx, Qt::EditRole).toString();
+ else
+ t = sourceModel->data(idx, QFileSystemModel::FileNameRole).toString();
list.prepend(t);
QModelIndex parent = idx.parent();
idx = parent.sibling(parent.row(), index.column());
@@ -1668,7 +1710,7 @@ QString QCompleter::pathFromIndex(const QModelIndex& index) const
in the model().
The default implementation of splitPath() splits a file system path based on
- QDir::separator() when the sourceModel() is a QDirModel.
+ QDir::separator() when the sourceModel() is a QFileSystemModel.
When used with list models, the first item in the returned list is used for
matching.
@@ -1678,12 +1720,19 @@ QString QCompleter::pathFromIndex(const QModelIndex& index) const
QStringList QCompleter::splitPath(const QString& path) const
{
bool isDirModel = false;
+ bool isFsModel = false;
#ifndef QT_NO_DIRMODEL
Q_D(const QCompleter);
isDirModel = qobject_cast<QDirModel *>(d->proxy->sourceModel()) != 0;
#endif
+#ifndef QT_NO_FILESYSTEMMODEL
+#ifdef QT_NO_DIRMODEL
+ Q_D(const QCompleter);
+#endif
+ isFsModel = qobject_cast<QFileSystemModel *>(d->proxy->sourceModel()) != 0;
+#endif
- if (!isDirModel || path.isEmpty())
+ if ((!isDirModel && !isFsModel) || path.isEmpty())
return QStringList(completionPrefix());
QString pathCopy = QDir::toNativeSeparators(path);
diff --git a/src/gui/util/qcompleter.h b/src/gui/util/qcompleter.h
index 5123a40..0cef9be 100644
--- a/src/gui/util/qcompleter.h
+++ b/src/gui/util/qcompleter.h
@@ -159,6 +159,7 @@ private:
Q_PRIVATE_SLOT(d_func(), void _q_complete(QModelIndex))
Q_PRIVATE_SLOT(d_func(), void _q_completionSelected(const QItemSelection&))
Q_PRIVATE_SLOT(d_func(), void _q_autoResizePopup())
+ Q_PRIVATE_SLOT(d_func(), void _q_fileSystemModelDirectoryLoaded(const QString&))
};
#endif // QT_NO_COMPLETER
diff --git a/src/gui/util/qcompleter_p.h b/src/gui/util/qcompleter_p.h
index 44be4c0..8f00793 100644
--- a/src/gui/util/qcompleter_p.h
+++ b/src/gui/util/qcompleter_p.h
@@ -98,6 +98,7 @@ public:
void _q_complete(QModelIndex, bool = false);
void _q_completionSelected(const QItemSelection&);
void _q_autoResizePopup();
+ void _q_fileSystemModelDirectoryLoaded(const QString &path);
void setCurrentIndex(QModelIndex, bool = true);
};
diff --git a/src/gui/util/qdesktopservices_win.cpp b/src/gui/util/qdesktopservices_win.cpp
index 9f3b6e1..aab7e16 100644
--- a/src/gui/util/qdesktopservices_win.cpp
+++ b/src/gui/util/qdesktopservices_win.cpp
@@ -59,7 +59,7 @@
# endif
#endif
-#if defined(Q_CC_MINGW) && !defined(CSIDL_MYMUSIC)
+#ifndef CSIDL_MYMUSIC
#define CSIDL_MYMUSIC 13
#define CSIDL_MYVIDEO 14
#endif
@@ -97,19 +97,19 @@ static bool launchWebBrowser(const QUrl &url)
if (url.scheme() == QLatin1String("mailto")) {
//Retrieve the commandline for the default mail client
//the default key used below is the command line for the mailto: shell command
- DWORD bufferSize = 2 * MAX_PATH;
+ DWORD bufferSize = sizeof(wchar_t) * MAX_PATH;
long returnValue = -1;
QString command;
HKEY handle;
LONG res;
- wchar_t keyValue[2 * MAX_PATH] = {0};
+ wchar_t keyValue[MAX_PATH] = {0};
QString keyName(QLatin1String("mailto"));
//Check if user has set preference, otherwise use default.
- res = RegOpenKeyExW(HKEY_CURRENT_USER,
- L"Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\mailto\\UserChoice",
- 0, KEY_READ, &handle);
+ res = RegOpenKeyEx(HKEY_CURRENT_USER,
+ L"Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\mailto\\UserChoice",
+ 0, KEY_READ, &handle);
if (res == ERROR_SUCCESS) {
returnValue = RegQueryValueEx(handle, L"Progid", 0, 0, reinterpret_cast<unsigned char*>(keyValue), &bufferSize);
if (!returnValue)
@@ -121,8 +121,8 @@ static bool launchWebBrowser(const QUrl &url)
if (res != ERROR_SUCCESS)
return false;
- bufferSize = 2 * MAX_PATH;
- returnValue = RegQueryValueExW(handle, L"", 0, 0, reinterpret_cast<unsigned char*>(keyValue), &bufferSize);
+ bufferSize = sizeof(wchar_t) * MAX_PATH;
+ returnValue = RegQueryValueEx(handle, L"", 0, 0, reinterpret_cast<unsigned char*>(keyValue), &bufferSize);
if (!returnValue)
command = QString::fromRawData((QChar*)keyValue, bufferSize);
RegCloseKey(handle);
diff --git a/src/gui/util/qsystemtrayicon_win.cpp b/src/gui/util/qsystemtrayicon_win.cpp
index 6db158e..8e482e0 100644
--- a/src/gui/util/qsystemtrayicon_win.cpp
+++ b/src/gui/util/qsystemtrayicon_win.cpp
@@ -53,7 +53,6 @@
#include <qt_windows.h>
#include <commctrl.h>
-#include <shlwapi.h>
#include <QBitmap>
#include <QLibrary>
#include <QApplication>
@@ -326,8 +325,6 @@ bool QSystemTrayIconSys::winEvent( MSG *m, long *result )
q->contextMenu()->move(gpos);
}
#endif
- q->contextMenu()->activateWindow();
- //Must be activated for proper keyboardfocus and menu closing on windows:
}
emit q->activated(QSystemTrayIcon::Context);
break;
diff --git a/src/gui/widgets/qcocoamenu_mac.mm b/src/gui/widgets/qcocoamenu_mac.mm
index a7e0b79..ce85919 100644
--- a/src/gui/widgets/qcocoamenu_mac.mm
+++ b/src/gui/widgets/qcocoamenu_mac.mm
@@ -46,6 +46,7 @@
#import <private/qcocoamenuloader_mac_p.h>
#include <private/qt_cocoa_helpers_mac_p.h>
#include <private/qapplication_p.h>
+#include <private/qaction_p.h>
#include <QtGui/QMenu>
@@ -70,6 +71,7 @@ QT_USE_NAMESPACE
self = [super init];
if (self) {
qmenu = menu;
+ previousAction = 0;
[self setAutoenablesItems:NO];
[self setDelegate:self];
}
@@ -81,13 +83,20 @@ QT_USE_NAMESPACE
Q_UNUSED(menu);
if (!item) {
- // ### According to the docs everything will be highlighted. Not sure what we should do in
- // Qt, so just return.
+ if (previousAction) {
+ qt_mac_clear_status_text(previousAction);
+ previousAction = 0;
+ }
return;
}
- if (QAction *action = reinterpret_cast<QAction *>([item tag]))
+ if (QAction *action = reinterpret_cast<QAction *>([item tag])) {
+ QMenu *qtmenu = static_cast<QT_MANGLE_NAMESPACE(QCocoaMenu) *>(menu)->qmenu;
+ previousAction = action;
action->activate(QAction::Hover);
+ qt_mac_menu_emit_hovered(qtmenu, action);
+ action->showStatusText(0); // 0 widget -> action's parent
+ }
}
- (void)menuWillOpen:(NSMenu*)menu;
@@ -100,9 +109,13 @@ QT_USE_NAMESPACE
qt_mac_menu_collapseSeparators(menu, qtmenu->separatorsCollapsible());
}
-- (void)menuWillClose:(NSMenu*)menu;
+- (void)menuDidClose:(NSMenu*)menu;
{
qt_mac_emit_menuSignals(((QT_MANGLE_NAMESPACE(QCocoaMenu) *)menu)->qmenu, false);
+ if (previousAction) {
+ qt_mac_clear_status_text(previousAction);
+ previousAction = 0;
+ }
}
- (BOOL)hasShortcut:(NSMenu *)menu forKey:(NSString *)key forModifiers:(NSUInteger)modifier
@@ -194,6 +207,18 @@ void qt_mac_emit_menuSignals(QMenu *menu, bool show)
}
qt_mac_menus_open_count += delta;
}
+
+void qt_mac_clear_status_text(QAction *action)
+{
+ action->d_func()->showStatusText(0, QString());
+}
+
+void qt_mac_menu_emit_hovered(QMenu *menu, QAction *action)
+{
+ emit menu->hovered(action);
+}
+
+
QT_END_NAMESPACE
#endif
diff --git a/src/gui/widgets/qcocoamenu_mac_p.h b/src/gui/widgets/qcocoamenu_mac_p.h
index 9f50c40..d6ac8c5 100644
--- a/src/gui/widgets/qcocoamenu_mac_p.h
+++ b/src/gui/widgets/qcocoamenu_mac_p.h
@@ -55,13 +55,14 @@
#import <Cocoa/Cocoa.h>
QT_FORWARD_DECLARE_CLASS(QMenu)
+QT_FORWARD_DECLARE_CLASS(QAction)
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
@protocol NSMenuDelegate <NSObject>
- (void)menu:(NSMenu*)menu willHighlightItem:(NSMenuItem*)item;
- (void)menuWillOpen:(NSMenu*)menu;
-- (void)menuWillClose:(NSMenu*)menu;
+- (void)menuDidClose:(NSMenu*)menu;
- (BOOL)hasShortcut:(NSMenu *)menu forKey:(NSString *)key forModifiers:(NSUInteger)modifier
whichItem:(NSMenuItem**)outItem;
@end
@@ -71,6 +72,7 @@ QT_FORWARD_DECLARE_CLASS(QMenu)
@interface QT_MANGLE_NAMESPACE(QCocoaMenu) : NSMenu <NSMenuDelegate>
{
QMenu *qmenu;
+ QAction *previousAction;
}
- (id)initWithQMenu:(QMenu*)menu;
- (BOOL)menuHasKeyEquivalent:(NSMenu *)menu forEvent:(NSEvent *)event target:(id *)target action:(SEL *)action;
diff --git a/src/gui/widgets/qcombobox.cpp b/src/gui/widgets/qcombobox.cpp
index 72f32dc..be20a38 100644
--- a/src/gui/widgets/qcombobox.cpp
+++ b/src/gui/widgets/qcombobox.cpp
@@ -1268,7 +1268,8 @@ QComboBox::~QComboBox()
By default, this property has a value of 10.
- \note This property is ignored for non-editable comboboxes in Mac style.
+ \note This property is ignored for non-editable comboboxes in styles that returns
+ false for QStyle::SH_ComboBox_Popup such as the Mac style or the Gtk+ Style.
*/
int QComboBox::maxVisibleItems() const
{
@@ -2348,7 +2349,7 @@ void QComboBox::showPopup()
toCheck.push(idx);
#endif
++count;
- if (!usePopup && count > d->maxVisibleItems) {
+ if (!usePopup && count >= d->maxVisibleItems) {
toCheck.clear();
break;
}
diff --git a/src/gui/widgets/qdatetimeedit.cpp b/src/gui/widgets/qdatetimeedit.cpp
index 762db86..50fa9c9 100644
--- a/src/gui/widgets/qdatetimeedit.cpp
+++ b/src/gui/widgets/qdatetimeedit.cpp
@@ -1175,7 +1175,7 @@ void QDateTimeEdit::keyPressEvent(QKeyEvent *event)
return; }
}
QAbstractSpinBox::keyPressEvent(event);
- if (select && !(event->modifiers() & Qt::ShiftModifier) && !d->edit->hasSelectedText()) {
+ if (select && !d->edit->hasSelectedText()) {
if (inserted && d->sectionAt(d->edit->cursorPosition()) == QDateTimeParser::NoSectionIndex) {
QString str = d->displayText();
int pos = d->edit->cursorPosition();
diff --git a/src/gui/widgets/qdockarealayout.cpp b/src/gui/widgets/qdockarealayout.cpp
index d754800..13f31df 100644
--- a/src/gui/widgets/qdockarealayout.cpp
+++ b/src/gui/widgets/qdockarealayout.cpp
@@ -220,15 +220,17 @@ static quintptr tabId(const QDockAreaLayoutItem &item)
}
#endif
+static const int zero = 0;
+
QDockAreaLayoutInfo::QDockAreaLayoutInfo()
- : sep(0), dockPos(QInternal::LeftDock), o(Qt::Horizontal), mainWindow(0)
+ : sep(&zero), dockPos(QInternal::LeftDock), o(Qt::Horizontal), mainWindow(0)
#ifndef QT_NO_TABBAR
, tabbed(false), tabBar(0), tabBarShape(QTabBar::RoundedSouth), tabBarVisible(false)
#endif
{
}
-QDockAreaLayoutInfo::QDockAreaLayoutInfo(int _sep, QInternal::DockPosition _dockPos,
+QDockAreaLayoutInfo::QDockAreaLayoutInfo(const int *_sep, QInternal::DockPosition _dockPos,
Qt::Orientation _o, int tbshape,
QMainWindow *window)
: sep(_sep), dockPos(_dockPos), o(_o), mainWindow(window)
@@ -281,7 +283,7 @@ QSize QDockAreaLayoutInfo::minimumSize() const
#endif
{
if (!first)
- a += sep;
+ a += *sep;
a += pick(o, min_size);
}
b = qMax(b, perp(o, min_size));
@@ -349,7 +351,7 @@ QSize QDockAreaLayoutInfo::maximumSize() const
#endif
{
if (!first)
- a += sep;
+ a += *sep;
a += pick(o, max_size);
}
b = qMin(b, perp(o, max_size));
@@ -415,7 +417,7 @@ QSize QDockAreaLayoutInfo::sizeHint() const
{
if (previous && !gap && !(previous->flags & QDockAreaLayoutItem::GapItem)
&& !previous->hasFixedSize(o)) {
- a += sep;
+ a += *sep;
}
a += gap ? item.size : pick(o, size_hint);
}
@@ -491,7 +493,7 @@ static int realMinSize(const QDockAreaLayoutInfo &info)
min = pick(info.o, item.minimumSize());
if (!first)
- result += info.sep;
+ result += *info.sep;
result += min;
first = false;
@@ -516,7 +518,7 @@ static int realMaxSize(const QDockAreaLayoutInfo &info)
max = pick(info.o, item.maximumSize());
if (!first)
- result += info.sep;
+ result += *info.sep;
result += max;
if (result >= QWIDGETSIZE_MAX)
@@ -555,7 +557,7 @@ void QDockAreaLayoutInfo::fitItems()
if (!(previous->flags & QDockAreaLayoutItem::GapItem)) {
QLayoutStruct &ls = layout_struct_list[j++];
ls.init();
- ls.minimumSize = ls.maximumSize = ls.sizeHint = previous->hasFixedSize(o) ? 0 : sep;
+ ls.minimumSize = ls.maximumSize = ls.sizeHint = previous->hasFixedSize(o) ? 0 : *sep;
ls.empty = false;
}
}
@@ -938,7 +940,7 @@ int QDockAreaLayoutInfo::separatorMove(int index, int delta)
if (item.skip()) {
ls.empty = true;
} else {
- const int separatorSpace = item.hasFixedSize(o) ? 0 : sep;
+ const int separatorSpace = item.hasFixedSize(o) ? 0 : *sep;
ls.empty = false;
ls.pos = item.pos;
ls.size = item.size + separatorSpace;
@@ -956,7 +958,7 @@ int QDockAreaLayoutInfo::separatorMove(int index, int delta)
if (item.skip())
continue;
QLayoutStruct &ls = list[i];
- const int separatorSpace = item.hasFixedSize(o) ? 0 : sep;
+ const int separatorSpace = item.hasFixedSize(o) ? 0 : *sep;
item.size = ls.size - separatorSpace;
item.pos = ls.pos;
if (item.subinfo != 0) {
@@ -1041,11 +1043,11 @@ QLayoutItem *QDockAreaLayoutInfo::plug(const QList<int> &path)
int next = this->next(index);
if (prev != -1 && !(item_list.at(prev).flags & QDockAreaLayoutItem::GapItem)) {
- item.pos += sep;
- item.size -= sep;
+ item.pos += *sep;
+ item.size -= *sep;
}
if (next != -1 && !(item_list.at(next).flags & QDockAreaLayoutItem::GapItem))
- item.size -= sep;
+ item.size -= *sep;
QPoint pos;
rpick(o, pos) = item.pos;
@@ -1083,11 +1085,11 @@ QLayoutItem *QDockAreaLayoutInfo::unplug(const QList<int> &path)
#endif
{
if (prev != -1 && !(item_list.at(prev).flags & QDockAreaLayoutItem::GapItem)) {
- item.pos -= sep;
- item.size += sep;
+ item.pos -= *sep;
+ item.size += *sep;
}
if (next != -1 && !(item_list.at(next).flags & QDockAreaLayoutItem::GapItem))
- item.size += sep;
+ item.size += *sep;
}
return item.widgetItem;
@@ -1255,9 +1257,9 @@ bool QDockAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *dockWid
QRect r = dockedGeometry(dockWidgetItem->widget());
gap_size = pick(o, r.size());
if (prev != -1 && !(item_list.at(prev).flags & QDockAreaLayoutItem::GapItem))
- sep_size += sep;
+ sep_size += *sep;
if (next != -1 && !(item_list.at(next).flags & QDockAreaLayoutItem::GapItem))
- sep_size += sep;
+ sep_size += *sep;
}
if (gap_size + sep_size > space)
gap_size = pick(o, gap_item.minimumSize());
@@ -1364,7 +1366,7 @@ QRect QDockAreaLayoutInfo::separatorRect(int index) const
QPoint pos = rect.topLeft();
rpick(o, pos) = item.pos + item.size;
QSize s = rect.size();
- rpick(o, s) = sep;
+ rpick(o, s) = *sep;
return QRect(pos, s);
}
@@ -1413,7 +1415,7 @@ QList<int> QDockAreaLayoutInfo::findSeparator(const QPoint &_pos) const
continue;
QRect sepRect = separatorRect(i);
- if (!sepRect.isNull() && sep == 1)
+ if (!sepRect.isNull() && *sep == 1)
sepRect.adjust(-2, -2, 2, 2);
//we also make sure we don't find a separator that's not there
if (sepRect.contains(_pos) && !item.hasFixedSize(o)) {
@@ -1560,7 +1562,7 @@ void QDockAreaLayoutInfo::apply(bool animate)
}
}
#ifndef QT_NO_TABBAR
- if (sep == 1)
+ if (*sep == 1)
updateSeparatorWidgets();
#endif //QT_NO_TABBAR
}
@@ -2010,7 +2012,7 @@ bool QDockAreaLayoutInfo::restoreState(QDataStream &stream, QList<QDockWidget*>
updateTabBar();
setCurrentTabId(tabId(item_list.at(index)));
}
- if (!testing && sep == 1)
+ if (!testing && *sep == 1)
updateSeparatorWidgets();
#endif
@@ -2273,13 +2275,13 @@ QDockAreaLayout::QDockAreaLayout(QMainWindow *win) : fallbackToSizeHints(true)
const int tabShape = 0;
#endif
docks[QInternal::LeftDock]
- = QDockAreaLayoutInfo(sep, QInternal::LeftDock, Qt::Vertical, tabShape, win);
+ = QDockAreaLayoutInfo(&sep, QInternal::LeftDock, Qt::Vertical, tabShape, win);
docks[QInternal::RightDock]
- = QDockAreaLayoutInfo(sep, QInternal::RightDock, Qt::Vertical, tabShape, win);
+ = QDockAreaLayoutInfo(&sep, QInternal::RightDock, Qt::Vertical, tabShape, win);
docks[QInternal::TopDock]
- = QDockAreaLayoutInfo(sep, QInternal::TopDock, Qt::Horizontal, tabShape, win);
+ = QDockAreaLayoutInfo(&sep, QInternal::TopDock, Qt::Horizontal, tabShape, win);
docks[QInternal::BottomDock]
- = QDockAreaLayoutInfo(sep, QInternal::BottomDock, Qt::Horizontal, tabShape, win);
+ = QDockAreaLayoutInfo(&sep, QInternal::BottomDock, Qt::Horizontal, tabShape, win);
centralWidgetItem = 0;
@@ -3028,7 +3030,7 @@ void QDockAreaLayout::addDockWidget(QInternal::DockPosition pos, QDockWidget *do
#else
int tbshape = 0;
#endif
- QDockAreaLayoutInfo new_info(sep, pos, orientation, tbshape, mainWindow);
+ QDockAreaLayoutInfo new_info(&sep, pos, orientation, tbshape, mainWindow);
new_info.item_list.append(new QDockAreaLayoutInfo(info));
new_info.item_list.append(dockWidgetItem);
info = new_info;
@@ -3324,6 +3326,12 @@ void QDockAreaLayout::keepSize(QDockWidget *w)
item.flags |= QDockAreaLayoutItem::KeepSize;
}
+void QDockAreaLayout::styleChangedEvent()
+{
+ sep = mainWindow->style()->pixelMetric(QStyle::PM_DockWidgetSeparatorExtent, 0, mainWindow);
+ fitLayout();
+}
+
QT_END_NAMESPACE
#endif // QT_NO_DOCKWIDGET
diff --git a/src/gui/widgets/qdockarealayout_p.h b/src/gui/widgets/qdockarealayout_p.h
index 0bc1aa9..0088f00 100644
--- a/src/gui/widgets/qdockarealayout_p.h
+++ b/src/gui/widgets/qdockarealayout_p.h
@@ -128,7 +128,7 @@ class Q_AUTOTEST_EXPORT QDockAreaLayoutInfo
{
public:
QDockAreaLayoutInfo();
- QDockAreaLayoutInfo(int _sep, QInternal::DockPosition _dockPos, Qt::Orientation _o,
+ QDockAreaLayoutInfo(const int *_sep, QInternal::DockPosition _dockPos, Qt::Orientation _o,
int tbhape, QMainWindow *window);
QSize minimumSize() const;
@@ -189,7 +189,7 @@ public:
QMainWindowLayout *mainWindowLayout() const;
- int sep;
+ const int *sep;
mutable QVector<QWidget*> separatorWidgets;
QInternal::DockPosition dockPos;
Qt::Orientation o;
@@ -300,6 +300,7 @@ public:
QSet<QTabBar*> usedTabBars() const;
QSet<QWidget*> usedSeparatorWidgets() const;
#endif //QT_NO_TABBAR
+ void styleChangedEvent();
};
QT_END_NAMESPACE
diff --git a/src/gui/widgets/qfocusframe.cpp b/src/gui/widgets/qfocusframe.cpp
index d9cd5bb..4f20bce0 100644
--- a/src/gui/widgets/qfocusframe.cpp
+++ b/src/gui/widgets/qfocusframe.cpp
@@ -53,11 +53,14 @@ class QFocusFramePrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QFocusFrame)
QWidget *widget;
-
+ QWidget *frameParent;
+ bool showFrameAboveWidget;
public:
QFocusFramePrivate() {
widget = 0;
+ frameParent = 0;
sendChildEvents = false;
+ showFrameAboveWidget = false;
}
void updateSize();
void update();
@@ -66,10 +69,10 @@ public:
void QFocusFramePrivate::update()
{
Q_Q(QFocusFrame);
- q->setParent(widget->parentWidget());
+ q->setParent(frameParent);
updateSize();
if (q->parentWidget()->rect().intersects(q->geometry())) {
- if (q->style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, q))
+ if (showFrameAboveWidget)
q->raise();
else
q->stackUnder(widget);
@@ -84,7 +87,10 @@ void QFocusFramePrivate::updateSize()
Q_Q(QFocusFrame);
int vmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameVMargin),
hmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameHMargin);
- QRect geom(widget->x()-hmargin, widget->y()-vmargin,
+ QPoint pos(widget->x(), widget->y());
+ if (q->parentWidget() != widget->parentWidget())
+ pos = widget->parentWidget()->mapTo(q->parentWidget(), pos);
+ QRect geom(pos.x()-hmargin, pos.y()-vmargin,
widget->width()+(hmargin*2), widget->height()+(vmargin*2));
if(q->geometry() == geom)
return;
@@ -176,14 +182,52 @@ void
QFocusFrame::setWidget(QWidget *widget)
{
Q_D(QFocusFrame);
- if(widget == d->widget)
- return;
- if(d->widget)
- d->widget->removeEventFilter(this);
- if(widget && !widget->isWindow() && widget->parentWidget()->windowType() != Qt::SubWindow) {
+ if (style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, this))
+ d->showFrameAboveWidget = true;
+ else
+ d->showFrameAboveWidget = false;
+
+ if (widget == d->widget)
+ return;
+ if (d->widget) {
+ // Remove event filters from the widget hierarchy.
+ QWidget *p = d->widget;
+ do {
+ p->removeEventFilter(this);
+ if (!d->showFrameAboveWidget || p == d->frameParent)
+ break;
+ p = p->parentWidget();
+ }while (p);
+ }
+ if (widget && !widget->isWindow() && widget->parentWidget()->windowType() != Qt::SubWindow) {
d->widget = widget;
- widget->installEventFilter(this);
+ d->widget->installEventFilter(this);
+ QWidget *p = widget->parentWidget();
+ QWidget *prev = 0;
+ if (d->showFrameAboveWidget) {
+ // Find the right parent for the focus frame.
+ while (p) {
+ // Traverse the hirerarchy of the 'widget' for setting event filter.
+ // During this if come across toolbar or a top level, use that
+ // as the parent for the focus frame. If we find a scroll area
+ // use its viewport as the parent.
+ bool isScrollArea = false;
+ if (p->isWindow() || p->inherits("QToolBar") || (isScrollArea = p->inherits("QAbstractScrollArea"))) {
+ d->frameParent = p;
+ // The previous one in the hierarchy will be the viewport.
+ if (prev && isScrollArea)
+ d->frameParent = prev;
+ break;
+ } else {
+ p->installEventFilter(this);
+ prev = p;
+ p = p->parentWidget();
+ }
+ }
+ } else {
+ d->frameParent = p;
+ }
d->update();
} else {
d->widget = 0;
@@ -210,9 +254,15 @@ QFocusFrame::widget() const
void
QFocusFrame::paintEvent(QPaintEvent *)
{
+ Q_D(QFocusFrame);
QStylePainter p(this);
QStyleOption option;
initStyleOption(&option);
+ int vmargin = style()->pixelMetric(QStyle::PM_FocusFrameVMargin);
+ int hmargin = style()->pixelMetric(QStyle::PM_FocusFrameHMargin);
+ QWidgetPrivate *wd = qt_widget_private(d->widget);
+ QRect rect = wd->clipRect().adjusted(0, 0, hmargin*2, vmargin*2);
+ p.setClipRect(rect);
p.drawControl(QStyle::CE_FocusFrame, option);
}
@@ -233,7 +283,13 @@ QFocusFrame::eventFilter(QObject *o, QEvent *e)
hide();
break;
case QEvent::ParentChange:
- d->update();
+ if (d->showFrameAboveWidget) {
+ QWidget *w = d->widget;
+ setWidget(0);
+ setWidget(w);
+ } else {
+ d->update();
+ }
break;
case QEvent::Show:
d->update();
@@ -254,6 +310,19 @@ QFocusFrame::eventFilter(QObject *o, QEvent *e)
default:
break;
}
+ } else if (d->showFrameAboveWidget) {
+ // Handle changes in the parent widgets we are monitoring.
+ switch(e->type()) {
+ case QEvent::Move:
+ case QEvent::Resize:
+ d->updateSize();
+ break;
+ case QEvent::ZOrderChange:
+ raise();
+ break;
+ default:
+ break;
+ }
}
return false;
}
diff --git a/src/gui/widgets/qlabel.cpp b/src/gui/widgets/qlabel.cpp
index 8428ad7..b81f04f 100644
--- a/src/gui/widgets/qlabel.cpp
+++ b/src/gui/widgets/qlabel.cpp
@@ -781,6 +781,95 @@ Qt::TextInteractionFlags QLabel::textInteractionFlags() const
return d->textInteractionFlags;
}
+/*!
+ Selects text from position \a start and for \a length characters.
+
+ \sa selectedText()
+
+ \bold{Note:} The textInteractionFlags set on the label need to include
+ either TextSelectableByMouse or TextSelectableByKeyboard.
+
+ \since 4.7
+*/
+void QLabel::setSelection(int start, int length)
+{
+ Q_D(QLabel);
+ if (d->control) {
+ d->ensureTextPopulated();
+ QTextCursor cursor = d->control->textCursor();
+ cursor.setPosition(start);
+ cursor.setPosition(start + length, QTextCursor::KeepAnchor);
+ d->control->setTextCursor(cursor);
+ }
+}
+
+/*!
+ \property QLabel::hasSelectedText
+ \brief whether there is any text selected
+
+ hasSelectedText() returns true if some or all of the text has been
+ selected by the user; otherwise returns false.
+
+ By default, this property is false.
+
+ \sa selectedText()
+
+ \bold{Note:} The textInteractionFlags set on the label need to include
+ either TextSelectableByMouse or TextSelectableByKeyboard.
+
+ \since 4.7
+*/
+bool QLabel::hasSelectedText() const
+{
+ Q_D(const QLabel);
+ if (d->control)
+ return d->control->textCursor().hasSelection();
+ return false;
+}
+
+/*!
+ \property QLabel::selectedText
+ \brief the selected text
+
+ If there is no selected text this property's value is
+ an empty string.
+
+ By default, this property contains an empty string.
+
+ \sa hasSelectedText()
+
+ \bold{Note:} The textInteractionFlags set on the label need to include
+ either TextSelectableByMouse or TextSelectableByKeyboard.
+
+ \since 4.7
+*/
+QString QLabel::selectedText() const
+{
+ Q_D(const QLabel);
+ if (d->control)
+ return d->control->textCursor().selectedText();
+ return QString();
+}
+
+/*!
+ selectionStart() returns the index of the first selected character in the
+ label or -1 if no text is selected.
+
+ \sa selectedText()
+
+ \bold{Note:} The textInteractionFlags set on the label need to include
+ either TextSelectableByMouse or TextSelectableByKeyboard.
+
+ \since 4.7
+*/
+int QLabel::selectionStart() const
+{
+ Q_D(const QLabel);
+ if (d->control && d->control->textCursor().hasSelection())
+ return d->control->textCursor().selectionStart();
+ return -1;
+}
+
/*!\reimp
*/
QSize QLabel::sizeHint() const
@@ -862,8 +951,8 @@ void QLabel::contextMenuEvent(QContextMenuEvent *ev)
return;
}
ev->accept();
- menu->exec(ev->globalPos());
- delete menu;
+ menu->setAttribute(Qt::WA_DeleteOnClose);
+ menu->popup(ev->globalPos());
#endif
}
diff --git a/src/gui/widgets/qlabel.h b/src/gui/widgets/qlabel.h
index d916078..54babb1 100644
--- a/src/gui/widgets/qlabel.h
+++ b/src/gui/widgets/qlabel.h
@@ -65,6 +65,8 @@ class Q_GUI_EXPORT QLabel : public QFrame
Q_PROPERTY(int indent READ indent WRITE setIndent)
Q_PROPERTY(bool openExternalLinks READ openExternalLinks WRITE setOpenExternalLinks)
Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
+ Q_PROPERTY(bool hasSelectedText READ hasSelectedText)
+ Q_PROPERTY(QString selectedText READ selectedText)
public:
explicit QLabel(QWidget *parent=0, Qt::WindowFlags f=0);
@@ -111,6 +113,11 @@ public:
void setTextInteractionFlags(Qt::TextInteractionFlags flags);
Qt::TextInteractionFlags textInteractionFlags() const;
+ void setSelection(int, int);
+ bool hasSelectedText() const;
+ QString selectedText() const;
+ int selectionStart() const;
+
public Q_SLOTS:
void setText(const QString &);
void setPixmap(const QPixmap &);
diff --git a/src/gui/widgets/qlineedit.cpp b/src/gui/widgets/qlineedit.cpp
index 2d2df92..0ba8b9f 100644
--- a/src/gui/widgets/qlineedit.cpp
+++ b/src/gui/widgets/qlineedit.cpp
@@ -1637,12 +1637,8 @@ void QLineEdit::keyPressEvent(QKeyEvent *event)
if (!hasEditFocus() && !(event->modifiers() & Qt::ControlModifier)) {
if (!event->text().isEmpty() && event->text().at(0).isPrint()
&& !isReadOnly())
- {
setEditFocus(true);
-#ifndef Q_OS_SYMBIAN
- clear();
-#endif
- } else {
+ else {
event->ignore();
return;
}
@@ -1698,12 +1694,8 @@ void QLineEdit::inputMethodEvent(QInputMethodEvent *e)
// commit text as they focus out without interfering with focus
if (QApplication::keypadNavigationEnabled()
&& hasFocus() && !hasEditFocus()
- && !e->preeditString().isEmpty()) {
+ && !e->preeditString().isEmpty())
setEditFocus(true);
-#ifndef Q_OS_SYMBIAN
- selectAll(); // so text is replaced rather than appended to
-#endif
- }
#endif
d->control->processInputMethodEvent(e);
@@ -2046,9 +2038,9 @@ void QLineEdit::dropEvent(QDropEvent* e)
*/
void QLineEdit::contextMenuEvent(QContextMenuEvent *event)
{
- QPointer<QMenu> menu = createStandardContextMenu();
- menu->exec(event->globalPos());
- delete menu;
+ QMenu *menu = createStandardContextMenu();
+ menu->setAttribute(Qt::WA_DeleteOnClose);
+ menu->popup(event->globalPos());
}
#if defined(Q_WS_WIN)
diff --git a/src/gui/widgets/qmainwindow.cpp b/src/gui/widgets/qmainwindow.cpp
index 269cd12..a63f3bf 100644
--- a/src/gui/widgets/qmainwindow.cpp
+++ b/src/gui/widgets/qmainwindow.cpp
@@ -1393,6 +1393,7 @@ bool QMainWindow::event(QEvent *event)
#endif // QT_NO_STATUSTIP
case QEvent::StyleChange:
+ d->layout->layoutState.dockAreaLayout.styleChangedEvent();
if (!d->explicitIconSize)
setIconSize(QSize());
break;
@@ -1554,11 +1555,15 @@ void QMainWindow::contextMenuEvent(QContextMenuEvent *event)
#ifndef QT_NO_MENU
QMenu *popup = createPopupMenu();
- if (popup && !popup->isEmpty()) {
- popup->exec(event->globalPos());
- event->accept();
+ if (popup) {
+ if (!popup->isEmpty()) {
+ popup->setAttribute(Qt::WA_DeleteOnClose);
+ popup->popup(event->globalPos());
+ event->accept();
+ } else {
+ delete popup;
+ }
}
- delete popup;
#endif
}
#endif // QT_NO_CONTEXTMENU
diff --git a/src/gui/widgets/qmenu.cpp b/src/gui/widgets/qmenu.cpp
index 8ce7cc0..08960da 100644
--- a/src/gui/widgets/qmenu.cpp
+++ b/src/gui/widgets/qmenu.cpp
@@ -2302,9 +2302,7 @@ void QMenu::mouseReleaseEvent(QMouseEvent *e)
QAction *action = d->actionAt(e->pos());
if (action && action == d->currentAction) {
- if (action->menu())
- action->menu()->d_func()->setFirstActionActive();
- else {
+ if (!action->menu()){
#if defined(Q_WS_WIN)
//On Windows only context menus can be activated with the right button
if (e->button() == Qt::LeftButton || d->topCausedWidget() == 0)
diff --git a/src/gui/widgets/qmenu.h b/src/gui/widgets/qmenu.h
index 47dff2b..a040afa 100644
--- a/src/gui/widgets/qmenu.h
+++ b/src/gui/widgets/qmenu.h
@@ -417,6 +417,7 @@ private:
friend OSStatus qt_mac_menu_event(EventHandlerCallRef, EventRef, void *);
friend bool qt_mac_activate_action(OSMenuRef, uint, QAction::ActionEvent, bool);
friend void qt_mac_emit_menuSignals(QMenu *, bool);
+ friend void qt_mac_menu_emit_hovered(QMenu *menu, QAction *action);
#endif
};
diff --git a/src/gui/widgets/qmenu_mac.mm b/src/gui/widgets/qmenu_mac.mm
index 7e4bbb5..658a020 100644
--- a/src/gui/widgets/qmenu_mac.mm
+++ b/src/gui/widgets/qmenu_mac.mm
@@ -247,7 +247,7 @@ bool qt_mac_activate_action(MenuRef menu, uint command, QAction::ActionEvent act
//now walk up firing for each "caused" widget (like in the platform independent menu)
QWidget *caused = 0;
- if (GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget, sizeof(caused), 0, &caused) == noErr) {
+ if (action_e == QAction::Hover && GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget, sizeof(caused), 0, &caused) == noErr) {
MenuRef caused_menu = 0;
if (QMenu *qmenu2 = qobject_cast<QMenu*>(caused))
caused_menu = qmenu2->macMenu();
@@ -260,25 +260,17 @@ bool qt_mac_activate_action(MenuRef menu, uint command, QAction::ActionEvent act
QWidget *widget = 0;
GetMenuItemProperty(caused_menu, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(widget), 0, &widget);
if (QMenu *qmenu = qobject_cast<QMenu*>(widget)) {
- if (action_e == QAction::Trigger) {
- emit qmenu->triggered(action->action);
- } else if (action_e == QAction::Hover) {
- action->action->showStatusText(widget);
- emit qmenu->hovered(action->action);
- }
+ action->action->showStatusText(widget);
+ emit qmenu->hovered(action->action);
} else if (QMenuBar *qmenubar = qobject_cast<QMenuBar*>(widget)) {
- if (action_e == QAction::Trigger) {
- emit qmenubar->triggered(action->action);
- } else if (action_e == QAction::Hover) {
- action->action->showStatusText(widget);
- emit qmenubar->hovered(action->action);
- }
+ action->action->showStatusText(widget);
+ emit qmenubar->hovered(action->action);
break; //nothing more..
}
//walk up
if (GetMenuItemProperty(caused_menu, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget,
- sizeof(caused), 0, &caused) != noErr)
+ sizeof(caused), 0, &caused) != noErr)
break;
if (QMenu *qmenu2 = qobject_cast<QMenu*>(caused))
caused_menu = qmenu2->macMenu();
@@ -649,7 +641,7 @@ static NSMenuItem *createNSMenuItem(const QString &title)
NSMenuItem *item = [[NSMenuItem alloc]
initWithTitle:qt_mac_QStringToNSString(title)
action:@selector(qtDispatcherToQAction:) keyEquivalent:@""];
- [item setTarget:getMenuLoader()];
+ [item setTarget:nil];
return item;
}
#endif
@@ -749,32 +741,6 @@ bool qt_mac_menubar_is_open()
return qt_mac_menus_open_count > 0;
}
-void qt_mac_clear_menubar()
-{
- if (QApplication::testAttribute(Qt::AA_MacPluginApplication))
- return;
-
-#ifndef QT_MAC_USE_COCOA
- MenuRef clear_menu = 0;
- if (CreateNewMenu(0, 0, &clear_menu) == noErr) {
- SetRootMenu(clear_menu);
- ReleaseMenu(clear_menu);
- } else {
- qWarning("QMenu: Internal error at %s:%d", __FILE__, __LINE__);
- }
- ClearMenuBar();
- qt_mac_command_set_enabled(0, kHICommandPreferences, false);
- InvalMenuBar();
-#else
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
- NSMenu *menu = [loader menu];
- [loader ensureAppMenuInMenu:menu];
- [NSApp setMainMenu:menu];
-#endif
-}
-
-
QMacMenuAction::~QMacMenuAction()
{
#ifdef QT_MAC_USE_COCOA
@@ -1130,7 +1096,7 @@ QMenuPrivate::QMacMenuPrivate::addAction(QMacMenuAction *action, QMacMenuAction
action->menu = merge;
[cmd retain];
[cmd setAction:@selector(qtDispatcherToQAction:)];
- [cmd setTarget:getMenuLoader()];
+ [cmd setTarget:nil];
[action->menuItem release];
action->menuItem = cmd;
QMenuMergeList *list = QMenuPrivate::mergeMenuItemsHash.value(merge);
@@ -1936,43 +1902,53 @@ static bool qt_mac_is_ancestor(QWidget* possibleAncestor, QWidget *child)
Returns true if the entries of menuBar should be disabled,
based on the modality type of modalWidget.
*/
-static bool qt_mac_should_disable_menu(QMenuBar *menuBar, QWidget *modalWidget)
+static bool qt_mac_should_disable_menu(QMenuBar *menuBar)
{
- if (modalWidget == 0 || menuBar == 0)
+ QWidget *modalWidget = qApp->activeModalWidget();
+ if (!modalWidget)
+ return false;
+
+ if (menuBar && menuBar == menubars()->value(modalWidget))
+ // The menu bar is owned by the modal widget.
+ // In that case we should enable it:
return false;
- // If there is an application modal window on
- // screen, the entries of the menubar should be disabled:
+ // When there is an application modal window on screen, the entries of
+ // the menubar should be disabled. The exception in Qt is that if the
+ // modal window is the only window on screen, then we enable the menu bar.
QWidget *w = modalWidget;
+ QWidgetList topLevelWidgets = QApplication::topLevelWidgets();
while (w) {
- if (w->isVisible() && w->windowModality() == Qt::ApplicationModal)
- return true;
+ if (w->isVisible() && w->windowModality() == Qt::ApplicationModal) {
+ for (int i=0; i<topLevelWidgets.size(); ++i) {
+ QWidget *top = topLevelWidgets.at(i);
+ if (w != top && [qt_mac_window_for(top) isVisible]) {
+ // INVARIANT: we found another visible window
+ // on screen other than our modalWidget. We therefore
+ // disable the menu bar to follow normal modality logic:
+ return true;
+ }
+ }
+ // INVARIANT: We have only one window on screen that happends
+ // to be application modal. We choose to enable the menu bar
+ // in that case to e.g. enable the quit menu item.
+ return false;
+ }
w = w->parentWidget();
}
// INVARIANT: modalWidget is window modal. Disable menu entries
- // if the menu bar belongs to an ancestor of modalWidget:
- return qt_mac_is_ancestor(menuBar->parentWidget(), modalWidget);
+ // if the menu bar belongs to an ancestor of modalWidget. If menuBar
+ // is nil, we understand it as the default menu bar set by the nib:
+ return menuBar ? qt_mac_is_ancestor(menuBar->parentWidget(), modalWidget) : false;
}
-/*!
- \internal
-
- This function will update the current menu bar and set it as the
- active menu bar in the Menu Manager.
-
- \warning This function is not portable.
-
- \sa QMenu::macMenu(), QMenuBar::macMenu()
-*/
-bool QMenuBar::macUpdateMenuBar()
+static QWidget *findWindowThatShouldDisplayMenubar()
{
- cancelAllMenuTracking();
- QMenuBar *mb = 0;
- //find a menu bar
QWidget *w = qApp->activeWindow();
-
if (!w) {
+ // We have no active window on screen. Try to
+ // find a window from the list of top levels:
QWidgetList tlws = QApplication::topLevelWidgets();
for(int i = 0; i < tlws.size(); ++i) {
QWidget *tlw = tlws.at(i);
@@ -1983,6 +1959,12 @@ bool QMenuBar::macUpdateMenuBar()
}
}
}
+ return w;
+}
+
+static QMenuBar *findMenubarForWindow(QWidget *w)
+{
+ QMenuBar *mb = 0;
if (w) {
mb = menubars()->value(w);
#ifndef QT_NO_MAINWINDOW
@@ -1996,11 +1978,65 @@ bool QMenuBar::macUpdateMenuBar()
while(w && !mb)
mb = menubars()->value((w = w->parentWidget()));
}
- if (!mb)
+
+ if (!mb) {
+ // We could not find a menu bar for the window. Lets
+ // check if we have a global (parentless) menu bar instead:
mb = fallback;
- //now set it
+ }
+
+ return mb;
+}
+
+void qt_mac_clear_menubar()
+{
+ if (QApplication::testAttribute(Qt::AA_MacPluginApplication))
+ return;
+
+#ifndef QT_MAC_USE_COCOA
+ MenuRef clear_menu = 0;
+ if (CreateNewMenu(0, 0, &clear_menu) == noErr) {
+ SetRootMenu(clear_menu);
+ ReleaseMenu(clear_menu);
+ } else {
+ qWarning("QMenu: Internal error at %s:%d", __FILE__, __LINE__);
+ }
+ ClearMenuBar();
+ qt_mac_command_set_enabled(0, kHICommandPreferences, false);
+ InvalMenuBar();
+#else
+ QMacCocoaAutoReleasePool pool;
+ QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
+ NSMenu *menu = [loader menu];
+ [loader ensureAppMenuInMenu:menu];
+ [NSApp setMainMenu:menu];
+ const bool modal = qt_mac_should_disable_menu(0);
+ if (qt_mac_current_menubar.qmenubar || modal != qt_mac_current_menubar.modal)
+ qt_mac_set_modal_state(menu, modal);
+ qt_mac_current_menubar.qmenubar = 0;
+ qt_mac_current_menubar.modal = modal;
+#endif
+}
+
+/*!
+ \internal
+
+ This function will update the current menu bar and set it as the
+ active menu bar in the Menu Manager.
+
+ \warning This function is not portable.
+
+ \sa QMenu::macMenu(), QMenuBar::macMenu()
+*/
+bool QMenuBar::macUpdateMenuBar()
+{
bool ret = false;
+ cancelAllMenuTracking();
+ QWidget *w = findWindowThatShouldDisplayMenubar();
+ QMenuBar *mb = findMenubarForWindow(w);
+
if (mb && mb->isNativeMenuBar()) {
+ bool modal = QApplicationPrivate::modalState();
#ifdef QT_MAC_USE_COCOA
QMacCocoaAutoReleasePool pool;
#endif
@@ -2030,16 +2066,18 @@ bool QMenuBar::macUpdateMenuBar()
}
}
#endif
- QWidget *modalWidget = qApp->activeModalWidget();
- if (mb != menubars()->value(modalWidget)) {
- qt_mac_set_modal_state(menu, qt_mac_should_disable_menu(mb, modalWidget));
- }
+ // Check if menu is modally shaddowed and should be disabled:
+ modal = qt_mac_should_disable_menu(mb);
+ if (mb != qt_mac_current_menubar.qmenubar || modal != qt_mac_current_menubar.modal)
+ qt_mac_set_modal_state(menu, modal);
}
qt_mac_current_menubar.qmenubar = mb;
- qt_mac_current_menubar.modal = QApplicationPrivate::modalState();
+ qt_mac_current_menubar.modal = modal;
ret = true;
} else if (qt_mac_current_menubar.qmenubar && qt_mac_current_menubar.qmenubar->isNativeMenuBar()) {
- const bool modal = QApplicationPrivate::modalState();
+ // INVARIANT: The currently active menu bar (if any) is not native. But we do have a
+ // native menu bar from before. So we need to decide whether or not is should be enabled:
+ const bool modal = qt_mac_should_disable_menu(qt_mac_current_menubar.qmenubar);
if (modal != qt_mac_current_menubar.modal) {
ret = true;
if (OSMenuRef menu = qt_mac_current_menubar.qmenubar->macMenu()) {
@@ -2051,14 +2089,12 @@ bool QMenuBar::macUpdateMenuBar()
[NSApp setMainMenu:menu];
syncMenuBarItemsVisiblity(qt_mac_current_menubar.qmenubar->d_func()->mac_menubar);
#endif
- QWidget *modalWidget = qApp->activeModalWidget();
- if (qt_mac_current_menubar.qmenubar != menubars()->value(modalWidget)) {
- qt_mac_set_modal_state(menu, qt_mac_should_disable_menu(mb, modalWidget));
- }
+ qt_mac_set_modal_state(menu, modal);
}
qt_mac_current_menubar.modal = modal;
}
}
+
if(!ret)
qt_mac_clear_menubar();
return ret;
diff --git a/src/gui/widgets/qplaintextedit.cpp b/src/gui/widgets/qplaintextedit.cpp
index ab598d9..02ffe13 100644
--- a/src/gui/widgets/qplaintextedit.cpp
+++ b/src/gui/widgets/qplaintextedit.cpp
@@ -911,6 +911,7 @@ void QPlainTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCurso
setTopBlock(block.blockNumber(), line);
if (moveCursor) {
+ cursor.setVisualNavigation(true);
// move using movePosition to keep the cursor's x
lastY += verticalOffset();
bool moved = false;
diff --git a/src/gui/widgets/qtabbar.cpp b/src/gui/widgets/qtabbar.cpp
index 22e8255..7559311 100644
--- a/src/gui/widgets/qtabbar.cpp
+++ b/src/gui/widgets/qtabbar.cpp
@@ -1947,7 +1947,8 @@ void QTabBar::changeEvent(QEvent *event)
{
Q_D(QTabBar);
if (event->type() == QEvent::StyleChange) {
- d->elideMode = Qt::TextElideMode(style()->styleHint(QStyle::SH_TabBar_ElideMode, 0, this));
+ if (!d->elideModeSetByUser)
+ d->elideMode = Qt::TextElideMode(style()->styleHint(QStyle::SH_TabBar_ElideMode, 0, this));
if (!d->useScrollButtonsSetByUser)
d->useScrollButtons = !style()->styleHint(QStyle::SH_TabBar_PreferNoArrows, 0, this);
d->refresh();
@@ -1980,6 +1981,7 @@ void QTabBar::setElideMode(Qt::TextElideMode mode)
{
Q_D(QTabBar);
d->elideMode = mode;
+ d->elideModeSetByUser = true;
d->refresh();
}
diff --git a/src/gui/widgets/qtabbar_p.h b/src/gui/widgets/qtabbar_p.h
index 7588035..83636e6 100644
--- a/src/gui/widgets/qtabbar_p.h
+++ b/src/gui/widgets/qtabbar_p.h
@@ -75,7 +75,7 @@ class QTabBarPrivate : public QWidgetPrivate
public:
QTabBarPrivate()
:currentIndex(-1), pressedIndex(-1), shape(QTabBar::RoundedNorth), layoutDirty(false),
- drawBase(true), scrollOffset(0), useScrollButtonsSetByUser(false) , expanding(true), closeButtonOnTabs(false),
+ drawBase(true), scrollOffset(0), elideModeSetByUser(false), useScrollButtonsSetByUser(false), expanding(true), closeButtonOnTabs(false),
selectionBehaviorOnRemove(QTabBar::SelectRightTab), paintWithOffsets(true), movable(false),
dragInProgress(false), documentMode(false), movingTab(0)
#ifdef Q_WS_MAC
@@ -186,6 +186,7 @@ public:
void makeVisible(int index);
QSize iconSize;
Qt::TextElideMode elideMode;
+ bool elideModeSetByUser;
bool useScrollButtons;
bool useScrollButtonsSetByUser;
diff --git a/src/gui/widgets/qtextedit.cpp b/src/gui/widgets/qtextedit.cpp
index b6886b4..4541730 100644
--- a/src/gui/widgets/qtextedit.cpp
+++ b/src/gui/widgets/qtextedit.cpp
@@ -1212,12 +1212,9 @@ void QTextEdit::keyPressEvent(QKeyEvent *e)
default:
if (QApplication::keypadNavigationEnabled()) {
if (!hasEditFocus() && !(e->modifiers() & Qt::ControlModifier)) {
- if (e->text()[0].isPrint()) {
+ if (e->text()[0].isPrint())
setEditFocus(true);
-#ifndef Q_OS_SYMBIAN
- clear();
-#endif
- } else {
+ else {
e->ignore();
return;
}
@@ -1677,12 +1674,8 @@ void QTextEdit::inputMethodEvent(QInputMethodEvent *e)
#ifdef QT_KEYPAD_NAVIGATION
if (d->control->textInteractionFlags() & Qt::TextEditable
&& QApplication::keypadNavigationEnabled()
- && !hasEditFocus()) {
+ && !hasEditFocus())
setEditFocus(true);
-#ifndef Q_OS_SYMBIAN
- selectAll(); // so text is replaced rather than appended to
-#endif
- }
#endif
d->sendControlEvent(e);
ensureCursorVisible();
diff --git a/src/gui/widgets/qtoolbar.cpp b/src/gui/widgets/qtoolbar.cpp
index 8beda55..7ed27ea 100644
--- a/src/gui/widgets/qtoolbar.cpp
+++ b/src/gui/widgets/qtoolbar.cpp
@@ -533,6 +533,14 @@ void QToolBarPrivate::plug(const QRect &r)
/*!
+ \fn void QToolBar::visibilityChanged(bool visible)
+ \since 4.7
+
+ This signal is emitted when the toolbar becomes \a visible (or
+ invisible). This happens when the widget is hidden or shown.
+*/
+
+/*!
Constructs a QToolBar with the given \a parent.
*/
QToolBar::QToolBar(QWidget *parent)
@@ -1122,6 +1130,7 @@ bool QToolBar::event(QEvent *event)
// fallthrough intended
case QEvent::Show:
d->toggleViewAction->setChecked(event->type() == QEvent::Show);
+ emit visibilityChanged(event->type() == QEvent::Show);
#if defined(Q_WS_MAC)
if (toolbarInUnifiedToolBar(this)) {
// I can static_cast because I did the qobject_cast in the if above, therefore
diff --git a/src/gui/widgets/qtoolbar.h b/src/gui/widgets/qtoolbar.h
index 90f20dd..b733477 100644
--- a/src/gui/widgets/qtoolbar.h
+++ b/src/gui/widgets/qtoolbar.h
@@ -143,6 +143,7 @@ Q_SIGNALS:
void iconSizeChanged(const QSize &iconSize);
void toolButtonStyleChanged(Qt::ToolButtonStyle toolButtonStyle);
void topLevelChanged(bool topLevel);
+ void visibilityChanged(bool visible);
protected:
void actionEvent(QActionEvent *event);
diff --git a/src/gui/widgets/qvalidator.cpp b/src/gui/widgets/qvalidator.cpp
index a5276d3..0b5cc5a 100644
--- a/src/gui/widgets/qvalidator.cpp
+++ b/src/gui/widgets/qvalidator.cpp
@@ -400,8 +400,10 @@ QValidator::State QIntValidator::validate(QString & input, int&) const
qlonglong entered = QLocalePrivate::bytearrayToLongLong(buff.constData(), 10, &ok, &overflow);
if (overflow || !ok)
return Invalid;
- if (entered >= b && entered <= t)
- return Acceptable;
+ if (entered >= b && entered <= t) {
+ locale().toInt(input, &ok);
+ return ok ? Acceptable : Intermediate;
+ }
if (entered >= 0) {
// the -entered < b condition is necessary to allow people to type
@@ -412,6 +414,20 @@ QValidator::State QIntValidator::validate(QString & input, int&) const
}
}
+/*! \reimp */
+void QIntValidator::fixup(QString &input) const
+{
+ QByteArray buff;
+ if (!locale().d()->validateChars(input, QLocalePrivate::IntegerMode, &buff)) {
+ QLocale cl(QLocale::C);
+ if (!cl.d()->validateChars(input, QLocalePrivate::IntegerMode, &buff))
+ return;
+ }
+ bool ok, overflow;
+ qlonglong entered = QLocalePrivate::bytearrayToLongLong(buff.constData(), 10, &ok, &overflow);
+ if (ok && !overflow)
+ input = locale().toString(entered);
+}
/*!
Sets the range of the validator to only accept integers between \a
diff --git a/src/gui/widgets/qvalidator.h b/src/gui/widgets/qvalidator.h
index 30afbd6..63734ca 100644
--- a/src/gui/widgets/qvalidator.h
+++ b/src/gui/widgets/qvalidator.h
@@ -105,6 +105,7 @@ public:
~QIntValidator();
QValidator::State validate(QString &, int &) const;
+ void fixup(QString &input) const;
void setBottom(int);
void setTop(int);
@@ -136,10 +137,11 @@ class Q_GUI_EXPORT QDoubleValidator : public QValidator
Q_PROPERTY(double bottom READ bottom WRITE setBottom)
Q_PROPERTY(double top READ top WRITE setTop)
Q_PROPERTY(int decimals READ decimals WRITE setDecimals)
+ Q_ENUMS(Notation)
Q_PROPERTY(Notation notation READ notation WRITE setNotation)
public:
- explicit QDoubleValidator(QObject * parent);
+ explicit QDoubleValidator(QObject * parent = 0);
QDoubleValidator(double bottom, double top, int decimals, QObject * parent);
~QDoubleValidator();
@@ -183,7 +185,7 @@ class Q_GUI_EXPORT QRegExpValidator : public QValidator
Q_PROPERTY(QRegExp regExp READ regExp WRITE setRegExp)
public:
- explicit QRegExpValidator(QObject *parent);
+ explicit QRegExpValidator(QObject *parent = 0);
QRegExpValidator(const QRegExp& rx, QObject *parent);
~QRegExpValidator();
diff --git a/src/multimedia/audio/qaudiodeviceinfo.cpp b/src/multimedia/audio/qaudiodeviceinfo.cpp
index 092efc5..ff04b4e 100644
--- a/src/multimedia/audio/qaudiodeviceinfo.cpp
+++ b/src/multimedia/audio/qaudiodeviceinfo.cpp
@@ -105,8 +105,8 @@ public:
The values supported by the the device for each of these
parameters can be fetched with
- supportedByteOrders(), supportedChannels(), supportedCodecs(),
- supportedFrequencies(), supportedSampleSizes(), and
+ supportedByteOrders(), supportedChannelCounts(), supportedCodecs(),
+ supportedSampleRates(), supportedSampleSizes(), and
supportedSampleTypes(). The combinations supported are dependent on the platform,
audio plugins installed and the audio device capabilities. If you need a specific format, you can check if
the device supports it with isFormatSupported(), or fetch a
@@ -259,7 +259,20 @@ QStringList QAudioDeviceInfo::supportedCodecs() const
}
/*!
- Returns a list of supported frequencies.
+ Returns a list of supported sample rates.
+
+ \since 4.7
+*/
+
+QList<int> QAudioDeviceInfo::supportedSampleRates() const
+{
+ return supportedFrequencies();
+}
+
+/*!
+ \obsolete
+
+ Use supportedSampleRates() instead.
*/
QList<int> QAudioDeviceInfo::supportedFrequencies() const
@@ -268,7 +281,20 @@ QList<int> QAudioDeviceInfo::supportedFrequencies() const
}
/*!
- Returns a list of supported channels.
+ Returns a list of supported channel counts.
+
+ \since 4.7
+*/
+
+QList<int> QAudioDeviceInfo::supportedChannelCounts() const
+{
+ return supportedChannels();
+}
+
+/*!
+ \obsolete
+
+ Use supportedChannelCount() instead.
*/
QList<int> QAudioDeviceInfo::supportedChannels() const
diff --git a/src/multimedia/audio/qaudiodeviceinfo.h b/src/multimedia/audio/qaudiodeviceinfo.h
index 62dc8a2..1cc0731 100644
--- a/src/multimedia/audio/qaudiodeviceinfo.h
+++ b/src/multimedia/audio/qaudiodeviceinfo.h
@@ -84,7 +84,9 @@ public:
QStringList supportedCodecs() const;
QList<int> supportedFrequencies() const;
+ QList<int> supportedSampleRates() const;
QList<int> supportedChannels() const;
+ QList<int> supportedChannelCounts() const;
QList<int> supportedSampleSizes() const;
QList<QAudioFormat::Endian> supportedByteOrders() const;
QList<QAudioFormat::SampleType> supportedSampleTypes() const;
diff --git a/src/multimedia/audio/qaudiodeviceinfo_win32_p.cpp b/src/multimedia/audio/qaudiodeviceinfo_win32_p.cpp
index f6b8154..955a880 100644
--- a/src/multimedia/audio/qaudiodeviceinfo_win32_p.cpp
+++ b/src/multimedia/audio/qaudiodeviceinfo_win32_p.cpp
@@ -95,14 +95,14 @@ QAudioFormat QAudioDeviceInfoInternal::preferredFormat() const
QAudioFormat nearest;
if(mode == QAudio::AudioOutput) {
nearest.setFrequency(44100);
- nearest.setChannels(2);
+ nearest.setChannelCount(2);
nearest.setByteOrder(QAudioFormat::LittleEndian);
nearest.setSampleType(QAudioFormat::SignedInt);
nearest.setSampleSize(16);
nearest.setCodec(QLatin1String("audio/pcm"));
} else {
nearest.setFrequency(11025);
- nearest.setChannels(1);
+ nearest.setChannelCount(1);
nearest.setByteOrder(QAudioFormat::LittleEndian);
nearest.setSampleType(QAudioFormat::SignedInt);
nearest.setSampleSize(8);
diff --git a/src/multimedia/audio/qaudioformat.cpp b/src/multimedia/audio/qaudioformat.cpp
index 89ae0ff..86d72f6 100644
--- a/src/multimedia/audio/qaudioformat.cpp
+++ b/src/multimedia/audio/qaudioformat.cpp
@@ -111,7 +111,7 @@ public:
\o Parameter
\o Description
\row
- \o Frequency
+ \o Sample Rate
\o Samples per second of audio data in Hertz.
\row
\o Number of channels
@@ -143,8 +143,8 @@ public:
Values are initialized as follows:
\list
- \o frequency() = -1
- \o channels() = -1
+ \o sampleRate() = -1
+ \o channelCount() = -1
\o sampleSize() = -1
\o byteOrder() = QAudioFormat::Endian(QSysInfo::ByteOrder)
\o sampleType() = QAudioFormat::Unknown
@@ -224,7 +224,20 @@ bool QAudioFormat::isValid() const
}
/*!
- Sets the frequency to \a frequency.
+ Sets the sample rate to \a samplerate Hertz.
+
+ \since 4.7
+*/
+
+void QAudioFormat::setSampleRate(int samplerate)
+{
+ d->frequency = samplerate;
+}
+
+/*!
+ \obsolete
+
+ Use setSampleRate() instead.
*/
void QAudioFormat::setFrequency(int frequency)
@@ -233,7 +246,20 @@ void QAudioFormat::setFrequency(int frequency)
}
/*!
- Returns the current frequency value.
+ Returns the current sample rate in Hertz.
+
+ \since 4.7
+*/
+
+int QAudioFormat::sampleRate() const
+{
+ return d->frequency;
+}
+
+/*!
+ \obsolete
+
+ Use sampleRate() instead.
*/
int QAudioFormat::frequency() const
@@ -242,7 +268,20 @@ int QAudioFormat::frequency() const
}
/*!
- Sets the channels to \a channels.
+ Sets the channel count to \a channels.
+
+ \since 4.7
+*/
+
+void QAudioFormat::setChannelCount(int channels)
+{
+ d->channels = channels;
+}
+
+/*!
+ \obsolete
+
+ Use setChannelCount() instead.
*/
void QAudioFormat::setChannels(int channels)
@@ -251,7 +290,20 @@ void QAudioFormat::setChannels(int channels)
}
/*!
- Returns the current channel value.
+ Returns the current channel count value.
+
+ \since 4.7
+*/
+
+int QAudioFormat::channelCount() const
+{
+ return d->channels;
+}
+
+/*!
+ \obsolete
+
+ Use channelCount() instead.
*/
int QAudioFormat::channels() const
diff --git a/src/multimedia/audio/qaudioformat.h b/src/multimedia/audio/qaudioformat.h
index cb58d1c..6c835b7 100644
--- a/src/multimedia/audio/qaudioformat.h
+++ b/src/multimedia/audio/qaudioformat.h
@@ -75,9 +75,13 @@ public:
void setFrequency(int frequency);
int frequency() const;
+ void setSampleRate(int sampleRate);
+ int sampleRate() const;
void setChannels(int channels);
int channels() const;
+ void setChannelCount(int channelCount);
+ int channelCount() const;
void setSampleSize(int sampleSize);
int sampleSize() const;
diff --git a/src/multimedia/audio/qaudioinput_win32_p.cpp b/src/multimedia/audio/qaudioinput_win32_p.cpp
index 17e8bfb..84fd2a5 100644
--- a/src/multimedia/audio/qaudioinput_win32_p.cpp
+++ b/src/multimedia/audio/qaudioinput_win32_p.cpp
@@ -230,6 +230,11 @@ bool QAudioInputPrivate::open()
} else {
period_size = buffer_size/5;
}
+#ifdef Q_OS_WINCE
+ // For wince reduce size to 40ms for buffer size and 20ms period
+ buffer_size = settings.sampleRate()*settings.channelCount()*(settings.sampleSize()/8)*0.04;
+ period_size = buffer_size/2;
+#endif
timeStamp.restart();
elapsedTimeOffset = 0;
wfx.nSamplesPerSec = settings.frequency();
diff --git a/src/multimedia/video/qabstractvideobuffer.cpp b/src/multimedia/video/qabstractvideobuffer.cpp
index 22b36f2..465a1e7 100644
--- a/src/multimedia/video/qabstractvideobuffer.cpp
+++ b/src/multimedia/video/qabstractvideobuffer.cpp
@@ -48,7 +48,6 @@ QT_BEGIN_NAMESPACE
/*!
\class QAbstractVideoBuffer
\brief The QAbstractVideoBuffer class is an abstraction for video data.
- \preliminary
\since 4.6
The QVideoFrame class makes use of a QAbstractVideoBuffer internally to reference a buffer of
diff --git a/src/multimedia/video/qabstractvideosurface.cpp b/src/multimedia/video/qabstractvideosurface.cpp
index 3f6bc08..3dabb6b 100644
--- a/src/multimedia/video/qabstractvideosurface.cpp
+++ b/src/multimedia/video/qabstractvideosurface.cpp
@@ -46,7 +46,6 @@ QT_BEGIN_NAMESPACE
/*!
\class QAbstractVideoSurface
\brief The QAbstractVideoSurface class is a base class for video presentation surfaces.
- \preliminary
\since 4.6
The QAbstractVideoSurface class defines the standard interface that video producers use to
diff --git a/src/multimedia/video/qvideoframe.cpp b/src/multimedia/video/qvideoframe.cpp
index f10ce97..2d66d9e 100644
--- a/src/multimedia/video/qvideoframe.cpp
+++ b/src/multimedia/video/qvideoframe.cpp
@@ -102,7 +102,6 @@ private:
/*!
\class QVideoFrame
\brief The QVideoFrame class provides a representation of a frame of video data.
- \preliminary
\since 4.6
A QVideoFrame encapsulates the data of a video frame, and information about the frame.
diff --git a/src/multimedia/video/qvideosurfaceformat.cpp b/src/multimedia/video/qvideosurfaceformat.cpp
index 6b16e6a..1fc13a6 100644
--- a/src/multimedia/video/qvideosurfaceformat.cpp
+++ b/src/multimedia/video/qvideosurfaceformat.cpp
@@ -136,7 +136,6 @@ public:
\class QVideoSurfaceFormat
\brief The QVideoSurfaceFormat class specifies the stream format of a video presentation
surface.
- \preliminary
\since 4.6
A video surface presents a stream of video frames. The surface's format describes the type of
diff --git a/src/network/access/qnetworkaccessdatabackend.cpp b/src/network/access/qnetworkaccessdatabackend.cpp
index 52c554f..a2e7ef5 100644
--- a/src/network/access/qnetworkaccessdatabackend.cpp
+++ b/src/network/access/qnetworkaccessdatabackend.cpp
@@ -43,6 +43,7 @@
#include "qnetworkrequest.h"
#include "qnetworkreply.h"
#include "qurlinfo.h"
+#include "private/qdataurl_p.h"
QT_BEGIN_NAMESPACE
@@ -78,53 +79,20 @@ void QNetworkAccessDataBackend::open()
return;
}
- if (uri.host().isEmpty()) {
- setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("text/plain;charset=US-ASCII"));
-
- // the following would have been the correct thing, but
- // reality often differs from the specification. People have
- // data: URIs with ? and #
- //QByteArray data = QByteArray::fromPercentEncoding(uri.encodedPath());
- QByteArray data = QByteArray::fromPercentEncoding(uri.toEncoded());
-
- // remove the data: scheme
- data.remove(0, 5);
-
- // parse it:
- int pos = data.indexOf(',');
- if (pos != -1) {
- QByteArray payload = data.mid(pos + 1);
- data.truncate(pos);
- data = data.trimmed();
-
- // find out if the payload is encoded in Base64
- if (data.endsWith(";base64")) {
- payload = QByteArray::fromBase64(payload);
- data.chop(7);
- }
-
- if (data.toLower().startsWith("charset")) {
- int i = 7; // strlen("charset")
- while (data.at(i) == ' ')
- ++i;
- if (data.at(i) == '=')
- data.prepend("text/plain;");
- }
-
- if (!data.isEmpty())
- setHeader(QNetworkRequest::ContentTypeHeader, data.trimmed());
-
- setHeader(QNetworkRequest::ContentLengthHeader, payload.size());
- emit metaDataChanged();
-
- QByteDataBuffer list;
- list.append(payload);
- payload.clear(); // important because of implicit sharing!
- writeDownstreamData(list);
-
- finished();
- return;
- }
+ QPair<QString, QByteArray> decoded = qDecodeDataUrl(uri);
+
+ if (! decoded.first.isNull()) {
+ setHeader(QNetworkRequest::ContentTypeHeader, decoded.first);
+ setHeader(QNetworkRequest::ContentLengthHeader, decoded.second.size());
+ emit metaDataChanged();
+
+ QByteDataBuffer list;
+ list.append(decoded.second);
+ decoded.second.clear(); // important because of implicit sharing!
+ writeDownstreamData(list);
+
+ finished();
+ return;
}
// something wrong with this URI
diff --git a/src/network/access/qnetworkaccesshttpbackend.cpp b/src/network/access/qnetworkaccesshttpbackend.cpp
index 61a95fe..8e02723 100644
--- a/src/network/access/qnetworkaccesshttpbackend.cpp
+++ b/src/network/access/qnetworkaccesshttpbackend.cpp
@@ -480,10 +480,24 @@ void QNetworkAccessHttpBackend::validateCache(QHttpNetworkRequest &httpRequest,
loadedFromCache = false;
}
+static QHttpNetworkRequest::Priority convert(const QNetworkRequest::Priority& prio)
+{
+ switch (prio) {
+ case QNetworkRequest::LowPriority:
+ return QHttpNetworkRequest::LowPriority;
+ case QNetworkRequest::HighPriority:
+ return QHttpNetworkRequest::HighPriority;
+ case QNetworkRequest::NormalPriority:
+ default:
+ return QHttpNetworkRequest::NormalPriority;
+ }
+}
+
void QNetworkAccessHttpBackend::postRequest()
{
bool loadedFromCache = false;
QHttpNetworkRequest httpRequest;
+ httpRequest.setPriority(convert(request().priority()));
switch (operation()) {
case QNetworkAccessManager::GetOperation:
httpRequest.setOperation(QHttpNetworkRequest::Get);
diff --git a/src/network/access/qnetworkaccessmanager.cpp b/src/network/access/qnetworkaccessmanager.cpp
index e16aedc..0b32533 100644
--- a/src/network/access/qnetworkaccessmanager.cpp
+++ b/src/network/access/qnetworkaccessmanager.cpp
@@ -549,7 +549,7 @@ void QNetworkAccessManager::setCookieJar(QNetworkCookieJar *cookieJar)
/*!
Posts a request to obtain the network headers for \a request
- and returns a new QNetworkReply object which will contain such headers
+ and returns a new QNetworkReply object which will contain such headers.
The function is named after the HTTP request associated (HEAD).
*/
diff --git a/src/network/access/qnetworkreply.cpp b/src/network/access/qnetworkreply.cpp
index 0a8ea5d..15748fe 100644
--- a/src/network/access/qnetworkreply.cpp
+++ b/src/network/access/qnetworkreply.cpp
@@ -533,6 +533,21 @@ QByteArray QNetworkReply::rawHeader(const QByteArray &headerName) const
return QByteArray();
}
+/*! \typedef QNetworkReply::RawHeaderPair
+
+ RawHeaderPair is a QPair<QByteArray, QByteArray> where the first
+ QByteArray is the header name and the second is the header.
+ */
+
+/*!
+ Returns a list of raw header pairs.
+ */
+const QList<QNetworkReply::RawHeaderPair>& QNetworkReply::rawHeaderPairs() const
+{
+ Q_D(const QNetworkReply);
+ return d->rawHeaders;
+}
+
/*!
Returns a list of headers fields that were sent by the remote
server, in the order that they were sent. Duplicate headers are
diff --git a/src/network/access/qnetworkreply.h b/src/network/access/qnetworkreply.h
index 5be4cce..5db4985 100644
--- a/src/network/access/qnetworkreply.h
+++ b/src/network/access/qnetworkreply.h
@@ -128,6 +128,9 @@ public:
QList<QByteArray> rawHeaderList() const;
QByteArray rawHeader(const QByteArray &headerName) const;
+ typedef QPair<QByteArray, QByteArray> RawHeaderPair;
+ const QList<RawHeaderPair>& rawHeaderPairs() const;
+
// attributes
QVariant attribute(QNetworkRequest::Attribute code) const;
diff --git a/src/network/access/qnetworkrequest.cpp b/src/network/access/qnetworkrequest.cpp
index a2bef67..b8438a2 100644
--- a/src/network/access/qnetworkrequest.cpp
+++ b/src/network/access/qnetworkrequest.cpp
@@ -218,8 +218,9 @@ class QNetworkRequestPrivate: public QSharedData, public QNetworkHeadersPrivate
{
public:
inline QNetworkRequestPrivate()
+ : priority(QNetworkRequest::NormalPriority)
#ifndef QT_NO_OPENSSL
- : sslConfiguration(0)
+ , sslConfiguration(0)
#endif
{ qRegisterMetaType<QNetworkRequest>(); }
~QNetworkRequestPrivate()
@@ -234,6 +235,7 @@ public:
: QSharedData(other), QNetworkHeadersPrivate(other)
{
url = other.url;
+ priority = other.priority;
#ifndef QT_NO_OPENSSL
sslConfiguration = 0;
@@ -245,12 +247,14 @@ public:
inline bool operator==(const QNetworkRequestPrivate &other) const
{
return url == other.url &&
+ priority == other.priority &&
rawHeaders == other.rawHeaders &&
attributes == other.attributes;
// don't compare cookedHeaders
}
QUrl url;
+ QNetworkRequest::Priority priority;
#ifndef QT_NO_OPENSSL
mutable QSslConfiguration *sslConfiguration;
#endif
@@ -516,6 +520,45 @@ QObject *QNetworkRequest::originatingObject() const
return d->originatingObject.data();
}
+/*!
+ \since 4.7
+
+ Return the priority of this request.
+
+ \sa setPriority()
+*/
+QNetworkRequest::Priority QNetworkRequest::priority() const
+{
+ return d->priority;
+}
+
+/*! \enum QNetworkRequest::Priority
+
+ \since 4.7
+
+ This enum lists the possible network request priorities.
+
+ \value HighPriority High priority
+ \value NormalPriority Normal priority
+ \value LowPriority Low priority
+ */
+
+/*!
+ \since 4.7
+
+ Set the priority of this request to \a priority.
+
+ \note The \a priority is only a hint to the network access
+ manager. It can use it or not. Currently it is used for HTTP to
+ decide which request should be sent first to a server.
+
+ \sa priority()
+*/
+void QNetworkRequest::setPriority(Priority priority)
+{
+ d->priority = priority;
+}
+
static QByteArray headerName(QNetworkRequest::KnownHeaders header)
{
switch (header) {
diff --git a/src/network/access/qnetworkrequest.h b/src/network/access/qnetworkrequest.h
index fe01f8c..bc2d9da 100644
--- a/src/network/access/qnetworkrequest.h
+++ b/src/network/access/qnetworkrequest.h
@@ -89,6 +89,12 @@ public:
AlwaysCache
};
+ enum Priority {
+ HighPriority = 1,
+ NormalPriority = 3,
+ LowPriority = 5
+ };
+
explicit QNetworkRequest(const QUrl &url = QUrl());
QNetworkRequest(const QNetworkRequest &other);
~QNetworkRequest();
@@ -123,6 +129,9 @@ public:
void setOriginatingObject(QObject *object);
QObject *originatingObject() const;
+ Priority priority() const;
+ void setPriority(Priority priority);
+
private:
QSharedDataPointer<QNetworkRequestPrivate> d;
friend class QNetworkRequestPrivate;
diff --git a/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp b/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp
index 516b847..03b1bf0 100644
--- a/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp
+++ b/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp
@@ -145,7 +145,7 @@ void QGL2PEXVertexArray::addPath(const QVectorPath &path, GLfloat curveInverseSc
// threshold based on same algorithm as in qtriangulatingstroker.cpp
int threshold = qMin<float>(64, qMax(bounds.width(), bounds.height()) * 3.14f / (curveInverseScale * 6));
if (threshold < 3) threshold = 3;
- qreal one_over_threshold_minus_1 = 1.f / (threshold - 1);
+ qreal one_over_threshold_minus_1 = qreal(1) / (threshold - 1);
for (int t=0; t<threshold; ++t) {
QPointF pt = b.pointAt(t * one_over_threshold_minus_1);
lineToArray(pt.x(), pt.y());
diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp
index 07f3159..d2fb925 100644
--- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp
+++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp
@@ -77,6 +77,7 @@
#include <private/qfontengine_p.h>
#include <private/qpixmapdata_gl_p.h>
#include <private/qdatabuffer_p.h>
+#include <private/qtriangulator_p.h>
#include "qglgradientcache_p.h"
#include "qglengineshadermanager_p.h"
@@ -608,10 +609,13 @@ struct QGL2PEVectorPathCache
{
#ifdef QT_OPENGL_CACHE_AS_VBOS
GLuint vbo;
+ GLuint ibo;
#else
float *vertices;
+ quint32 *indices;
#endif
int vertexCount;
+ int indexCount;
GLenum primitiveType;
qreal iscale;
};
@@ -622,9 +626,12 @@ void QGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *d
#ifdef QT_OPENGL_CACHE_AS_VBOS
Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
static_cast<QGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
+ if (c->ibo)
+ d->unusedIBOSToClean << c->ibo;
#else
Q_UNUSED(engine);
qFree(c->vertices);
+ qFree(c->indices);
#endif
delete c;
}
@@ -655,6 +662,9 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
+ // ### Remove before release...
+ static bool do_vectorpath_cache = qgetenv("QT_OPENGL_NO_PATH_CACHE").isEmpty();
+
// Check to see if there's any hints
if (path.shape() == QVectorPath::RectangleHint) {
QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
@@ -666,6 +676,8 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
QVectorPath::CacheEntry *data = path.lookupCacheData(q);
QGL2PEVectorPathCache *cache;
+ bool updateCache = false;
+
if (data) {
cache = (QGL2PEVectorPathCache *) data->data;
// Check if scale factor is exceeded for curved paths and generate curves if so...
@@ -675,34 +687,39 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
#ifdef QT_OPENGL_CACHE_AS_VBOS
glDeleteBuffers(1, &cache->vbo);
cache->vbo = 0;
+ Q_ASSERT(cache->ibo == 0);
#else
qFree(cache->vertices);
+ Q_ASSERT(cache->indices == 0);
#endif
- cache->vertexCount = 0;
+ updateCache = true;
}
}
} else {
cache = new QGL2PEVectorPathCache;
- cache->vertexCount = 0;
data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
+ updateCache = true;
}
// Flatten the path at the current scale factor and fill it into the cache struct.
- if (!cache->vertexCount) {
+ if (updateCache) {
vertexCoordinateArray.clear();
vertexCoordinateArray.addPath(path, inverseScale, false);
int vertexCount = vertexCoordinateArray.vertexCount();
int floatSizeInBytes = vertexCount * 2 * sizeof(float);
cache->vertexCount = vertexCount;
+ cache->indexCount = 0;
cache->primitiveType = GL_TRIANGLE_FAN;
cache->iscale = inverseScale;
#ifdef QT_OPENGL_CACHE_AS_VBOS
glGenBuffers(1, &cache->vbo);
glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
+ cache->ibo = 0;
#else
cache->vertices = (float *) qMalloc(floatSizeInBytes);
memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
+ cache->indices = 0;
#endif
}
@@ -718,8 +735,6 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
} else {
// printf(" - Marking path as cachable...\n");
// Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
- // ### Remove before release...
- static bool do_vectorpath_cache = qgetenv("QT_OPENGL_NO_PATH_CACHE").isEmpty();
if (do_vectorpath_cache)
path.makeCacheable();
vertexCoordinateArray.clear();
@@ -729,31 +744,117 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
}
} else {
- // The path is too complicated & needs the stencil technique
- vertexCoordinateArray.clear();
- vertexCoordinateArray.addPath(path, inverseScale, false);
+ bool useCache = path.isCacheable();
+ if (useCache) {
+ QRectF bbox = path.controlPointRect();
+ // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
+ useCache &= (bbox.left() > -0x8000 * inverseScale)
+ && (bbox.right() < 0x8000 * inverseScale)
+ && (bbox.top() > -0x8000 * inverseScale)
+ && (bbox.bottom() < 0x8000 * inverseScale);
+ }
- fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
+ if (useCache) {
+ QVectorPath::CacheEntry *data = path.lookupCacheData(q);
+ QGL2PEVectorPathCache *cache;
- glStencilMask(0xff);
- glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
+ bool updateCache = false;
+
+ if (data) {
+ cache = (QGL2PEVectorPathCache *) data->data;
+ // Check if scale factor is exceeded for curved paths and generate curves if so...
+ if (path.isCurved()) {
+ qreal scaleFactor = cache->iscale / inverseScale;
+ if (scaleFactor < 0.5 || scaleFactor > 2.0) {
+#ifdef QT_OPENGL_CACHE_AS_VBOS
+ glDeleteBuffers(1, &cache->vbo);
+ glDeleteBuffers(1, &cache->ibo);
+#else
+ qFree(cache->vertices);
+ qFree(cache->indices);
+#endif
+ updateCache = true;
+ }
+ }
+ } else {
+ cache = new QGL2PEVectorPathCache;
+ data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
+ updateCache = true;
+ }
+
+ // Flatten the path at the current scale factor and fill it into the cache struct.
+ if (updateCache) {
+ QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
+ cache->vertexCount = polys.vertices.size() / 2;
+ cache->indexCount = polys.indices.size();
+ cache->primitiveType = GL_TRIANGLES;
+ cache->iscale = inverseScale;
+
+#ifdef QT_OPENGL_CACHE_AS_VBOS
+ glGenBuffers(1, &cache->vbo);
+ glGenBuffers(1, &cache->ibo);
+ glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
+
+ QVarLengthArray<float> vertices(polys.vertices.size());
+ for (int i = 0; i < polys.vertices.size(); ++i)
+ vertices[i] = float(inverseScale * polys.vertices.at(i));
+ glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
+#else
+ cache->vertices = (float *) qMalloc(sizeof(float) * polys.vertices.size());
+ cache->indices = (quint32 *) qMalloc(sizeof(quint32) * polys.indices.size());
+ memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
+ for (int i = 0; i < polys.vertices.size(); ++i)
+ cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
+#endif
+ }
+
+ prepareForDraw(currentBrush.isOpaque());
+#ifdef QT_OPENGL_CACHE_AS_VBOS
+ glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
+ setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
+ glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+#else
+ setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
+ glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, cache->indices);
+#endif
- if (q->state()->clipTestEnabled) {
- // Pass when high bit is set, replace stencil value with current clip
- glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
- } else if (path.hasWindingFill()) {
- // Pass when any bit is set, replace stencil value with 0
- glStencilFunc(GL_NOTEQUAL, 0, 0xff);
} else {
- // Pass when high bit is set, replace stencil value with 0
- glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
- }
- prepareForDraw(currentBrush.isOpaque());
+ // printf(" - Marking path as cachable...\n");
+ // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
+ if (do_vectorpath_cache)
+ path.makeCacheable();
- // Stencil the brush onto the dest buffer
- composite(vertexCoordinateArray.boundingRect());
- glStencilMask(0);
- updateClipScissorTest();
+ // The path is too complicated & needs the stencil technique
+ vertexCoordinateArray.clear();
+ vertexCoordinateArray.addPath(path, inverseScale, false);
+
+ fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
+
+ glStencilMask(0xff);
+ glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
+
+ if (q->state()->clipTestEnabled) {
+ // Pass when high bit is set, replace stencil value with current clip
+ glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
+ } else if (path.hasWindingFill()) {
+ // Pass when any bit is set, replace stencil value with 0
+ glStencilFunc(GL_NOTEQUAL, 0, 0xff);
+ } else {
+ // Pass when high bit is set, replace stencil value with 0
+ glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
+ }
+ prepareForDraw(currentBrush.isOpaque());
+
+ // Stencil the brush onto the dest buffer
+ composite(vertexCoordinateArray.boundingRect());
+ glStencilMask(0);
+ updateClipScissorTest();
+ }
}
}
@@ -1231,14 +1332,14 @@ void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem
? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
: d->glyphCacheType;
- if (txtype > QTransform::TxTranslate)
- glyphType = QFontEngineGlyphCache::Raster_A8;
- if (glyphType == QFontEngineGlyphCache::Raster_RGBMask
- && state()->composition_mode != QPainter::CompositionMode_Source
- && state()->composition_mode != QPainter::CompositionMode_SourceOver)
- {
- drawCached = false;
+ if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
+ if (d->deviceHasAlpha || txtype > QTransform::TxTranslate
+ || (state()->composition_mode != QPainter::CompositionMode_Source
+ && state()->composition_mode != QPainter::CompositionMode_SourceOver))
+ {
+ glyphType = QFontEngineGlyphCache::Raster_A8;
+ }
}
if (drawCached) {
@@ -1529,6 +1630,23 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
d->stencilClean = true;
+ switch (pdev->devType()) {
+ case QInternal::Pixmap:
+ d->deviceHasAlpha = static_cast<QPixmap *>(pdev)->hasAlphaChannel();
+ break;
+ case QInternal::FramebufferObject:
+ {
+ GLenum f = static_cast<QGLFramebufferObject *>(pdev)->format().internalTextureFormat();
+ d->deviceHasAlpha = (f != GL_RGB && f != GL_RGB5 && f != GL_RGB8);
+ }
+ break;
+ default:
+ // widget, pbuffer
+ d->deviceHasAlpha = d->ctx->d_func()->reqFormat.alpha();
+ break;
+ }
+
+
// Calling begin paint should make the correct context current. So, any
// code which calls into GL or otherwise needs a current context *must*
// go after beginPaint:
@@ -1601,6 +1719,10 @@ bool QGL2PaintEngineEx::end()
glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
d->unusedVBOSToClean.clear();
}
+ if (!d->unusedIBOSToClean.isEmpty()) {
+ glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
+ d->unusedIBOSToClean.clear();
+ }
#endif
return false;
diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h
index 8fa0eff..e816e17 100644
--- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h
+++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h
@@ -278,6 +278,7 @@ public:
bool needsSync;
bool multisamplingAlwaysEnabled;
+ bool deviceHasAlpha;
GLfloat depthRange[2];
@@ -293,6 +294,7 @@ public:
QSet<QVectorPath::CacheEntry *> pathCaches;
QVector<GLuint> unusedVBOSToClean;
+ QVector<GLuint> unusedIBOSToClean;
const GLfloat *vertexAttribPointers[3];
};
diff --git a/src/opengl/gl2paintengineex/qtriangulator.cpp b/src/opengl/gl2paintengineex/qtriangulator.cpp
new file mode 100644
index 0000000..115f31b
--- /dev/null
+++ b/src/opengl/gl2paintengineex/qtriangulator.cpp
@@ -0,0 +1,2983 @@
+/****************************************************************************
+**
+** 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 QtOpenGL module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qtriangulator_p.h"
+
+#include <QtGui/qdialog.h>
+#include <QtGui/qevent.h>
+#include <QtGui/qpainter.h>
+#include <QtGui/qpainterpath.h>
+#include <QtGui/private/qbezier_p.h>
+#include <QtGui/private/qdatabuffer_p.h>
+#include <QtCore/qbitarray.h>
+#include <QtCore/qvarlengtharray.h>
+#include <QtCore/qqueue.h>
+#include <QtCore/qglobal.h>
+#include <QtCore/qpoint.h>
+#include <QtCore/qalgorithms.h>
+#include <QtDebug>
+
+#include <math.h>
+
+QT_BEGIN_NAMESPACE
+
+//#define Q_TRIANGULATOR_DEBUG
+
+#define Q_FIXED_POINT_SCALE 32
+
+// Quick sort.
+template <class T, class LessThan>
+static void sort(T *array, int count, LessThan lessThan)
+{
+ // If the number of elements fall below some threshold, use insertion sort.
+ const int INSERTION_SORT_LIMIT = 7; // About 7 is fastest on my computer...
+ if (count <= INSERTION_SORT_LIMIT) {
+ for (int i = 1; i < count; ++i) {
+ T temp = array[i];
+ int j = i;
+ while (j > 0 && lessThan(temp, array[j - 1])) {
+ array[j] = array[j - 1];
+ --j;
+ }
+ array[j] = temp;
+ }
+ return;
+ }
+
+ int high = count - 1;
+ int low = 0;
+ int mid = high / 2;
+ if (lessThan(array[mid], array[low]))
+ qSwap(array[mid], array[low]);
+ if (lessThan(array[high], array[mid]))
+ qSwap(array[high], array[mid]);
+ if (lessThan(array[mid], array[low]))
+ qSwap(array[mid], array[low]);
+
+ --high;
+ ++low;
+ qSwap(array[mid], array[high]);
+ int pivot = high;
+ --high;
+
+ while (low <= high) {
+ while (!lessThan(array[pivot], array[low])) {
+ ++low;
+ if (low > high)
+ goto sort_loop_end;
+ }
+ while (!lessThan(array[high], array[pivot])) {
+ --high;
+ if (low > high)
+ goto sort_loop_end;
+ }
+ qSwap(array[low], array[high]);
+ ++low;
+ --high;
+ }
+sort_loop_end:
+ if (low != pivot)
+ qSwap(array[pivot], array[low]);
+ sort(array, low, lessThan);
+ sort(array + low + 1, count - low - 1, lessThan);
+}
+
+// Quick sort.
+template <class T>
+static void sort(T *array, int count)
+{
+ // If the number of elements fall below some threshold, use insertion sort.
+ const int INSERTION_SORT_LIMIT = 25; // About 25 is fastest on my computer...
+ if (count <= INSERTION_SORT_LIMIT) {
+ for (int i = 1; i < count; ++i) {
+ T temp = array[i];
+ int j = i;
+ while (j > 0 && (temp < array[j - 1])) {
+ array[j] = array[j - 1];
+ --j;
+ }
+ array[j] = temp;
+ }
+ return;
+ }
+
+ int high = count - 1;
+ int low = 0;
+ int mid = high / 2;
+ if ((array[mid] < array[low]))
+ qSwap(array[mid], array[low]);
+ if ((array[high] < array[mid]))
+ qSwap(array[high], array[mid]);
+ if ((array[mid] < array[low]))
+ qSwap(array[mid], array[low]);
+
+ --high;
+ ++low;
+ qSwap(array[mid], array[high]);
+ int pivot = high;
+ --high;
+
+ while (low <= high) {
+ while (!(array[pivot] < array[low])) {
+ ++low;
+ if (low > high)
+ goto sort_loop_end;
+ }
+ while (!(array[high] < array[pivot])) {
+ --high;
+ if (low > high)
+ goto sort_loop_end;
+ }
+ qSwap(array[low], array[high]);
+ ++low;
+ --high;
+ }
+sort_loop_end:
+ if (low != pivot)
+ qSwap(array[pivot], array[low]);
+ sort(array, low);
+ sort(array + low + 1, count - low - 1);
+}
+
+//============================================================================//
+// QFraction //
+//============================================================================//
+
+// Fraction must be in the range [0, 1)
+struct QFraction
+{
+ // Comparison operators must not be called on invalid fractions.
+ inline bool operator < (const QFraction &other) const;
+ inline bool operator == (const QFraction &other) const;
+ inline bool operator != (const QFraction &other) const {return !(*this == other);}
+ inline bool operator > (const QFraction &other) const {return other < *this;}
+ inline bool operator >= (const QFraction &other) const {return !(*this < other);}
+ inline bool operator <= (const QFraction &other) const {return !(*this > other);}
+
+ inline bool isValid() const {return denominator != 0;}
+
+ // numerator and denominator must not have common denominators.
+ quint64 numerator, denominator;
+};
+
+static inline quint64 gcd(quint64 x, quint64 y)
+{
+ while (y != 0) {
+ quint64 z = y;
+ y = x % y;
+ x = z;
+ }
+ return x;
+}
+
+static inline int compare(quint64 a, quint64 b)
+{
+ return (a > b) - (a < b);
+}
+
+// Compare a/b with c/d.
+// Return negative if less, 0 if equal, positive if greater.
+// a < b, c < d
+static int qCompareFractions(quint64 a, quint64 b, quint64 c, quint64 d)
+{
+ const quint64 LIMIT = Q_UINT64_C(0x100000000);
+ for (;;) {
+ // If the products 'ad' and 'bc' fit into 64 bits, they can be directly compared.
+ if (b < LIMIT && d < LIMIT)
+ return compare(a * d, b * c);
+
+ if (a == 0 || c == 0)
+ return compare(a, c);
+
+ // a/b < c/d <=> d/c < b/a
+ quint64 b_div_a = b / a;
+ quint64 d_div_c = d / c;
+ if (b_div_a != d_div_c)
+ return compare(d_div_c, b_div_a);
+
+ // floor(d/c) == floor(b/a)
+ // frac(d/c) < frac(b/a) ?
+ // frac(x/y) = (x%y)/y
+ d -= d_div_c * c; //d %= c;
+ b -= b_div_a * a; //b %= a;
+ qSwap(a, d);
+ qSwap(b, c);
+ }
+}
+
+// Fraction must be in the range [0, 1)
+// Assume input is valid.
+static QFraction qFraction(quint64 n, quint64 d) {
+ QFraction result;
+ if (n == 0) {
+ result.numerator = 0;
+ result.denominator = 1;
+ } else {
+ quint64 g = gcd(n, d);
+ result.numerator = n / g;
+ result.denominator = d / g;
+ }
+ return result;
+}
+
+inline bool QFraction::operator < (const QFraction &other) const
+{
+ return qCompareFractions(numerator, denominator, other.numerator, other.denominator) < 0;
+}
+
+inline bool QFraction::operator == (const QFraction &other) const
+{
+ return numerator == other.numerator && denominator == other.denominator;
+}
+
+//============================================================================//
+// QPodPoint //
+//============================================================================//
+
+struct QPodPoint
+{
+ inline bool operator < (const QPodPoint &other) const
+ {
+ if (y != other.y)
+ return y < other.y;
+ return x < other.x;
+ }
+
+ inline bool operator > (const QPodPoint &other) const {return other < *this;}
+ inline bool operator <= (const QPodPoint &other) const {return !(*this > other);}
+ inline bool operator >= (const QPodPoint &other) const {return !(*this < other);}
+ inline bool operator == (const QPodPoint &other) const {return x == other.x && y == other.y;}
+ inline bool operator != (const QPodPoint &other) const {return x != other.x || y != other.y;}
+
+ inline QPodPoint &operator += (const QPodPoint &other) {x += other.x; y += other.y; return *this;}
+ inline QPodPoint &operator -= (const QPodPoint &other) {x -= other.x; y -= other.y; return *this;}
+ inline QPodPoint operator + (const QPodPoint &other) const {QPodPoint result = {x + other.x, y + other.y}; return result;}
+ inline QPodPoint operator - (const QPodPoint &other) const {QPodPoint result = {x - other.x, y - other.y}; return result;}
+
+ int x;
+ int y;
+};
+
+static inline qint64 qCross(const QPodPoint &u, const QPodPoint &v)
+{
+ return qint64(u.x) * qint64(v.y) - qint64(u.y) * qint64(v.x);
+}
+
+static inline qint64 qDot(const QPodPoint &u, const QPodPoint &v)
+{
+ return qint64(u.x) * qint64(v.x) + qint64(u.y) * qint64(v.y);
+}
+
+// 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).
+static inline qint64 qPointDistanceFromLine(const QPodPoint &p, const QPodPoint &v1, const QPodPoint &v2)
+{
+ return qCross(v2 - v1, p - v1);
+}
+
+static inline bool qPointIsLeftOfLine(const QPodPoint &p, const QPodPoint &v1, const QPodPoint &v2)
+{
+ return qPointDistanceFromLine(p, v1, v2) < 0;
+}
+
+// Return:
+// -1 if u < v
+// 0 if u == v
+// 1 if u > v
+static int comparePoints(const QPodPoint &u, const QPodPoint &v)
+{
+ if (u.y < v.y)
+ return -1;
+ if (u.y > v.y)
+ return 1;
+ if (u.x < v.x)
+ return -1;
+ if (u.x > v.x)
+ return 1;
+ return 0;
+}
+
+//============================================================================//
+// QIntersectionPoint //
+//============================================================================//
+
+struct QIntersectionPoint
+{
+ inline bool isValid() const {return xOffset.isValid() && yOffset.isValid();}
+ QPodPoint round() const;
+ inline bool isAccurate() const {return xOffset.numerator == 0 && yOffset.numerator == 0;}
+ bool operator < (const QIntersectionPoint &other) const;
+ bool operator == (const QIntersectionPoint &other) const;
+ inline bool operator != (const QIntersectionPoint &other) const {return !(*this == other);}
+ inline bool operator > (const QIntersectionPoint &other) const {return other < *this;}
+ inline bool operator >= (const QIntersectionPoint &other) const {return !(*this < other);}
+ inline bool operator <= (const QIntersectionPoint &other) const {return !(*this > other);}
+ bool isOnLine(const QPodPoint &u, const QPodPoint &v) const;
+
+ QPodPoint upperLeft;
+ QFraction xOffset;
+ QFraction yOffset;
+};
+
+static inline QIntersectionPoint qIntersectionPoint(const QPodPoint &point)
+{
+ // upperLeft = point, xOffset = 0/1, yOffset = 0/1.
+ QIntersectionPoint p = {{point.x, point.y}, {0, 1}, {0, 1}};
+ return p;
+}
+
+static inline QIntersectionPoint qIntersectionPoint(int x, int y)
+{
+ // upperLeft = (x, y), xOffset = 0/1, yOffset = 0/1.
+ QIntersectionPoint p = {{x, y}, {0, 1}, {0, 1}};
+ return p;
+}
+
+static QIntersectionPoint qIntersectionPoint(const QPodPoint &u1, const QPodPoint &u2, const QPodPoint &v1, const QPodPoint &v2)
+{
+ QIntersectionPoint result = {{0, 0}, {0, 0}, {0, 0}};
+
+ QPodPoint u = u2 - u1;
+ QPodPoint v = v2 - v1;
+ qint64 d1 = qCross(u, v1 - u1);
+ qint64 d2 = qCross(u, v2 - u1);
+ qint64 det = d2 - d1;
+ qint64 d3 = qCross(v, u1 - v1);
+ qint64 d4 = d3 - det; //qCross(v, u2 - v1);
+
+ // Check that the math is correct.
+ Q_ASSERT(d4 == qCross(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 21 bits per vector component.
+ // TODO: Make code path for 31 bits per vector component.
+ if (v.x >= 0) {
+ result.upperLeft.x = v1.x + (-v.x * d1) / det;
+ result.xOffset = qFraction(quint64(-v.x * d1) % quint64(det), quint64(det));
+ } else {
+ result.upperLeft.x = v2.x + (-v.x * d2) / det;
+ result.xOffset = qFraction(quint64(-v.x * d2) % quint64(det), quint64(det));
+ }
+
+ if (v.y >= 0) {
+ result.upperLeft.y = v1.y + (-v.y * d1) / det;
+ result.yOffset = qFraction(quint64(-v.y * d1) % quint64(det), quint64(det));
+ } else {
+ result.upperLeft.y = v2.y + (-v.y * d2) / det;
+ result.yOffset = qFraction(quint64(-v.y * d2) % quint64(det), quint64(det));
+ }
+
+ Q_ASSERT(result.xOffset.isValid());
+ Q_ASSERT(result.yOffset.isValid());
+ return result;
+}
+
+QPodPoint QIntersectionPoint::round() const
+{
+ QPodPoint result = upperLeft;
+ if (2 * xOffset.numerator >= xOffset.denominator)
+ ++result.x;
+ if (2 * yOffset.numerator >= yOffset.denominator)
+ ++result.y;
+ return result;
+}
+
+bool QIntersectionPoint::operator < (const QIntersectionPoint &other) const
+{
+ if (upperLeft.y != other.upperLeft.y)
+ return upperLeft.y < other.upperLeft.y;
+ if (yOffset != other.yOffset)
+ return yOffset < other.yOffset;
+ if (upperLeft.x != other.upperLeft.x)
+ return upperLeft.x < other.upperLeft.x;
+ return xOffset < other.xOffset;
+}
+
+bool QIntersectionPoint::operator == (const QIntersectionPoint &other) const
+{
+ return upperLeft == other.upperLeft && xOffset == other.xOffset && yOffset == other.yOffset;
+}
+
+// Returns true if this point is on the infinite line passing through 'u' and 'v'.
+bool QIntersectionPoint::isOnLine(const QPodPoint &u, const QPodPoint &v) const
+{
+ // TODO: Make code path for coordinates with more than 21 bits.
+ const QPodPoint p = upperLeft - u;
+ const QPodPoint q = v - u;
+ bool isHorizontal = p.y == 0 && yOffset.numerator == 0;
+ bool isVertical = p.x == 0 && xOffset.numerator == 0;
+ if (isHorizontal && isVertical)
+ return true;
+ if (isHorizontal)
+ return q.y == 0;
+ if (q.y == 0)
+ return false;
+ if (isVertical)
+ return q.x == 0;
+ if (q.x == 0)
+ return false;
+
+ // At this point, 'p+offset' and 'q' cannot lie on the x or y axis.
+
+ if (((q.x < 0) == (q.y < 0)) != ((p.x < 0) == (p.y < 0)))
+ return false; // 'p + offset' and 'q' pass through different quadrants.
+
+ // Move all coordinates into the first quadrant.
+ quint64 nx, ny;
+ if (p.x < 0)
+ nx = quint64(-p.x) * xOffset.denominator - xOffset.numerator;
+ else
+ nx = quint64(p.x) * xOffset.denominator + xOffset.numerator;
+ if (p.y < 0)
+ ny = quint64(-p.y) * yOffset.denominator - yOffset.numerator;
+ else
+ ny = quint64(p.y) * yOffset.denominator + yOffset.numerator;
+
+ return qFraction(quint64(qAbs(q.x)) * xOffset.denominator, quint64(qAbs(q.y)) * yOffset.denominator) == qFraction(nx, ny);
+}
+
+//============================================================================//
+// QMaxHeap //
+//============================================================================//
+
+template <class T>
+class QMaxHeap
+{
+public:
+ inline int size() const {return m_data.size();}
+ inline bool empty() const {return m_data.isEmpty();}
+ inline bool isEmpty() const {return m_data.isEmpty();}
+ void push(const T &x);
+ T pop();
+ inline const T &top() const {return m_data.first();}
+private:
+ static inline int parent(int i) {return (i - 1) / 2;}
+ static inline int left(int i) {return 2 * i + 1;}
+ static inline int right(int i) {return 2 * i + 2;}
+
+ QDataBuffer<T> m_data;
+};
+
+template <class T>
+void QMaxHeap<T>::push(const T &x)
+{
+ int current = m_data.size();
+ int parent = QMaxHeap::parent(current);
+ m_data.add(x);
+ while (current != 0 && m_data.at(parent) < x) {
+ m_data.at(current) = m_data.at(parent);
+ current = parent;
+ parent = QMaxHeap::parent(current);
+ }
+ m_data.at(current) = x;
+}
+
+template <class T>
+T QMaxHeap<T>::pop()
+{
+ T result = m_data.first();
+ T back = m_data.last();
+ m_data.pop_back();
+ if (!m_data.isEmpty()) {
+ int current = 0;
+ for (;;) {
+ int left = QMaxHeap::left(current);
+ int right = QMaxHeap::right(current);
+ if (left >= m_data.size())
+ break;
+ int greater = left;
+ if (right < m_data.size() && m_data.at(left) < m_data.at(right))
+ greater = right;
+ if (m_data.at(greater) < back)
+ break;
+ m_data.at(current) = m_data.at(greater);
+ current = greater;
+ }
+ m_data.at(current) = back;
+ }
+ return result;
+}
+
+//============================================================================//
+// QRBTree //
+//============================================================================//
+
+template <class T>
+struct QRBTree
+{
+ struct Node
+ {
+ inline Node() : parent(0), left(0), right(0), red(true) { }
+ inline ~Node() {if (left) delete left; if (right) delete right;}
+ T data;
+ Node *parent;
+ Node *left;
+ Node *right;
+ bool red;
+ };
+
+ inline QRBTree() : root(0), freeList(0) { }
+ inline ~QRBTree();
+
+ inline void clear();
+
+ void attachBefore(Node *parent, Node *child);
+ void attachAfter(Node *parent, Node *child);
+
+ inline Node *front(Node *node) const;
+ inline Node *back(Node *node) const;
+ Node *next(Node *node) const;
+ Node *previous(Node *node) const;
+
+ inline void deleteNode(Node *&node);
+ inline Node *newNode();
+
+ // Return 1 if 'left' comes after 'right', 0 if equal, and -1 otherwise.
+ // 'left' and 'right' cannot be null.
+ int order(Node *left, Node *right);
+ inline bool verify() const;
+
+private:
+ void rotateLeft(Node *node);
+ void rotateRight(Node *node);
+ void update(Node *node);
+
+ inline void attachLeft(Node *parent, Node *child);
+ inline void attachRight(Node *parent, Node *child);
+
+ int blackDepth(Node *top) const;
+ bool checkRedBlackProperty(Node *top) const;
+
+ void swapNodes(Node *n1, Node *n2);
+ void detach(Node *node);
+
+ // 'node' must be black. rebalance will reduce the depth of black nodes by one in the sibling tree.
+ void rebalance(Node *node);
+
+public:
+ Node *root;
+private:
+ Node *freeList;
+};
+
+template <class T>
+inline QRBTree<T>::~QRBTree()
+{
+ clear();
+ while (freeList) {
+ // Avoid recursively calling the destructor, as this list may become large.
+ Node *next = freeList->right;
+ freeList->right = 0;
+ delete freeList;
+ freeList = next;
+ }
+}
+
+template <class T>
+inline void QRBTree<T>::clear()
+{
+ if (root)
+ delete root;
+ root = 0;
+}
+
+template <class T>
+void QRBTree<T>::rotateLeft(Node *node)
+{
+ // | | //
+ // N B //
+ // / \ / \ //
+ // A B ---> N D //
+ // / \ / \ //
+ // C D A C //
+
+ Node *&ref = (node->parent ? (node == node->parent->left ? node->parent->left : node->parent->right) : root);
+ ref = node->right;
+ node->right->parent = node->parent;
+
+ // : //
+ // N //
+ // / :| //
+ // A B //
+ // / \ //
+ // C D //
+
+ node->right = ref->left;
+ if (ref->left)
+ ref->left->parent = node;
+
+ // : | //
+ // N B //
+ // / \ : \ //
+ // A C D //
+
+ ref->left = node;
+ node->parent = ref;
+
+ // | //
+ // B //
+ // / \ //
+ // N D //
+ // / \ //
+ // A C //
+}
+
+template <class T>
+void QRBTree<T>::rotateRight(Node *node)
+{
+ // | | //
+ // N A //
+ // / \ / \ //
+ // A B ---> C N //
+ // / \ / \ //
+ // C D D B //
+
+ Node *&ref = (node->parent ? (node == node->parent->left ? node->parent->left : node->parent->right) : root);
+ ref = node->left;
+ node->left->parent = node->parent;
+
+ node->left = ref->right;
+ if (ref->right)
+ ref->right->parent = node;
+
+ ref->right = node;
+ node->parent = ref;
+}
+
+template <class T>
+void QRBTree<T>::update(Node *node) // call this after inserting a node
+{
+ for (;;) {
+ Node *parent = node->parent;
+
+ // if the node is the root, color it black
+ if (!parent) {
+ node->red = false;
+ return;
+ }
+
+ // if the parent is black, the node can be left red
+ if (!parent->red)
+ return;
+
+ // at this point, the parent is red and cannot be the root
+ Node *grandpa = parent->parent;
+ Q_ASSERT(grandpa);
+
+ Node *uncle = (parent == grandpa->left ? grandpa->right : grandpa->left);
+ if (uncle && uncle->red) {
+ // grandpa's black, parent and uncle are red.
+ // let parent and uncle be black, grandpa red and recursively update grandpa.
+ Q_ASSERT(!grandpa->red);
+ parent->red = false;
+ uncle->red = false;
+ grandpa->red = true;
+ node = grandpa;
+ continue;
+ }
+
+ // at this point, uncle is black
+ if (node == parent->right && parent == grandpa->left)
+ rotateLeft(node = parent);
+ else if (node == parent->left && parent == grandpa->right)
+ rotateRight(node = parent);
+ parent = node->parent;
+
+ if (parent == grandpa->left) {
+ rotateRight(grandpa);
+ parent->red = false;
+ grandpa->red = true;
+ } else {
+ rotateLeft(grandpa);
+ parent->red = false;
+ grandpa->red = true;
+ }
+ return;
+ }
+}
+
+template <class T>
+inline void QRBTree<T>::attachLeft(Node *parent, Node *child)
+{
+ Q_ASSERT(!parent->left);
+ parent->left = child;
+ child->parent = parent;
+ update(child);
+}
+
+template <class T>
+inline void QRBTree<T>::attachRight(Node *parent, Node *child)
+{
+ Q_ASSERT(!parent->right);
+ parent->right = child;
+ child->parent = parent;
+ update(child);
+}
+
+template <class T>
+void QRBTree<T>::attachBefore(Node *parent, Node *child)
+{
+ if (!root)
+ update(root = child);
+ else if (!parent)
+ attachRight(back(root), child);
+ else if (parent->left)
+ attachRight(back(parent->left), child);
+ else
+ attachLeft(parent, child);
+}
+
+template <class T>
+void QRBTree<T>::attachAfter(Node *parent, Node *child)
+{
+ if (!root)
+ update(root = child);
+ else if (!parent)
+ attachLeft(front(root), child);
+ else if (parent->right)
+ attachLeft(front(parent->right), child);
+ else
+ attachRight(parent, child);
+}
+
+template <class T>
+void QRBTree<T>::swapNodes(Node *n1, Node *n2)
+{
+ // Since iterators must not be invalidated, it is not sufficient to only swap the data.
+ if (n1->parent == n2) {
+ n1->parent = n2->parent;
+ n2->parent = n1;
+ } else if (n2->parent == n1) {
+ n2->parent = n1->parent;
+ n1->parent = n2;
+ } else {
+ qSwap(n1->parent, n2->parent);
+ }
+
+ qSwap(n1->left, n2->left);
+ qSwap(n1->right, n2->right);
+ qSwap(n1->red, n2->red);
+
+ if (n1->parent) {
+ if (n1->parent->left == n2)
+ n1->parent->left = n1;
+ else
+ n1->parent->right = n1;
+ } else {
+ root = n1;
+ }
+
+ if (n2->parent) {
+ if (n2->parent->left == n1)
+ n2->parent->left = n2;
+ else
+ n2->parent->right = n2;
+ } else {
+ root = n2;
+ }
+
+ if (n1->left)
+ n1->left->parent = n1;
+ if (n1->right)
+ n1->right->parent = n1;
+
+ if (n2->left)
+ n2->left->parent = n2;
+ if (n2->right)
+ n2->right->parent = n2;
+}
+
+template <class T>
+void QRBTree<T>::detach(Node *node) // call this before removing a node.
+{
+ if (node->right)
+ swapNodes(node, front(node->right));
+
+ Node *child = (node->left ? node->left : node->right);
+
+ if (!node->red) {
+ if (child && child->red)
+ child->red = false;
+ else
+ rebalance(node);
+ }
+
+ Node *&ref = (node->parent ? (node == node->parent->left ? node->parent->left : node->parent->right) : root);
+ ref = child;
+ if (child)
+ child->parent = node->parent;
+ node->left = node->right = node->parent = 0;
+}
+
+// 'node' must be black. rebalance will reduce the depth of black nodes by one in the sibling tree.
+template <class T>
+void QRBTree<T>::rebalance(Node *node)
+{
+ Q_ASSERT(!node->red);
+ for (;;) {
+ if (!node->parent)
+ return;
+
+ // at this point, node is not a parent, it is black, thus it must have a sibling.
+ Node *sibling = (node == node->parent->left ? node->parent->right : node->parent->left);
+ Q_ASSERT(sibling);
+
+ if (sibling->red) {
+ sibling->red = false;
+ node->parent->red = true;
+ if (node == node->parent->left)
+ rotateLeft(node->parent);
+ else
+ rotateRight(node->parent);
+ sibling = (node == node->parent->left ? node->parent->right : node->parent->left);
+ Q_ASSERT(sibling);
+ }
+
+ // at this point, the sibling is black.
+ Q_ASSERT(!sibling->red);
+
+ if ((!sibling->left || !sibling->left->red) && (!sibling->right || !sibling->right->red)) {
+ bool parentWasRed = node->parent->red;
+ sibling->red = true;
+ node->parent->red = false;
+ if (parentWasRed)
+ return;
+ node = node->parent;
+ continue;
+ }
+
+ // at this point, at least one of the sibling's children is red.
+
+ if (node == node->parent->left) {
+ if (!sibling->right || !sibling->right->red) {
+ Q_ASSERT(sibling->left);
+ sibling->red = true;
+ sibling->left->red = false;
+ rotateRight(sibling);
+
+ sibling = sibling->parent;
+ Q_ASSERT(sibling);
+ }
+ sibling->red = node->parent->red;
+ node->parent->red = false;
+
+ Q_ASSERT(sibling->right->red);
+ sibling->right->red = false;
+ rotateLeft(node->parent);
+ } else {
+ if (!sibling->left || !sibling->left->red) {
+ Q_ASSERT(sibling->right);
+ sibling->red = true;
+ sibling->right->red = false;
+ rotateLeft(sibling);
+
+ sibling = sibling->parent;
+ Q_ASSERT(sibling);
+ }
+ sibling->red = node->parent->red;
+ node->parent->red = false;
+
+ Q_ASSERT(sibling->left->red);
+ sibling->left->red = false;
+ rotateRight(node->parent);
+ }
+ return;
+ }
+}
+
+template <class T>
+inline typename QRBTree<T>::Node *QRBTree<T>::front(Node *node) const
+{
+ while (node->left)
+ node = node->left;
+ return node;
+}
+
+template <class T>
+inline typename QRBTree<T>::Node *QRBTree<T>::back(Node *node) const
+{
+ while (node->right)
+ node = node->right;
+ return node;
+}
+
+template <class T>
+typename QRBTree<T>::Node *QRBTree<T>::next(Node *node) const
+{
+ if (node->right)
+ return front(node->right);
+ while (node->parent && node == node->parent->right)
+ node = node->parent;
+ return node->parent;
+}
+
+template <class T>
+typename QRBTree<T>::Node *QRBTree<T>::previous(Node *node) const
+{
+ if (node->left)
+ return back(node->left);
+ while (node->parent && node == node->parent->left)
+ node = node->parent;
+ return node->parent;
+}
+
+template <class T>
+int QRBTree<T>::blackDepth(Node *top) const
+{
+ if (!top)
+ return 0;
+ int leftDepth = blackDepth(top->left);
+ int rightDepth = blackDepth(top->right);
+ if (leftDepth != rightDepth)
+ return -1;
+ if (!top->red)
+ ++leftDepth;
+ return leftDepth;
+}
+
+template <class T>
+bool QRBTree<T>::checkRedBlackProperty(Node *top) const
+{
+ if (!top)
+ return true;
+ if (top->left && !checkRedBlackProperty(top->left))
+ return false;
+ if (top->right && !checkRedBlackProperty(top->right))
+ return false;
+ return !(top->red && ((top->left && top->left->red) || (top->right && top->right->red)));
+}
+
+template <class T>
+inline bool QRBTree<T>::verify() const
+{
+ return checkRedBlackProperty(root) && blackDepth(root) != -1;
+}
+
+template <class T>
+inline void QRBTree<T>::deleteNode(Node *&node)
+{
+ Q_ASSERT(node);
+ detach(node);
+ node->right = freeList;
+ freeList = node;
+ node = 0;
+}
+
+template <class T>
+inline typename QRBTree<T>::Node *QRBTree<T>::newNode()
+{
+ if (freeList) {
+ Node *node = freeList;
+ freeList = freeList->right;
+ node->parent = node->left = node->right = 0;
+ node->red = true;
+ return node;
+ }
+ return new Node;
+}
+
+// Return 1 if 'left' comes after 'right', 0 if equal, and -1 otherwise.
+// 'left' and 'right' cannot be null.
+template <class T>
+int QRBTree<T>::order(Node *left, Node *right)
+{
+ Q_ASSERT(left && right);
+ if (left == right)
+ return 0;
+
+ QVector<Node *> leftAncestors;
+ QVector<Node *> rightAncestors;
+ while (left) {
+ leftAncestors.push_back(left);
+ left = left->parent;
+ }
+ while (right) {
+ rightAncestors.push_back(right);
+ right = right->parent;
+ }
+ Q_ASSERT(leftAncestors.back() == root && rightAncestors.back() == root);
+
+ while (!leftAncestors.empty() && !rightAncestors.empty() && leftAncestors.back() == rightAncestors.back()) {
+ leftAncestors.pop_back();
+ rightAncestors.pop_back();
+ }
+
+ if (!leftAncestors.empty())
+ return (leftAncestors.back() == leftAncestors.back()->parent->left ? -1 : 1);
+
+ if (!rightAncestors.empty())
+ return (rightAncestors.back() == rightAncestors.back()->parent->right ? -1 : 1);
+
+ // The code should never reach this point.
+ Q_ASSERT(!leftAncestors.empty() || !rightAncestors.empty());
+ return 0;
+}
+
+//============================================================================//
+// QInt64Hash //
+//============================================================================//
+
+// Copied from qhash.cpp
+static const uchar prime_deltas[] = {
+ 0, 0, 1, 3, 1, 5, 3, 3, 1, 9, 7, 5, 3, 9, 25, 3,
+ 1, 21, 3, 21, 7, 15, 9, 5, 3, 29, 15, 0, 0, 0, 0, 0
+};
+
+// Copied from qhash.cpp
+static inline int primeForNumBits(int numBits)
+{
+ return (1 << numBits) + prime_deltas[numBits];
+}
+
+static inline int primeForCount(int count)
+{
+ int low = 0;
+ int high = 32;
+ for (int i = 0; i < 5; ++i) {
+ int mid = (high + low) / 2;
+ if (count >= 1 << mid)
+ low = mid;
+ else
+ high = mid;
+ }
+ return primeForNumBits(high);
+}
+
+// Hash set of quint64s. Elements cannot be removed without clearing the
+// entire set. A value of -1 is used to mark unused entries.
+class QInt64Set
+{
+public:
+ inline QInt64Set(int capacity = 64);
+ inline ~QInt64Set() {if (m_array) delete[] m_array;}
+ inline bool isValid() const {return m_array;}
+ void insert(quint64 key);
+ bool contains(quint64 key) const;
+ inline void clear();
+private:
+ bool rehash(int capacity);
+
+ static const quint64 UNUSED;
+
+ quint64 *m_array;
+ int m_capacity;
+ int m_count;
+};
+
+const quint64 QInt64Set::UNUSED = quint64(-1);
+
+inline QInt64Set::QInt64Set(int capacity)
+{
+ m_capacity = primeForCount(capacity);
+ m_array = new quint64[m_capacity];
+ if (m_array)
+ clear();
+ else
+ m_capacity = 0;
+}
+
+bool QInt64Set::rehash(int capacity)
+{
+ quint64 *oldArray = m_array;
+ int oldCapacity = m_capacity;
+
+ m_capacity = capacity;
+ m_array = new quint64[m_capacity];
+ if (m_array) {
+ clear();
+ if (oldArray) {
+ for (int i = 0; i < oldCapacity; ++i) {
+ if (oldArray[i] != UNUSED)
+ insert(oldArray[i]);
+ }
+ delete[] oldArray;
+ }
+ return true;
+ } else {
+ m_capacity = oldCapacity;
+ m_array = oldArray;
+ return false;
+ }
+}
+
+void QInt64Set::insert(quint64 key)
+{
+ if (m_count > 3 * m_capacity / 4)
+ rehash(primeForCount(2 * m_capacity));
+ Q_ASSERT_X(m_array, "QInt64Hash<T>::insert", "Hash set not allocated.");
+ int index = int(key % m_capacity);
+ for (int i = 0; i < m_capacity; ++i) {
+ index += i;
+ if (index >= m_capacity)
+ index -= m_capacity;
+ if (m_array[index] == key)
+ return;
+ if (m_array[index] == UNUSED) {
+ ++m_count;
+ m_array[index] = key;
+ return;
+ }
+ }
+ Q_ASSERT_X(0, "QInt64Hash<T>::insert", "Hash set full.");
+}
+
+bool QInt64Set::contains(quint64 key) const
+{
+ Q_ASSERT_X(m_array, "QInt64Hash<T>::contains", "Hash set not allocated.");
+ int index = int(key % m_capacity);
+ for (int i = 0; i < m_capacity; ++i) {
+ index += i;
+ if (index >= m_capacity)
+ index -= m_capacity;
+ if (m_array[index] == key)
+ return true;
+ if (m_array[index] == UNUSED)
+ return false;
+ }
+ return false;
+}
+
+inline void QInt64Set::clear()
+{
+ Q_ASSERT_X(m_array, "QInt64Hash<T>::clear", "Hash set not allocated.");
+ for (int i = 0; i < m_capacity; ++i)
+ m_array[i] = UNUSED;
+ m_count = 0;
+}
+
+//============================================================================//
+// QRingBuffer //
+//============================================================================//
+
+// T must be POD.
+template <class T>
+class QRingBuffer
+{
+public:
+ inline QRingBuffer() : m_array(0), m_head(0), m_size(0), m_capacity(0) { }
+ inline ~QRingBuffer() {if (m_array) delete[] m_array;}
+ bool reallocate(int capacity);
+ inline const T &head() const {Q_ASSERT(m_size > 0); return m_array[m_head];}
+ inline const T &dequeue();
+ inline void enqueue(const T &x);
+ inline bool isEmpty() const {return m_size == 0;}
+private:
+ T *m_array;
+ int m_head;
+ int m_size;
+ int m_capacity;
+};
+
+template <class T>
+bool QRingBuffer<T>::reallocate(int capacity)
+{
+ T *oldArray = m_array;
+ m_array = new T[capacity];
+ if (m_array) {
+ if (oldArray) {
+ if (m_head + m_size > m_capacity) {
+ memcpy(m_array, oldArray + m_head, (m_capacity - m_head) * sizeof(T));
+ memcpy(m_array + (m_capacity - m_head), oldArray, (m_head + m_size - m_capacity) * sizeof(T));
+ } else {
+ memcpy(m_array, oldArray + m_head, m_size * sizeof(T));
+ }
+ delete[] oldArray;
+ }
+ m_capacity = capacity;
+ m_head = 0;
+ return true;
+ } else {
+ m_array = oldArray;
+ return false;
+ }
+}
+
+template <class T>
+inline const T &QRingBuffer<T>::dequeue()
+{
+ Q_ASSERT(m_size > 0);
+ Q_ASSERT(m_array);
+ Q_ASSERT(m_capacity >= m_size);
+ int index = m_head;
+ if (++m_head >= m_capacity)
+ m_head -= m_capacity;
+ --m_size;
+ return m_array[index];
+}
+
+template <class T>
+inline void QRingBuffer<T>::enqueue(const T &x)
+{
+ if (m_size == m_capacity)
+ reallocate(qMax(2 * m_capacity, 64));
+ int index = m_head + m_size;
+ if (index >= m_capacity)
+ index -= m_capacity;
+ m_array[index] = x;
+ ++m_size;
+}
+
+//============================================================================//
+// QTriangulator //
+//============================================================================//
+
+class QTriangulator
+{
+public:
+ typedef QVarLengthArray<int, 6> ShortArray;
+
+ //================================//
+ // QTriangulator::ComplexToSimple //
+ //================================//
+ friend class ComplexToSimple;
+ class ComplexToSimple
+ {
+ public:
+ inline ComplexToSimple(QTriangulator *parent) : m_parent(parent) { }
+ void decompose();
+ private:
+ struct Edge
+ {
+ inline int &upper() {return pointingUp ? to : from;}
+ inline int &lower() {return pointingUp ? from : to;}
+ inline int upper() const {return pointingUp ? to : from;}
+ inline int lower() const {return pointingUp ? from : to;}
+
+ QRBTree<int>::Node *node;
+ int from, to; // vertex
+ int next, previous; // edge
+ int winding;
+ bool mayIntersect;
+ bool pointingUp, originallyPointingUp;
+ };
+
+ friend class CompareEdges;
+ class CompareEdges
+ {
+ public:
+ inline CompareEdges(ComplexToSimple *parent) : m_parent(parent) { }
+ bool operator () (int i, int j) const;
+ private:
+ ComplexToSimple *m_parent;
+ };
+
+ struct Intersection
+ {
+ bool operator < (const Intersection &other) const {return other.intersectionPoint < intersectionPoint;}
+
+ QIntersectionPoint intersectionPoint;
+ int vertex;
+ int leftEdge;
+ int rightEdge;
+ };
+
+ struct Split
+ {
+ int vertex;
+ int edge;
+ bool accurate;
+ };
+
+ struct Event
+ {
+ enum Type {Upper, Lower};
+ inline bool operator < (const Event &other) const;
+
+ QPodPoint point;
+ Type type;
+ int edge;
+ };
+
+#ifdef Q_TRIANGULATOR_DEBUG
+ friend class DebugDialog;
+ friend class QTriangulator;
+ class DebugDialog : public QDialog
+ {
+ public:
+ DebugDialog(ComplexToSimple *parent, int currentVertex);
+ protected:
+ void paintEvent(QPaintEvent *);
+ void wheelEvent(QWheelEvent *);
+ void mouseMoveEvent(QMouseEvent *);
+ void mousePressEvent(QMouseEvent *);
+ private:
+ ComplexToSimple *m_parent;
+ QRectF m_window;
+ QPoint m_lastMousePos;
+ int m_vertex;
+ };
+#endif
+
+ void initEdges();
+ bool calculateIntersection(int left, int right);
+ bool edgeIsLeftOfEdge(int leftEdgeIndex, int rightEdgeIndex) const;
+ QRBTree<int>::Node *searchEdgeLeftOf(int edgeIndex) const;
+ QRBTree<int>::Node *searchEdgeLeftOf(int edgeIndex, QRBTree<int>::Node *after) const;
+ QPair<QRBTree<int>::Node *, QRBTree<int>::Node *> bounds(const QPodPoint &point) const;
+ QPair<QRBTree<int>::Node *, QRBTree<int>::Node *> outerBounds(const QPodPoint &point) const;
+ void splitEdgeListRange(QRBTree<int>::Node *leftmost, QRBTree<int>::Node *rightmost, int vertex, const QIntersectionPoint &intersectionPoint);
+ void reorderEdgeListRange(QRBTree<int>::Node *leftmost, QRBTree<int>::Node *rightmost);
+ void sortEdgeList(const QPodPoint eventPoint);
+ void fillPriorityQueue();
+ void calculateIntersections();
+ int splitEdge(int splitIndex);
+ bool splitEdgesAtIntersections();
+ void insertEdgeIntoVectorIfWanted(ShortArray &orderedEdges, int i);
+ void removeUnwantedEdgesAndConnect();
+ void removeUnusedPoints();
+
+ QTriangulator *m_parent;
+ QDataBuffer<Edge> m_edges;
+ QRBTree<int> m_edgeList;
+ QDataBuffer<Event> m_events;
+ QDataBuffer<Split> m_splits;
+ QMaxHeap<Intersection> m_topIntersection;
+ QInt64Set m_processedEdgePairs;
+ int m_initialPointCount;
+ };
+#ifdef Q_TRIANGULATOR_DEBUG
+ friend class ComplexToSimple::DebugDialog;
+#endif
+
+ //=================================//
+ // QTriangulator::SimpleToMonotone //
+ //=================================//
+ friend class SimpleToMonotone;
+ class SimpleToMonotone
+ {
+ public:
+ inline SimpleToMonotone(QTriangulator *parent) : m_parent(parent) { }
+ void decompose();
+ private:
+ enum VertexType {MergeVertex, EndVertex, RegularVertex, StartVertex, SplitVertex};
+
+ struct Edge
+ {
+ QRBTree<int>::Node *node;
+ int helper, twin, next, previous;
+ quint32 from, to;
+ VertexType type;
+ bool pointingUp;
+ int upper() const {return (pointingUp ? to : from);}
+ int lower() const {return (pointingUp ? from : to);}
+ };
+
+ friend class CompareVertices;
+ class CompareVertices
+ {
+ public:
+ CompareVertices(SimpleToMonotone *parent) : m_parent(parent) { }
+ bool operator () (int i, int j) const;
+ private:
+ SimpleToMonotone *m_parent;
+ };
+
+ void setupDataStructures();
+ void removeZeroLengthEdges();
+ void fillPriorityQueue();
+ bool edgeIsLeftOfEdge(int leftEdgeIndex, int rightEdgeIndex) const;
+ // Returns the rightmost edge not to the right of the given edge.
+ QRBTree<int>::Node *searchEdgeLeftOfEdge(int edgeIndex) const;
+ // Returns the rightmost edge left of the given point.
+ QRBTree<int>::Node *searchEdgeLeftOfPoint(int pointIndex) const;
+ void classifyVertex(int i);
+ void classifyVertices();
+ bool pointIsInSector(const QPodPoint &p, const QPodPoint &v1, const QPodPoint &v2, const QPodPoint &v3);
+ bool pointIsInSector(int vertex, int sector);
+ int findSector(int edge, int vertex);
+ void createDiagonal(int lower, int upper);
+ void monotoneDecomposition();
+
+ QTriangulator *m_parent;
+ QRBTree<int> m_edgeList;
+ QDataBuffer<Edge> m_edges;
+ QDataBuffer<int> m_upperVertex;
+ bool m_clockwiseOrder;
+ };
+
+ //====================================//
+ // QTriangulator::MonotoneToTriangles //
+ //====================================//
+ friend class MonotoneToTriangles;
+ class MonotoneToTriangles
+ {
+ public:
+ inline MonotoneToTriangles(QTriangulator *parent) : m_parent(parent) { }
+ void decompose();
+ private:
+ inline quint32 indices(int index) const {return m_parent->m_indices.at(index + m_first);}
+ inline int next(int index) const {return (index + 1) % m_length;}
+ inline int previous(int index) const {return (index + m_length - 1) % m_length;}
+ inline bool less(int i, int j) const {return m_parent->m_vertices.at(indices(i)) < m_parent->m_vertices.at(indices(j));}
+ inline bool leftOfEdge(int i, int j, int k) const
+ {
+ return qPointIsLeftOfLine(m_parent->m_vertices.at(indices(i)),
+ m_parent->m_vertices.at(indices(j)), m_parent->m_vertices.at(indices(k)));
+ }
+
+ QTriangulator *m_parent;
+ int m_first;
+ int m_length;
+ };
+
+ inline QTriangulator() { }
+
+ // Call this only once.
+ void initialize(const qreal *polygon, int count, uint hint, const QTransform &matrix);
+ // Call this only once.
+ void initialize(const QVectorPath &path, const QTransform &matrix, qreal lod);
+ // Call this only once.
+ void initialize(const QPainterPath &path, const QTransform &matrix, qreal lod);
+ // Call either triangulate() or polyline() only once.
+ QTriangleSet triangulate();
+ QPolylineSet polyline();
+private:
+ QDataBuffer<QPodPoint> m_vertices;
+ QVector<quint32> m_indices;
+ uint m_hint;
+};
+
+//============================================================================//
+// QTriangulator //
+//============================================================================//
+
+QTriangleSet QTriangulator::triangulate()
+{
+ for (int i = 0; i < m_vertices.size(); ++i) {
+ Q_ASSERT(qAbs(m_vertices.at(i).x) < (1 << 21));
+ Q_ASSERT(qAbs(m_vertices.at(i).y) < (1 << 21));
+ }
+
+ if (!(m_hint & (QVectorPath::OddEvenFill | QVectorPath::WindingFill)))
+ m_hint |= QVectorPath::OddEvenFill;
+
+ if (m_hint & QVectorPath::NonConvexShapeMask) {
+ ComplexToSimple c2s(this);
+ c2s.decompose();
+ SimpleToMonotone s2m(this);
+ s2m.decompose();
+ }
+ MonotoneToTriangles m2t(this);
+ m2t.decompose();
+
+ QTriangleSet result;
+ result.indices = m_indices;
+ result.vertices.resize(2 * m_vertices.size());
+ for (int i = 0; i < m_vertices.size(); ++i) {
+ result.vertices[2 * i + 0] = qreal(m_vertices.at(i).x) / Q_FIXED_POINT_SCALE;
+ result.vertices[2 * i + 1] = qreal(m_vertices.at(i).y) / Q_FIXED_POINT_SCALE;
+ }
+ return result;
+}
+
+QPolylineSet QTriangulator::polyline()
+{
+ QPolylineSet result;
+ result.indices = m_indices;
+ result.vertices.resize(2 * m_vertices.size());
+ for (int i = 0; i < m_vertices.size(); ++i) {
+ result.vertices[2 * i + 0] = qreal(m_vertices.at(i).x) / Q_FIXED_POINT_SCALE;
+ result.vertices[2 * i + 1] = qreal(m_vertices.at(i).y) / Q_FIXED_POINT_SCALE;
+ }
+ return result;
+}
+
+void QTriangulator::initialize(const qreal *polygon, int count, uint hint, const QTransform &matrix)
+{
+ m_hint = hint;
+ m_vertices.resize(count);
+ m_indices.resize(count + 1);
+ for (int i = 0; i < count; ++i) {
+ qreal x, y;
+ matrix.map(polygon[2 * i + 0], polygon[2 * i + 1], &x, &y);
+ m_vertices.at(i).x = qRound(x * Q_FIXED_POINT_SCALE);
+ m_vertices.at(i).y = qRound(y * Q_FIXED_POINT_SCALE);
+ m_indices[i] = i;
+ }
+ m_indices[count] = Q_TRIANGULATE_END_OF_POLYGON;
+}
+
+void QTriangulator::initialize(const QVectorPath &path, const QTransform &matrix, qreal lod)
+{
+ m_hint = path.hints();
+ // Curved paths will be converted to complex polygons.
+ m_hint &= ~QVectorPath::CurvedShapeMask;
+
+ const qreal *p = path.points();
+ const QPainterPath::ElementType *e = path.elements();
+ if (e) {
+ for (int i = 0; i < path.elementCount(); ++i, ++e, p += 2) {
+ switch (*e) {
+ case QPainterPath::MoveToElement:
+ if (!m_indices.isEmpty())
+ m_indices.push_back(Q_TRIANGULATE_END_OF_POLYGON);
+ // Fall through.
+ case QPainterPath::LineToElement:
+ m_indices.push_back(quint32(m_vertices.size()));
+ m_vertices.resize(m_vertices.size() + 1);
+ qreal x, y;
+ matrix.map(p[0], p[1], &x, &y);
+ m_vertices.last().x = qRound(x * Q_FIXED_POINT_SCALE);
+ m_vertices.last().y = qRound(y * Q_FIXED_POINT_SCALE);
+ break;
+ case QPainterPath::CurveToElement:
+ {
+ qreal pts[8];
+ for (int i = 0; i < 4; ++i)
+ matrix.map(p[2 * i - 2], p[2 * i - 1], &pts[2 * i + 0], &pts[2 * i + 1]);
+ for (int i = 0; i < 8; ++i)
+ pts[i] *= lod;
+ QBezier bezier = QBezier::fromPoints(QPointF(pts[0], pts[1]), QPointF(pts[2], pts[3]), QPointF(pts[4], pts[5]), QPointF(pts[6], pts[7]));
+ QPolygonF poly = bezier.toPolygon();
+ // Skip first point, it already exists in 'm_vertices'.
+ for (int j = 1; j < poly.size(); ++j) {
+ m_indices.push_back(quint32(m_vertices.size()));
+ m_vertices.resize(m_vertices.size() + 1);
+ m_vertices.last().x = qRound(poly.at(j).x() * Q_FIXED_POINT_SCALE / lod);
+ m_vertices.last().y = qRound(poly.at(j).y() * Q_FIXED_POINT_SCALE / lod);
+ }
+ }
+ i += 2;
+ e += 2;
+ p += 4;
+ break;
+ default:
+ Q_ASSERT_X(0, "QTriangulator::triangulate", "Unexpected element type.");
+ break;
+ }
+ }
+ } else {
+ for (int i = 0; i < path.elementCount(); ++i, p += 2) {
+ m_indices.push_back(quint32(m_vertices.size()));
+ m_vertices.resize(m_vertices.size() + 1);
+ qreal x, y;
+ matrix.map(p[0], p[1], &x, &y);
+ m_vertices.last().x = qRound(x * Q_FIXED_POINT_SCALE);
+ m_vertices.last().y = qRound(y * Q_FIXED_POINT_SCALE);
+ }
+ }
+ m_indices.push_back(Q_TRIANGULATE_END_OF_POLYGON);
+}
+
+void QTriangulator::initialize(const QPainterPath &path, const QTransform &matrix, qreal lod)
+{
+ initialize(qtVectorPathForPath(path), matrix, lod);
+}
+
+//============================================================================//
+// QTriangulator::ComplexToSimple //
+//============================================================================//
+
+void QTriangulator::ComplexToSimple::decompose()
+{
+ m_initialPointCount = m_parent->m_vertices.size();
+ initEdges();
+ do {
+ calculateIntersections();
+ } while (splitEdgesAtIntersections());
+
+ removeUnwantedEdgesAndConnect();
+ removeUnusedPoints();
+
+ m_parent->m_indices.clear();
+ QBitArray processed(m_edges.size(), false);
+ for (int first = 0; first < m_edges.size(); ++first) {
+ // If already processed, or if unused path, skip.
+ if (processed.at(first) || m_edges.at(first).next == -1)
+ continue;
+
+ int i = first;
+ do {
+ Q_ASSERT(!processed.at(i));
+ Q_ASSERT(m_edges.at(m_edges.at(i).next).previous == i);
+ m_parent->m_indices.push_back(m_edges.at(i).from);
+ processed.setBit(i);
+ i = m_edges.at(i).next; // CCW order
+ } while (i != first);
+ m_parent->m_indices.push_back(Q_TRIANGULATE_END_OF_POLYGON);
+ }
+}
+
+void QTriangulator::ComplexToSimple::initEdges()
+{
+ // Initialize edge structure.
+ // 'next' and 'previous' are not being initialized at this point.
+ int first = 0;
+ for (int i = 0; i < m_parent->m_indices.size(); ++i) {
+ if (m_parent->m_indices.at(i) == Q_TRIANGULATE_END_OF_POLYGON) {
+ if (m_edges.size() != first)
+ m_edges.last().to = m_edges.at(first).from;
+ first = m_edges.size();
+ } else {
+ Q_ASSERT(i + 1 < m_parent->m_indices.size());
+ // {node, from, to, next, previous, winding, mayIntersect, pointingUp, originallyPointingUp}
+ Edge edge = {0, m_parent->m_indices.at(i), m_parent->m_indices.at(i + 1), -1, -1, 0, true, false, false};
+ m_edges.add(edge);
+ }
+ }
+ if (first != m_edges.size())
+ m_edges.last().to = m_edges.at(first).from;
+ for (int i = 0; i < m_edges.size(); ++i) {
+ m_edges.at(i).originallyPointingUp = m_edges.at(i).pointingUp =
+ m_parent->m_vertices.at(m_edges.at(i).to) < m_parent->m_vertices.at(m_edges.at(i).from);
+ }
+}
+
+// Return true if new intersection was found
+bool QTriangulator::ComplexToSimple::calculateIntersection(int left, int right)
+{
+ const Edge &e1 = m_edges.at(left);
+ const Edge &e2 = m_edges.at(right);
+
+ const QPodPoint &u1 = m_parent->m_vertices.at(e1.from);
+ const QPodPoint &u2 = m_parent->m_vertices.at(e1.to);
+ const QPodPoint &v1 = m_parent->m_vertices.at(e2.from);
+ const QPodPoint &v2 = m_parent->m_vertices.at(e2.to);
+ if (qMax(u1.x, u2.x) <= qMin(v1.x, v2.x))
+ return false;
+
+ quint64 key = (left > right ? (quint64(right) << 32) | quint64(left) : (quint64(left) << 32) | quint64(right));
+ if (m_processedEdgePairs.contains(key))
+ return false;
+ m_processedEdgePairs.insert(key);
+
+ Intersection intersection;
+ intersection.leftEdge = left;
+ intersection.rightEdge = right;
+ intersection.intersectionPoint = qIntersectionPoint(u1, u2, v1, v2);
+
+ if (!intersection.intersectionPoint.isValid())
+ return false;
+
+ Q_ASSERT(intersection.intersectionPoint.isOnLine(u1, u2));
+ Q_ASSERT(intersection.intersectionPoint.isOnLine(v1, v2));
+
+ intersection.vertex = m_parent->m_vertices.size();
+ m_topIntersection.push(intersection);
+ m_parent->m_vertices.add(intersection.intersectionPoint.round());
+ return true;
+}
+
+bool QTriangulator::ComplexToSimple::edgeIsLeftOfEdge(int leftEdgeIndex, int rightEdgeIndex) const
+{
+ const Edge &leftEdge = m_edges.at(leftEdgeIndex);
+ const Edge &rightEdge = m_edges.at(rightEdgeIndex);
+ const QPodPoint &u = m_parent->m_vertices.at(rightEdge.upper());
+ const QPodPoint &l = m_parent->m_vertices.at(rightEdge.lower());
+ const QPodPoint &upper = m_parent->m_vertices.at(leftEdge.upper());
+ if (upper.x < qMin(l.x, u.x))
+ return true;
+ if (upper.x > qMax(l.x, u.x))
+ return false;
+ qint64 d = qPointDistanceFromLine(upper, l, u);
+ // d < 0: left, d > 0: right, d == 0: on top
+ if (d == 0)
+ d = qPointDistanceFromLine(m_parent->m_vertices.at(leftEdge.lower()), l, u);
+ return d < 0;
+}
+
+QRBTree<int>::Node *QTriangulator::ComplexToSimple::searchEdgeLeftOf(int edgeIndex) const
+{
+ QRBTree<int>::Node *current = m_edgeList.root;
+ QRBTree<int>::Node *result = 0;
+ while (current) {
+ if (edgeIsLeftOfEdge(edgeIndex, current->data)) {
+ current = current->left;
+ } else {
+ result = current;
+ current = current->right;
+ }
+ }
+ return result;
+}
+
+QRBTree<int>::Node *QTriangulator::ComplexToSimple::searchEdgeLeftOf(int edgeIndex, QRBTree<int>::Node *after) const
+{
+ if (!m_edgeList.root)
+ return after;
+ QRBTree<int>::Node *result = after;
+ QRBTree<int>::Node *current = (after ? m_edgeList.next(after) : m_edgeList.front(m_edgeList.root));
+ while (current) {
+ if (edgeIsLeftOfEdge(edgeIndex, current->data))
+ return result;
+ result = current;
+ current = m_edgeList.next(current);
+ }
+ return result;
+}
+
+QPair<QRBTree<int>::Node *, QRBTree<int>::Node *> QTriangulator::ComplexToSimple::bounds(const QPodPoint &point) const
+{
+ QRBTree<int>::Node *current = m_edgeList.root;
+ QPair<QRBTree<int>::Node *, QRBTree<int>::Node *> result(0, 0);
+ while (current) {
+ const QPodPoint &v1 = m_parent->m_vertices.at(m_edges.at(current->data).lower());
+ const QPodPoint &v2 = m_parent->m_vertices.at(m_edges.at(current->data).upper());
+ qint64 d = qPointDistanceFromLine(point, v1, v2);
+ if (d == 0) {
+ result.first = result.second = current;
+ break;
+ }
+ current = (d < 0 ? current->left : current->right);
+ }
+ if (current == 0)
+ return result;
+
+ current = result.first->left;
+ while (current) {
+ const QPodPoint &v1 = m_parent->m_vertices.at(m_edges.at(current->data).lower());
+ const QPodPoint &v2 = m_parent->m_vertices.at(m_edges.at(current->data).upper());
+ qint64 d = qPointDistanceFromLine(point, v1, v2);
+ Q_ASSERT(d >= 0);
+ if (d == 0) {
+ result.first = current;
+ current = current->left;
+ } else {
+ current = current->right;
+ }
+ }
+
+ current = result.second->right;
+ while (current) {
+ const QPodPoint &v1 = m_parent->m_vertices.at(m_edges.at(current->data).lower());
+ const QPodPoint &v2 = m_parent->m_vertices.at(m_edges.at(current->data).upper());
+ qint64 d = qPointDistanceFromLine(point, v1, v2);
+ Q_ASSERT(d <= 0);
+ if (d == 0) {
+ result.second = current;
+ current = current->right;
+ } else {
+ current = current->left;
+ }
+ }
+
+ return result;
+}
+
+QPair<QRBTree<int>::Node *, QRBTree<int>::Node *> QTriangulator::ComplexToSimple::outerBounds(const QPodPoint &point) const
+{
+ QRBTree<int>::Node *current = m_edgeList.root;
+ QPair<QRBTree<int>::Node *, QRBTree<int>::Node *> result(0, 0);
+
+ while (current) {
+ const QPodPoint &v1 = m_parent->m_vertices.at(m_edges.at(current->data).lower());
+ const QPodPoint &v2 = m_parent->m_vertices.at(m_edges.at(current->data).upper());
+ qint64 d = qPointDistanceFromLine(point, v1, v2);
+ if (d == 0)
+ break;
+ if (d < 0) {
+ result.second = current;
+ current = current->left;
+ } else {
+ result.first = current;
+ current = current->right;
+ }
+ }
+
+ if (!current)
+ return result;
+
+ QRBTree<int>::Node *mid = current;
+
+ current = mid->left;
+ while (current) {
+ const QPodPoint &v1 = m_parent->m_vertices.at(m_edges.at(current->data).lower());
+ const QPodPoint &v2 = m_parent->m_vertices.at(m_edges.at(current->data).upper());
+ qint64 d = qPointDistanceFromLine(point, v1, v2);
+ Q_ASSERT(d >= 0);
+ if (d == 0) {
+ current = current->left;
+ } else {
+ result.first = current;
+ current = current->right;
+ }
+ }
+
+ current = mid->right;
+ while (current) {
+ const QPodPoint &v1 = m_parent->m_vertices.at(m_edges.at(current->data).lower());
+ const QPodPoint &v2 = m_parent->m_vertices.at(m_edges.at(current->data).upper());
+ qint64 d = qPointDistanceFromLine(point, v1, v2);
+ Q_ASSERT(d <= 0);
+ if (d == 0) {
+ current = current->right;
+ } else {
+ result.second = current;
+ current = current->left;
+ }
+ }
+
+ return result;
+}
+
+void QTriangulator::ComplexToSimple::splitEdgeListRange(QRBTree<int>::Node *leftmost, QRBTree<int>::Node *rightmost, int vertex, const QIntersectionPoint &intersectionPoint)
+{
+ Q_ASSERT(leftmost && rightmost);
+
+ // Split.
+ for (;;) {
+ const QPodPoint &u = m_parent->m_vertices.at(m_edges.at(leftmost->data).from);
+ const QPodPoint &v = m_parent->m_vertices.at(m_edges.at(leftmost->data).to);
+ Q_ASSERT(intersectionPoint.isOnLine(u, v));
+ const Split split = {vertex, leftmost->data, intersectionPoint.isAccurate()};
+ if (intersectionPoint.xOffset.numerator != 0 || intersectionPoint.yOffset.numerator != 0 || (intersectionPoint.upperLeft != u && intersectionPoint.upperLeft != v))
+ m_splits.add(split);
+ if (leftmost == rightmost)
+ break;
+ leftmost = m_edgeList.next(leftmost);
+ }
+}
+
+
+void QTriangulator::ComplexToSimple::reorderEdgeListRange(QRBTree<int>::Node *leftmost, QRBTree<int>::Node *rightmost)
+{
+ Q_ASSERT(leftmost && rightmost);
+
+ QRBTree<int>::Node *storeLeftmost = leftmost;
+ QRBTree<int>::Node *storeRightmost = rightmost;
+
+ // Reorder.
+ while (leftmost != rightmost) {
+ Edge &left = m_edges.at(leftmost->data);
+ Edge &right = m_edges.at(rightmost->data);
+ qSwap(left.node, right.node);
+ qSwap(leftmost->data, rightmost->data);
+ leftmost = m_edgeList.next(leftmost);
+ if (leftmost == rightmost)
+ break;
+ rightmost = m_edgeList.previous(rightmost);
+ }
+
+ rightmost = m_edgeList.next(storeRightmost);
+ leftmost = m_edgeList.previous(storeLeftmost);
+ if (leftmost)
+ calculateIntersection(leftmost->data, storeLeftmost->data);
+ if (rightmost)
+ calculateIntersection(storeRightmost->data, rightmost->data);
+}
+
+void QTriangulator::ComplexToSimple::sortEdgeList(const QPodPoint eventPoint)
+{
+ QIntersectionPoint eventPoint2 = qIntersectionPoint(eventPoint);
+ while (!m_topIntersection.isEmpty() && m_topIntersection.top().intersectionPoint < eventPoint2) {
+ Intersection intersection = m_topIntersection.pop();
+
+ QIntersectionPoint currentIntersectionPoint = intersection.intersectionPoint;
+ int currentVertex = intersection.vertex;
+
+ QRBTree<int>::Node *leftmost = m_edges.at(intersection.leftEdge).node;
+ QRBTree<int>::Node *rightmost = m_edges.at(intersection.rightEdge).node;
+
+ for (;;) {
+ QRBTree<int>::Node *previous = m_edgeList.previous(leftmost);
+ if (!previous)
+ break;
+ const Edge &edge = m_edges.at(previous->data);
+ const QPodPoint &u = m_parent->m_vertices.at(edge.from);
+ const QPodPoint &v = m_parent->m_vertices.at(edge.to);
+ if (!currentIntersectionPoint.isOnLine(u, v)) {
+ Q_ASSERT(!currentIntersectionPoint.isAccurate() || qCross(currentIntersectionPoint.upperLeft - u, v - u) != 0);
+ break;
+ }
+ leftmost = previous;
+ }
+
+ for (;;) {
+ QRBTree<int>::Node *next = m_edgeList.next(rightmost);
+ if (!next)
+ break;
+ const Edge &edge = m_edges.at(next->data);
+ const QPodPoint &u = m_parent->m_vertices.at(edge.from);
+ const QPodPoint &v = m_parent->m_vertices.at(edge.to);
+ if (!currentIntersectionPoint.isOnLine(u, v)) {
+ Q_ASSERT(!currentIntersectionPoint.isAccurate() || qCross(currentIntersectionPoint.upperLeft - u, v - u) != 0);
+ break;
+ }
+ rightmost = next;
+ }
+
+ Q_ASSERT(leftmost && rightmost);
+ splitEdgeListRange(leftmost, rightmost, currentVertex, currentIntersectionPoint);
+ reorderEdgeListRange(leftmost, rightmost);
+
+ while (!m_topIntersection.isEmpty() && m_topIntersection.top().intersectionPoint <= currentIntersectionPoint)
+ m_topIntersection.pop();
+
+#ifdef Q_TRIANGULATOR_DEBUG
+ DebugDialog dialog(this, intersection.vertex);
+ dialog.exec();
+#endif
+
+ }
+}
+
+void QTriangulator::ComplexToSimple::fillPriorityQueue()
+{
+ m_events.reset();
+ m_events.reserve(m_edges.size() * 2);
+ for (int i = 0; i < m_edges.size(); ++i) {
+ Q_ASSERT(m_edges.at(i).previous == -1 && m_edges.at(i).next == -1);
+ Q_ASSERT(m_edges.at(i).node == 0);
+ Q_ASSERT(m_edges.at(i).pointingUp == m_edges.at(i).originallyPointingUp);
+ Q_ASSERT(m_edges.at(i).pointingUp == (m_parent->m_vertices.at(m_edges.at(i).to) < m_parent->m_vertices.at(m_edges.at(i).from)));
+ // Ignore zero-length edges.
+ if (m_parent->m_vertices.at(m_edges.at(i).to) != m_parent->m_vertices.at(m_edges.at(i).from)) {
+ QPodPoint upper = m_parent->m_vertices.at(m_edges.at(i).upper());
+ QPodPoint lower = m_parent->m_vertices.at(m_edges.at(i).lower());
+ Event upperEvent = {{upper.x, upper.y}, Event::Upper, i};
+ Event lowerEvent = {{lower.x, lower.y}, Event::Lower, i};
+ m_events.add(upperEvent);
+ m_events.add(lowerEvent);
+ }
+ }
+ //qSort(m_events.data(), m_events.data() + m_events.size());
+ sort(m_events.data(), m_events.size());
+}
+
+void QTriangulator::ComplexToSimple::calculateIntersections()
+{
+ fillPriorityQueue();
+
+ Q_ASSERT(m_topIntersection.empty());
+ Q_ASSERT(m_edgeList.root == 0);
+
+ // Find all intersection points.
+ while (!m_events.isEmpty()) {
+ Event event = m_events.last();
+ sortEdgeList(event.point);
+
+ // Find all edges in the edge list that contain the current vertex and mark them to be split later.
+ QPair<QRBTree<int>::Node *, QRBTree<int>::Node *> range = bounds(event.point);
+ QRBTree<int>::Node *leftNode = range.first ? m_edgeList.previous(range.first) : 0;
+ int vertex = (event.type == Event::Upper ? m_edges.at(event.edge).upper() : m_edges.at(event.edge).lower());
+ QIntersectionPoint eventPoint = qIntersectionPoint(event.point);
+
+ if (range.first != 0) {
+ splitEdgeListRange(range.first, range.second, vertex, eventPoint);
+ reorderEdgeListRange(range.first, range.second);
+ }
+
+ // Handle the edges with start or end point in the current vertex.
+ while (!m_events.isEmpty() && m_events.last().point == event.point) {
+ event = m_events.last();
+ m_events.pop_back();
+ int i = event.edge;
+
+ if (m_edges.at(i).node) {
+ // Remove edge from edge list.
+ Q_ASSERT(event.type == Event::Lower);
+ QRBTree<int>::Node *left = m_edgeList.previous(m_edges.at(i).node);
+ QRBTree<int>::Node *right = m_edgeList.next(m_edges.at(i).node);
+ m_edgeList.deleteNode(m_edges.at(i).node);
+ if (!left || !right)
+ continue;
+ calculateIntersection(left->data, right->data);
+ } else {
+ // Insert edge into edge list.
+ Q_ASSERT(event.type == Event::Upper);
+ QRBTree<int>::Node *left = searchEdgeLeftOf(i, leftNode);
+ m_edgeList.attachAfter(left, m_edges.at(i).node = m_edgeList.newNode());
+ m_edges.at(i).node->data = i;
+ QRBTree<int>::Node *right = m_edgeList.next(m_edges.at(i).node);
+ if (left)
+ calculateIntersection(left->data, i);
+ if (right)
+ calculateIntersection(i, right->data);
+ }
+ }
+ while (!m_topIntersection.isEmpty() && m_topIntersection.top().intersectionPoint <= eventPoint)
+ m_topIntersection.pop();
+#ifdef Q_TRIANGULATOR_DEBUG
+ DebugDialog dialog(this, vertex);
+ dialog.exec();
+#endif
+ }
+ m_processedEdgePairs.clear();
+}
+
+// Split an edge into two pieces at the given point.
+// The upper piece is pushed to the end of the 'm_edges' vector.
+// The lower piece replaces the old edge.
+// Return the edge whose 'from' is 'pointIndex'.
+int QTriangulator::ComplexToSimple::splitEdge(int splitIndex)
+{
+ const Split &split = m_splits.at(splitIndex);
+ Edge &lowerEdge = m_edges.at(split.edge);
+ Q_ASSERT(lowerEdge.node == 0);
+ Q_ASSERT(lowerEdge.previous == -1 && lowerEdge.next == -1);
+
+ if (lowerEdge.from == split.vertex)
+ return split.edge;
+ if (lowerEdge.to == split.vertex)
+ return lowerEdge.next;
+
+ // Check that angle >= 90 degrees.
+ //Q_ASSERT(qDot(m_points.at(m_edges.at(edgeIndex).from) - m_points.at(pointIndex),
+ // m_points.at(m_edges.at(edgeIndex).to) - m_points.at(pointIndex)) <= 0);
+
+ Edge upperEdge = lowerEdge;
+ upperEdge.mayIntersect |= !split.accurate; // The edge may have been split before at an inaccurate split point.
+ lowerEdge.mayIntersect = !split.accurate;
+ if (lowerEdge.pointingUp) {
+ lowerEdge.to = upperEdge.from = split.vertex;
+ m_edges.add(upperEdge);
+ return m_edges.size() - 1;
+ } else {
+ lowerEdge.from = upperEdge.to = split.vertex;
+ m_edges.add(upperEdge);
+ return split.edge;
+ }
+}
+
+bool QTriangulator::ComplexToSimple::splitEdgesAtIntersections()
+{
+ for (int i = 0; i < m_edges.size(); ++i)
+ m_edges.at(i).mayIntersect = false;
+ bool checkForNewIntersections = false;
+ for (int i = 0; i < m_splits.size(); ++i) {
+ splitEdge(i);
+ checkForNewIntersections |= !m_splits.at(i).accurate;
+ }
+ for (int i = 0; i < m_edges.size(); ++i) {
+ m_edges.at(i).originallyPointingUp = m_edges.at(i).pointingUp =
+ m_parent->m_vertices.at(m_edges.at(i).to) < m_parent->m_vertices.at(m_edges.at(i).from);
+ }
+ m_splits.reset();
+ return checkForNewIntersections;
+}
+
+void QTriangulator::ComplexToSimple::insertEdgeIntoVectorIfWanted(ShortArray &orderedEdges, int i)
+{
+ // Edges with zero length should not reach this part.
+ Q_ASSERT(m_parent->m_vertices.at(m_edges.at(i).from) != m_parent->m_vertices.at(m_edges.at(i).to));
+
+ // Skip edges with unwanted winding number.
+ int windingNumber = m_edges.at(i).winding;
+ if (m_edges.at(i).originallyPointingUp)
+ ++windingNumber;
+
+ // Make sure exactly one fill rule is specified.
+ Q_ASSERT(((m_parent->m_hint & QVectorPath::WindingFill) != 0) != ((m_parent->m_hint & QVectorPath::OddEvenFill) != 0));
+
+ if ((m_parent->m_hint & QVectorPath::WindingFill) && windingNumber != 0 && windingNumber != 1)
+ return;
+
+ // Skip cancelling edges.
+ if (!orderedEdges.isEmpty()) {
+ int j = orderedEdges[orderedEdges.size() - 1];
+ // If the last edge is already connected in one end, it should not be cancelled.
+ if (m_edges.at(j).next == -1 && m_edges.at(j).previous == -1
+ && (m_parent->m_vertices.at(m_edges.at(i).from) == m_parent->m_vertices.at(m_edges.at(j).to))
+ && (m_parent->m_vertices.at(m_edges.at(i).to) == m_parent->m_vertices.at(m_edges.at(j).from))) {
+ orderedEdges.removeLast();
+ return;
+ }
+ }
+ orderedEdges.append(i);
+}
+
+void QTriangulator::ComplexToSimple::removeUnwantedEdgesAndConnect()
+{
+ Q_ASSERT(m_edgeList.root == 0);
+ // Initialize priority queue.
+ fillPriorityQueue();
+
+ ShortArray orderedEdges;
+
+ while (!m_events.isEmpty()) {
+ Event event = m_events.last();
+ int edgeIndex = event.edge;
+
+ // Check that all the edges in the list crosses the current scanline
+ //if (m_edgeList.root) {
+ // for (QRBTree<int>::Node *node = m_edgeList.front(m_edgeList.root); node; node = m_edgeList.next(node)) {
+ // Q_ASSERT(event.point <= m_points.at(m_edges.at(node->data).lower()));
+ // }
+ //}
+
+ orderedEdges.clear();
+ QPair<QRBTree<int>::Node *, QRBTree<int>::Node *> b = outerBounds(event.point);
+ if (m_edgeList.root) {
+ QRBTree<int>::Node *current = (b.first ? m_edgeList.next(b.first) : m_edgeList.front(m_edgeList.root));
+ // Process edges that are going to be removed from the edge list at the current event point.
+ while (current != b.second) {
+ Q_ASSERT(current);
+ Q_ASSERT(m_edges.at(current->data).node == current);
+ Q_ASSERT(qIntersectionPoint(event.point).isOnLine(m_parent->m_vertices.at(m_edges.at(current->data).from), m_parent->m_vertices.at(m_edges.at(current->data).to)));
+ Q_ASSERT(m_parent->m_vertices.at(m_edges.at(current->data).from) == event.point || m_parent->m_vertices.at(m_edges.at(current->data).to) == event.point);
+ insertEdgeIntoVectorIfWanted(orderedEdges, current->data);
+ current = m_edgeList.next(current);
+ }
+ }
+
+ // Remove edges above the event point, insert edges below the event point.
+ do {
+ event = m_events.last();
+ m_events.pop_back();
+ edgeIndex = event.edge;
+
+ // Edges with zero length should not reach this part.
+ Q_ASSERT(m_parent->m_vertices.at(m_edges.at(edgeIndex).from) != m_parent->m_vertices.at(m_edges.at(edgeIndex).to));
+
+ if (m_edges.at(edgeIndex).node) {
+ Q_ASSERT(event.type == Event::Lower);
+ Q_ASSERT(event.point == m_parent->m_vertices.at(m_edges.at(event.edge).lower()));
+ m_edgeList.deleteNode(m_edges.at(edgeIndex).node);
+ } else {
+ Q_ASSERT(event.type == Event::Upper);
+ Q_ASSERT(event.point == m_parent->m_vertices.at(m_edges.at(event.edge).upper()));
+ QRBTree<int>::Node *left = searchEdgeLeftOf(edgeIndex, b.first);
+ m_edgeList.attachAfter(left, m_edges.at(edgeIndex).node = m_edgeList.newNode());
+ m_edges.at(edgeIndex).node->data = edgeIndex;
+ }
+ } while (!m_events.isEmpty() && m_events.last().point == event.point);
+
+ if (m_edgeList.root) {
+ QRBTree<int>::Node *current = (b.first ? m_edgeList.next(b.first) : m_edgeList.front(m_edgeList.root));
+
+ // Calculate winding number and turn counter-clockwise.
+ int currentWindingNumber = (b.first ? m_edges.at(b.first->data).winding : 0);
+ while (current != b.second) {
+ Q_ASSERT(current);
+ //Q_ASSERT(b.second == 0 || m_edgeList.order(current, b.second) < 0);
+ int i = current->data;
+ Q_ASSERT(m_edges.at(i).node == current);
+
+ // Winding number.
+ int ccwWindingNumber = m_edges.at(i).winding = currentWindingNumber;
+ if (m_edges.at(i).originallyPointingUp) {
+ --m_edges.at(i).winding;
+ } else {
+ ++m_edges.at(i).winding;
+ ++ccwWindingNumber;
+ }
+ currentWindingNumber = m_edges.at(i).winding;
+
+ // Turn counter-clockwise.
+ if ((ccwWindingNumber & 1) == 0) {
+ Q_ASSERT(m_edges.at(i).previous == -1 && m_edges.at(i).next == -1);
+ qSwap(m_edges.at(i).from, m_edges.at(i).to);
+ m_edges.at(i).pointingUp = !m_edges.at(i).pointingUp;
+ }
+
+ current = m_edgeList.next(current);
+ }
+
+ // Process edges that were inserted into the edge list at the current event point.
+ current = (b.second ? m_edgeList.previous(b.second) : m_edgeList.back(m_edgeList.root));
+ while (current != b.first) {
+ Q_ASSERT(current);
+ Q_ASSERT(m_edges.at(current->data).node == current);
+ insertEdgeIntoVectorIfWanted(orderedEdges, current->data);
+ current = m_edgeList.previous(current);
+ }
+ }
+ if (orderedEdges.isEmpty())
+ continue;
+
+ Q_ASSERT((orderedEdges.size() & 1) == 0);
+
+ // Connect edges.
+ // First make sure the first edge point towards the current point.
+ int i;
+ if (m_parent->m_vertices.at(m_edges.at(orderedEdges[0]).from) == event.point) {
+ i = 1;
+ int copy = orderedEdges[0]; // Make copy in case the append() will cause a reallocation.
+ orderedEdges.append(copy);
+ } else {
+ Q_ASSERT(m_parent->m_vertices.at(m_edges.at(orderedEdges[0]).to) == event.point);
+ i = 0;
+ }
+
+ // Remove references to duplicate points. First find the point with lowest index.
+ int pointIndex = INT_MAX;
+ for (int j = i; j < orderedEdges.size(); j += 2) {
+ Q_ASSERT(j + 1 < orderedEdges.size());
+ Q_ASSERT(m_parent->m_vertices.at(m_edges.at(orderedEdges[j]).to) == event.point);
+ Q_ASSERT(m_parent->m_vertices.at(m_edges.at(orderedEdges[j + 1]).from) == event.point);
+ if (m_edges.at(orderedEdges[j]).to < pointIndex)
+ pointIndex = m_edges.at(orderedEdges[j]).to;
+ if (m_edges.at(orderedEdges[j + 1]).from < pointIndex)
+ pointIndex = m_edges.at(orderedEdges[j + 1]).from;
+ }
+
+ for (; i < orderedEdges.size(); i += 2) {
+ // Remove references to duplicate points by making all edges reference one common point.
+ m_edges.at(orderedEdges[i]).to = m_edges.at(orderedEdges[i + 1]).from = pointIndex;
+
+ Q_ASSERT(m_edges.at(orderedEdges[i]).pointingUp || m_edges.at(orderedEdges[i]).previous != -1);
+ Q_ASSERT(!m_edges.at(orderedEdges[i + 1]).pointingUp || m_edges.at(orderedEdges[i + 1]).next != -1);
+
+ m_edges.at(orderedEdges[i]).next = orderedEdges[i + 1];
+ m_edges.at(orderedEdges[i + 1]).previous = orderedEdges[i];
+ }
+ } // end while
+}
+
+void QTriangulator::ComplexToSimple::removeUnusedPoints() {
+ QBitArray used(m_parent->m_vertices.size(), false);
+ for (int i = 0; i < m_edges.size(); ++i) {
+ Q_ASSERT((m_edges.at(i).previous == -1) == (m_edges.at(i).next == -1));
+ if (m_edges.at(i).next != -1)
+ used.setBit(m_edges.at(i).from);
+ }
+ QDataBuffer<quint32> newMapping(m_parent->m_vertices.size());
+ newMapping.resize(m_parent->m_vertices.size());
+ int count = 0;
+ for (int i = 0; i < m_parent->m_vertices.size(); ++i) {
+ if (used.at(i)) {
+ m_parent->m_vertices.at(count) = m_parent->m_vertices.at(i);
+ newMapping.at(i) = count;
+ ++count;
+ }
+ }
+ m_parent->m_vertices.resize(count);
+ for (int i = 0; i < m_edges.size(); ++i) {
+ m_edges.at(i).from = newMapping.at(m_edges.at(i).from);
+ m_edges.at(i).to = newMapping.at(m_edges.at(i).to);
+ }
+}
+
+bool QTriangulator::ComplexToSimple::CompareEdges::operator () (int i, int j) const
+{
+ int cmp = comparePoints(m_parent->m_parent->m_vertices.at(m_parent->m_edges.at(i).from),
+ m_parent->m_parent->m_vertices.at(m_parent->m_edges.at(j).from));
+ if (cmp == 0) {
+ cmp = comparePoints(m_parent->m_parent->m_vertices.at(m_parent->m_edges.at(i).to),
+ m_parent->m_parent->m_vertices.at(m_parent->m_edges.at(j).to));
+ }
+ return cmp > 0;
+}
+
+inline bool QTriangulator::ComplexToSimple::Event::operator < (const Event &other) const
+{
+ if (point == other.point)
+ return type < other.type; // 'Lower' has higher priority than 'Upper'.
+ return other.point < point;
+}
+
+//============================================================================//
+// QTriangulator::ComplexToSimple::DebugDialog //
+//============================================================================//
+
+#ifdef Q_TRIANGULATOR_DEBUG
+
+QTriangulator::ComplexToSimple::DebugDialog::DebugDialog(ComplexToSimple *parent, int currentVertex)
+ : m_parent(parent), m_vertex(currentVertex)
+{
+ QDataBuffer<QPodPoint> &vertices = m_parent->m_parent->m_vertices;
+ if (vertices.isEmpty())
+ return;
+
+ int minX, maxX, minY, maxY;
+ minX = maxX = vertices.at(0).x;
+ minY = maxY = vertices.at(0).y;
+ for (int i = 1; i < vertices.size(); ++i) {
+ minX = qMin(minX, vertices.at(i).x);
+ maxX = qMax(maxX, vertices.at(i).x);
+ minY = qMin(minY, vertices.at(i).y);
+ maxY = qMax(maxY, vertices.at(i).y);
+ }
+ int w = maxX - minX;
+ int h = maxY - minY;
+ qreal border = qMin(w, h) / 10.0;
+ m_window = QRectF(minX - border, minY - border, (maxX - minX + 2 * border), (maxY - minY + 2 * border));
+}
+
+void QTriangulator::ComplexToSimple::DebugDialog::paintEvent(QPaintEvent *)
+{
+ QPainter p(this);
+ p.setRenderHint(QPainter::Antialiasing, true);
+ p.fillRect(rect(), Qt::black);
+ QDataBuffer<QPodPoint> &vertices = m_parent->m_parent->m_vertices;
+ if (vertices.isEmpty())
+ return;
+
+ qreal halfPointSize = qMin(m_window.width(), m_window.height()) / 300.0;
+ p.setWindow(m_window.toRect());
+
+ p.setPen(Qt::white);
+
+ QDataBuffer<Edge> &edges = m_parent->m_edges;
+ for (int i = 0; i < edges.size(); ++i) {
+ QPodPoint u = vertices.at(edges.at(i).from);
+ QPodPoint v = vertices.at(edges.at(i).to);
+ p.drawLine(u.x, u.y, v.x, v.y);
+ }
+
+ for (int i = 0; i < vertices.size(); ++i) {
+ QPodPoint q = vertices.at(i);
+ p.fillRect(QRectF(q.x - halfPointSize, q.y - halfPointSize, 2 * halfPointSize, 2 * halfPointSize), Qt::red);
+ }
+
+ Qt::GlobalColor colors[6] = {Qt::red, Qt::green, Qt::blue, Qt::cyan, Qt::magenta, Qt::yellow};
+ p.setOpacity(0.5);
+ int count = 0;
+ if (m_parent->m_edgeList.root) {
+ QRBTree<int>::Node *current = m_parent->m_edgeList.front(m_parent->m_edgeList.root);
+ while (current) {
+ p.setPen(colors[count++ % 6]);
+ QPodPoint u = vertices.at(edges.at(current->data).from);
+ QPodPoint v = vertices.at(edges.at(current->data).to);
+ p.drawLine(u.x, u.y, v.x, v.y);
+ current = m_parent->m_edgeList.next(current);
+ }
+ }
+
+ p.setOpacity(1.0);
+ QPodPoint q = vertices.at(m_vertex);
+ p.fillRect(QRectF(q.x - halfPointSize, q.y - halfPointSize, 2 * halfPointSize, 2 * halfPointSize), Qt::green);
+
+ p.setPen(Qt::gray);
+ QDataBuffer<Split> &splits = m_parent->m_splits;
+ for (int i = 0; i < splits.size(); ++i) {
+ QPodPoint q = vertices.at(splits.at(i).vertex);
+ QPodPoint u = vertices.at(edges.at(splits.at(i).edge).from) - q;
+ QPodPoint v = vertices.at(edges.at(splits.at(i).edge).to) - q;
+ qreal uLen = sqrt(qreal(qDot(u, u)));
+ qreal vLen = sqrt(qreal(qDot(v, v)));
+ if (uLen) {
+ u.x *= 2 * halfPointSize / uLen;
+ u.y *= 2 * halfPointSize / uLen;
+ }
+ if (vLen) {
+ v.x *= 2 * halfPointSize / vLen;
+ v.y *= 2 * halfPointSize / vLen;
+ }
+ u += q;
+ v += q;
+ p.drawLine(u.x, u.y, v.x, v.y);
+ }
+}
+
+void QTriangulator::ComplexToSimple::DebugDialog::wheelEvent(QWheelEvent *event)
+{
+ qreal scale = exp(-0.001 * event->delta());
+ QPointF center = m_window.center();
+ QPointF delta = scale * (m_window.bottomRight() - center);
+ m_window = QRectF(center - delta, center + delta);
+ event->accept();
+ update();
+}
+
+void QTriangulator::ComplexToSimple::DebugDialog::mouseMoveEvent(QMouseEvent *event)
+{
+ if (event->buttons() & Qt::LeftButton) {
+ QPointF delta = event->pos() - m_lastMousePos;
+ delta.setX(delta.x() * m_window.width() / width());
+ delta.setY(delta.y() * m_window.height() / height());
+ m_window.translate(-delta.x(), -delta.y());
+ m_lastMousePos = event->pos();
+ event->accept();
+ update();
+ }
+}
+
+void QTriangulator::ComplexToSimple::DebugDialog::mousePressEvent(QMouseEvent *event)
+{
+ if (event->button() == Qt::LeftButton)
+ m_lastMousePos = event->pos();
+ event->accept();
+}
+
+
+#endif
+
+//============================================================================//
+// QTriangulator::SimpleToMonotone //
+//============================================================================//
+
+void QTriangulator::SimpleToMonotone::decompose()
+{
+ setupDataStructures();
+ removeZeroLengthEdges();
+ monotoneDecomposition();
+
+ m_parent->m_indices.clear();
+ QBitArray processed(m_edges.size(), false);
+ for (int first = 0; first < m_edges.size(); ++first) {
+ if (processed.at(first))
+ continue;
+ int i = first;
+ do {
+ Q_ASSERT(!processed.at(i));
+ Q_ASSERT(m_edges.at(m_edges.at(i).next).previous == i);
+ m_parent->m_indices.push_back(m_edges.at(i).from);
+ processed.setBit(i);
+ i = m_edges.at(i).next;
+ } while (i != first);
+ if (m_parent->m_indices.size() > 0 && m_parent->m_indices.back() != Q_TRIANGULATE_END_OF_POLYGON)
+ m_parent->m_indices.push_back(Q_TRIANGULATE_END_OF_POLYGON);
+ }
+}
+
+void QTriangulator::SimpleToMonotone::setupDataStructures()
+{
+ int i = 0;
+ Edge e;
+ e.node = 0;
+ e.twin = -1;
+
+ while (i + 3 <= m_parent->m_indices.size()) {
+ int start = m_edges.size();
+
+ do {
+ e.from = m_parent->m_indices.at(i);
+ e.type = RegularVertex;
+ e.next = m_edges.size() + 1;
+ e.previous = m_edges.size() - 1;
+ m_edges.add(e);
+ ++i;
+ Q_ASSERT(i < m_parent->m_indices.size());
+ } while (m_parent->m_indices.at(i) != Q_TRIANGULATE_END_OF_POLYGON);
+
+ m_edges.last().next = start;
+ m_edges.at(start).previous = m_edges.size() - 1;
+ ++i; // Skip Q_TRIANGULATE_END_OF_POLYGON.
+ }
+
+ for (i = 0; i < m_edges.size(); ++i) {
+ m_edges.at(i).to = m_edges.at(m_edges.at(i).next).from;
+ m_edges.at(i).pointingUp = m_parent->m_vertices.at(m_edges.at(i).to) < m_parent->m_vertices.at(m_edges.at(i).from);
+ m_edges.at(i).helper = -1; // Not initialized here.
+ }
+}
+
+void QTriangulator::SimpleToMonotone::removeZeroLengthEdges()
+{
+ for (int i = 0; i < m_edges.size(); ++i) {
+ if (m_parent->m_vertices.at(m_edges.at(i).from) == m_parent->m_vertices.at(m_edges.at(i).to)) {
+ m_edges.at(m_edges.at(i).previous).next = m_edges.at(i).next;
+ m_edges.at(m_edges.at(i).next).previous = m_edges.at(i).previous;
+ m_edges.at(m_edges.at(i).next).from = m_edges.at(i).from;
+ m_edges.at(i).next = -1; // Mark as removed.
+ }
+ }
+
+ QDataBuffer<int> newMapping(m_edges.size());
+ newMapping.resize(m_edges.size());
+ int count = 0;
+ for (int i = 0; i < m_edges.size(); ++i) {
+ if (m_edges.at(i).next != -1) {
+ m_edges.at(count) = m_edges.at(i);
+ newMapping.at(i) = count;
+ ++count;
+ }
+ }
+ m_edges.resize(count);
+ for (int i = 0; i < m_edges.size(); ++i) {
+ m_edges.at(i).next = newMapping.at(m_edges.at(i).next);
+ m_edges.at(i).previous = newMapping.at(m_edges.at(i).previous);
+ }
+}
+
+void QTriangulator::SimpleToMonotone::fillPriorityQueue()
+{
+ m_upperVertex.reset();
+ m_upperVertex.reserve(m_edges.size());
+ for (int i = 0; i < m_edges.size(); ++i)
+ m_upperVertex.add(i);
+ CompareVertices cmp(this);
+ //qSort(m_upperVertex.data(), m_upperVertex.data() + m_upperVertex.size(), cmp);
+ sort(m_upperVertex.data(), m_upperVertex.size(), cmp);
+ //for (int i = 1; i < m_upperVertex.size(); ++i) {
+ // Q_ASSERT(!cmp(m_upperVertex.at(i), m_upperVertex.at(i - 1)));
+ //}
+}
+
+bool QTriangulator::SimpleToMonotone::edgeIsLeftOfEdge(int leftEdgeIndex, int rightEdgeIndex) const
+{
+ const Edge &leftEdge = m_edges.at(leftEdgeIndex);
+ const Edge &rightEdge = m_edges.at(rightEdgeIndex);
+ const QPodPoint &u = m_parent->m_vertices.at(rightEdge.upper());
+ const QPodPoint &l = m_parent->m_vertices.at(rightEdge.lower());
+ qint64 d = qPointDistanceFromLine(m_parent->m_vertices.at(leftEdge.upper()), l, u);
+ // d < 0: left, d > 0: right, d == 0: on top
+ if (d == 0)
+ d = qPointDistanceFromLine(m_parent->m_vertices.at(leftEdge.lower()), l, u);
+ return d < 0;
+}
+
+// Returns the rightmost edge not to the right of the given edge.
+QRBTree<int>::Node *QTriangulator::SimpleToMonotone::searchEdgeLeftOfEdge(int edgeIndex) const
+{
+ QRBTree<int>::Node *current = m_edgeList.root;
+ QRBTree<int>::Node *result = 0;
+ while (current) {
+ if (edgeIsLeftOfEdge(edgeIndex, current->data)) {
+ current = current->left;
+ } else {
+ result = current;
+ current = current->right;
+ }
+ }
+ return result;
+}
+
+// Returns the rightmost edge left of the given point.
+QRBTree<int>::Node *QTriangulator::SimpleToMonotone::searchEdgeLeftOfPoint(int pointIndex) const
+{
+ QRBTree<int>::Node *current = m_edgeList.root;
+ QRBTree<int>::Node *result = 0;
+ while (current) {
+ const QPodPoint &p1 = m_parent->m_vertices.at(m_edges.at(current->data).lower());
+ const QPodPoint &p2 = m_parent->m_vertices.at(m_edges.at(current->data).upper());
+ qint64 d = qPointDistanceFromLine(m_parent->m_vertices.at(pointIndex), p1, p2);
+ if (d <= 0) {
+ current = current->left;
+ } else {
+ result = current;
+ current = current->right;
+ }
+ }
+ return result;
+}
+
+void QTriangulator::SimpleToMonotone::classifyVertex(int i)
+{
+ Edge &e2 = m_edges.at(i);
+ const Edge &e1 = m_edges.at(e2.previous);
+
+ bool startOrSplit = (e1.pointingUp && !e2.pointingUp);
+ bool endOrMerge = (!e1.pointingUp && e2.pointingUp);
+
+ const QPodPoint &p1 = m_parent->m_vertices.at(e1.from);
+ const QPodPoint &p2 = m_parent->m_vertices.at(e2.from);
+ const QPodPoint &p3 = m_parent->m_vertices.at(e2.to);
+ qint64 d = qPointDistanceFromLine(p1, p2, p3);
+ Q_ASSERT(d != 0 || (!startOrSplit && !endOrMerge));
+
+ e2.type = RegularVertex;
+
+ if (m_clockwiseOrder) {
+ if (startOrSplit)
+ e2.type = (d < 0 ? SplitVertex : StartVertex);
+ else if (endOrMerge)
+ e2.type = (d < 0 ? MergeVertex : EndVertex);
+ } else {
+ if (startOrSplit)
+ e2.type = (d > 0 ? SplitVertex : StartVertex);
+ else if (endOrMerge)
+ e2.type = (d > 0 ? MergeVertex : EndVertex);
+ }
+}
+
+void QTriangulator::SimpleToMonotone::classifyVertices()
+{
+ for (int i = 0; i < m_edges.size(); ++i)
+ classifyVertex(i);
+}
+
+bool QTriangulator::SimpleToMonotone::pointIsInSector(const QPodPoint &p, const QPodPoint &v1, const QPodPoint &v2, const QPodPoint &v3)
+{
+ bool leftOfPreviousEdge = !qPointIsLeftOfLine(p, v2, v1);
+ bool leftOfNextEdge = !qPointIsLeftOfLine(p, v3, v2);
+
+ if (qPointIsLeftOfLine(v1, v2, v3))
+ return leftOfPreviousEdge && leftOfNextEdge;
+ else
+ return leftOfPreviousEdge || leftOfNextEdge;
+}
+
+bool QTriangulator::SimpleToMonotone::pointIsInSector(int vertex, int sector)
+{
+ const QPodPoint &center = m_parent->m_vertices.at(m_edges.at(sector).from);
+ // Handle degenerate edges.
+ while (m_parent->m_vertices.at(m_edges.at(vertex).from) == center)
+ vertex = m_edges.at(vertex).next;
+ int next = m_edges.at(sector).next;
+ while (m_parent->m_vertices.at(m_edges.at(next).from) == center)
+ next = m_edges.at(next).next;
+ int previous = m_edges.at(sector).previous;
+ while (m_parent->m_vertices.at(m_edges.at(previous).from) == center)
+ previous = m_edges.at(previous).previous;
+
+ const QPodPoint &p = m_parent->m_vertices.at(m_edges.at(vertex).from);
+ const QPodPoint &v1 = m_parent->m_vertices.at(m_edges.at(previous).from);
+ const QPodPoint &v3 = m_parent->m_vertices.at(m_edges.at(next).from);
+ if (m_clockwiseOrder)
+ return pointIsInSector(p, v3, center, v1);
+ else
+ return pointIsInSector(p, v1, center, v3);
+}
+
+int QTriangulator::SimpleToMonotone::findSector(int edge, int vertex)
+{
+ while (!pointIsInSector(vertex, edge)) {
+ edge = m_edges.at(m_edges.at(edge).previous).twin;
+ Q_ASSERT(edge != -1);
+ }
+ return edge;
+}
+
+void QTriangulator::SimpleToMonotone::createDiagonal(int lower, int upper)
+{
+ lower = findSector(lower, upper);
+ upper = findSector(upper, lower);
+
+ int prevLower = m_edges.at(lower).previous;
+ int prevUpper = m_edges.at(upper).previous;
+
+ Edge e;
+
+ e.twin = m_edges.size() + 1;
+ e.next = upper;
+ e.previous = prevLower;
+ e.from = m_edges.at(lower).from;
+ e.to = m_edges.at(upper).from;
+ m_edges.at(upper).previous = m_edges.at(prevLower).next = int(m_edges.size());
+ m_edges.add(e);
+
+ e.twin = m_edges.size() - 1;
+ e.next = lower;
+ e.previous = prevUpper;
+ e.from = m_edges.at(upper).from;
+ e.to = m_edges.at(lower).from;
+ m_edges.at(lower).previous = m_edges.at(prevUpper).next = int(m_edges.size());
+ m_edges.add(e);
+}
+
+void QTriangulator::SimpleToMonotone::monotoneDecomposition()
+{
+ if (m_edges.isEmpty())
+ return;
+
+ Q_ASSERT(!m_edgeList.root);
+ QDataBuffer<QPair<int, int> > diagonals;
+
+ int i = 0;
+ for (int index = 1; index < m_edges.size(); ++index) {
+ if (m_parent->m_vertices.at(m_edges.at(index).from) < m_parent->m_vertices.at(m_edges.at(i).from))
+ i = index;
+ }
+ Q_ASSERT(i < m_edges.size());
+ int j = m_edges.at(i).previous;
+ Q_ASSERT(j < m_edges.size());
+ m_clockwiseOrder = qPointIsLeftOfLine(m_parent->m_vertices.at(m_edges.at(i).from),
+ m_parent->m_vertices.at(m_edges.at(j).from), m_parent->m_vertices.at(m_edges.at(i).to));
+
+ classifyVertices();
+ fillPriorityQueue();
+
+ // debug: set helpers explicitly (shouldn't be necessary)
+ //for (int i = 0; i < m_edges.size(); ++i)
+ // m_edges.at(i).helper = m_edges.at(i).upper();
+
+ while (!m_upperVertex.isEmpty()) {
+ i = m_upperVertex.last();
+ Q_ASSERT(i < m_edges.size());
+ m_upperVertex.pop_back();
+ j = m_edges.at(i).previous;
+ Q_ASSERT(j < m_edges.size());
+
+ QRBTree<int>::Node *leftEdgeNode = 0;
+
+ switch (m_edges.at(i).type) {
+ case RegularVertex:
+ // If polygon interior is to the right of the vertex...
+ if (m_edges.at(i).pointingUp == m_clockwiseOrder) {
+ if (m_edges.at(i).node) {
+ Q_ASSERT(!m_edges.at(j).node);
+ if (m_edges.at(m_edges.at(i).helper).type == MergeVertex)
+ diagonals.add(QPair<int, int>(i, m_edges.at(i).helper));
+ m_edges.at(j).node = m_edges.at(i).node;
+ m_edges.at(i).node = 0;
+ m_edges.at(j).node->data = j;
+ m_edges.at(j).helper = i;
+ } else if (m_edges.at(j).node) {
+ Q_ASSERT(!m_edges.at(i).node);
+ if (m_edges.at(m_edges.at(j).helper).type == MergeVertex)
+ diagonals.add(QPair<int, int>(i, m_edges.at(j).helper));
+ m_edges.at(i).node = m_edges.at(j).node;
+ m_edges.at(j).node = 0;
+ m_edges.at(i).node->data = i;
+ m_edges.at(i).helper = i;
+ } else {
+ qWarning("Inconsistent polygon. (#1)");
+ }
+ } else {
+ leftEdgeNode = searchEdgeLeftOfPoint(m_edges.at(i).from);
+ if (leftEdgeNode) {
+ if (m_edges.at(m_edges.at(leftEdgeNode->data).helper).type == MergeVertex)
+ diagonals.add(QPair<int, int>(i, m_edges.at(leftEdgeNode->data).helper));
+ m_edges.at(leftEdgeNode->data).helper = i;
+ } else {
+ qWarning("Inconsistent polygon. (#2)");
+ }
+ }
+ break;
+ case SplitVertex:
+ leftEdgeNode = searchEdgeLeftOfPoint(m_edges.at(i).from);
+ if (leftEdgeNode) {
+ diagonals.add(QPair<int, int>(i, m_edges.at(leftEdgeNode->data).helper));
+ m_edges.at(leftEdgeNode->data).helper = i;
+ } else {
+ qWarning("Inconsistent polygon. (#3)");
+ }
+ // Fall through.
+ case StartVertex:
+ if (m_clockwiseOrder) {
+ leftEdgeNode = searchEdgeLeftOfEdge(j);
+ QRBTree<int>::Node *node = m_edgeList.newNode();
+ node->data = j;
+ m_edges.at(j).node = node;
+ m_edges.at(j).helper = i;
+ m_edgeList.attachAfter(leftEdgeNode, node);
+ Q_ASSERT(m_edgeList.verify());
+ } else {
+ leftEdgeNode = searchEdgeLeftOfEdge(i);
+ QRBTree<int>::Node *node = m_edgeList.newNode();
+ node->data = i;
+ m_edges.at(i).node = node;
+ m_edges.at(i).helper = i;
+ m_edgeList.attachAfter(leftEdgeNode, node);
+ Q_ASSERT(m_edgeList.verify());
+ }
+ break;
+ case MergeVertex:
+ leftEdgeNode = searchEdgeLeftOfPoint(m_edges.at(i).from);
+ if (leftEdgeNode) {
+ if (m_edges.at(m_edges.at(leftEdgeNode->data).helper).type == MergeVertex)
+ diagonals.add(QPair<int, int>(i, m_edges.at(leftEdgeNode->data).helper));
+ m_edges.at(leftEdgeNode->data).helper = i;
+ } else {
+ qWarning("Inconsistent polygon. (#4)");
+ }
+ // Fall through.
+ case EndVertex:
+ if (m_clockwiseOrder) {
+ if (m_edges.at(m_edges.at(i).helper).type == MergeVertex)
+ diagonals.add(QPair<int, int>(i, m_edges.at(i).helper));
+ if (m_edges.at(i).node) {
+ m_edgeList.deleteNode(m_edges.at(i).node);
+ Q_ASSERT(m_edgeList.verify());
+ } else {
+ qWarning("Inconsistent polygon. (#5)");
+ }
+ } else {
+ if (m_edges.at(m_edges.at(j).helper).type == MergeVertex)
+ diagonals.add(QPair<int, int>(i, m_edges.at(j).helper));
+ if (m_edges.at(j).node) {
+ m_edgeList.deleteNode(m_edges.at(j).node);
+ Q_ASSERT(m_edgeList.verify());
+ } else {
+ qWarning("Inconsistent polygon. (#6)");
+ }
+ }
+ break;
+ }
+ }
+
+ for (int i = 0; i < diagonals.size(); ++i)
+ createDiagonal(diagonals.at(i).first, diagonals.at(i).second);
+}
+
+bool QTriangulator::SimpleToMonotone::CompareVertices::operator () (int i, int j) const
+{
+ if (m_parent->m_edges.at(i).from == m_parent->m_edges.at(j).from)
+ return m_parent->m_edges.at(i).type > m_parent->m_edges.at(j).type;
+ return m_parent->m_parent->m_vertices.at(m_parent->m_edges.at(i).from) >
+ m_parent->m_parent->m_vertices.at(m_parent->m_edges.at(j).from);
+}
+
+//============================================================================//
+// QTriangulator::MonotoneToTriangles //
+//============================================================================//
+
+void QTriangulator::MonotoneToTriangles::decompose()
+{
+ QVector<quint32> result;
+ QDataBuffer<int> stack;
+ m_first = 0;
+ // Require at least three more indices.
+ while (m_first + 3 <= m_parent->m_indices.size()) {
+ m_length = 0;
+ while (m_parent->m_indices.at(m_first + m_length) != Q_TRIANGULATE_END_OF_POLYGON) {
+ ++m_length;
+ Q_ASSERT(m_first + m_length < m_parent->m_indices.size());
+ }
+ if (m_length < 3) {
+ m_first += m_length + 1;
+ continue;
+ }
+
+ int minimum = 0;
+ while (less(next(minimum), minimum))
+ minimum = next(minimum);
+ while (less(previous(minimum), minimum))
+ minimum = previous(minimum);
+
+ stack.reset();
+ stack.add(minimum);
+ int left = previous(minimum);
+ int right = next(minimum);
+ bool stackIsOnLeftSide;
+ bool clockwiseOrder = leftOfEdge(minimum, left, right);
+
+ if (less(left, right)) {
+ stack.add(left);
+ left = previous(left);
+ stackIsOnLeftSide = true;
+ } else {
+ stack.add(right);
+ right = next(right);
+ stackIsOnLeftSide = false;
+ }
+
+ for (int count = 0; count + 2 < m_length; ++count)
+ {
+ Q_ASSERT(stack.size() >= 2);
+ if (less(left, right)) {
+ if (stackIsOnLeftSide == false) {
+ for (int i = 0; i + 1 < stack.size(); ++i) {
+ result.push_back(indices(stack.at(i + 1)));
+ result.push_back(indices(left));
+ result.push_back(indices(stack.at(i)));
+ }
+ stack.first() = stack.last();
+ stack.resize(1);
+ } else {
+ while (stack.size() >= 2 && (clockwiseOrder ^ !leftOfEdge(left, stack.at(stack.size() - 2), stack.last()))) {
+ result.push_back(indices(stack.at(stack.size() - 2)));
+ result.push_back(indices(left));
+ result.push_back(indices(stack.last()));
+ stack.pop_back();
+ }
+ }
+ stack.add(left);
+ left = previous(left);
+ stackIsOnLeftSide = true;
+ } else {
+ if (stackIsOnLeftSide == true) {
+ for (int i = 0; i + 1 < stack.size(); ++i) {
+ result.push_back(indices(stack.at(i)));
+ result.push_back(indices(right));
+ result.push_back(indices(stack.at(i + 1)));
+ }
+ stack.first() = stack.last();
+ stack.resize(1);
+ } else {
+ while (stack.size() >= 2 && (clockwiseOrder ^ !leftOfEdge(right, stack.last(), stack.at(stack.size() - 2)))) {
+ result.push_back(indices(stack.last()));
+ result.push_back(indices(right));
+ result.push_back(indices(stack.at(stack.size() - 2)));
+ stack.pop_back();
+ }
+ }
+ stack.add(right);
+ right = next(right);
+ stackIsOnLeftSide = false;
+ }
+ }
+
+ m_first += m_length + 1;
+ }
+ m_parent->m_indices = result;
+}
+
+//============================================================================//
+// qTriangulate //
+//============================================================================//
+
+QTriangleSet qTriangulate(const qreal *polygon, int count, uint hint, const QTransform &matrix)
+{
+ QTriangulator triangulator;
+ triangulator.initialize(polygon, count, hint, matrix);
+ return triangulator.triangulate();
+}
+
+QTriangleSet qTriangulate(const QVectorPath &path, const QTransform &matrix, qreal lod)
+{
+ QTriangulator triangulator;
+ triangulator.initialize(path, matrix, lod);
+ return triangulator.triangulate();
+}
+
+QTriangleSet qTriangulate(const QPainterPath &path, const QTransform &matrix, qreal lod)
+{
+ QTriangulator triangulator;
+ triangulator.initialize(path, matrix, lod);
+ return triangulator.triangulate();
+}
+
+QPolylineSet qPolyline(const QVectorPath &path, const QTransform &matrix, qreal lod)
+{
+ QTriangulator triangulator;
+ triangulator.initialize(path, matrix, lod);
+ return triangulator.polyline();
+}
+
+QPolylineSet qPolyline(const QPainterPath &path, const QTransform &matrix, qreal lod)
+{
+ QTriangulator triangulator;
+ triangulator.initialize(path, matrix, lod);
+ return triangulator.polyline();
+}
+
+QT_END_NAMESPACE
diff --git a/src/opengl/gl2paintengineex/qtriangulator_p.h b/src/opengl/gl2paintengineex/qtriangulator_p.h
new file mode 100644
index 0000000..da47666
--- /dev/null
+++ b/src/opengl/gl2paintengineex/qtriangulator_p.h
@@ -0,0 +1,98 @@
+/****************************************************************************
+**
+** 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 QtOpenGL module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QTRIANGULATOR_P_H
+#define QTRIANGULATOR_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/qvector.h>
+#include <QtGui/private/qvectorpath_p.h>
+
+QT_BEGIN_NAMESPACE
+
+#define Q_TRIANGULATE_END_OF_POLYGON quint32(-1)
+
+struct QTriangleSet
+{
+ inline QTriangleSet() { }
+ inline QTriangleSet(const QTriangleSet &other) : vertices(other.vertices), indices(other.indices) { }
+ QTriangleSet &operator = (const QTriangleSet &other) {vertices = other.vertices; indices = other.indices; return *this;}
+
+ // The vertices of a triangle are given by: (x[i[n]], y[i[n]]), (x[j[n]], y[j[n]]), (x[k[n]], y[k[n]]), n = 0, 1, ...
+ QVector<qreal> vertices; // [x[0], y[0], x[1], y[1], x[2], ...]
+ QVector<quint32> indices; // [i[0], j[0], k[0], i[1], j[1], k[1], i[2], ...]
+};
+
+struct QPolylineSet
+{
+ inline QPolylineSet() { }
+ inline QPolylineSet(const QPolylineSet &other) : vertices(other.vertices), indices(other.indices) { }
+ QPolylineSet &operator = (const QPolylineSet &other) {vertices = other.vertices; indices = other.indices; return *this;}
+
+ QVector<qreal> vertices; // [x[0], y[0], x[1], y[1], x[2], ...]
+ QVector<quint32> indices;
+
+};
+
+// The vertex coordinates of the returned triangle set will be rounded to a grid with a mesh size
+// of 1/32. The polygon is first transformed, then scaled by 32, the coordinates are rounded to
+// integers, the polygon is triangulated, and then scaled back by 1/32.
+// 'hint' should be a combination of QVectorPath::Hints.
+// 'lod' is the level of detail. Default is 1. Curves are split into more lines when 'lod' is higher.
+QTriangleSet qTriangulate(const qreal *polygon, int count, uint hint = QVectorPath::PolygonHint | QVectorPath::OddEvenFill, const QTransform &matrix = QTransform());
+QTriangleSet qTriangulate(const QVectorPath &path, const QTransform &matrix = QTransform(), qreal lod = 1);
+QTriangleSet qTriangulate(const QPainterPath &path, const QTransform &matrix = QTransform(), qreal lod = 1);
+QPolylineSet qPolyline(const QVectorPath &path, const QTransform &matrix = QTransform(), qreal lod = 1);
+QPolylineSet qPolyline(const QPainterPath &path, const QTransform &matrix = QTransform(), qreal lod = 1);
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/opengl/opengl.pro b/src/opengl/opengl.pro
index 6076891..ff42a49 100644
--- a/src/opengl/opengl.pro
+++ b/src/opengl/opengl.pro
@@ -13,7 +13,6 @@ include(../qbase.pri)
!win32:!embedded:!mac:CONFIG += x11
contains(QT_CONFIG, opengl):CONFIG += opengl
contains(QT_CONFIG, opengles1):CONFIG += opengles1
-contains(QT_CONFIG, opengles1cl):CONFIG += opengles1cl
contains(QT_CONFIG, opengles2):CONFIG += opengles2
contains(QT_CONFIG, egl):CONFIG += egl
@@ -26,6 +25,7 @@ HEADERS += qgl.h \
qglframebufferobject_p.h \
qglextensions_p.h \
qglpaintdevice_p.h \
+ qglbuffer.h \
SOURCES += qgl.cpp \
@@ -34,6 +34,7 @@ SOURCES += qgl.cpp \
qglframebufferobject.cpp \
qglextensions.cpp \
qglpaintdevice.cpp \
+ qglbuffer.cpp \
!contains(QT_CONFIG, opengles2) {
@@ -41,7 +42,7 @@ SOURCES += qgl.cpp \
SOURCES += qpaintengine_opengl.cpp
}
-!contains(QT_CONFIG, opengles1):!contains(QT_CONFIG, opengles1cl) {
+!contains(QT_CONFIG, opengles1) {
HEADERS += qglshaderprogram.h \
qglpixmapfilter_p.h \
qgraphicsshadereffect_p.h \
@@ -55,6 +56,7 @@ SOURCES += qgl.cpp \
gl2paintengineex/qglengineshadersource_p.h \
gl2paintengineex/qglcustomshaderstage_p.h \
gl2paintengineex/qtriangulatingstroker_p.h \
+ gl2paintengineex/qtriangulator_p.h \
gl2paintengineex/qtextureglyphcache_gl_p.h
SOURCES += qglshaderprogram.cpp \
@@ -69,12 +71,13 @@ SOURCES += qgl.cpp \
gl2paintengineex/qpaintengineex_opengl2.cpp \
gl2paintengineex/qglcustomshaderstage.cpp \
gl2paintengineex/qtriangulatingstroker.cpp \
+ gl2paintengineex/qtriangulator.cpp \
gl2paintengineex/qtextureglyphcache_gl.cpp
}
x11 {
- contains(QT_CONFIG, opengles1)|contains(QT_CONFIG, opengles1cl)|contains(QT_CONFIG, opengles2) {
+ contains(QT_CONFIG, opengles1)|contains(QT_CONFIG, opengles2) {
SOURCES += qgl_x11egl.cpp \
qglpixelbuffer_egl.cpp \
qgl_egl.cpp \
@@ -121,8 +124,7 @@ wince*: {
qglpixelbuffer_egl.cpp \
qgl_egl.cpp
- HEADERS += qgl_cl_p.h \
- qgl_egl_p.h \
+ HEADERS += qgl_egl_p.h
}
embedded {
diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp
index 0a89412..cfcbbf8 100644
--- a/src/opengl/qgl.cpp
+++ b/src/opengl/qgl.cpp
@@ -67,7 +67,7 @@
#include "qimage.h"
#include "qgl_p.h"
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
#include "gl2paintengineex/qpaintengineex_opengl2_p.h"
#endif
@@ -95,11 +95,6 @@
QT_BEGIN_NAMESPACE
-#ifdef QT_OPENGL_ES_1_CL
-#include "qgl_cl_p.h"
-#endif
-
-
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
QGLExtensionFuncs QGLContextPrivate::qt_extensionFuncs;
#endif
@@ -226,6 +221,9 @@ bool qt_gl_preferGL2Engine()
\value DirectRendering Specifies that the context is used for direct rendering to a display.
\value HasOverlay Enables the use of an overlay.
\value SampleBuffers Enables the use of sample buffers.
+ \value DeprecatedFunctions Enables the use of deprecated functionality for OpenGL 3.x
+ contexts. A context with deprecated functionality enabled is
+ called a full context in the OpenGL specification.
\value SingleBuffer Specifies the use of a single buffer, as opposed to double buffers.
\value NoDepthBuffer Disables the use of a depth buffer.
\value ColorIndex Specifies that the context should use a color index as its pixel format.
@@ -236,6 +234,9 @@ bool qt_gl_preferGL2Engine()
\value IndirectRendering Specifies that the context is used for indirect rendering to a buffer.
\value NoOverlay Disables the use of an overlay.
\value NoSampleBuffers Disables the use of sample buffers.
+ \value NoDeprecatedFunctions Disables the use of deprecated functionality for OpenGL 3.x
+ contexts. A context with deprecated functionality disabled is
+ called a forward compatible context in the OpenGL specification.
\sa {Sample Buffers Example}
*/
@@ -1081,6 +1082,90 @@ int QGLFormat::stencilBufferSize() const
}
/*!
+ \since 4.7
+
+ Set the OpenGL version to the \a major and \a minor numbers. If a
+ context compatible with the requested OpenGL version cannot be
+ created, a context compatible with version 1.x is created instead.
+
+ \sa majorVersion(), minorVersion()
+*/
+void QGLFormat::setVersion(int major, int minor)
+{
+ if (major < 1 || minor < 0) {
+ qWarning("QGLFormat::setVersion: Cannot set zero or negative version number %d.%d", major, minor);
+ return;
+ }
+ detach();
+ d->majorVersion = major;
+ d->minorVersion = minor;
+}
+
+/*!
+ \since 4.7
+
+ Returns the OpenGL major version.
+
+ \sa setVersion(), minorVersion()
+*/
+int QGLFormat::majorVersion() const
+{
+ return d->majorVersion;
+}
+
+/*!
+ \since 4.7
+
+ Returns the OpenGL minor version.
+
+ \sa setVersion(), majorVersion()
+*/
+int QGLFormat::minorVersion() const
+{
+ return d->minorVersion;
+}
+
+/*!
+ \enum QGLFormat::OpenGLContextProfile
+ \since 4.7
+
+ This enum describes the OpenGL context profiles that can be
+ specified for contexts implementing OpenGL version 3.2 or
+ higher. These profiles are different from OpenGL ES profiles.
+
+ \value NoProfile OpenGL version is lower than 3.2.
+ \value CoreProfile Functionality deprecated in OpenGL version 3.0 is not available.
+ \value CompatibilityProfile Functionality from earlier OpenGL versions is available.
+*/
+
+/*!
+ \since 4.7
+
+ Set the OpenGL context profile to \a profile. The \a profile is
+ ignored if the requested OpenGL version is less than 3.2.
+
+ \sa profile()
+*/
+void QGLFormat::setProfile(OpenGLContextProfile profile)
+{
+ detach();
+ d->profile = profile;
+}
+
+/*!
+ \since 4.7
+
+ Returns the OpenGL context profile.
+
+ \sa setProfile()
+*/
+QGLFormat::OpenGLContextProfile QGLFormat::profile() const
+{
+ return d->profile;
+}
+
+
+/*!
\fn bool QGLFormat::hasOpenGL()
Returns true if the window system has any OpenGL support;
@@ -1116,25 +1201,21 @@ QGLFormat::OpenGLVersionFlags Q_AUTOTEST_EXPORT qOpenGLVersionFlagsFromString(co
if (parts[2].startsWith(QLatin1String("1.1")))
versionFlags |= QGLFormat::OpenGL_ES_Common_Version_1_1 |
QGLFormat::OpenGL_ES_CommonLite_Version_1_1;
- }
- else {
+ } else {
// Not -CM, must be CL, CommonLite
versionFlags |= QGLFormat::OpenGL_ES_CommonLite_Version_1_0;
if (parts[2].startsWith(QLatin1String("1.1")))
versionFlags |= QGLFormat::OpenGL_ES_CommonLite_Version_1_1;
}
- }
- else {
+ } else {
// OpenGL ES version 2.0 or higher
versionFlags |= QGLFormat::OpenGL_ES_Version_2_0;
}
- }
- else {
+ } else {
// if < 3 parts to the name, it is an unrecognised OpenGL ES
qWarning("Unrecognised OpenGL ES version");
}
- }
- else {
+ } else {
// not ES, regular OpenGL, the version numbers are first in the string
if (versionString.startsWith(QLatin1String("1."))) {
switch (versionString[2].toAscii()) {
@@ -1151,30 +1232,35 @@ QGLFormat::OpenGLVersionFlags Q_AUTOTEST_EXPORT qOpenGLVersionFlagsFromString(co
default:
break;
}
- }
- else if (versionString.startsWith(QLatin1String("2."))) {
+ } else if (versionString.startsWith(QLatin1String("2."))) {
versionFlags |= QGLFormat::OpenGL_Version_1_1 |
QGLFormat::OpenGL_Version_1_2 |
QGLFormat::OpenGL_Version_1_3 |
QGLFormat::OpenGL_Version_1_4 |
QGLFormat::OpenGL_Version_1_5 |
QGLFormat::OpenGL_Version_2_0;
- QString minorVersion = versionString.section(QLatin1Char(' '), 0, 0).section(QLatin1Char('.'), 1, 1);
- if (minorVersion == QChar(QLatin1Char('1')))
+ if (versionString[2].toAscii() == '1')
versionFlags |= QGLFormat::OpenGL_Version_2_1;
- }
- else if (versionString.startsWith(QLatin1String("3."))) {
- versionFlags |= QGLFormat::OpenGL_Version_1_1 |
- QGLFormat::OpenGL_Version_1_2 |
- QGLFormat::OpenGL_Version_1_3 |
- QGLFormat::OpenGL_Version_1_4 |
- QGLFormat::OpenGL_Version_1_5 |
- QGLFormat::OpenGL_Version_2_0 |
- QGLFormat::OpenGL_Version_2_1 |
- QGLFormat::OpenGL_Version_3_0;
- }
- else
+ } else if (versionString.startsWith(QLatin1String("3."))) {
+ versionFlags |= QGLFormat::OpenGL_Version_1_1 |
+ QGLFormat::OpenGL_Version_1_2 |
+ QGLFormat::OpenGL_Version_1_3 |
+ QGLFormat::OpenGL_Version_1_4 |
+ QGLFormat::OpenGL_Version_1_5 |
+ QGLFormat::OpenGL_Version_2_0 |
+ QGLFormat::OpenGL_Version_2_1 |
+ QGLFormat::OpenGL_Version_3_0;
+ switch (versionString[2].toAscii()) {
+ case '2':
+ versionFlags |= QGLFormat::OpenGL_Version_3_2;
+ case '1':
+ versionFlags |= QGLFormat::OpenGL_Version_3_1;
+ default:
+ break;
+ }
+ } else {
qWarning("Unrecognised OpenGL version");
+ }
}
return versionFlags;
}
@@ -1206,6 +1292,12 @@ QGLFormat::OpenGLVersionFlags Q_AUTOTEST_EXPORT qOpenGLVersionFlagsFromString(co
\value OpenGL_Version_3_0 OpenGL version 3.0 or higher is present.
+ \value OpenGL_Version_3_1 OpenGL version 3.1 or higher is present.
+ Note that OpenGL version 3.1 or higher does not necessarily support all the features of
+ version 3.0 and lower.
+
+ \value OpenGL_Version_3_2 OpenGL version 3.2 or higher is present.
+
\value OpenGL_ES_CommonLite_Version_1_0 OpenGL ES version 1.0 Common Lite or higher is present.
\value OpenGL_ES_Common_Version_1_0 OpenGL ES version 1.0 Common or higher is present.
@@ -1377,14 +1469,20 @@ void QGLFormat::setDefaultOverlayFormat(const QGLFormat &f)
bool operator==(const QGLFormat& a, const QGLFormat& b)
{
- return (int) a.d->opts == (int) b.d->opts && a.d->pln == b.d->pln && a.d->alphaSize == b.d->alphaSize
- && a.d->accumSize == b.d->accumSize && a.d->stencilSize == b.d->stencilSize
+ return (a.d == b.d) || ((int) a.d->opts == (int) b.d->opts
+ && a.d->pln == b.d->pln
+ && a.d->alphaSize == b.d->alphaSize
+ && a.d->accumSize == b.d->accumSize
+ && a.d->stencilSize == b.d->stencilSize
&& a.d->depthSize == b.d->depthSize
&& a.d->redSize == b.d->redSize
&& a.d->greenSize == b.d->greenSize
&& a.d->blueSize == b.d->blueSize
&& a.d->numSamples == b.d->numSamples
- && a.d->swapInterval == b.d->swapInterval;
+ && a.d->swapInterval == b.d->swapInterval
+ && a.d->majorVersion == b.d->majorVersion
+ && a.d->minorVersion == b.d->minorVersion
+ && a.d->profile == b.d->profile);
}
@@ -1558,7 +1656,7 @@ QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alp
QImage img(size, alpha_format ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32);
int w = size.width();
int h = size.height();
-#if !defined(QT_OPENGL_ES_2) && !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_2) && !defined(QT_OPENGL_ES_1)
//### glGetTexImage not in GL ES 2.0, need to do something else here!
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits());
#endif
@@ -2331,7 +2429,7 @@ QGLTexture *QGLContextPrivate::bindTexture(const QPixmap &pixmap, GLenum target,
{
Q_Q(QGLContext);
QPixmapData *pd = pixmap.pixmapData();
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
if (target == GL_TEXTURE_2D && pd->classId() == QPixmapData::OpenGLClass) {
const QGLPixmapData *data = static_cast<const QGLPixmapData *>(pd);
@@ -2581,41 +2679,41 @@ void QGLContext::deleteTexture(QMacCompatGLuint id)
}
#endif
-void qt_add_rect_to_array(const QRectF &r, q_vertexType *array)
+void qt_add_rect_to_array(const QRectF &r, GLfloat *array)
{
qreal left = r.left();
qreal right = r.right();
qreal top = r.top();
qreal bottom = r.bottom();
- array[0] = f2vt(left);
- array[1] = f2vt(top);
- array[2] = f2vt(right);
- array[3] = f2vt(top);
- array[4] = f2vt(right);
- array[5] = f2vt(bottom);
- array[6] = f2vt(left);
- array[7] = f2vt(bottom);
+ array[0] = left;
+ array[1] = top;
+ array[2] = right;
+ array[3] = top;
+ array[4] = right;
+ array[5] = bottom;
+ array[6] = left;
+ array[7] = bottom;
}
-void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array)
+void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, GLfloat *array)
{
- array[0] = f2vt(x1);
- array[1] = f2vt(y1);
- array[2] = f2vt(x2);
- array[3] = f2vt(y1);
- array[4] = f2vt(x2);
- array[5] = f2vt(y2);
- array[6] = f2vt(x1);
- array[7] = f2vt(y2);
+ array[0] = x1;
+ array[1] = y1;
+ array[2] = x2;
+ array[3] = y1;
+ array[4] = x2;
+ array[5] = y2;
+ array[6] = x1;
+ array[7] = y2;
}
#if !defined(QT_OPENGL_ES_2)
static void qDrawTextureRect(const QRectF &target, GLint textureWidth, GLint textureHeight, GLenum textureTarget)
{
- q_vertexType tx = f2vt(1);
- q_vertexType ty = f2vt(1);
+ GLfloat tx = 1.0f;
+ GLfloat ty = 1.0f;
#ifdef QT_OPENGL_ES
Q_UNUSED(textureWidth);
@@ -2628,20 +2726,20 @@ static void qDrawTextureRect(const QRectF &target, GLint textureWidth, GLint tex
glGetTexLevelParameteriv(textureTarget, 0, GL_TEXTURE_HEIGHT, &textureHeight);
}
- tx = f2vt(textureWidth);
- ty = f2vt(textureHeight);
+ tx = GLfloat(textureWidth);
+ ty = GLfloat(textureHeight);
}
#endif
- q_vertexType texCoordArray[4*2] = {
+ GLfloat texCoordArray[4*2] = {
0, ty, tx, ty, tx, 0, 0, 0
};
- q_vertexType vertexArray[4*2];
+ GLfloat vertexArray[4*2];
qt_add_rect_to_array(target, vertexArray);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
- glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
+ glTexCoordPointer(2, GL_FLOAT, 0, texCoordArray);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
@@ -4803,7 +4901,7 @@ void QGLWidget::drawTexture(const QPointF &point, QMacCompatGLuint textureId, QM
}
#endif
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_2_engine)
#endif
@@ -4813,7 +4911,7 @@ Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_engine)
Q_OPENGL_EXPORT QPaintEngine* qt_qgl_paint_engine()
{
-#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_1_CL)
+#if defined(QT_OPENGL_ES_1)
return qt_gl_engine();
#elif defined(QT_OPENGL_ES_2)
return qt_gl_2_engine();
@@ -4936,7 +5034,7 @@ QGLExtensions::Extensions QGLExtensions::currentContextExtensions()
glExtensions |= GenerateMipmap;
glExtensions |= FragmentShader;
#endif
-#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_1_CL)
+#if defined(QT_OPENGL_ES_1)
if (extensions.match("GL_OES_framebuffer_object"))
glExtensions |= FramebufferObject;
#endif
diff --git a/src/opengl/qgl.h b/src/opengl/qgl.h
index 1a04ff9..64f54a3 100644
--- a/src/opengl/qgl.h
+++ b/src/opengl/qgl.h
@@ -57,7 +57,7 @@ QT_BEGIN_HEADER
#if defined(Q_WS_MAC)
# include <OpenGL/gl.h>
# include <OpenGL/glu.h>
-#elif defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_1_CL)
+#elif defined(QT_OPENGL_ES_1)
# include <GLES/gl.h>
#ifndef GL_DOUBLE
# define GL_DOUBLE GL_FLOAT
@@ -144,6 +144,7 @@ namespace QGL
DirectRendering = 0x0080,
HasOverlay = 0x0100,
SampleBuffers = 0x0200,
+ DeprecatedFunctions = 0x0400,
SingleBuffer = DoubleBuffer << 16,
NoDepthBuffer = DepthBuffer << 16,
ColorIndex = Rgba << 16,
@@ -153,7 +154,8 @@ namespace QGL
NoStereoBuffers = StereoBuffers << 16,
IndirectRendering = DirectRendering << 16,
NoOverlay = HasOverlay << 16,
- NoSampleBuffers = SampleBuffers << 16
+ NoSampleBuffers = SampleBuffers << 16,
+ NoDeprecatedFunctions = DeprecatedFunctions << 16
};
Q_DECLARE_FLAGS(FormatOptions, FormatOption)
}
@@ -235,7 +237,20 @@ public:
static bool hasOpenGL();
static bool hasOpenGLOverlays();
- enum OpenGLVersionFlag {
+ void setVersion(int major, int minor);
+ int majorVersion() const;
+ int minorVersion() const;
+
+ enum OpenGLContextProfile {
+ NoProfile,
+ CoreProfile,
+ CompatibilityProfile
+ };
+
+ void setProfile(OpenGLContextProfile profile);
+ OpenGLContextProfile profile() const;
+
+ enum OpenGLVersionFlag {
OpenGL_Version_None = 0x00000000,
OpenGL_Version_1_1 = 0x00000001,
OpenGL_Version_1_2 = 0x00000002,
@@ -249,7 +264,9 @@ public:
OpenGL_ES_Common_Version_1_1 = 0x00000200,
OpenGL_ES_CommonLite_Version_1_1 = 0x00000400,
OpenGL_ES_Version_2_0 = 0x00000800,
- OpenGL_Version_3_0 = 0x00001000
+ OpenGL_Version_3_0 = 0x00001000,
+ OpenGL_Version_3_1 = 0x00002000,
+ OpenGL_Version_3_2 = 0x00004000
};
Q_DECLARE_FLAGS(OpenGLVersionFlags, OpenGLVersionFlag)
diff --git a/src/opengl/qgl_cl_p.h b/src/opengl/qgl_cl_p.h
deleted file mode 100644
index 82b492b..0000000
--- a/src/opengl/qgl_cl_p.h
+++ /dev/null
@@ -1,141 +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 QtOpenGL module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the Technology Preview License Agreement accompanying
-** this package.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Nokia gives you certain additional
-** rights. These rights are described in the Nokia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** If you have questions regarding the use of this file, please contact
-** Nokia at qt-info@nokia.com.
-**
-**
-**
-**
-**
-**
-**
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifdef QT_OPENGL_ES_1_CL
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of the QGLWidget class. This header file may change from
-// version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-QT_BEGIN_NAMESPACE
-
-inline void glTexParameterf (GLenum target, GLenum pname, GLfloat param)
-{
- glTexParameterx(target, pname, FLOAT2X(param));
-}
-inline void glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
-{
- glClearColorx(FLOAT2X(red) ,FLOAT2X(green), FLOAT2X(blue), FLOAT2X(alpha));
-}
-inline void glColor4f (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
-{
- glColor4x(FLOAT2X(red) ,FLOAT2X(green), FLOAT2X(blue), FLOAT2X(alpha));
-}
-
-inline void glOrthof (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar)
-{
- glOrthox(FLOAT2X(left), FLOAT2X(right), FLOAT2X(bottom), FLOAT2X(top), FLOAT2X(zNear), FLOAT2X(zFar));
-}
-
-inline void glPointSize (GLfloat size)
-{
- glPointSizex(FLOAT2X(size));
-}
-
-inline void glPolygonOffset (GLfloat factor, GLfloat units)
-{
- glPolygonOffsetx (FLOAT2X(factor), FLOAT2X(units));
-}
-
-inline void glRotatef (GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
-{
- glRotatex(FLOAT2X(angle), FLOAT2X(x), FLOAT2X(y), FLOAT2X(z));
-}
-
-inline void glTranslatef (GLfloat x, GLfloat y, GLfloat z)
-{
- glTranslatex(FLOAT2X(x) ,FLOAT2X(y) ,FLOAT2X(z));
-}
-
-inline void glNormal3f (GLfloat nx, GLfloat ny, GLfloat nz)
-{
- glNormal3x(FLOAT2X(nx), FLOAT2X(ny), FLOAT2X(nz));
-}
-
-inline void glScalef(GLfloat x, GLfloat y, GLfloat z)
-{
- glScalex(FLOAT2X(x), FLOAT2X(y), FLOAT2X(z));
-}
-
-inline void glClearDepthf (GLclampf depth)
-{
- glClearDepthx(FLOAT2X(depth));
-}
-
-inline void glAlphaFunc (GLenum func, GLclampf ref)
-{
- glAlphaFuncx(func, FLOAT2X(ref));
-}
-
-inline void glLoadMatrixf (const GLfloat *_m)
-{
- GLfixed m[16];
- for (int i =0; i < 16; i++)
- m[i] = FLOAT2X(_m[i]);
- glLoadMatrixx(m);
-}
-
-inline void glMultMatrixf (const GLfloat *_m)
-{
- GLfixed m[16];
- for (int i =0; i < 16; i++)
- m[i] = FLOAT2X(_m[i]);
- glMultMatrixx (m);
-}
-
-
-inline void glLineWidth (GLfloat width)
-{
- glLineWidthx(FLOAT2X(width));
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_OPENGL_ES_1_CL
-
diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h
index da0887e..efd2090 100644
--- a/src/opengl/qgl_p.h
+++ b/src/opengl/qgl_p.h
@@ -64,22 +64,6 @@
#include "qcache.h"
#include "qglpaintdevice_p.h"
-#ifndef QT_OPENGL_ES_1_CL
-#define q_vertexType float
-#define q_vertexTypeEnum GL_FLOAT
-#define f2vt(f) (f)
-#define vt2f(x) (x)
-#define i2vt(i) (float(i))
-#else
-#define FLOAT2X(f) (int( (f) * (65536)))
-#define X2FLOAT(x) (float(x) / 65536.0f)
-#define f2vt(f) FLOAT2X(f)
-#define i2vt(i) ((i)*65536)
-#define vt2f(x) X2FLOAT(x)
-#define q_vertexType GLfixed
-#define q_vertexTypeEnum GL_FIXED
-#endif //QT_OPENGL_ES_1_CL
-
#ifdef QT_OPENGL_ES
QT_BEGIN_INCLUDE_NAMESPACE
#if defined(QT_OPENGL_ES_2)
@@ -132,11 +116,15 @@ public:
QGLFormatPrivate()
: ref(1)
{
- opts = QGL::DoubleBuffer | QGL::DepthBuffer | QGL::Rgba | QGL::DirectRendering | QGL::StencilBuffer;
+ opts = QGL::DoubleBuffer | QGL::DepthBuffer | QGL::Rgba | QGL::DirectRendering
+ | QGL::StencilBuffer | QGL::DeprecatedFunctions;
pln = 0;
depthSize = accumSize = stencilSize = redSize = greenSize = blueSize = alphaSize = -1;
numSamples = -1;
swapInterval = -1;
+ majorVersion = 1;
+ minorVersion = 0;
+ profile = QGLFormat::NoProfile;
}
QGLFormatPrivate(const QGLFormatPrivate *other)
: ref(1),
@@ -150,7 +138,10 @@ public:
blueSize(other->blueSize),
alphaSize(other->alphaSize),
numSamples(other->numSamples),
- swapInterval(other->swapInterval)
+ swapInterval(other->swapInterval),
+ majorVersion(other->majorVersion),
+ minorVersion(other->minorVersion),
+ profile(other->profile)
{
}
QAtomicInt ref;
@@ -165,6 +156,9 @@ public:
int alphaSize;
int numSamples;
int swapInterval;
+ int majorVersion;
+ int minorVersion;
+ QGLFormat::OpenGLContextProfile profile;
};
class QGLWidgetPrivate : public QWidgetPrivate
@@ -346,6 +340,10 @@ public:
void syncGlState(); // Makes sure the GL context's state is what we think it is
#if defined(Q_WS_WIN)
+ void updateFormatVersion();
+#endif
+
+#if defined(Q_WS_WIN)
HGLRC rc;
HDC dc;
WId win;
diff --git a/src/opengl/qgl_win.cpp b/src/opengl/qgl_win.cpp
index ed4814f..b5f952e 100644
--- a/src/opengl/qgl_win.cpp
+++ b/src/opengl/qgl_win.cpp
@@ -122,6 +122,30 @@ typedef bool (APIENTRY *PFNWGLCHOOSEPIXELFORMATARB)(HDC hdc,
#define WGL_TYPE_COLORINDEX_ARB 0x202C
#endif
+#ifndef WGL_ARB_create_context
+#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
+#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
+#define WGL_CONTEXT_LAYER_PLANE_ARB 0x2093
+#define WGL_CONTEXT_FLAGS_ARB 0x2094
+#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
+#define WGL_CONTEXT_DEBUG_BIT_ARB 0x0001
+#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002
+#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x0001
+#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x0002
+// Error codes returned by GetLastError().
+#define ERROR_INVALID_VERSION_ARB 0x2095
+#define ERROR_INVALID_PROFILE_ARB 0x2096
+#endif
+
+#ifndef GL_VERSION_3_2
+#define GL_CONTEXT_PROFILE_MASK 0x9126
+#define GL_MAJOR_VERSION 0x821B
+#define GL_MINOR_VERSION 0x821C
+#define GL_NUM_EXTENSIONS 0x821D
+#define GL_CONTEXT_FLAGS 0x821E
+#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x0001
+#endif
+
QT_BEGIN_NAMESPACE
class QGLCmapPrivate
@@ -682,8 +706,118 @@ QGLTemporaryContext::~QGLTemporaryContext()
wglMakeCurrent(d->old_dc, d->old_context);
}
+static bool qgl_create_context(HDC hdc, QGLContextPrivate *d, QGLContextPrivate *shareContext)
+{
+ d->rc = 0;
+
+ typedef HGLRC (APIENTRYP PFNWGLCREATECONTEXTATTRIBSARB)(HDC, HGLRC, const int *);
+ PFNWGLCREATECONTEXTATTRIBSARB wglCreateContextAttribsARB =
+ (PFNWGLCREATECONTEXTATTRIBSARB) wglGetProcAddress("wglCreateContextAttribsARB");
+ if (wglCreateContextAttribsARB) {
+ int attributes[11];
+ int attribIndex = 0;
+ const int major = d->reqFormat.majorVersion();
+ const int minor = d->reqFormat.minorVersion();
+ attributes[attribIndex++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
+ attributes[attribIndex++] = major;
+ attributes[attribIndex++] = WGL_CONTEXT_MINOR_VERSION_ARB;
+ attributes[attribIndex++] = minor;
+
+ if (major >= 3 && !d->reqFormat.testOption(QGL::DeprecatedFunctions)) {
+ attributes[attribIndex++] = WGL_CONTEXT_FLAGS_ARB;
+ attributes[attribIndex++] = WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
+ }
+
+ if ((major == 3 && minor >= 2) || major > 3) {
+ switch (d->reqFormat.profile()) {
+ case QGLFormat::NoProfile:
+ break;
+ case QGLFormat::CoreProfile:
+ attributes[attribIndex++] = WGL_CONTEXT_PROFILE_MASK_ARB;
+ attributes[attribIndex++] = WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
+ break;
+ case QGLFormat::CompatibilityProfile:
+ attributes[attribIndex++] = WGL_CONTEXT_PROFILE_MASK_ARB;
+ attributes[attribIndex++] = WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
+ break;
+ default:
+ qWarning("QGLContext::chooseContext(): Context profile not supported.");
+ return false;
+ }
+ }
+
+ if (d->reqFormat.plane() != 0) {
+ attributes[attribIndex++] = WGL_CONTEXT_LAYER_PLANE_ARB;
+ attributes[attribIndex++] = d->reqFormat.plane();
+ }
+
+ attributes[attribIndex++] = 0; // Terminate list.
+ d->rc = wglCreateContextAttribsARB(hdc, shareContext && shareContext->valid
+ ? shareContext->rc : 0, attributes);
+ if (d->rc) {
+ if (shareContext)
+ shareContext->sharing = d->sharing = true;
+ return true;
+ }
+ }
+
+ d->rc = wglCreateLayerContext(hdc, d->reqFormat.plane());
+ if (d->rc && shareContext && shareContext->valid)
+ shareContext->sharing = d->sharing = wglShareLists(shareContext->rc, d->rc);
+ return d->rc != 0;
+}
+
+void QGLContextPrivate::updateFormatVersion()
+{
+ const GLubyte *s = glGetString(GL_VERSION);
+
+ if (!(s && s[0] >= '0' && s[0] <= '9' && s[1] == '.' && s[2] >= '0' && s[2] <= '9')) {
+ if (!s)
+ qWarning("QGLContext::chooseContext(): OpenGL version string is null.");
+ else
+ qWarning("QGLContext::chooseContext(): Unexpected OpenGL version string format.");
+ glFormat.setVersion(0, 0);
+ glFormat.setProfile(QGLFormat::NoProfile);
+ glFormat.setOption(QGL::DeprecatedFunctions);
+ return;
+ }
+
+ int major = s[0] - '0';
+ int minor = s[2] - '0';
+ glFormat.setVersion(major, minor);
+
+ if (major < 3) {
+ glFormat.setProfile(QGLFormat::NoProfile);
+ glFormat.setOption(QGL::DeprecatedFunctions);
+ } else {
+ GLint value = 0;
+ if (major > 3 || minor >= 2)
+ glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &value);
+
+ switch (value) {
+ case WGL_CONTEXT_CORE_PROFILE_BIT_ARB:
+ glFormat.setProfile(QGLFormat::CoreProfile);
+ break;
+ case WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB:
+ glFormat.setProfile(QGLFormat::CompatibilityProfile);
+ break;
+ default:
+ glFormat.setProfile(QGLFormat::NoProfile);
+ break;
+ }
+
+ glGetIntegerv(GL_CONTEXT_FLAGS, &value);
+ if (value & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)
+ glFormat.setOption(QGL::NoDeprecatedFunctions);
+ else
+ glFormat.setOption(QGL::DeprecatedFunctions);
+ }
+}
+
bool QGLContext::chooseContext(const QGLContext* shareContext)
{
+ QGLContextPrivate *share = shareContext ? const_cast<QGLContext *>(shareContext)->d_func() : 0;
+
Q_D(QGLContext);
// workaround for matrox driver:
// make a cheap call to opengl to force loading of DLL
@@ -741,8 +875,7 @@ bool QGLContext::chooseContext(const QGLContext* shareContext)
goto end;
}
- d->rc = wglCreateLayerContext(myDc, d->glFormat.plane());
- if (!d->rc) {
+ if (!qgl_create_context(myDc, d, share)) {
qwglError("QGLContext::chooseContext()", "CreateLayerContext");
result = false;
goto end;
@@ -792,16 +925,7 @@ bool QGLContext::chooseContext(const QGLContext* shareContext)
d->cmap = new QGLCmap(1 << lpfd.cColorBits);
d->cmap->setEntry(lpfd.crTransparent, qRgb(1, 2, 3));//, QGLCmap::Reserved);
}
-
- if (shareContext && shareContext->isValid()) {
- QGLContext *share = const_cast<QGLContext *>(shareContext);
- d->sharing = (wglShareLists(shareContext->d_func()->rc, d->rc) != 0);
- share->d_func()->sharing = d->sharing;
- }
-
- goto end;
- }
- {
+ } else {
PIXELFORMATDESCRIPTOR pfd;
PIXELFORMATDESCRIPTOR realPfd;
d->pixelFormatId = choosePixelFormat(&pfd, myDc);
@@ -840,17 +964,12 @@ bool QGLContext::chooseContext(const QGLContext* shareContext)
goto end;
}
- if (!(d->rc = wglCreateLayerContext(myDc, 0))) {
+ if (!qgl_create_context(myDc, d, share)) {
qwglError("QGLContext::chooseContext()", "wglCreateContext");
result = false;
goto end;
}
- if (shareContext && shareContext->isValid()) {
- d->sharing = (wglShareLists(shareContext->d_func()->rc, d->rc) != 0);
- const_cast<QGLContext *>(shareContext)->d_func()->sharing = d->sharing;
- }
-
if(!deviceIsPixmap()) {
QRgb* pal = qgl_create_rgb_palette(&realPfd);
if (pal) {
@@ -865,6 +984,9 @@ bool QGLContext::chooseContext(const QGLContext* shareContext)
end:
// vblanking
wglMakeCurrent(myDc, d->rc);
+ if (d->rc)
+ d->updateFormatVersion();
+
typedef BOOL (APIENTRYP PFNWGLSWAPINTERVALEXT) (int interval);
typedef int (APIENTRYP PFNWGLGETSWAPINTERVALEXT) (void);
PFNWGLSWAPINTERVALEXT wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXT) wglGetProcAddress("wglSwapIntervalEXT");
diff --git a/src/opengl/qglbuffer.cpp b/src/opengl/qglbuffer.cpp
new file mode 100644
index 0000000..7022a53
--- /dev/null
+++ b/src/opengl/qglbuffer.cpp
@@ -0,0 +1,454 @@
+/****************************************************************************
+**
+** 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 QtOpenGL module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtOpenGL/qgl.h>
+#include <QtOpenGL/private/qgl_p.h>
+#include <QtOpenGL/private/qglextensions_p.h>
+#include "qglbuffer.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QGLBuffer
+ \brief The QGLBuffer class provides functions for creating and managing GL buffer objects.
+ \since 4.7
+ \ingroup painting-3D
+
+ Buffer objects are created in the GL server so that the
+ client application can avoid uploading vertices, indices,
+ texture image data, etc every time they are needed.
+*/
+
+/*!
+ \enum QGLBuffer::Type
+ This enum defines the type of GL buffer object to create with QGLBuffer.
+
+ \value VertexBuffer Vertex buffer object for use when specifying
+ vertex arrays.
+ \value IndexBuffer Index buffer object for use with \c{glDrawElements()}.
+ \value PixelPackBuffer Pixel pack buffer object for reading pixel
+ data from the GL server (for example, with \c{glReadPixels()}).
+ Not supported under OpenGL/ES.
+ \value PixelUnpackBuffer Pixel unpack buffer object for writing pixel
+ data to the GL server (for example, with \c{glTexImage2D()}).
+ Not supported under OpenGL/ES.
+*/
+
+/*!
+ \enum QGLBuffer::UsagePattern
+ This enum defines the usage pattern of a QGLBuffer object.
+
+ \value StreamDraw The data will be set once and used a few times
+ for drawing operations. Under OpenGL/ES 1.1 this is identical
+ to StaticDraw.
+ \value StreamRead The data will be set once and used a few times
+ for reading data back from the GL server. Not supported
+ under OpenGL/ES.
+ \value StreamCopy The data will be set once and used a few times
+ for reading data back from the GL server for use in further
+ drawing operations. Not supported under OpenGL/ES.
+ \value StaticDraw The data will be set once and used many times
+ for drawing operations.
+ \value StaticRead The data will be set once and used many times
+ for reading data back from the GL server. Not supported
+ under OpenGL/ES.
+ \value StaticCopy The data will be set once and used many times
+ for reading data back from the GL server for use in further
+ drawing operations. Not supported under OpenGL/ES.
+ \value DynamicDraw The data will be modified repeatedly and used
+ many times for drawing operations.
+ \value DynamicRead The data will be modified repeatedly and used
+ many times for reading data back from the GL server.
+ Not supported under OpenGL/ES.
+ \value DynamicCopy The data will be modified repeatedly and used
+ many times for reading data back from the GL server for
+ use in further drawing operations. Not supported under OpenGL/ES.
+*/
+
+/*!
+ \enum QGLBuffer::Access
+ This enum defines the access mode for QGLBuffer::map().
+
+ \value ReadOnly The buffer will be mapped for reading only.
+ \value WriteOnly The buffer will be mapped for writing only.
+ \value ReadWrite The buffer will be mapped for reading and writing.
+*/
+
+class QGLBufferPrivate
+{
+public:
+ QGLBufferPrivate(QGLBuffer::Type t)
+ : type(t),
+ guard(0),
+ usagePattern(QGLBuffer::StaticDraw),
+ actualUsagePattern(QGLBuffer::StaticDraw)
+ {
+ }
+
+ QGLBuffer::Type type;
+ QGLSharedResourceGuard guard;
+ QGLBuffer::UsagePattern usagePattern;
+ QGLBuffer::UsagePattern actualUsagePattern;
+};
+
+/*!
+ Constructs a new buffer object of \a type.
+
+ Note: this constructor just creates the QGLBuffer instance. The actual
+ buffer object in the GL server is not created until create() is called.
+
+ \sa create()
+*/
+QGLBuffer::QGLBuffer(QGLBuffer::Type type)
+ : d_ptr(new QGLBufferPrivate(type))
+{
+}
+
+#define ctx d->guard.context()
+
+/*!
+ Destroys this buffer object, including the storage being
+ used in the GL server.
+*/
+QGLBuffer::~QGLBuffer()
+{
+ Q_D(QGLBuffer);
+ GLuint bufferId = d->guard.id();
+ if (bufferId) {
+ // Switch to the original creating context to destroy it.
+ QGLShareContextScope scope(d->guard.context());
+ glDeleteBuffers(1, &bufferId);
+ }
+}
+
+/*!
+ Returns the type of buffer represented by this object.
+*/
+QGLBuffer::Type QGLBuffer::type() const
+{
+ Q_D(const QGLBuffer);
+ return d->type;
+}
+
+/*!
+ Returns the usage pattern for this buffer object.
+ The default value is StaticDraw.
+
+ \sa setUsagePattern()
+*/
+QGLBuffer::UsagePattern QGLBuffer::usagePattern() const
+{
+ Q_D(const QGLBuffer);
+ return d->usagePattern;
+}
+
+/*!
+ Sets the usage pattern for this buffer object to \a value.
+ This function must be called before allocate() or write().
+
+ \sa usagePattern(), allocate(), write()
+*/
+void QGLBuffer::setUsagePattern(QGLBuffer::UsagePattern value)
+{
+ Q_D(QGLBuffer);
+#if defined(QT_OPENGL_ES_1)
+ // OpenGL/ES 1.1 does not support GL_STREAM_DRAW, so use GL_STATIC_DRAW.
+ // OpenGL/ES 2.0 does support GL_STREAM_DRAW.
+ d->usagePattern = value;
+ if (value == StreamDraw)
+ d->actualUsagePattern = StaticDraw;
+ else
+ d->actualUsagePattern = value;
+#else
+ d->usagePattern = d->actualUsagePattern = value;
+#endif
+}
+
+#undef ctx
+
+/*!
+ Creates the buffer object in the GL server. Returns true if
+ the object was created; false otherwise.
+
+ This function must be called with a current QGLContext.
+ The buffer will be bound to and can only be used in
+ that context (or any other context that is shared with it).
+
+ This function will return false if the GL implementation
+ does not support buffers, or there is no current QGLContext.
+
+ \sa isCreated(), allocate(), write()
+*/
+bool QGLBuffer::create()
+{
+ Q_D(QGLBuffer);
+ if (d->guard.id())
+ return true;
+ const QGLContext *ctx = QGLContext::currentContext();
+ if (ctx) {
+ if (!qt_resolve_buffer_extensions(const_cast<QGLContext *>(ctx)))
+ return false;
+ GLuint bufferId = 0;
+ glGenBuffers(1, &bufferId);
+ if (bufferId) {
+ d->guard.setContext(ctx);
+ d->guard.setId(bufferId);
+ return true;
+ }
+ }
+ return false;
+}
+
+#define ctx d->guard.context()
+
+/*!
+ Returns true if this buffer has been created; false otherwise.
+
+ \sa create()
+*/
+bool QGLBuffer::isCreated() const
+{
+ Q_D(const QGLBuffer);
+ return d->guard.id() != 0;
+}
+
+/*!
+ Reads the \a count bytes in this buffer starting at \a offset
+ into \a data. Returns true on success; false if reading from
+ the buffer is not supported. Buffer reading is not supported
+ under OpenGL/ES.
+
+ It is assumed that this buffer has been bound to the current context.
+
+ \sa write(), bind()
+*/
+bool QGLBuffer::read(int offset, void *data, int count)
+{
+#if !defined(QT_OPENGL_ES)
+ Q_D(QGLBuffer);
+ if (!glGetBufferSubData || !d->guard.id())
+ return false;
+ while (glGetError() != GL_NO_ERROR) ; // Clear error state.
+ glGetBufferSubData(d->type, offset, count, data);
+ return glGetError() == GL_NO_ERROR;
+#else
+ Q_UNUSED(offset);
+ Q_UNUSED(data);
+ Q_UNUSED(count);
+ return false;
+#endif
+}
+
+/*!
+ Replaces the \a count bytes of this buffer starting at \a offset
+ with the contents of \a data. Any other bytes in the buffer
+ will be left unmodified.
+
+ It is assumed that create() has been called on this buffer and that
+ it has been bound to the current context.
+
+ \sa create(), read(), allocate()
+*/
+void QGLBuffer::write(int offset, const void *data, int count)
+{
+ Q_D(QGLBuffer);
+ if (d->guard.id())
+ glBufferSubData(d->type, offset, count, data);
+}
+
+/*!
+ Allocates \a count bytes of space to the buffer, initialized to
+ the contents of \a data. Any previous contents will be removed.
+
+ It is assumed that create() has been called on this buffer and that
+ it has been bound to the current context.
+
+ \sa create(), read(), write()
+*/
+void QGLBuffer::allocate(const void *data, int count)
+{
+ Q_D(QGLBuffer);
+ if (d->guard.id())
+ glBufferData(d->type, count, data, d->actualUsagePattern);
+}
+
+/*!
+ \fn void QGLBuffer::allocate(int count)
+ \overload
+
+ Allocates \a count bytes of space to the buffer. Any previous
+ contents will be removed.
+
+ It is assumed that create() has been called on this buffer and that
+ it has been bound to the current context.
+
+ \sa create(), write()
+*/
+
+/*!
+ Binds the buffer associated with this object to the current
+ GL context. Returns false if binding was not possible, usually because
+ type() is not supported on this GL implementation.
+
+ The buffer must be bound to the same QGLContext current when create()
+ was called, or to another QGLContext that is sharing with it.
+ Otherwise, false will be returned from this function.
+
+ \sa release(), create()
+*/
+bool QGLBuffer::bind() const
+{
+ Q_D(const QGLBuffer);
+ GLuint bufferId = d->guard.id();
+ if (bufferId) {
+ if (!QGLContext::areSharing(QGLContext::currentContext(),
+ d->guard.context())) {
+#ifndef QT_NO_DEBUG
+ qWarning("QGLBuffer::bind: buffer is not valid in the current context");
+#endif
+ return false;
+ }
+ glBindBuffer(d->type, bufferId);
+ return true;
+ } else {
+ return false;
+ }
+}
+
+/*!
+ Releases the buffer associated with this object from the
+ current GL context.
+
+ This function must be called with the same QGLContext current
+ as when bind() was called on the buffer.
+
+ \sa bind()
+*/
+void QGLBuffer::release() const
+{
+ Q_D(const QGLBuffer);
+ if (d->guard.id())
+ glBindBuffer(d->type, 0);
+}
+
+/*!
+ Returns the GL identifier associated with this buffer; zero if
+ the buffer has not been created.
+
+ \sa isCreated()
+*/
+uint QGLBuffer::bufferId() const
+{
+ Q_D(const QGLBuffer);
+ return d->guard.id();
+}
+
+#ifndef GL_BUFFER_SIZE
+#define GL_BUFFER_SIZE 0x8764
+#endif
+
+/*!
+ Returns the size of the data in this buffer, for reading operations.
+ Returns -1 if fetching the buffer size is not supported, or the
+ buffer has not been created.
+
+ It is assumed that this buffer has been bound to the current context.
+
+ \sa isCreated(), bind()
+*/
+int QGLBuffer::size() const
+{
+ Q_D(const QGLBuffer);
+ if (!d->guard.id())
+ return -1;
+ GLint value = -1;
+ glGetBufferParameteriv(d->type, GL_BUFFER_SIZE, &value);
+ return value;
+}
+
+/*!
+ Maps the contents of this buffer into the application's memory
+ space and returns a pointer to it. Returns null if memory
+ mapping is not possible. The \a access parameter indicates the
+ type of access to be performed.
+
+ It is assumed that create() has been called on this buffer and that
+ it has been bound to the current context.
+
+ This function is only supported under OpenGL/ES if the
+ \c{GL_OES_mapbuffer} extension is present.
+
+ \sa unmap(), create(), bind()
+*/
+void *QGLBuffer::map(QGLBuffer::Access access)
+{
+ Q_D(QGLBuffer);
+ if (!d->guard.id())
+ return 0;
+ if (!glMapBufferARB)
+ return 0;
+ return glMapBufferARB(d->type, access);
+}
+
+/*!
+ Unmaps the buffer after it was mapped into the application's
+ memory space with a previous call to map(). Returns true if
+ the unmap succeeded; false otherwise.
+
+ It is assumed that this buffer has been bound to the current context,
+ and that it was previously mapped with map().
+
+ This function is only supported under OpenGL/ES if the
+ \c{GL_OES_mapbuffer} extension is present.
+
+ \sa map()
+*/
+bool QGLBuffer::unmap()
+{
+ Q_D(QGLBuffer);
+ if (!d->guard.id())
+ return false;
+ if (!glUnmapBufferARB)
+ return false;
+ return glUnmapBufferARB(d->type) == GL_TRUE;
+}
+
+QT_END_NAMESPACE
diff --git a/src/opengl/qglbuffer.h b/src/opengl/qglbuffer.h
new file mode 100644
index 0000000..ecb86e2
--- /dev/null
+++ b/src/opengl/qglbuffer.h
@@ -0,0 +1,124 @@
+/****************************************************************************
+**
+** 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 QtOpenGL module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QGLBUFFER_H
+#define QGLBUFFER_H
+
+#include <QtCore/qscopedpointer.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(OpenGL)
+
+class QGLBufferPrivate;
+
+class Q_OPENGL_EXPORT QGLBuffer
+{
+public:
+ enum Type
+ {
+ VertexBuffer = 0x8892, // GL_ARRAY_BUFFER
+ IndexBuffer = 0x8893, // GL_ELEMENT_ARRAY_BUFFER
+ PixelPackBuffer = 0x88EB, // GL_PIXEL_PACK_BUFFER
+ PixelUnpackBuffer = 0x88EC // GL_PIXEL_UNPACK_BUFFER
+ };
+
+ explicit QGLBuffer(QGLBuffer::Type type);
+ ~QGLBuffer();
+
+ enum UsagePattern
+ {
+ StreamDraw = 0x88E0, // GL_STREAM_DRAW
+ StreamRead = 0x88E1, // GL_STREAM_READ
+ StreamCopy = 0x88E2, // GL_STREAM_COPY
+ StaticDraw = 0x88E4, // GL_STATIC_DRAW
+ StaticRead = 0x88E5, // GL_STATIC_READ
+ StaticCopy = 0x88E6, // GL_STATIC_COPY
+ DynamicDraw = 0x88E8, // GL_DYNAMIC_DRAW
+ DynamicRead = 0x88E9, // GL_DYNAMIC_READ
+ DynamicCopy = 0x88EA // GL_DYNAMIC_COPY
+ };
+
+ enum Access
+ {
+ ReadOnly = 0x88B8, // GL_READ_ONLY
+ WriteOnly = 0x88B9, // GL_WRITE_ONLY
+ ReadWrite = 0x88BA // GL_READ_WRITE
+ };
+
+ QGLBuffer::Type type() const;
+
+ QGLBuffer::UsagePattern usagePattern() const;
+ void setUsagePattern(QGLBuffer::UsagePattern value);
+
+ bool create();
+ bool isCreated() const;
+
+ bool bind() const;
+ void release() const;
+
+ uint bufferId() const;
+
+ int size() const;
+
+ bool read(int offset, void *data, int count);
+ void write(int offset, const void *data, int count);
+
+ void allocate(const void *data, int count);
+ inline void allocate(int count) { allocate(0, count); }
+
+ void *map(QGLBuffer::Access access);
+ bool unmap();
+
+private:
+ QScopedPointer<QGLBufferPrivate> d_ptr;
+
+ Q_DISABLE_COPY(QGLBuffer)
+ Q_DECLARE_PRIVATE(QGLBuffer)
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif
diff --git a/src/opengl/qglextensions.cpp b/src/opengl/qglextensions.cpp
index c091191..02d5501 100644
--- a/src/opengl/qglextensions.cpp
+++ b/src/opengl/qglextensions.cpp
@@ -191,35 +191,45 @@ bool qt_resolve_frag_program_extensions(QGLContext *ctx)
bool qt_resolve_buffer_extensions(QGLContext *ctx)
{
- if (glMapBufferARB && glUnmapBufferARB
-#if !defined(QT_OPENGL_ES_2)
- && glBindBuffer && glDeleteBuffers && glGenBuffers && glBufferData
-#endif
- )
+#if defined(QGL_RESOLVE_BUFFER_FUNCS)
+ if (glBindBuffer && glDeleteBuffers && glGenBuffers && glBufferData
+ && glBufferSubData && glGetBufferParameteriv)
return true;
+#endif
-#if !defined(QT_OPENGL_ES_2)
+#if defined(QGL_RESOLVE_BUFFER_FUNCS)
glBindBuffer = (_glBindBuffer) qt_gl_getProcAddressARB(ctx, "glBindBuffer");
glDeleteBuffers = (_glDeleteBuffers) qt_gl_getProcAddressARB(ctx, "glDeleteBuffers");
glGenBuffers = (_glGenBuffers) qt_gl_getProcAddressARB(ctx, "glGenBuffers");
glBufferData = (_glBufferData) qt_gl_getProcAddressARB(ctx, "glBufferData");
+ glBufferSubData = (_glBufferSubData) qt_gl_getProcAddressARB(ctx, "glBufferSubData");
+ glGetBufferSubData = (_glGetBufferSubData) qt_gl_getProcAddressARB(ctx, "glGetBufferSubData");
+ glGetBufferParameteriv = (_glGetBufferParameteriv) qt_gl_getProcAddressARB(ctx, "glGetBufferParameteriv");
#endif
glMapBufferARB = (_glMapBufferARB) qt_gl_getProcAddressARB(ctx, "glMapBuffer");
glUnmapBufferARB = (_glUnmapBufferARB) qt_gl_getProcAddressARB(ctx, "glUnmapBuffer");
- return glMapBufferARB
- && glUnmapBufferARB
-#if !defined(QT_OPENGL_ES_2)
- && glBindBuffer
+#if defined(QGL_RESOLVE_BUFFER_FUNCS)
+ return glBindBuffer
&& glDeleteBuffers
&& glGenBuffers
&& glBufferData
+ && glBufferSubData
+ && glGetBufferParameteriv;
+ // glGetBufferSubData() is optional
+#else
+ return true;
#endif
- ;
}
bool qt_resolve_glsl_extensions(QGLContext *ctx)
{
+ // Geometry shaders are optional...
+ glProgramParameteriEXT = (_glProgramParameteriEXT) ctx->getProcAddress(QLatin1String("glProgramParameteriEXT"));
+ glFramebufferTextureEXT = (_glFramebufferTextureEXT) ctx->getProcAddress(QLatin1String("glFramebufferTextureEXT"));
+ glFramebufferTextureLayerEXT = (_glFramebufferTextureLayerEXT) ctx->getProcAddress(QLatin1String("glFramebufferTextureLayerEXT"));
+ glFramebufferTextureFaceEXT = (_glFramebufferTextureFaceEXT) ctx->getProcAddress(QLatin1String("glFramebufferTextureFaceEXT"));
+
#if defined(QT_OPENGL_ES_2)
// The GLSL shader functions are always present in OpenGL/ES 2.0.
// The only exceptions are glGetProgramBinaryOES and glProgramBinaryOES.
diff --git a/src/opengl/qglextensions_p.h b/src/opengl/qglextensions_p.h
index b0cb429..4edd5f7 100644
--- a/src/opengl/qglextensions_p.h
+++ b/src/opengl/qglextensions_p.h
@@ -71,6 +71,7 @@
#include <QtCore/qglobal.h>
#ifndef GL_ARB_vertex_buffer_object
+typedef ptrdiff_t GLintptrARB;
typedef ptrdiff_t GLsizeiptrARB;
#endif
@@ -78,13 +79,25 @@ typedef ptrdiff_t GLsizeiptrARB;
typedef char GLchar;
#endif
-// ARB_pixel_buffer_object
+// ARB_vertex_buffer_object
typedef void (APIENTRY *_glBindBuffer) (GLenum, GLuint);
typedef void (APIENTRY *_glDeleteBuffers) (GLsizei, const GLuint *);
typedef void (APIENTRY *_glGenBuffers) (GLsizei, GLuint *);
typedef void (APIENTRY *_glBufferData) (GLenum, GLsizeiptrARB, const GLvoid *, GLenum);
+typedef void (APIENTRY *_glBufferSubData) (GLenum, GLintptrARB, GLsizeiptrARB, const GLvoid *);
+typedef void (APIENTRY *_glGetBufferSubData) (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid *);
+typedef void (APIENTRY *_glGetBufferParameteriv) (GLenum, GLenum, GLint *);
typedef GLvoid* (APIENTRY *_glMapBufferARB) (GLenum, GLenum);
typedef GLboolean (APIENTRY *_glUnmapBufferARB) (GLenum);
+// We can call the buffer functions directly in OpenGL/ES 1.1 or higher,
+// but all other platforms need to resolve the extensions.
+#if defined(QT_OPENGL_ES)
+#if defined(GL_OES_VERSION_1_0) && !defined(GL_OES_VERSION_1_1)
+#define QGL_RESOLVE_BUFFER_FUNCS 1
+#endif
+#else
+#define QGL_RESOLVE_BUFFER_FUNCS 1
+#endif
// ARB_fragment_program
typedef void (APIENTRY *_glProgramStringARB) (GLenum, GLenum, GLsizei, const GLvoid *);
@@ -184,6 +197,15 @@ typedef void (APIENTRY *_glBlitFramebufferEXT) (int srcX0, int srcY0, int srcX1,
typedef void (APIENTRY *_glRenderbufferStorageMultisampleEXT) (GLenum target, GLsizei samples,
GLenum internalformat, GLsizei width, GLsizei height);
+// GL_EXT_geometry_shader4
+typedef void (APIENTRY *_glProgramParameteriEXT)(GLuint program, GLenum pname, GLint value);
+typedef void (APIENTRY *_glFramebufferTextureEXT)(GLenum target, GLenum attachment,
+ GLuint texture, GLint level);
+typedef void (APIENTRY *_glFramebufferTextureLayerEXT)(GLenum target, GLenum attachment,
+ GLuint texture, GLint level, GLint layer);
+typedef void (APIENTRY *_glFramebufferTextureFaceEXT)(GLenum target, GLenum attachment,
+ GLuint texture, GLint level, GLenum face);
+
// ARB_texture_compression
typedef void (APIENTRY *_glCompressedTexImage2DARB) (GLenum, GLint, GLenum, GLsizei,
GLsizei, GLint, GLsizei, const GLvoid *);
@@ -285,15 +307,22 @@ struct QGLExtensionFuncs
qt_glRenderbufferStorageMultisampleEXT = 0;
// Buffer objects:
-#if !defined(QT_OPENGL_ES_2)
+#if defined(QGL_RESOLVE_BUFFER_FUNCS)
qt_glBindBuffer = 0;
qt_glDeleteBuffers = 0;
qt_glGenBuffers = 0;
qt_glBufferData = 0;
+ qt_glBufferSubData = 0;
+ qt_glGetBufferSubData = 0;
+ qt_glGetBufferParameteriv = 0;
#endif
qt_glMapBufferARB = 0;
qt_glUnmapBufferARB = 0;
+ qt_glProgramParameteriEXT = 0;
+ qt_glFramebufferTextureEXT = 0;
+ qt_glFramebufferTextureLayerEXT = 0;
+ qt_glFramebufferTextureFaceEXT = 0;
#if !defined(QT_OPENGL_ES)
// Texture compression
qt_glCompressedTexImage2DARB = 0;
@@ -397,15 +426,23 @@ struct QGLExtensionFuncs
_glRenderbufferStorageMultisampleEXT qt_glRenderbufferStorageMultisampleEXT;
// Buffer objects
-#if !defined(QT_OPENGL_ES_2)
+#if defined(QGL_RESOLVE_BUFFER_FUNCS)
_glBindBuffer qt_glBindBuffer;
_glDeleteBuffers qt_glDeleteBuffers;
_glGenBuffers qt_glGenBuffers;
_glBufferData qt_glBufferData;
+ _glBufferSubData qt_glBufferSubData;
+ _glGetBufferSubData qt_glGetBufferSubData;
+ _glGetBufferParameteriv qt_glGetBufferParameteriv;
#endif
_glMapBufferARB qt_glMapBufferARB;
_glUnmapBufferARB qt_glUnmapBufferARB;
+ // Geometry shaders...
+ _glProgramParameteriEXT qt_glProgramParameteriEXT;
+ _glFramebufferTextureEXT qt_glFramebufferTextureEXT;
+ _glFramebufferTextureLayerEXT qt_glFramebufferTextureLayerEXT;
+ _glFramebufferTextureFaceEXT qt_glFramebufferTextureFaceEXT;
#if !defined(QT_OPENGL_ES)
// Texture compression
_glCompressedTexImage2DARB qt_glCompressedTexImage2DARB;
@@ -428,11 +465,11 @@ struct QGLExtensionFuncs
#endif
#ifndef GL_RGB16
-#define GL_RGB16 32852
+#define GL_RGB16 0x8054
#endif
#ifndef GL_UNSIGNED_SHORT_5_6_5
-#define GL_UNSIGNED_SHORT_5_6_5 33635
+#define GL_UNSIGNED_SHORT_5_6_5 0x8363
#endif
#ifndef GL_UNSIGNED_INT_8_8_8_8_REV
@@ -599,6 +636,20 @@ struct QGLExtensionFuncs
#define GL_DECR_WRAP 0x8508
#endif
+#ifndef GL_VERSION_1_5
+#define GL_ARRAY_BUFFER 0x8892
+#define GL_ELEMENT_ARRAY_BUFFER 0x8893
+#define GL_STREAM_DRAW 0x88E0
+#define GL_STREAM_READ 0x88E1
+#define GL_STREAM_COPY 0x88E2
+#define GL_STATIC_DRAW 0x88E4
+#define GL_STATIC_READ 0x88E5
+#define GL_STATIC_COPY 0x88E6
+#define GL_DYNAMIC_DRAW 0x88E8
+#define GL_DYNAMIC_READ 0x88E9
+#define GL_DYNAMIC_COPY 0x88EA
+#endif
+
#ifndef GL_VERSION_2_0
#define GL_FRAGMENT_SHADER 0x8B30
#define GL_VERTEX_SHADER 0x8B31
@@ -628,6 +679,29 @@ struct QGLExtensionFuncs
#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A
#endif
+// Geometry shader defines
+#ifndef GL_GEOMETRY_SHADER_EXT
+# define GL_GEOMETRY_SHADER_EXT 0x8DD9
+# define GL_GEOMETRY_VERTICES_OUT_EXT 0x8DDA
+# define GL_GEOMETRY_INPUT_TYPE_EXT 0x8DDB
+# define GL_GEOMETRY_OUTPUT_TYPE_EXT 0x8DDC
+# define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29
+# define GL_MAX_GEOMETRY_VARYING_COMPONENTS_EXT 0x8DDD
+# define GL_MAX_VERTEX_VARYING_COMPONENTS_EXT 0x8DDE
+# define GL_MAX_VARYING_COMPONENTS_EXT 0x8B4B
+# define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF
+# define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0
+# define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1
+# define GL_LINES_ADJACENCY_EXT 0xA
+# define GL_LINE_STRIP_ADJACENCY_EXT 0xB
+# define GL_TRIANGLES_ADJACENCY_EXT 0xC
+# define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0xD
+# define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8
+# define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT 0x8DA9
+# define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7
+# define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4
+# define GL_PROGRAM_POINT_SIZE_EXT 0x8642
+#endif
#if !defined(QT_OPENGL_ES_2)
#define glProgramStringARB QGLContextPrivate::extensionFuncs(ctx).qt_glProgramStringARB
@@ -667,11 +741,14 @@ struct QGLExtensionFuncs
// Buffer objects
-#if !defined(QT_OPENGL_ES_2)
+#if defined(QGL_RESOLVE_BUFFER_FUNCS)
#define glBindBuffer QGLContextPrivate::extensionFuncs(ctx).qt_glBindBuffer
#define glDeleteBuffers QGLContextPrivate::extensionFuncs(ctx).qt_glDeleteBuffers
#define glGenBuffers QGLContextPrivate::extensionFuncs(ctx).qt_glGenBuffers
#define glBufferData QGLContextPrivate::extensionFuncs(ctx).qt_glBufferData
+#define glBufferSubData QGLContextPrivate::extensionFuncs(ctx).qt_glBufferSubData
+#define glGetBufferSubData QGLContextPrivate::extensionFuncs(ctx).qt_glGetBufferSubData
+#define glGetBufferParameteriv QGLContextPrivate::extensionFuncs(ctx).qt_glGetBufferParameteriv
#endif
#define glMapBufferARB QGLContextPrivate::extensionFuncs(ctx).qt_glMapBufferARB
#define glUnmapBufferARB QGLContextPrivate::extensionFuncs(ctx).qt_glUnmapBufferARB
@@ -745,6 +822,11 @@ struct QGLExtensionFuncs
#define glClearDepth glClearDepthf
#endif
+#define glProgramParameteriEXT QGLContextPrivate::extensionFuncs(ctx).qt_glProgramParameteriEXT
+#define glFramebufferTextureEXT QGLContextPrivate::extensionFuncs(ctx).qt_glFramebufferTextureEXT
+#define glFramebufferTextureLayerEXT QGLContextPrivate::extensionFuncs(ctx).qt_glFramebufferTextureLayerEXT
+#define glFramebufferTextureFaceEXT QGLContextPrivate::extensionFuncs(ctx).qt_glFramebufferTextureFaceEXT
+
#if !defined(QT_OPENGL_ES)
#define glCompressedTexImage2D QGLContextPrivate::extensionFuncs(ctx).qt_glCompressedTexImage2DARB
#endif
diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp
index ce80796..f1d2325 100644
--- a/src/opengl/qglframebufferobject.cpp
+++ b/src/opengl/qglframebufferobject.cpp
@@ -44,7 +44,7 @@
#include <qdebug.h>
#include <private/qgl_p.h>
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
#include <private/qpaintengineex_opengl2_p.h>
#endif
@@ -56,10 +56,6 @@
#include <qlibrary.h>
#include <qimage.h>
-#ifdef QT_OPENGL_ES_1_CL
-#include "qgl_cl_p.h"
-#endif
-
QT_BEGIN_NAMESPACE
extern QImage qt_gl_read_framebuffer(const QSize&, bool, bool);
@@ -980,7 +976,7 @@ QImage QGLFramebufferObject::toImage() const
return image;
}
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_buffer_2_engine)
#endif
@@ -995,7 +991,7 @@ QPaintEngine *QGLFramebufferObject::paintEngine() const
if (d->engine)
return d->engine;
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
#if !defined (QT_OPENGL_ES_2)
if (qt_gl_preferGL2Engine()) {
#endif
diff --git a/src/opengl/qglpaintdevice.cpp b/src/opengl/qglpaintdevice.cpp
index 7697570..a0b1a79 100644
--- a/src/opengl/qglpaintdevice.cpp
+++ b/src/opengl/qglpaintdevice.cpp
@@ -48,14 +48,10 @@
#include <private/qpixmapdata_x11gl_p.h>
#endif
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
#include <private/qpixmapdata_gl_p.h>
#endif
-#if defined(QT_OPENGL_ES_1_CL)
-#include "qgl_cl_p.h"
-#endif
-
QT_BEGIN_NAMESPACE
QGLPaintDevice::QGLPaintDevice()
@@ -198,7 +194,7 @@ QGLPaintDevice* QGLPaintDevice::getDevice(QPaintDevice* pd)
glpd = &(static_cast<QGLFramebufferObject*>(pd)->d_func()->glDevice);
break;
case QInternal::Pixmap: {
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
QPixmapData* pmd = static_cast<QPixmap*>(pd)->pixmapData();
if (pmd->classId() == QPixmapData::OpenGLClass)
glpd = static_cast<QGLPixmapData*>(pmd)->glDevice();
diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp
index 46f7697..eca9550 100644
--- a/src/opengl/qglpixelbuffer.cpp
+++ b/src/opengl/qglpixelbuffer.cpp
@@ -78,7 +78,7 @@
#include <QtCore/qglobal.h>
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
#include <private/qpaintengineex_opengl2_p.h>
#endif
@@ -387,7 +387,7 @@ bool QGLPixelBuffer::isValid() const
return !d->invalid;
}
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_buffer_2_engine)
#endif
@@ -398,7 +398,7 @@ Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_engine)
/*! \reimp */
QPaintEngine *QGLPixelBuffer::paintEngine() const
{
-#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_1_CL)
+#if defined(QT_OPENGL_ES_1)
return qt_buffer_engine();
#elif defined(QT_OPENGL_ES_2)
return qt_buffer_2_engine();
diff --git a/src/opengl/qglpixelbuffer_egl.cpp b/src/opengl/qglpixelbuffer_egl.cpp
index ca19011..1e3223e 100644
--- a/src/opengl/qglpixelbuffer_egl.cpp
+++ b/src/opengl/qglpixelbuffer_egl.cpp
@@ -47,10 +47,6 @@
#include <qimage.h>
#include <private/qgl_p.h>
-#ifdef QT_OPENGL_ES_1_CL
-#include "qgl_cl_p.h"
-#endif
-
QT_BEGIN_NAMESPACE
#ifdef EGL_BIND_TO_TEXTURE_RGBA
diff --git a/src/opengl/qglshaderprogram.cpp b/src/opengl/qglshaderprogram.cpp
index 79484fa..a0b332d 100644
--- a/src/opengl/qglshaderprogram.cpp
+++ b/src/opengl/qglshaderprogram.cpp
@@ -50,7 +50,7 @@
QT_BEGIN_NAMESPACE
-#if !defined(QT_OPENGL_ES_1_CL) && !defined(QT_OPENGL_ES_1)
+#if !defined(QT_OPENGL_ES_1)
/*!
\class QGLShaderProgram
@@ -143,6 +143,8 @@ QT_BEGIN_NAMESPACE
\value Vertex Vertex shader written in the OpenGL Shading Language (GLSL).
\value Fragment Fragment shader written in the OpenGL Shading Language (GLSL).
+ \value Geometry Geometry shaders written in the OpenGL Shading
+ Language (GLSL), based on the GL_EXT_geometry_shader4 extension.
*/
#ifndef GL_FRAGMENT_SHADER
@@ -226,6 +228,8 @@ bool QGLShaderPrivate::create()
GLuint shader;
if (shaderType == QGLShader::Vertex)
shader = glCreateShader(GL_VERTEX_SHADER);
+ else if (shaderType == QGLShader::Geometry)
+ shader = glCreateShader(GL_GEOMETRY_SHADER_EXT);
else
shader = glCreateShader(GL_FRAGMENT_SHADER);
if (!shader) {
@@ -509,6 +513,10 @@ GLuint QGLShader::shaderId() const
return d->shaderGuard.id();
}
+
+
+
+
#undef ctx
#define ctx programGuard.context()
@@ -521,8 +529,9 @@ public:
, linked(false)
, inited(false)
, removingShaders(false)
- , vertexShader(0)
- , fragmentShader(0)
+ , geometryVertexCount(64)
+ , geometryInputType(0)
+ , geometryOutputType(0)
{
}
~QGLShaderProgramPrivate();
@@ -531,11 +540,14 @@ public:
bool linked;
bool inited;
bool removingShaders;
+
+ int geometryVertexCount;
+ GLenum geometryInputType;
+ GLenum geometryOutputType;
+
QString log;
QList<QGLShader *> shaders;
QList<QGLShader *> anonShaders;
- QGLShader *vertexShader;
- QGLShader *fragmentShader;
bool hasShader(QGLShader::ShaderType type) const;
};
@@ -604,6 +616,7 @@ bool QGLShaderProgram::init()
context = QGLContext::currentContext();
d->programGuard.setContext(context);
}
+
if (!context)
return false;
if (qt_resolve_glsl_extensions(const_cast<QGLContext *>(context))) {
@@ -831,6 +844,7 @@ bool QGLShaderProgram::link()
GLuint program = d->programGuard.id();
if (!program)
return false;
+
GLint value;
if (d->shaders.isEmpty()) {
// If there are no explicit shaders, then it is possible that the
@@ -843,6 +857,22 @@ bool QGLShaderProgram::link()
if (d->linked)
return true;
}
+
+ // Set up the geometry shader parameters
+ if (glProgramParameteriEXT) {
+ foreach (QGLShader *shader, d->shaders) {
+ if (shader->shaderType() & QGLShader::Geometry) {
+ glProgramParameteriEXT(program, GL_GEOMETRY_INPUT_TYPE_EXT,
+ d->geometryInputType);
+ glProgramParameteriEXT(program, GL_GEOMETRY_OUTPUT_TYPE_EXT,
+ d->geometryOutputType);
+ glProgramParameteriEXT(program, GL_GEOMETRY_VERTICES_OUT_EXT,
+ d->geometryVertexCount);
+ break;
+ }
+ }
+ }
+
glLinkProgram(program);
value = 0;
glGetProgramiv(program, GL_LINK_STATUS, &value);
@@ -1426,6 +1456,38 @@ void QGLShaderProgram::setAttributeArray
}
/*!
+ Sets an array of vertex \a values on the attribute at \a location
+ in this shader program. The \a stride indicates the number of bytes
+ between vertices. A default \a stride value of zero indicates that
+ the vertices are densely packed in \a values.
+
+ The \a type indicates the type of elements in the \a values array,
+ usually \c{GL_FLOAT}, \c{GL_UNSIGNED_BYTE}, etc. The \a tupleSize
+ indicates the number of components per vertex: 1, 2, 3, or 4.
+
+ The array will become active when enableAttributeArray() is called
+ on the \a location. Otherwise the value specified with
+ setAttributeValue() for \a location will be used.
+
+ The setAttributeBuffer() function can be used to set the attribute
+ array to an offset within a vertex buffer.
+
+ \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
+ \sa disableAttributeArray(), setAttributeBuffer()
+ \since 4.7
+*/
+void QGLShaderProgram::setAttributeArray
+ (int location, GLenum type, const void *values, int tupleSize, int stride)
+{
+ Q_D(QGLShaderProgram);
+ Q_UNUSED(d);
+ if (location != -1) {
+ glVertexAttribPointer(location, tupleSize, type, GL_FALSE,
+ stride, values);
+ }
+}
+
+/*!
\overload
Sets an array of vertex \a values on the attribute called \a name
@@ -1511,6 +1573,92 @@ void QGLShaderProgram::setAttributeArray
}
/*!
+ \overload
+
+ Sets an array of vertex \a values on the attribute called \a name
+ in this shader program. The \a stride indicates the number of bytes
+ between vertices. A default \a stride value of zero indicates that
+ the vertices are densely packed in \a values.
+
+ The \a type indicates the type of elements in the \a values array,
+ usually \c{GL_FLOAT}, \c{GL_UNSIGNED_BYTE}, etc. The \a tupleSize
+ indicates the number of components per vertex: 1, 2, 3, or 4.
+
+ The array will become active when enableAttributeArray() is called
+ on the \a name. Otherwise the value specified with
+ setAttributeValue() for \a name will be used.
+
+ The setAttributeBuffer() function can be used to set the attribute
+ array to an offset within a vertex buffer.
+
+ \sa setAttributeValue(), setUniformValue(), enableAttributeArray()
+ \sa disableAttributeArray(), setAttributeBuffer()
+ \since 4.7
+*/
+void QGLShaderProgram::setAttributeArray
+ (const char *name, GLenum type, const void *values, int tupleSize, int stride)
+{
+ setAttributeArray(attributeLocation(name), type, values, tupleSize, stride);
+}
+
+/*!
+ Sets an array of vertex values on the attribute at \a location in
+ this shader program, starting at a specific \a offset in the
+ currently bound vertex buffer. The \a stride indicates the number
+ of bytes between vertices. A default \a stride value of zero
+ indicates that the vertices are densely packed in the value array.
+
+ The \a type indicates the type of elements in the vertex value
+ array, usually \c{GL_FLOAT}, \c{GL_UNSIGNED_BYTE}, etc. The \a
+ tupleSize indicates the number of components per vertex: 1, 2, 3,
+ or 4.
+
+ The array will become active when enableAttributeArray() is called
+ on the \a location. Otherwise the value specified with
+ setAttributeValue() for \a location will be used.
+
+ \sa setAttributeArray()
+ \since 4.7
+*/
+void QGLShaderProgram::setAttributeBuffer
+ (int location, GLenum type, int offset, int tupleSize, int stride)
+{
+ Q_D(QGLShaderProgram);
+ Q_UNUSED(d);
+ if (location != -1) {
+ glVertexAttribPointer(location, tupleSize, type, GL_FALSE, stride,
+ reinterpret_cast<const void *>(offset));
+ }
+}
+
+/*!
+ \overload
+
+ Sets an array of vertex values on the attribute called \a name
+ in this shader program, starting at a specific \a offset in the
+ currently bound vertex buffer. The \a stride indicates the number
+ of bytes between vertices. A default \a stride value of zero
+ indicates that the vertices are densely packed in the value array.
+
+ The \a type indicates the type of elements in the vertex value
+ array, usually \c{GL_FLOAT}, \c{GL_UNSIGNED_BYTE}, etc. The \a
+ tupleSize indicates the number of components per vertex: 1, 2, 3,
+ or 4.
+
+ The array will become active when enableAttributeArray() is called
+ on the \a name. Otherwise the value specified with
+ setAttributeValue() for \a name will be used.
+
+ \sa setAttributeArray()
+ \since 4.7
+*/
+void QGLShaderProgram::setAttributeBuffer
+ (const char *name, GLenum type, int offset, int tupleSize, int stride)
+{
+ setAttributeBuffer(attributeLocation(name), type, offset, tupleSize, stride);
+}
+
+/*!
Enables the vertex array at \a location in this shader program
so that the value set by setAttributeArray() on \a location
will be used by the shader program.
@@ -2307,6 +2455,42 @@ void QGLShaderProgram::setUniformValue(const char *name, const QMatrix4x4& value
\overload
Sets the uniform variable at \a location in the current context
+ to a 2x2 matrix \a value. The matrix elements must be specified
+ in column-major order.
+
+ \sa setAttributeValue()
+ \since 4.7
+*/
+void QGLShaderProgram::setUniformValue(int location, const GLfloat value[2][2])
+{
+ Q_D(QGLShaderProgram);
+ Q_UNUSED(d);
+ if (location != -1)
+ glUniformMatrix2fv(location, 1, GL_FALSE, value[0]);
+}
+
+/*!
+ \overload
+
+ Sets the uniform variable at \a location in the current context
+ to a 3x3 matrix \a value. The matrix elements must be specified
+ in column-major order.
+
+ \sa setAttributeValue()
+ \since 4.7
+*/
+void QGLShaderProgram::setUniformValue(int location, const GLfloat value[3][3])
+{
+ Q_D(QGLShaderProgram);
+ Q_UNUSED(d);
+ if (location != -1)
+ glUniformMatrix3fv(location, 1, GL_FALSE, value[0]);
+}
+
+/*!
+ \overload
+
+ Sets the uniform variable at \a location in the current context
to a 4x4 matrix \a value. The matrix elements must be specified
in column-major order.
@@ -2320,6 +2504,37 @@ void QGLShaderProgram::setUniformValue(int location, const GLfloat value[4][4])
glUniformMatrix4fv(location, 1, GL_FALSE, value[0]);
}
+
+/*!
+ \overload
+
+ Sets the uniform variable called \a name in the current context
+ to a 2x2 matrix \a value. The matrix elements must be specified
+ in column-major order.
+
+ \sa setAttributeValue()
+ \since 4.7
+*/
+void QGLShaderProgram::setUniformValue(const char *name, const GLfloat value[2][2])
+{
+ setUniformValue(uniformLocation(name), value);
+}
+
+/*!
+ \overload
+
+ Sets the uniform variable called \a name in the current context
+ to a 3x3 matrix \a value. The matrix elements must be specified
+ in column-major order.
+
+ \sa setAttributeValue()
+ \since 4.7
+*/
+void QGLShaderProgram::setUniformValue(const char *name, const GLfloat value[3][3])
+{
+ setUniformValue(uniformLocation(name), value);
+}
+
/*!
\overload
@@ -2862,6 +3077,109 @@ void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix4x4 *
#undef ctx
/*!
+ Returns the hardware limit for how many vertices a geometry shader
+ can output.
+
+ \since 4.7
+
+ \sa setGeometryShaderOutputVertexCount
+*/
+int QGLShaderProgram::maxGeometryOutputVertices() const
+{
+ int n;
+ glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT, &n);
+ return n;
+}
+
+
+
+/*!
+ Sets the maximum number of vertices the current geometry shader
+ program will produce, if active.
+
+ \since 4.7
+
+ This parameter takes effect the next time the program is linked.
+*/
+void QGLShaderProgram::setGeometryOutputVertexCount(int count)
+{
+#ifndef QT_NO_DEBUG
+ int max = maxGeometryOutputVertices();
+ if (count > max) {
+ qWarning("QGLShaderProgram::setGeometryOutputVertexCount: count: %d higher than maximum: %d",
+ count, max);
+ }
+#endif
+ d_func()->geometryVertexCount = count;
+}
+
+
+/*!
+ Returns the maximum number of vertices the current geometry shader
+ program will produce, if active.
+
+ \since 4.7
+
+ This parameter takes effect the ntext time the program is linked.
+*/
+int QGLShaderProgram::geometryOutputVertexCount() const
+{
+ return d_func()->geometryVertexCount;
+}
+
+
+/*!
+ Sets the output type from the geometry shader, if active.
+
+ This parameter takes effect the next time the program is linked.
+*/
+void QGLShaderProgram::setGeometryInputType(GLenum inputType)
+{
+ d_func()->geometryInputType = inputType;
+}
+
+
+/*!
+ Returns the geometry shader input type, if active.
+
+ This parameter takes effect the next time the program is linked.
+
+ \since 4.7
+ */
+
+GLenum QGLShaderProgram::geometryInputType() const
+{
+ return d_func()->geometryInputType;
+}
+
+
+/*!
+ Sets the output type from the geometry shader, if active.
+
+ This parameter takes effect the next time the program is linked.
+
+ \since 4.7
+*/
+void QGLShaderProgram::setGeometryOutputType(GLenum outputType)
+{
+ d_func()->geometryOutputType = outputType;
+}
+
+
+/*!
+ Returns the geometry shader output type, if active.
+
+ This parameter takes effect the next time the program is linked.
+
+ \since 4.7
+ */
+GLenum QGLShaderProgram::geometryOutputType() const
+{
+ return d_func()->geometryOutputType;
+}
+
+
+/*!
Returns true if shader programs written in the OpenGL Shading
Language (GLSL) are supported on this system; false otherwise.
@@ -2893,8 +3211,71 @@ void QGLShaderProgram::shaderDestroyed()
removeShader(shader);
}
+
+#undef ctx
+#undef context
+
+/*!
+ Returns true if shader programs of type \a type are supported on
+ this system; false otherwise.
+
+ The \a context is used to resolve the GLSL extensions.
+ If \a context is null, then QGLContext::currentContext() is used.
+
+ \since 4.7
+*/
+bool QGLShader::hasOpenGLShaders(ShaderType type, const QGLContext *context)
+{
+ if (!context)
+ context = QGLContext::currentContext();
+ if (!context)
+ return false;
+
+ if ((type & ~(Geometry | Vertex | Fragment)) || type == 0)
+ return false;
+
+ bool resolved = qt_resolve_glsl_extensions(const_cast<QGLContext *>(context));
+ if (!resolved)
+ return false;
+
+ if ((type & Geometry) && !QByteArray((const char *) glGetString(GL_EXTENSIONS)).contains("GL_EXT_geometry_shader4"))
+ return false;
+
+ return true;
+}
+
+
+
#ifdef Q_MAC_COMPAT_GL_FUNCTIONS
/*! \internal */
+void QGLShaderProgram::setAttributeArray
+ (int location, QMacCompatGLenum type, const void *values, int tupleSize, int stride)
+{
+ setAttributeArray(location, GLenum(type), values, tupleSize, stride);
+}
+
+/*! \internal */
+void QGLShaderProgram::setAttributeArray
+ (const char *name, QMacCompatGLenum type, const void *values, int tupleSize, int stride)
+{
+ setAttributeArray(name, GLenum(type), values, tupleSize, stride);
+}
+
+/*! \internal */
+void QGLShaderProgram::setAttributeBuffer
+ (int location, QMacCompatGLenum type, int offset, int tupleSize, int stride)
+{
+ setAttributeBuffer(location, GLenum(type), offset, tupleSize, stride);
+}
+
+/*! \internal */
+void QGLShaderProgram::setAttributeBuffer
+ (const char *name, QMacCompatGLenum type, int offset, int tupleSize, int stride)
+{
+ setAttributeBuffer(name, GLenum(type), offset, tupleSize, stride);
+}
+
+/*! \internal */
void QGLShaderProgram::setUniformValue(int location, QMacCompatGLint value)
{
setUniformValue(location, GLint(value));
@@ -2943,6 +3324,6 @@ void QGLShaderProgram::setUniformValueArray(const char *name, const QMacCompatGL
}
#endif
-#endif // !defined(QT_OPENGL_ES_1_CL) && !defined(QT_OPENGL_ES_1)
+#endif // !defined(QT_OPENGL_ES_1)
QT_END_NAMESPACE
diff --git a/src/opengl/qglshaderprogram.h b/src/opengl/qglshaderprogram.h
index 24ab986..d612b05 100644
--- a/src/opengl/qglshaderprogram.h
+++ b/src/opengl/qglshaderprogram.h
@@ -54,7 +54,7 @@ QT_BEGIN_NAMESPACE
QT_MODULE(OpenGL)
-#if !defined(QT_OPENGL_ES_1_CL) && !defined(QT_OPENGL_ES_1)
+#if !defined(QT_OPENGL_ES_1)
class QGLShaderProgram;
class QGLShaderPrivate;
@@ -66,7 +66,8 @@ public:
enum ShaderTypeBit
{
Vertex = 0x0001,
- Fragment = 0x0002
+ Fragment = 0x0002,
+ Geometry = 0x0004
};
Q_DECLARE_FLAGS(ShaderType, ShaderTypeBit)
@@ -88,6 +89,8 @@ public:
GLuint shaderId() const;
+ static bool hasOpenGLShaders(ShaderType type, const QGLContext *context = 0);
+
private:
friend class QGLShaderProgram;
@@ -100,6 +103,14 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(QGLShader::ShaderType)
class QGLShaderProgramPrivate;
+#ifndef GL_EXT_geometry_shader4
+# define GL_LINES_ADJACENCY_EXT 0xA
+# define GL_LINE_STRIP_ADJACENCY_EXT 0xB
+# define GL_TRIANGLES_ADJACENCY_EXT 0xC
+# define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0xD
+#endif
+
+
class Q_OPENGL_EXPORT QGLShaderProgram : public QObject
{
Q_OBJECT
@@ -128,6 +139,17 @@ public:
GLuint programId() const;
+ int maxGeometryOutputVertices() const;
+
+ void setGeometryOutputVertexCount(int count);
+ int geometryOutputVertexCount() const;
+
+ void setGeometryInputType(GLenum inputType);
+ GLenum geometryInputType() const;
+
+ void setGeometryOutputType(GLenum outputType);
+ GLenum geometryOutputType() const;
+
void bindAttributeLocation(const char *name, int location);
void bindAttributeLocation(const QByteArray& name, int location);
void bindAttributeLocation(const QString& name, int location);
@@ -165,6 +187,8 @@ public:
void setAttributeArray
(int location, const QVector4D *values, int stride = 0);
void setAttributeArray
+ (int location, GLenum type, const void *values, int tupleSize, int stride = 0);
+ void setAttributeArray
(const char *name, const GLfloat *values, int tupleSize, int stride = 0);
void setAttributeArray
(const char *name, const QVector2D *values, int stride = 0);
@@ -172,6 +196,24 @@ public:
(const char *name, const QVector3D *values, int stride = 0);
void setAttributeArray
(const char *name, const QVector4D *values, int stride = 0);
+ void setAttributeArray
+ (const char *name, GLenum type, const void *values, int tupleSize, int stride = 0);
+
+ void setAttributeBuffer
+ (int location, GLenum type, int offset, int tupleSize, int stride = 0);
+ void setAttributeBuffer
+ (const char *name, GLenum type, int offset, int tupleSize, int stride = 0);
+
+#ifdef Q_MAC_COMPAT_GL_FUNCTIONS
+ void setAttributeArray
+ (int location, QMacCompatGLenum type, const void *values, int tupleSize, int stride = 0);
+ void setAttributeArray
+ (const char *name, QMacCompatGLenum type, const void *values, int tupleSize, int stride = 0);
+ void setAttributeBuffer
+ (int location, QMacCompatGLenum type, int offset, int tupleSize, int stride = 0);
+ void setAttributeBuffer
+ (const char *name, QMacCompatGLenum type, int offset, int tupleSize, int stride = 0);
+#endif
void enableAttributeArray(int location);
void enableAttributeArray(const char *name);
@@ -216,6 +258,8 @@ public:
void setUniformValue(int location, const QMatrix4x2& value);
void setUniformValue(int location, const QMatrix4x3& value);
void setUniformValue(int location, const QMatrix4x4& value);
+ void setUniformValue(int location, const GLfloat value[2][2]);
+ void setUniformValue(int location, const GLfloat value[3][3]);
void setUniformValue(int location, const GLfloat value[4][4]);
void setUniformValue(int location, const QTransform& value);
@@ -242,6 +286,8 @@ public:
void setUniformValue(const char *name, const QMatrix4x2& value);
void setUniformValue(const char *name, const QMatrix4x3& value);
void setUniformValue(const char *name, const QMatrix4x4& value);
+ void setUniformValue(const char *name, const GLfloat value[2][2]);
+ void setUniformValue(const char *name, const GLfloat value[3][3]);
void setUniformValue(const char *name, const GLfloat value[4][4]);
void setUniformValue(const char *name, const QTransform& value);
diff --git a/src/opengl/qgraphicsshadereffect.cpp b/src/opengl/qgraphicsshadereffect.cpp
index dddc85d..f53ef54 100644
--- a/src/opengl/qgraphicsshadereffect.cpp
+++ b/src/opengl/qgraphicsshadereffect.cpp
@@ -40,7 +40,7 @@
****************************************************************************/
#include "qgraphicsshadereffect_p.h"
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
#include "qglshaderprogram.h"
#include "gl2paintengineex/qglcustomshaderstage_p.h"
#define QGL_HAVE_CUSTOM_SHADERS 1
diff --git a/src/opengl/qpaintengine_opengl.cpp b/src/opengl/qpaintengine_opengl.cpp
index 57918d0..3845e43 100644
--- a/src/opengl/qpaintengine_opengl.cpp
+++ b/src/opengl/qpaintengine_opengl.cpp
@@ -71,10 +71,6 @@
#include "private/qwsmanager_p.h"
#endif
-#ifdef QT_OPENGL_ES_1_CL
-#include "qgl_cl_p.h"
-#endif
-
#define QGL_FUNC_CONTEXT QGLContext *ctx = const_cast<QGLContext *>(device->context());
#include <stdlib.h>
@@ -780,7 +776,7 @@ public:
void drawOffscreenPath(const QPainterPath &path);
void composite(const QRectF &rect, const QPoint &maskOffset = QPoint());
- void composite(GLuint primitive, const q_vertexType *vertexArray, int vertexCount, const QPoint &maskOffset = QPoint());
+ void composite(GLuint primitive, const GLfloat *vertexArray, int vertexCount, const QPoint &maskOffset = QPoint());
bool createFragmentPrograms();
void deleteFragmentPrograms();
@@ -1787,7 +1783,7 @@ class QOpenGLTrapezoidToArrayTessellator : public QOpenGLTessellator
public:
QOpenGLTrapezoidToArrayTessellator() : vertices(0), allocated(0), size(0) {}
~QOpenGLTrapezoidToArrayTessellator() { free(vertices); }
- q_vertexType *vertices;
+ GLfloat *vertices;
int allocated;
int size;
QRectF bounds;
@@ -1808,36 +1804,36 @@ void QOpenGLTrapezoidToArrayTessellator::addTrap(const Trapezoid &trap)
if (size > allocated - 12) {
#endif
allocated = qMax(2*allocated, 512);
- vertices = (q_vertexType *)realloc(vertices, allocated * sizeof(q_vertexType));
+ vertices = (GLfloat *)realloc(vertices, allocated * sizeof(GLfloat));
}
QGLTrapezoid t = toGLTrapezoid(trap);
#ifndef QT_OPENGL_ES
- vertices[size++] = f2vt(t.topLeftX);
- vertices[size++] = f2vt(t.top);
- vertices[size++] = f2vt(t.topRightX);
- vertices[size++] = f2vt(t.top);
- vertices[size++] = f2vt(t.bottomRightX);
- vertices[size++] = f2vt(t.bottom);
- vertices[size++] = f2vt(t.bottomLeftX);
- vertices[size++] = f2vt(t.bottom);
+ vertices[size++] = t.topLeftX;
+ vertices[size++] = t.top;
+ vertices[size++] = t.topRightX;
+ vertices[size++] = t.top;
+ vertices[size++] = t.bottomRightX;
+ vertices[size++] = t.bottom;
+ vertices[size++] = t.bottomLeftX;
+ vertices[size++] = t.bottom;
#else
// First triangle
- vertices[size++] = f2vt(t.topLeftX);
- vertices[size++] = f2vt(t.top);
- vertices[size++] = f2vt(t.topRightX);
- vertices[size++] = f2vt(t.top);
- vertices[size++] = f2vt(t.bottomRightX);
- vertices[size++] = f2vt(t.bottom);
+ vertices[size++] = t.topLeftX;
+ vertices[size++] = t.top;
+ vertices[size++] = t.topRightX;
+ vertices[size++] = t.top;
+ vertices[size++] = t.bottomRightX;
+ vertices[size++] = t.bottom;
// Second triangle
- vertices[size++] = f2vt(t.bottomLeftX);
- vertices[size++] = f2vt(t.bottom);
- vertices[size++] = f2vt(t.topLeftX);
- vertices[size++] = f2vt(t.top);
- vertices[size++] = f2vt(t.bottomRightX);
- vertices[size++] = f2vt(t.bottom);
+ vertices[size++] = t.bottomLeftX;
+ vertices[size++] = t.bottom;
+ vertices[size++] = t.topLeftX;
+ vertices[size++] = t.top;
+ vertices[size++] = t.bottomRightX;
+ vertices[size++] = t.bottom;
#endif
}
@@ -1864,7 +1860,7 @@ void QOpenGLPaintEnginePrivate::fillPolygon_dev(const QPointF *polygonPoints, in
if (use_fragment_programs && !(fast_style && has_fast_composition_mode)) {
composite(geometry_mode, tessellator.vertices, tessellator.size / 2);
} else {
- glVertexPointer(2, q_vertexTypeEnum, 0, tessellator.vertices);
+ glVertexPointer(2, GL_FLOAT, 0, tessellator.vertices);
glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(geometry_mode, 0, tessellator.size/2);
glDisableClientState(GL_VERTEX_ARRAY);
@@ -2265,7 +2261,7 @@ void QOpenGLPaintEnginePrivate::updateDepthClip()
return;
}
-#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_2) || defined(QT_OPENGL_ES_1_CL)
+#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_2)
glClearDepthf(0.0f);
#else
glClearDepth(0.0f);
@@ -2281,12 +2277,12 @@ void QOpenGLPaintEnginePrivate::updateDepthClip()
const QVector<QRect> rects = q->state()->clipEnabled ? q->state()->clipRegion.rects() : q->systemClip().rects();
// rectangle count * 2 (triangles) * vertex count * component count (Z omitted)
- QDataBuffer<q_vertexType> clipVertex(rects.size()*2*3*2);
+ QDataBuffer<GLfloat> clipVertex(rects.size()*2*3*2);
for (int i = 0; i < rects.size(); ++i) {
- q_vertexType x = i2vt(rects.at(i).left());
- q_vertexType w = i2vt(rects.at(i).width());
- q_vertexType h = i2vt(rects.at(i).height());
- q_vertexType y = i2vt(rects.at(i).top());
+ GLfloat x = GLfloat(rects.at(i).left());
+ GLfloat w = GLfloat(rects.at(i).width());
+ GLfloat h = GLfloat(rects.at(i).height());
+ GLfloat y = GLfloat(rects.at(i).top());
// First triangle
clipVertex.add(x);
@@ -2314,7 +2310,7 @@ void QOpenGLPaintEnginePrivate::updateDepthClip()
glLoadIdentity();
glEnableClientState(GL_VERTEX_ARRAY);
- glVertexPointer(2, q_vertexTypeEnum, 0, clipVertex.data());
+ glVertexPointer(2, GL_FLOAT, 0, clipVertex.data());
glDrawArrays(GL_TRIANGLES, 0, rects.size()*2*3);
glDisableClientState(GL_VERTEX_ARRAY);
@@ -3106,8 +3102,8 @@ QGLTrapezoidMaskGenerator::QGLTrapezoidMaskGenerator(const QPainterPath &path, c
{
}
-extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array);
-extern void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array);
+extern void qt_add_rect_to_array(const QRectF &r, GLfloat *array);
+extern void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, GLfloat *array);
void QGLTrapezoidMaskGenerator::drawMask(const QRect &rect)
{
@@ -3138,7 +3134,7 @@ void QGLTrapezoidMaskGenerator::drawMask(const QRect &rect)
// clear mask
glBlendFunc(GL_ZERO, GL_ZERO); // clear
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
@@ -3369,7 +3365,7 @@ void QGLEllipseMaskGenerator::drawMask(const QRect &rect)
glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, maskVariableLocations[VAR_ELLIPSE_OFFSET], ellipse_offset);
glEnableClientState(GL_VERTEX_ARRAY);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisable(GL_FRAGMENT_PROGRAM_ARB);
@@ -3399,7 +3395,7 @@ void QOpenGLPaintEnginePrivate::drawFastRect(const QRectF &r)
Q_Q(QOpenGLPaintEngine);
DEBUG_ONCE_STR("QOpenGLPaintEngine::drawRects(): drawing fast rect");
- q_vertexType vertexArray[10];
+ GLfloat vertexArray[10];
qt_add_rect_to_array(r, vertexArray);
if (has_pen)
@@ -3420,7 +3416,7 @@ void QOpenGLPaintEnginePrivate::drawFastRect(const QRectF &r)
if (fast_style && has_fast_composition_mode) {
glEnableClientState(GL_VERTEX_ARRAY);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
} else {
@@ -3439,7 +3435,7 @@ void QOpenGLPaintEnginePrivate::drawFastRect(const QRectF &r)
vertexArray[8] = vertexArray[0];
vertexArray[9] = vertexArray[1];
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(GL_LINE_STRIP, 0, 5);
glDisableClientState(GL_VERTEX_ARRAY);
@@ -3546,7 +3542,7 @@ void QOpenGLPaintEngine::drawRects(const QRectF *rects, int rectCount)
}
}
-static void addQuadAsTriangle(q_vertexType *quad, q_vertexType *triangle)
+static void addQuadAsTriangle(GLfloat *quad, GLfloat *triangle)
{
triangle[0] = quad[0];
triangle[1] = quad[1];
@@ -3607,7 +3603,7 @@ void QOpenGLPaintEngine::drawPoints(const QPointF *points, int pointCount)
d->flushDrawQueue();
if (d->has_fast_pen) {
- QVarLengthArray<q_vertexType> vertexArray(6 * pointCount);
+ QVarLengthArray<GLfloat> vertexArray(6 * pointCount);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
@@ -3617,25 +3613,22 @@ void QOpenGLPaintEngine::drawPoints(const QPointF *points, int pointCount)
for (int i = 0; i < pointCount; ++i) {
QPointF mapped = d->matrix.map(points[i]);
- qreal xf = qRound(mapped.x());
- qreal yf = qRound(mapped.y());
-
- q_vertexType x = f2vt(xf);
- q_vertexType y = f2vt(yf);
+ GLfloat x = GLfloat(qRound(mapped.x()));
+ GLfloat y = GLfloat(qRound(mapped.y()));
vertexArray[j++] = x;
- vertexArray[j++] = y - f2vt(0.5);
+ vertexArray[j++] = y - 0.5f;
- vertexArray[j++] = x + f2vt(1.5);
- vertexArray[j++] = y + f2vt(1.0);
+ vertexArray[j++] = x + 1.5f;
+ vertexArray[j++] = y + 1.0f;
vertexArray[j++] = x;
- vertexArray[j++] = y + f2vt(1.0);
+ vertexArray[j++] = y + 1.0f;
}
glEnableClientState(GL_VERTEX_ARRAY);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray.constData());
glDrawArrays(GL_TRIANGLES, 0, pointCount*3);
glDisableClientState(GL_VERTEX_ARRAY);
@@ -3652,7 +3645,7 @@ void QOpenGLPaintEngine::drawPoints(const QPointF *points, int pointCount)
}
else {
Q_ASSERT(sizeof(QPointF) == 8);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
}
glEnableClientState(GL_VERTEX_ARRAY);
@@ -3720,47 +3713,47 @@ void QOpenGLPaintEngine::drawLines(const QLineF *lines, int lineCount)
}
}
- q_vertexType endCap = f2vt(d->cpen.capStyle() == Qt::FlatCap ? 0 : 0.5);
+ GLfloat endCap = d->cpen.capStyle() == Qt::FlatCap ? 0.0f : 0.5f;
if (useRects) {
- QVarLengthArray<q_vertexType> vertexArray(12 * lineCount);
+ QVarLengthArray<GLfloat> vertexArray(12 * lineCount);
- q_vertexType quad[8];
+ GLfloat quad[8];
for (int i = 0; i < lineCount; ++i) {
- q_vertexType x1 = f2vt(lines[i].x1());
- q_vertexType x2 = f2vt(lines[i].x2());
- q_vertexType y1 = f2vt(lines[i].y1());
- q_vertexType y2 = f2vt(lines[i].y2());
+ GLfloat x1 = lines[i].x1();
+ GLfloat x2 = lines[i].x2();
+ GLfloat y1 = lines[i].y1();
+ GLfloat y2 = lines[i].y2();
if (x1 == x2) {
if (y1 > y2)
qSwap(y1, y2);
- quad[0] = x1 - f2vt(0.5);
+ quad[0] = x1 - 0.5f;
quad[1] = y1 - endCap;
- quad[2] = x1 + f2vt(0.5);
+ quad[2] = x1 + 0.5f;
quad[3] = y1 - endCap;
- quad[4] = x1 + f2vt(0.5);
+ quad[4] = x1 + 0.5f;
quad[5] = y2 + endCap;
- quad[6] = x1 - f2vt(0.5);
+ quad[6] = x1 - 0.5f;
quad[7] = y2 + endCap;
} else {
if (x1 > x2)
qSwap(x1, x2);
quad[0] = x1 - endCap;
- quad[1] = y1 + f2vt(0.5);
+ quad[1] = y1 + 0.5f;
quad[2] = x1 - endCap;
- quad[3] = y1 - f2vt(0.5);
+ quad[3] = y1 - 0.5f;
quad[4] = x2 + endCap;
- quad[5] = y1 - f2vt(0.5);
+ quad[5] = y1 - 0.5f;
quad[6] = x2 + endCap;
- quad[7] = y1 + f2vt(0.5);
+ quad[7] = y1 + 0.5f;
}
addQuadAsTriangle(quad, &vertexArray[12*i]);
@@ -3768,26 +3761,26 @@ void QOpenGLPaintEngine::drawLines(const QLineF *lines, int lineCount)
glEnableClientState(GL_VERTEX_ARRAY);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray.constData());
glDrawArrays(GL_TRIANGLES, 0, lineCount*6);
glDisableClientState(GL_VERTEX_ARRAY);
} else {
- QVarLengthArray<q_vertexType> vertexArray(4 * lineCount);
+ QVarLengthArray<GLfloat> vertexArray(4 * lineCount);
for (int i = 0; i < lineCount; ++i) {
const QPointF a = lines[i].p1();
- vertexArray[4*i] = f2vt(lines[i].x1());
- vertexArray[4*i+1] = f2vt(lines[i].y1());
- vertexArray[4*i+2] = f2vt(lines[i].x2());
- vertexArray[4*i+3] = f2vt(lines[i].y2());
+ vertexArray[4*i] = lines[i].x1();
+ vertexArray[4*i+1] = lines[i].y1();
+ vertexArray[4*i+2] = lines[i].x2();
+ vertexArray[4*i+3] = lines[i].y2();
}
glEnableClientState(GL_VERTEX_ARRAY);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray.constData());
glDrawArrays(GL_LINES, 0, lineCount*2);
- glVertexPointer(2, q_vertexTypeEnum, 4*sizeof(q_vertexType), vertexArray.constData() + 2);
+ glVertexPointer(2, GL_FLOAT, 4*sizeof(GLfloat), vertexArray.constData() + 2);
glDrawArrays(GL_POINTS, 0, lineCount);
glDisableClientState(GL_VERTEX_ARRAY);
@@ -3874,7 +3867,7 @@ void QOpenGLPaintEngine::drawPolygon(const QPointF *points, int pointCount, Poly
}
else {
Q_ASSERT(sizeof(QPointF) == 8);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
}
glEnableClientState(GL_VERTEX_ARRAY);
@@ -3893,12 +3886,12 @@ void QOpenGLPaintEngine::drawPolygon(const QPointF *points, int pointCount, Poly
if (d->has_pen) {
if (d->has_fast_pen && !d->high_quality_antialiasing) {
d->setGradientOps(d->cpen.brush(), bounds);
- QVarLengthArray<q_vertexType> vertexArray(pointCount*2 + 2);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
+ QVarLengthArray<GLfloat> vertexArray(pointCount*2 + 2);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray.constData());
int i;
for (i=0; i<pointCount; ++i) {
- vertexArray[i*2] = f2vt(points[i].x());
- vertexArray[i*2+1] = f2vt(points[i].y());
+ vertexArray[i*2] = points[i].x();
+ vertexArray[i*2+1] = points[i].y();
}
glEnableClientState(GL_VERTEX_ARRAY);
@@ -4074,7 +4067,7 @@ void QOpenGLPaintEnginePrivate::strokePathFastPen(const QPainterPath &path, bool
switch (e.type) {
case QPainterPath::MoveToElement:
if (i != 0) {
- glVertexPointer(2, q_vertexTypeEnum, 0, tess_points.data());
+ glVertexPointer(2, GL_FLOAT, 0, tess_points.data());
glDrawArrays(GL_LINE_STRIP, 0, tess_points.size());
tess_points.reset();
}
@@ -4124,7 +4117,7 @@ void QOpenGLPaintEnginePrivate::strokePathFastPen(const QPainterPath &path, bool
break;
} // end of switch
}
- glVertexPointer(2, q_vertexTypeEnum, 0, tess_points.data());
+ glVertexPointer(2, GL_FLOAT, 0, tess_points.data());
glDrawArrays(GL_LINE_STRIP, 0, tess_points.size());
glDisableClientState(GL_VERTEX_ARRAY);
#endif
@@ -4391,8 +4384,8 @@ void QOpenGLPaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pm, con
glRotatef(180.0, 0.0, 0.0, 1.0);
}
- q_vertexType vertexArray[4*2];
- q_vertexType texCoordArray[4*2];
+ GLfloat vertexArray[4*2];
+ GLfloat texCoordArray[4*2];
double offset_x = offset.x() / pm.width();
double offset_y = offset.y() / pm.height();
@@ -4401,8 +4394,8 @@ void QOpenGLPaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pm, con
qt_add_texcoords_to_array(offset_x, offset_y,
tc_w + offset_x, tc_h + offset_y, texCoordArray);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
- glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
+ glTexCoordPointer(2, GL_FLOAT, 0, texCoordArray);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
@@ -4483,14 +4476,14 @@ void QOpenGLPaintEngine::drawTextureRect(int tx_width, int tx_height, const QRec
y2 = sr.y();
}
- q_vertexType vertexArray[4*2];
- q_vertexType texCoordArray[4*2];
+ GLfloat vertexArray[4*2];
+ GLfloat texCoordArray[4*2];
qt_add_rect_to_array(r, vertexArray);
qt_add_texcoords_to_array(x1, y2, x2, y1, texCoordArray);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
- glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
+ glTexCoordPointer(2, GL_FLOAT, 0, texCoordArray);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
@@ -4943,11 +4936,11 @@ void QOpenGLPaintEngine::drawTextItem(const QPointF &p, const QTextItem &textIte
#endif
// do the actual drawing
- q_vertexType vertexArray[4*2];
- q_vertexType texCoordArray[4*2];
+ GLfloat vertexArray[4*2];
+ GLfloat texCoordArray[4*2];
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
- glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
+ glTexCoordPointer(2, GL_FLOAT, 0, texCoordArray);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
@@ -5160,7 +5153,7 @@ void QOpenGLPaintEnginePrivate::composite(const QRectF &rect, const QPoint &mask
Q_UNUSED(rect);
Q_UNUSED(maskOffset);
#else
- q_vertexType vertexArray[8];
+ GLfloat vertexArray[8];
qt_add_rect_to_array(rect, vertexArray);
composite(GL_TRIANGLE_FAN, vertexArray, 4, maskOffset);
@@ -5168,7 +5161,7 @@ void QOpenGLPaintEnginePrivate::composite(const QRectF &rect, const QPoint &mask
}
-void QOpenGLPaintEnginePrivate::composite(GLuint primitive, const q_vertexType *vertexArray, int vertexCount, const QPoint &maskOffset)
+void QOpenGLPaintEnginePrivate::composite(GLuint primitive, const GLfloat *vertexArray, int vertexCount, const QPoint &maskOffset)
{
#ifdef QT_OPENGL_ES
Q_UNUSED(primitive);
@@ -5191,8 +5184,8 @@ void QOpenGLPaintEnginePrivate::composite(GLuint primitive, const q_vertexType *
qreal minX = 1e9, minY = 1e9, maxX = -1e9, maxY = -1e9;
for (int i = 0; i < vertexCount; ++i) {
- qreal x = vt2f(vertexArray[2 * i]);
- qreal y = vt2f(vertexArray[2 * i + 1]);
+ qreal x = vertexArray[2 * i];
+ qreal y = vertexArray[2 * i + 1];
qreal tx, ty;
matrix.map(x, y, &tx, &ty);
@@ -5251,7 +5244,7 @@ void QOpenGLPaintEnginePrivate::composite(GLuint primitive, const q_vertexType *
}
glEnableClientState(GL_VERTEX_ARRAY);
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
glEnable(GL_FRAGMENT_PROGRAM_ARB);
GLuint program = qt_gl_program_cache()->getProgram(device->context(),
fragment_brush,
diff --git a/src/opengl/qpixmapdata_x11gl_egl.cpp b/src/opengl/qpixmapdata_x11gl_egl.cpp
index 55aa1d0..edce56a 100644
--- a/src/opengl/qpixmapdata_x11gl_egl.cpp
+++ b/src/opengl/qpixmapdata_x11gl_egl.cpp
@@ -45,7 +45,7 @@
#include <private/qegl_p.h>
#include <private/qeglproperties_p.h>
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
#include <private/qpaintengineex_opengl2_p.h>
#endif
@@ -196,7 +196,7 @@ QX11GLPixmapData::~QX11GLPixmapData()
{
}
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_pixmap_2_engine)
#endif
@@ -220,7 +220,7 @@ QPaintEngine* QX11GLPixmapData::paintEngine() const
QPaintEngine* engine;
-#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_1_CL)
+#if defined(QT_OPENGL_ES_1)
engine = qt_gl_pixmap_engine();
#elif defined(QT_OPENGL_ES_2)
engine = qt_gl_pixmap_2_engine();
@@ -237,7 +237,7 @@ QPaintEngine* QX11GLPixmapData::paintEngine() const
if (engine->isActive()) {
qWarning("Pixmap paint engine already active");
-#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_1_CL)
+#if defined(QT_OPENGL_ES_1)
engine = new QOpenGLPaintEngine;
#elif defined(QT_OPENGL_ES_2)
engine = new QGL2PaintEngineEx;
diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp
index 7a565e6..4ac4a3a 100644
--- a/src/opengl/qwindowsurface_gl.cpp
+++ b/src/opengl/qwindowsurface_gl.cpp
@@ -82,10 +82,6 @@
#define GLX_SAMPLES_ARB 100001
#endif
-#ifdef QT_OPENGL_ES_1_CL
-#include "qgl_cl_p.h"
-#endif
-
#ifdef QT_OPENGL_ES
#include <private/qegl_p.h>
#endif
@@ -838,22 +834,22 @@ static void drawTexture(const QRectF &rect, GLuint tex_id, const QSize &texSize,
src.setBottom(src.bottom() / height);
}
- const q_vertexType tx1 = f2vt(src.left());
- const q_vertexType tx2 = f2vt(src.right());
- const q_vertexType ty1 = f2vt(src.top());
- const q_vertexType ty2 = f2vt(src.bottom());
+ const GLfloat tx1 = src.left();
+ const GLfloat tx2 = src.right();
+ const GLfloat ty1 = src.top();
+ const GLfloat ty2 = src.bottom();
- q_vertexType texCoordArray[4*2] = {
+ GLfloat texCoordArray[4*2] = {
tx1, ty2, tx2, ty2, tx2, ty1, tx1, ty1
};
- q_vertexType vertexArray[4*2];
- extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array); // qpaintengine_opengl.cpp
+ GLfloat vertexArray[4*2];
+ extern void qt_add_rect_to_array(const QRectF &r, GLfloat *array); // qpaintengine_opengl.cpp
qt_add_rect_to_array(rect, vertexArray);
#if !defined(QT_OPENGL_ES_2)
- glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
- glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
+ glVertexPointer(2, GL_FLOAT, 0, vertexArray);
+ glTexCoordPointer(2, GL_FLOAT, 0, texCoordArray);
glBindTexture(target, tex_id);
glEnable(target);
diff --git a/src/openvg/qpaintengine_vg.cpp b/src/openvg/qpaintengine_vg.cpp
index 6813d2f..18d6b0a 100644
--- a/src/openvg/qpaintengine_vg.cpp
+++ b/src/openvg/qpaintengine_vg.cpp
@@ -980,7 +980,7 @@ static QImage colorizeBitmap(const QImage &image, const QColor &color)
int height = sourceImage.height();
int width = sourceImage.width();
for (int y=0; y<height; ++y) {
- uchar *source = sourceImage.scanLine(y);
+ const uchar *source = sourceImage.constScanLine(y);
QRgb *target = reinterpret_cast<QRgb *>(dest.scanLine(y));
for (int x=0; x < width; ++x)
target[x] = (source[x>>3] >> (x&7)) & 1 ? fg : bg;
@@ -988,9 +988,6 @@ static QImage colorizeBitmap(const QImage &image, const QColor &color)
return dest;
}
-// defined in qpixmapdata_vg.cpp.
-const uchar *qt_vg_imageBits(const QImage& image);
-
static VGImage toVGImage
(const QImage & image, Qt::ImageConversionFlags flags = Qt::AutoColor)
{
@@ -1024,7 +1021,7 @@ static VGImage toVGImage
break;
}
- const uchar *pixels = qt_vg_imageBits(img);
+ const uchar *pixels = img.constBits();
VGImage vgImg = QVGImagePool::instance()->createPermanentImage
(format, img.width(), img.height(), VG_IMAGE_QUALITY_FASTER);
@@ -1068,7 +1065,7 @@ static VGImage toVGImageSubRect
break;
}
- const uchar *pixels = qt_vg_imageBits(img) + bpp * sr.x() +
+ const uchar *pixels = img.constBits() + bpp * sr.x() +
img.bytesPerLine() * sr.y();
VGImage vgImg = QVGImagePool::instance()->createPermanentImage
@@ -1090,7 +1087,7 @@ static VGImage toVGImageWithOpacity(const QImage & image, qreal opacity)
painter.drawImage(0, 0, image);
painter.end();
- const uchar *pixels = qt_vg_imageBits(img);
+ const uchar *pixels = img.constBits();
VGImage vgImg = QVGImagePool::instance()->createPermanentImage
(VG_sARGB_8888_PRE, img.width(), img.height(), VG_IMAGE_QUALITY_FASTER);
@@ -1112,7 +1109,7 @@ static VGImage toVGImageWithOpacitySubRect
painter.drawImage(QPoint(0, 0), image, sr);
painter.end();
- const uchar *pixels = qt_vg_imageBits(img);
+ const uchar *pixels = img.constBits();
VGImage vgImg = QVGImagePool::instance()->createPermanentImage
(VG_sARGB_8888_PRE, img.width(), img.height(), VG_IMAGE_QUALITY_FASTER);
@@ -3228,15 +3225,15 @@ void QVGFontGlyphCache::cacheGlyphs
if (!scaledImage.isNull()) { // Not a space character
if (scaledImage.format() == QImage::Format_Indexed8) {
vgImage = vgCreateImage(VG_A_8, scaledImage.width(), scaledImage.height(), VG_IMAGE_QUALITY_FASTER);
- vgImageSubData(vgImage, qt_vg_imageBits(scaledImage), scaledImage.bytesPerLine(), VG_A_8, 0, 0, scaledImage.width(), scaledImage.height());
+ vgImageSubData(vgImage, scaledImage.constBits(), scaledImage.bytesPerLine(), VG_A_8, 0, 0, scaledImage.width(), scaledImage.height());
} else if (scaledImage.format() == QImage::Format_Mono) {
QImage img = scaledImage.convertToFormat(QImage::Format_Indexed8);
vgImage = vgCreateImage(VG_A_8, img.width(), img.height(), VG_IMAGE_QUALITY_FASTER);
- vgImageSubData(vgImage, qt_vg_imageBits(img), img.bytesPerLine(), VG_A_8, 0, 0, img.width(), img.height());
+ vgImageSubData(vgImage, img.constBits(), img.bytesPerLine(), VG_A_8, 0, 0, img.width(), img.height());
} else {
QImage img = scaledImage.convertToFormat(QImage::Format_ARGB32_Premultiplied);
vgImage = vgCreateImage(VG_sARGB_8888_PRE, img.width(), img.height(), VG_IMAGE_QUALITY_FASTER);
- vgImageSubData(vgImage, qt_vg_imageBits(img), img.bytesPerLine(), VG_sARGB_8888_PRE, 0, 0, img.width(), img.height());
+ vgImageSubData(vgImage, img.constBits(), img.bytesPerLine(), VG_sARGB_8888_PRE, 0, 0, img.width(), img.height());
}
}
origin[0] = -metrics.x.toReal() + 0.5f;
@@ -3704,7 +3701,7 @@ void QVGCompositionHelper::drawCursorPixmap
if (vgImage == VG_INVALID_HANDLE)
return;
vgImageSubData
- (vgImage, qt_vg_imageBits(img) + img.bytesPerLine() * (img.height() - 1),
+ (vgImage, img.constBits() + img.bytesPerLine() * (img.height() - 1),
-(img.bytesPerLine()), VG_sARGB_8888_PRE, 0, 0,
img.width(), img.height());
diff --git a/src/openvg/qpixmapdata_vg.cpp b/src/openvg/qpixmapdata_vg.cpp
index 3087b77..44814cc 100644
--- a/src/openvg/qpixmapdata_vg.cpp
+++ b/src/openvg/qpixmapdata_vg.cpp
@@ -231,14 +231,6 @@ QPaintEngine* QVGPixmapData::paintEngine() const
return source.paintEngine();
}
-// This function works around QImage::bits() making a deep copy if the
-// QImage is not const. We force it to be const and then get the bits.
-// XXX: Should add a QImage::constBits() in the future to replace this.
-const uchar *qt_vg_imageBits(const QImage& image)
-{
- return image.bits();
-}
-
VGImage QVGPixmapData::toVGImage()
{
if (!isValid())
@@ -271,7 +263,7 @@ VGImage QVGPixmapData::toVGImage()
if (!source.isNull() && recreate) {
vgImageSubData
(vgImage,
- qt_vg_imageBits(source), source.bytesPerLine(),
+ source.constBits(), source.bytesPerLine(),
VG_sARGB_8888_PRE, 0, 0, w, h);
}
@@ -670,7 +662,7 @@ void* QVGPixmapData::toNativeType(NativeType type)
if (bitmap) {
if (bitmap->Create(TSize(source.width(), source.height()),
EColor16MAP) == KErrNone) {
- const uchar *sptr = qt_vg_imageBits(source);
+ const uchar *sptr = source.constBits();
bitmap->BeginDataAccess();
uchar *dptr = (uchar*)bitmap->DataAddress();
diff --git a/src/plugins/accessible/widgets/qaccessiblewidgets.cpp b/src/plugins/accessible/widgets/qaccessiblewidgets.cpp
index ad33d0b..499eb1d 100644
--- a/src/plugins/accessible/widgets/qaccessiblewidgets.cpp
+++ b/src/plugins/accessible/widgets/qaccessiblewidgets.cpp
@@ -176,7 +176,7 @@ static inline QWidget *mdiAreaNavigate(QWidget *area,
int minimumDistance = INT_MAX;
QWidget *target = 0;
- foreach (QWidget *candidate, candidates.values()) {
+ foreach (QWidget *candidate, candidates) {
switch (relation) {
case QAccessible::Up:
case QAccessible::Down:
diff --git a/src/plugins/graphicssystems/opengl/main.cpp b/src/plugins/graphicssystems/opengl/main.cpp
index 19631b6..abcfb7f 100644
--- a/src/plugins/graphicssystems/opengl/main.cpp
+++ b/src/plugins/graphicssystems/opengl/main.cpp
@@ -56,7 +56,7 @@ QStringList QGLGraphicsSystemPlugin::keys() const
{
QStringList list;
list << QLatin1String("OpenGL") << QLatin1String("OpenGL1");
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
list << QLatin1String("OpenGL2");
#endif
return list;
@@ -69,7 +69,7 @@ QGraphicsSystem* QGLGraphicsSystemPlugin::create(const QString& system)
return new QGLGraphicsSystem;
}
-#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
+#if !defined(QT_OPENGL_ES_1)
if (system.toLower() == QLatin1String("opengl2")) {
QGL::setPreferredPaintEngine(QPaintEngine::OpenGL2);
return new QGLGraphicsSystem;
diff --git a/src/plugins/imageformats/jpeg/qjpeghandler.cpp b/src/plugins/imageformats/jpeg/qjpeghandler.cpp
index 6cb93ad..4b4712c 100644
--- a/src/plugins/imageformats/jpeg/qjpeghandler.cpp
+++ b/src/plugins/imageformats/jpeg/qjpeghandler.cpp
@@ -52,8 +52,6 @@
#undef FAR
#endif
-// hw: optimize smoothscaler for returning 24-bit images
-
// including jpeglib.h seems to be a little messy
extern "C" {
// mingw includes rpcndr.h but does not define boolean
@@ -76,433 +74,6 @@ extern "C" {
QT_BEGIN_NAMESPACE
-//#define QT_NO_IMAGE_SMOOTHSCALE
-#ifndef QT_NO_IMAGE_SMOOTHSCALE
-class QImageSmoothScalerPrivate;
-class QImageSmoothScaler
-{
-public:
- QImageSmoothScaler(const int w, const int h, const QImage &src);
- QImageSmoothScaler(const int srcWidth, const int srcHeight,
- const int dstWidth, const int dstHeight);
-
- virtual ~QImageSmoothScaler(void);
-
- QImage scale();
-
-private:
- QImageSmoothScalerPrivate *d;
- virtual QRgb *scanLine(const int line = 0, const QImage *src = 0);
-};
-
-class QImageSmoothScalerPrivate
-{
-public:
- int cols;
- int newcols;
- int rows;
- int newrows;
- bool hasAlpha;
-
- const QImage *src;
-
- void setup(const int srcWidth, const int srcHeight, const int dstWidth,
- const int dstHeight, bool hasAlphaChannel);
-};
-
-QImageSmoothScaler::QImageSmoothScaler(const int w, const int h,
- const QImage &src)
-{
- d = new QImageSmoothScalerPrivate;
-
- d->setup(src.width(), src.height(), w, h, src.hasAlphaChannel() );
- this->d->src = &src;
-}
-
-QImageSmoothScaler::QImageSmoothScaler(const int srcWidth, const int srcHeight,
- const int dstWidth, const int dstHeight)
-{
- d = new QImageSmoothScalerPrivate;
- d->setup(srcWidth, srcHeight, dstWidth, dstHeight, 0);
-}
-
-void QImageSmoothScalerPrivate::setup(const int srcWidth, const int srcHeight,
- const int dstWidth, const int dstHeight,
- bool hasAlphaChannel)
-{
- cols = srcWidth;
- rows = srcHeight;
- newcols = dstWidth;
- newrows = dstHeight;
- hasAlpha = hasAlphaChannel;
-}
-
-QImageSmoothScaler::~QImageSmoothScaler()
-{
- delete d;
-}
-
-inline QRgb *QImageSmoothScaler::scanLine(const int line, const QImage *src)
-{
- return (QRgb*)src->scanLine(line);
-}
-
-/*
- This function uses code based on pnmscale.c by Jef Poskanzer.
-
- pnmscale.c - read a portable anymap and scale it
-
- Copyright (C) 1989, 1991 by Jef Poskanzer.
-
- Permission to use, copy, modify, and distribute this software and its
- documentation for any purpose and without fee is hereby granted, provided
- that the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation. This software is provided "as is" without express or
- implied warranty.
-*/
-
-QImage QImageSmoothScaler::scale()
-{
- long SCALE;
- long HALFSCALE;
- QRgb *xelrow = 0;
- QRgb *tempxelrow = 0;
- QRgb *xP;
- QRgb *nxP;
- int row, rowsread;
- int col, needtoreadrow;
- uchar maxval = 255;
- qreal xscale, yscale;
- long sxscale, syscale;
- long fracrowtofill, fracrowleft;
- long *as;
- long *rs;
- long *gs;
- long *bs;
- int rowswritten = 0;
- QImage dst;
-
- if (d->cols > 4096) {
- SCALE = 4096;
- HALFSCALE = 2048;
- } else {
- int fac = 4096;
- while (d->cols * fac > 4096)
- fac /= 2;
-
- SCALE = fac * d->cols;
- HALFSCALE = fac * d->cols / 2;
- }
-
- xscale = (qreal)d->newcols / (qreal)d->cols;
- yscale = (qreal)d->newrows / (qreal)d->rows;
- sxscale = (long)(xscale * SCALE);
- syscale = (long)(yscale * SCALE);
-
- // shortcut Y scaling if possible
- if (d->newrows != d->rows)
- tempxelrow = new QRgb[d->cols];
-
- if (d->hasAlpha) {
- as = new long[d->cols];
- for (col = 0; col < d->cols; ++col)
- as[col] = HALFSCALE;
- } else {
- as = 0;
- }
- rs = new long[d->cols];
- gs = new long[d->cols];
- bs = new long[d->cols];
- rowsread = 0;
- fracrowleft = syscale;
- needtoreadrow = 1;
- for (col = 0; col < d->cols; ++col)
- rs[col] = gs[col] = bs[col] = HALFSCALE;
- fracrowtofill = SCALE;
-
- dst = QImage(d->newcols, d->newrows, d->hasAlpha ? QImage::Format_ARGB32 : QImage::Format_RGB32);
-
- for (row = 0; row < d->newrows; ++row) {
- // First scale Y from xelrow into tempxelrow.
- if (d->newrows == d->rows) {
- // shortcut Y scaling if possible
- tempxelrow = xelrow = scanLine(rowsread++, d->src);
- } else {
- while (fracrowleft < fracrowtofill) {
- if (needtoreadrow && rowsread < d->rows)
- xelrow = scanLine(rowsread++, d->src);
- for (col = 0, xP = xelrow; col < d->cols; ++col, ++xP) {
- if (as) {
- as[col] += fracrowleft * qAlpha(*xP);
- rs[col] += fracrowleft * qRed(*xP) * qAlpha(*xP) / 255;
- gs[col] += fracrowleft * qGreen(*xP) * qAlpha(*xP) / 255;
- bs[col] += fracrowleft * qBlue(*xP) * qAlpha(*xP) / 255;
- } else {
- rs[col] += fracrowleft * qRed(*xP);
- gs[col] += fracrowleft * qGreen(*xP);
- bs[col] += fracrowleft * qBlue(*xP);
- }
- }
- fracrowtofill -= fracrowleft;
- fracrowleft = syscale;
- needtoreadrow = 1;
- }
- // Now fracrowleft is >= fracrowtofill, so we can produce a row.
- if (needtoreadrow && rowsread < d->rows) {
- xelrow = scanLine(rowsread++, d->src);
- needtoreadrow = 0;
- }
- for (col = 0, xP = xelrow, nxP = tempxelrow; col < d->cols; ++col, ++xP, ++nxP) {
- register long a, r, g, b;
-
- if (as) {
- r = rs[col] + fracrowtofill * qRed(*xP) * qAlpha(*xP) / 255;
- g = gs[col] + fracrowtofill * qGreen(*xP) * qAlpha(*xP) / 255;
- b = bs[col] + fracrowtofill * qBlue(*xP) * qAlpha(*xP) / 255;
- a = as[col] + fracrowtofill * qAlpha(*xP);
- if (a) {
- r = r * 255 / a * SCALE;
- g = g * 255 / a * SCALE;
- b = b * 255 / a * SCALE;
- }
- } else {
- r = rs[col] + fracrowtofill * qRed(*xP);
- g = gs[col] + fracrowtofill * qGreen(*xP);
- b = bs[col] + fracrowtofill * qBlue(*xP);
- a = 0; // unwarn
- }
- r /= SCALE;
- if (r > maxval)
- r = maxval;
- g /= SCALE;
- if (g > maxval)
- g = maxval;
- b /= SCALE;
- if (b > maxval)
- b = maxval;
- if (as) {
- a /= SCALE;
- if (a > maxval)
- a = maxval;
- *nxP = qRgba((int)r, (int)g, (int)b, (int)a);
- as[col] = HALFSCALE;
- } else {
- *nxP = qRgb((int)r, (int)g, (int)b);
- }
- rs[col] = gs[col] = bs[col] = HALFSCALE;
- }
- fracrowleft -= fracrowtofill;
- if (fracrowleft == 0) {
- fracrowleft = syscale;
- needtoreadrow = 1;
- }
- fracrowtofill = SCALE;
- }
-
- // Now scale X from tempxelrow into dst and write it out.
- if (d->newcols == d->cols) {
- // shortcut X scaling if possible
- memcpy(dst.scanLine(rowswritten++), tempxelrow, d->newcols * 4);
- } else {
- register long a, r, g, b;
- register long fraccoltofill, fraccolleft = 0;
- register int needcol;
-
- nxP = (QRgb *)dst.scanLine(rowswritten++);
- QRgb *nxPEnd = nxP + d->newcols;
- fraccoltofill = SCALE;
- a = r = g = b = HALFSCALE;
- needcol = 0;
- for (col = 0, xP = tempxelrow; col < d->cols; ++col, ++xP) {
- fraccolleft = sxscale;
- while (fraccolleft >= fraccoltofill) {
- if (needcol) {
- ++nxP;
- a = r = g = b = HALFSCALE;
- }
- if (as) {
- r += fraccoltofill * qRed(*xP) * qAlpha(*xP) / 255;
- g += fraccoltofill * qGreen(*xP) * qAlpha(*xP) / 255;
- b += fraccoltofill * qBlue(*xP) * qAlpha(*xP) / 255;
- a += fraccoltofill * qAlpha(*xP);
- if (a) {
- r = r * 255 / a * SCALE;
- g = g * 255 / a * SCALE;
- b = b * 255 / a * SCALE;
- }
- } else {
- r += fraccoltofill * qRed(*xP);
- g += fraccoltofill * qGreen(*xP);
- b += fraccoltofill * qBlue(*xP);
- }
- r /= SCALE;
- if (r > maxval)
- r = maxval;
- g /= SCALE;
- if (g > maxval)
- g = maxval;
- b /= SCALE;
- if (b > maxval)
- b = maxval;
- if (as) {
- a /= SCALE;
- if (a > maxval)
- a = maxval;
- *nxP = qRgba((int)r, (int)g, (int)b, (int)a);
- } else {
- *nxP = qRgb((int)r, (int)g, (int)b);
- }
- fraccolleft -= fraccoltofill;
- fraccoltofill = SCALE;
- needcol = 1;
- }
- if (fraccolleft > 0) {
- if (needcol) {
- ++nxP;
- a = r = g = b = HALFSCALE;
- needcol = 0;
- }
- if (as) {
- a += fraccolleft * qAlpha(*xP);
- r += fraccolleft * qRed(*xP) * qAlpha(*xP) / 255;
- g += fraccolleft * qGreen(*xP) * qAlpha(*xP) / 255;
- b += fraccolleft * qBlue(*xP) * qAlpha(*xP) / 255;
- } else {
- r += fraccolleft * qRed(*xP);
- g += fraccolleft * qGreen(*xP);
- b += fraccolleft * qBlue(*xP);
- }
- fraccoltofill -= fraccolleft;
- }
- }
- if (fraccoltofill > 0) {
- --xP;
- if (as) {
- a += fraccolleft * qAlpha(*xP);
- r += fraccoltofill * qRed(*xP) * qAlpha(*xP) / 255;
- g += fraccoltofill * qGreen(*xP) * qAlpha(*xP) / 255;
- b += fraccoltofill * qBlue(*xP) * qAlpha(*xP) / 255;
- if (a) {
- r = r * 255 / a * SCALE;
- g = g * 255 / a * SCALE;
- b = b * 255 / a * SCALE;
- }
- } else {
- r += fraccoltofill * qRed(*xP);
- g += fraccoltofill * qGreen(*xP);
- b += fraccoltofill * qBlue(*xP);
- }
- }
- if (nxP < nxPEnd) {
- r /= SCALE;
- if (r > maxval)
- r = maxval;
- g /= SCALE;
- if (g > maxval)
- g = maxval;
- b /= SCALE;
- if (b > maxval)
- b = maxval;
- if (as) {
- a /= SCALE;
- if (a > maxval)
- a = maxval;
- *nxP = qRgba((int)r, (int)g, (int)b, (int)a);
- } else {
- *nxP = qRgb((int)r, (int)g, (int)b);
- }
- while (++nxP != nxPEnd)
- nxP[0] = nxP[-1];
- }
- }
- }
-
- if (d->newrows != d->rows && tempxelrow)// Robust, tempxelrow might be 0 1 day
- delete [] tempxelrow;
- if (as) // Avoid purify complaint
- delete [] as;
- if (rs) // Robust, rs might be 0 one day
- delete [] rs;
- if (gs) // Robust, gs might be 0 one day
- delete [] gs;
- if (bs) // Robust, bs might be 0 one day
- delete [] bs;
-
- return dst;
-}
-
-class jpegSmoothScaler : public QImageSmoothScaler
-{
-public:
- jpegSmoothScaler(struct jpeg_decompress_struct *info, const QSize& dstSize, const QRect& clipRect)
- : QImageSmoothScaler(clipRect.width(), clipRect.height(),
- dstSize.width(), dstSize.height())
- {
- cinfo = info;
- clip = clipRect;
- imageCache = QImage(info->output_width, 1, QImage::Format_RGB32);
- }
-
-private:
- QRect clip;
- QImage imageCache;
- struct jpeg_decompress_struct *cinfo;
-
- QRgb *scanLine(const int line = 0, const QImage *src = 0)
- {
- QRgb *out;
- uchar *in;
-
- Q_UNUSED(line);
- Q_UNUSED(src);
-
- uchar* data = imageCache.bits();
-
- // Read ahead if we haven't reached the first clipped scanline yet.
- while (int(cinfo->output_scanline) < clip.y() &&
- cinfo->output_scanline < cinfo->output_height)
- jpeg_read_scanlines(cinfo, &data, 1);
-
- // Read the next scanline. We assume that "line"
- // will never be >= clip.height().
- jpeg_read_scanlines(cinfo, &data, 1);
- if (cinfo->output_scanline == cinfo->output_height)
- jpeg_finish_decompress(cinfo);
-
- out = ((QRgb*)data) + clip.x();
-
- //
- // The smooth scale algorithm only works on 32-bit images;
- // convert from (8|24) bits to 32.
- //
- if (cinfo->output_components == 1) {
- in = data + clip.right();
- for (int i = clip.width(); i--; ) {
- out[i] = qRgb(*in, *in, *in);
- in--;
- }
- } else if (cinfo->out_color_space == JCS_CMYK) {
- in = data + clip.right() * 4;
- for (int i = clip.width(); i--; ) {
- int k = in[3];
- out[i] = qRgb(k * in[0] / 255, k * in[1] / 255, k * in[2] / 255);
- in -= 4;
- }
- } else {
- in = data + clip.right() * 3;
- for (int i = clip.width(); i--; ) {
- out[i] = qRgb(in[0], in[1], in[2]);
- in -= 3;
- }
- }
-
- return out;
- }
-
-};
-#endif
-
struct my_error_mgr : public jpeg_error_mgr {
jmp_buf setjmp_buffer;
};
@@ -844,93 +415,82 @@ static bool read_jpeg_image(QIODevice *device, QImage *outImage,
clip = clip.intersected(imageRect);
}
-#ifndef QT_NO_IMAGE_SMOOTHSCALE
- if (scaledSize.isValid() && scaledSize != clip.size()
- && quality >= HIGH_QUALITY_THRESHOLD) {
+ // Allocate memory for the clipped QImage.
+ if (!ensureValidImage(outImage, &cinfo, clip.size()))
+ longjmp(jerr.setjmp_buffer, 1);
+
+ // Avoid memcpy() overhead if grayscale with no clipping.
+ bool quickGray = (cinfo.output_components == 1 &&
+ clip == imageRect);
+ if (!quickGray) {
+ // Ask the jpeg library to allocate a temporary row.
+ // The library will automatically delete it for us later.
+ // The libjpeg docs say we should do this before calling
+ // jpeg_start_decompress(). We can't use "new" here
+ // because we are inside the setjmp() block and an error
+ // in the jpeg input stream would cause a memory leak.
+ JSAMPARRAY rows = (cinfo.mem->alloc_sarray)
+ ((j_common_ptr)&cinfo, JPOOL_IMAGE,
+ cinfo.output_width * cinfo.output_components, 1);
(void) jpeg_start_decompress(&cinfo);
- jpegSmoothScaler scaler(&cinfo, scaledSize, clip);
- *outImage = scaler.scale();
- } else
-#endif
- {
- // Allocate memory for the clipped QImage.
- if (!ensureValidImage(outImage, &cinfo, clip.size()))
- longjmp(jerr.setjmp_buffer, 1);
-
- // Avoid memcpy() overhead if grayscale with no clipping.
- bool quickGray = (cinfo.output_components == 1 &&
- clip == imageRect);
- if (!quickGray) {
- // Ask the jpeg library to allocate a temporary row.
- // The library will automatically delete it for us later.
- // The libjpeg docs say we should do this before calling
- // jpeg_start_decompress(). We can't use "new" here
- // because we are inside the setjmp() block and an error
- // in the jpeg input stream would cause a memory leak.
- JSAMPARRAY rows = (cinfo.mem->alloc_sarray)
- ((j_common_ptr)&cinfo, JPOOL_IMAGE,
- cinfo.output_width * cinfo.output_components, 1);
-
- (void) jpeg_start_decompress(&cinfo);
-
- while (cinfo.output_scanline < cinfo.output_height) {
- int y = int(cinfo.output_scanline) - clip.y();
- if (y >= clip.height())
- break; // We've read the entire clip region, so abort.
-
- (void) jpeg_read_scanlines(&cinfo, rows, 1);
-
- if (y < 0)
- continue; // Haven't reached the starting line yet.
-
- if (cinfo.output_components == 3) {
- // Expand 24->32 bpp.
- uchar *in = rows[0] + clip.x() * 3;
- QRgb *out = (QRgb*)outImage->scanLine(y);
- for (int i = 0; i < clip.width(); ++i) {
- *out++ = qRgb(in[0], in[1], in[2]);
- in += 3;
- }
- } else if (cinfo.out_color_space == JCS_CMYK) {
- // Convert CMYK->RGB.
- uchar *in = rows[0] + clip.x() * 4;
- QRgb *out = (QRgb*)outImage->scanLine(y);
- for (int i = 0; i < clip.width(); ++i) {
- int k = in[3];
- *out++ = qRgb(k * in[0] / 255, k * in[1] / 255,
- k * in[2] / 255);
- in += 4;
- }
- } else if (cinfo.output_components == 1) {
- // Grayscale.
- memcpy(outImage->scanLine(y),
- rows[0] + clip.x(), clip.width());
+ while (cinfo.output_scanline < cinfo.output_height) {
+ int y = int(cinfo.output_scanline) - clip.y();
+ if (y >= clip.height())
+ break; // We've read the entire clip region, so abort.
+
+ (void) jpeg_read_scanlines(&cinfo, rows, 1);
+
+ if (y < 0)
+ continue; // Haven't reached the starting line yet.
+
+ if (cinfo.output_components == 3) {
+ // Expand 24->32 bpp.
+ uchar *in = rows[0] + clip.x() * 3;
+ QRgb *out = (QRgb*)outImage->scanLine(y);
+ for (int i = 0; i < clip.width(); ++i) {
+ *out++ = qRgb(in[0], in[1], in[2]);
+ in += 3;
}
- }
- } else {
- // Load unclipped grayscale data directly into the QImage.
- (void) jpeg_start_decompress(&cinfo);
- while (cinfo.output_scanline < cinfo.output_height) {
- uchar *row = outImage->scanLine(cinfo.output_scanline);
- (void) jpeg_read_scanlines(&cinfo, &row, 1);
+ } else if (cinfo.out_color_space == JCS_CMYK) {
+ // Convert CMYK->RGB.
+ uchar *in = rows[0] + clip.x() * 4;
+ QRgb *out = (QRgb*)outImage->scanLine(y);
+ for (int i = 0; i < clip.width(); ++i) {
+ int k = in[3];
+ *out++ = qRgb(k * in[0] / 255, k * in[1] / 255,
+ k * in[2] / 255);
+ in += 4;
+ }
+ } else if (cinfo.output_components == 1) {
+ // Grayscale.
+ memcpy(outImage->scanLine(y),
+ rows[0] + clip.x(), clip.width());
}
}
+ } else {
+ // Load unclipped grayscale data directly into the QImage.
+ (void) jpeg_start_decompress(&cinfo);
+ while (cinfo.output_scanline < cinfo.output_height) {
+ uchar *row = outImage->scanLine(cinfo.output_scanline);
+ (void) jpeg_read_scanlines(&cinfo, &row, 1);
+ }
+ }
- if (cinfo.output_scanline == cinfo.output_height)
- (void) jpeg_finish_decompress(&cinfo);
+ if (cinfo.output_scanline == cinfo.output_height)
+ (void) jpeg_finish_decompress(&cinfo);
- if (cinfo.density_unit == 1) {
- outImage->setDotsPerMeterX(int(100. * cinfo.X_density / 2.54));
- outImage->setDotsPerMeterY(int(100. * cinfo.Y_density / 2.54));
- } else if (cinfo.density_unit == 2) {
- outImage->setDotsPerMeterX(int(100. * cinfo.X_density));
- outImage->setDotsPerMeterY(int(100. * cinfo.Y_density));
- }
+ if (cinfo.density_unit == 1) {
+ outImage->setDotsPerMeterX(int(100. * cinfo.X_density / 2.54));
+ outImage->setDotsPerMeterY(int(100. * cinfo.Y_density / 2.54));
+ } else if (cinfo.density_unit == 2) {
+ outImage->setDotsPerMeterX(int(100. * cinfo.X_density));
+ outImage->setDotsPerMeterY(int(100. * cinfo.Y_density));
+ }
- if (scaledSize.isValid() && scaledSize != clip.size())
- *outImage = outImage->scaled(scaledSize, Qt::IgnoreAspectRatio, Qt::FastTransformation);
+ if (scaledSize.isValid() && scaledSize != clip.size()) {
+ *outImage = outImage->scaled(scaledSize, Qt::IgnoreAspectRatio, quality >= HIGH_QUALITY_THRESHOLD ? Qt::SmoothTransformation : Qt::FastTransformation);
}
}
diff --git a/src/plugins/phonon/ds9/ds9.pro b/src/plugins/phonon/ds9/ds9.pro
index 786338a..301808e 100644
--- a/src/plugins/phonon/ds9/ds9.pro
+++ b/src/plugins/phonon/ds9/ds9.pro
@@ -22,7 +22,6 @@ HEADERS += \
$$PHONON_DS9_DIR/mediaobject.h \
$$PHONON_DS9_DIR/videowidget.h \
$$PHONON_DS9_DIR/videorenderer_soft.h \
- $$PHONON_DS9_DIR/videorenderer_vmr9.h \
$$PHONON_DS9_DIR/volumeeffect.h \
$$PHONON_DS9_DIR/qbasefilter.h \
$$PHONON_DS9_DIR/qpin.h \
@@ -45,7 +44,6 @@ SOURCES += \
$$PHONON_DS9_DIR/mediaobject.cpp \
$$PHONON_DS9_DIR/videowidget.cpp \
$$PHONON_DS9_DIR/videorenderer_soft.cpp \
- $$PHONON_DS9_DIR/videorenderer_vmr9.cpp \
$$PHONON_DS9_DIR/volumeeffect.cpp \
$$PHONON_DS9_DIR/qbasefilter.cpp \
$$PHONON_DS9_DIR/qpin.cpp \
@@ -53,6 +51,14 @@ SOURCES += \
$$PHONON_DS9_DIR/qaudiocdreader.cpp \
$$PHONON_DS9_DIR/qmeminputpin.cpp
+#the EVR renderer (only available on desktop)
+!wince*:SOURCES += $$PHONON_DS9_DIR/videorenderer_evr.cpp \
+ $$PHONON_DS9_DIR/videorenderer_vmr9.cpp
+!wince*:HEADERS += $$PHONON_DS9_DIR/qevr9.h \
+ $$PHONON_DS9_DIR/videorenderer_evr.h \
+ $$PHONON_DS9_DIR/videorenderer_vmr9.h
+wince*:SOURCES += $$PHONON_DS9_DIR/videorenderer_default.cpp
+wince*:HEADERS += $$PHONON_DS9_DIR/videorenderer_default.h
target.path = $$[QT_INSTALL_PLUGINS]/phonon_backend
INSTALLS += target
diff --git a/src/plugins/qpluginbase.pri b/src/plugins/qpluginbase.pri
index 3af8b40..3dd3d2e 100644
--- a/src/plugins/qpluginbase.pri
+++ b/src/plugins/qpluginbase.pri
@@ -1,6 +1,6 @@
TEMPLATE = lib
isEmpty(QT_MAJOR_VERSION) {
- VERSION=4.6.2
+ VERSION=4.7.0
} else {
VERSION=$${QT_MAJOR_VERSION}.$${QT_MINOR_VERSION}.$${QT_PATCH_VERSION}
}
diff --git a/src/qbase.pri b/src/qbase.pri
index 710a2b6..58bb6d4 100644
--- a/src/qbase.pri
+++ b/src/qbase.pri
@@ -4,7 +4,7 @@ INCLUDEPATH *= $$QMAKE_INCDIR_QT/$$TARGET #just for today to have some compat
isEmpty(QT_ARCH):!isEmpty(ARCH):QT_ARCH=$$ARCH #another compat that will rot for change #215700
TEMPLATE = lib
isEmpty(QT_MAJOR_VERSION) {
- VERSION=4.6.2
+ VERSION=4.7.0
} else {
VERSION=$${QT_MAJOR_VERSION}.$${QT_MINOR_VERSION}.$${QT_PATCH_VERSION}
}
diff --git a/src/s60installs/qt.iby b/src/s60installs/qt.iby
index bdd668c..a6a96ec 100644
--- a/src/s60installs/qt.iby
+++ b/src/s60installs/qt.iby
@@ -113,6 +113,7 @@ data=\epoc32\data\z\resource\qt\plugins\phonon_backend\phonon_mmf.qtplugin resou
data=\epoc32\data\z\resource\qt\plugins\graphicssystems\qvggraphicssystem.qtplugin resource\qt\plugins\graphicssystems\qvggraphicssystem.qtplugin
// Stub sis file
-data=ZSYSTEM\install\qt.sis System\Install\qt.sis
+data=ZSYSTEM\install\qt_stub.sis System\Install\qt_stub.sis
+data=ZSYSTEM\install\qtwebkit_stub.sis System\Install\qtwebkit_stub.sis
#endif // __QT_IBY__
diff --git a/src/script/api/qscriptprogram.cpp b/src/script/api/qscriptprogram.cpp
index c452052..d4a32f4 100644
--- a/src/script/api/qscriptprogram.cpp
+++ b/src/script/api/qscriptprogram.cpp
@@ -63,7 +63,6 @@ QScriptProgramPrivate::QScriptProgramPrivate(const QString &src,
QScriptProgramPrivate::~QScriptProgramPrivate()
{
- delete _executable;
}
QScriptProgramPrivate *QScriptProgramPrivate::get(const QScriptProgram &q)
@@ -76,17 +75,17 @@ JSC::EvalExecutable *QScriptProgramPrivate::executable(JSC::ExecState *exec,
{
if (_executable) {
if (eng == engine)
- return _executable;
- delete _executable;
+ return _executable.get();
+ _executable = 0;
}
WTF::PassRefPtr<QScript::UStringSourceProviderWithFeedback> provider
= QScript::UStringSourceProviderWithFeedback::create(sourceCode, fileName, firstLineNumber, eng);
sourceId = provider->asID();
JSC::SourceCode source(provider, firstLineNumber); //after construction of SourceCode provider variable will be null.
- _executable = new JSC::EvalExecutable(exec, source);
+ _executable = JSC::EvalExecutable::create(exec, source);
engine = eng;
isCompiled = false;
- return _executable;
+ return _executable.get();
}
/*!
diff --git a/src/script/api/qscriptprogram_p.h b/src/script/api/qscriptprogram_p.h
index 427ab34..95e75fd 100644
--- a/src/script/api/qscriptprogram_p.h
+++ b/src/script/api/qscriptprogram_p.h
@@ -37,6 +37,8 @@
#include <QtCore/qobjectdefs.h>
+#include "RefPtr.h"
+
namespace JSC
{
class EvalExecutable;
@@ -67,7 +69,7 @@ public:
int firstLineNumber;
QScriptEnginePrivate *engine;
- JSC::EvalExecutable *_executable;
+ WTF::RefPtr<JSC::EvalExecutable> _executable;
intptr_t sourceId;
bool isCompiled;
};
diff --git a/src/script/bridge/qscriptdeclarativeclass.cpp b/src/script/bridge/qscriptdeclarativeclass.cpp
index 24037e1..ce2fc23 100644
--- a/src/script/bridge/qscriptdeclarativeclass.cpp
+++ b/src/script/bridge/qscriptdeclarativeclass.cpp
@@ -35,7 +35,113 @@
QT_BEGIN_NAMESPACE
+/*!
+\class QScriptDeclarativeClass::Value
+\internal
+\brief The QScriptDeclarativeClass::Value class acts as a container for JavaScript data types.
+
+QScriptDeclarativeClass::Value class is similar to QScriptValue, but it is slightly faster.
+Unlike QScriptValue, however, Value instances cannot be stored as they may not survive garbage
+collection. If you need to store a Value, convert it to a QScriptValue and store that.
+*/
+
+QScriptDeclarativeClass::Value::Value()
+{
+ new (this) JSC::JSValue(JSC::jsUndefined());
+}
+
+QScriptDeclarativeClass::Value::Value(const Value &other)
+{
+ new (this) JSC::JSValue((JSC::JSValue &)other);
+}
+
+static QScriptDeclarativeClass::Value jscToValue(const JSC::JSValue &val)
+{
+ return QScriptDeclarativeClass::Value((QScriptDeclarativeClass::Value &)val);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptContext *ctxt, int value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::frameForContext(ctxt), value);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptContext *ctxt, uint value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::frameForContext(ctxt), value);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptContext *ctxt, bool value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::frameForContext(ctxt), value);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptContext *ctxt, double value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::frameForContext(ctxt), value);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptContext *ctxt, float value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::frameForContext(ctxt), value);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptContext *ctxt, const QString &value)
+{
+ new (this) JSC::JSValue(JSC::jsString(QScriptEnginePrivate::frameForContext(ctxt), value));
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptContext *ctxt, const QScriptValue &value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::get(ctxt->engine())->scriptValueToJSCValue(value));
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptEngine *eng, int value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::get(eng)->currentFrame, value);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptEngine *eng, uint value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::get(eng)->currentFrame, value);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptEngine *eng, bool value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::get(eng)->currentFrame, value);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptEngine *eng, double value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::get(eng)->currentFrame, value);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptEngine *eng, float value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::get(eng)->currentFrame, value);
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptEngine *eng, const QString &value)
+{
+ new (this) JSC::JSValue(JSC::jsString(QScriptEnginePrivate::get(eng)->currentFrame, value));
+}
+
+QScriptDeclarativeClass::Value::Value(QScriptEngine *eng, const QScriptValue &value)
+{
+ new (this) JSC::JSValue(QScriptEnginePrivate::get(eng)->scriptValueToJSCValue(value));
+}
+
+QScriptDeclarativeClass::Value::~Value()
+{
+ ((JSC::JSValue *)(this))->~JSValue();
+}
+
+QScriptValue QScriptDeclarativeClass::Value::toScriptValue(QScriptEngine *engine) const
+{
+ return QScriptEnginePrivate::get(engine)->scriptValueFromJSCValue((JSC::JSValue &)*this);
+}
+
QScriptDeclarativeClass::PersistentIdentifier::PersistentIdentifier()
+: identifier(0)
{
new (&d) JSC::Identifier();
}
@@ -82,6 +188,22 @@ QScriptValue QScriptDeclarativeClass::newObject(QScriptEngine *engine,
return p->scriptValueFromJSCValue(result);
}
+QScriptDeclarativeClass::Value
+QScriptDeclarativeClass::newObjectValue(QScriptEngine *engine,
+ QScriptDeclarativeClass *scriptClass,
+ Object *object)
+{
+ Q_ASSERT(engine);
+ Q_ASSERT(scriptClass);
+
+ QScriptEnginePrivate *p = static_cast<QScriptEnginePrivate *>(QObjectPrivate::get(engine));
+
+ JSC::ExecState* exec = p->currentFrame;
+ QScriptObject *result = new (exec) QScriptObject(p->scriptObjectStructure);
+ result->setDelegate(new QScript::DeclarativeObjectDelegate(scriptClass, object));
+ return jscToValue(JSC::JSValue(result));
+}
+
QScriptDeclarativeClass *QScriptDeclarativeClass::scriptClass(const QScriptValue &v)
{
QScriptValuePrivate *d = QScriptValuePrivate::get(v);
@@ -151,6 +273,53 @@ QScriptValue QScriptDeclarativeClass::property(const QScriptValue &v, const Iden
return QScriptValue();
}
+QScriptDeclarativeClass::Value
+QScriptDeclarativeClass::functionValue(const QScriptValue &v, const Identifier &name)
+{
+ QScriptValuePrivate *d = QScriptValuePrivate::get(v);
+
+ if (!d->isObject())
+ return Value();
+
+ JSC::ExecState *exec = d->engine->currentFrame;
+ JSC::JSObject *object = d->jscValue.getObject();
+ JSC::PropertySlot slot(const_cast<JSC::JSObject*>(object));
+ JSC::JSValue result;
+
+ JSC::Identifier id(exec, (JSC::UString::Rep *)name);
+
+ if (const_cast<JSC::JSObject*>(object)->getOwnPropertySlot(exec, id, slot)) {
+ result = slot.getValue(exec, id);
+ if (QScript::isFunction(result))
+ return jscToValue(result);
+ }
+
+ return Value();
+}
+
+QScriptDeclarativeClass::Value
+QScriptDeclarativeClass::propertyValue(const QScriptValue &v, const Identifier &name)
+{
+ QScriptValuePrivate *d = QScriptValuePrivate::get(v);
+
+ if (!d->isObject())
+ return Value();
+
+ JSC::ExecState *exec = d->engine->currentFrame;
+ JSC::JSObject *object = d->jscValue.getObject();
+ JSC::PropertySlot slot(const_cast<JSC::JSObject*>(object));
+ JSC::JSValue result;
+
+ JSC::Identifier id(exec, (JSC::UString::Rep *)name);
+
+ if (const_cast<JSC::JSObject*>(object)->getOwnPropertySlot(exec, id, slot)) {
+ result = slot.getValue(exec, id);
+ return jscToValue(result);
+ }
+
+ return Value();
+}
+
/*
Returns the scope chain entry at \a index. If index is less than 0, returns
entries starting at the end. For example, scopeChainValue(context, -1) will return
@@ -241,6 +410,16 @@ QScriptEngine *QScriptDeclarativeClass::engine() const
return d_ptr->engine;
}
+bool QScriptDeclarativeClass::supportsCall() const
+{
+ return d_ptr->supportsCall;
+}
+
+void QScriptDeclarativeClass::setSupportsCall(bool c)
+{
+ d_ptr->supportsCall = c;
+}
+
QScriptDeclarativeClass::PersistentIdentifier
QScriptDeclarativeClass::createPersistentIdentifier(const QString &str)
{
@@ -290,11 +469,12 @@ QScriptDeclarativeClass::queryProperty(Object *object, const Identifier &name,
return 0;
}
-QScriptValue QScriptDeclarativeClass::property(Object *object, const Identifier &name)
+QScriptDeclarativeClass::Value
+QScriptDeclarativeClass::property(Object *object, const Identifier &name)
{
Q_UNUSED(object);
Q_UNUSED(name);
- return QScriptValue();
+ return Value();
}
void QScriptDeclarativeClass::setProperty(Object *object, const Identifier &name,
@@ -313,6 +493,14 @@ QScriptDeclarativeClass::propertyFlags(Object *object, const Identifier &name)
return 0;
}
+QScriptDeclarativeClass::Value QScriptDeclarativeClass::call(Object *object,
+ QScriptContext *ctxt)
+{
+ Q_UNUSED(object);
+ Q_UNUSED(ctxt);
+ return Value();
+}
+
QStringList QScriptDeclarativeClass::propertyNames(Object *object)
{
Q_UNUSED(object);
diff --git a/src/script/bridge/qscriptdeclarativeclass_p.h b/src/script/bridge/qscriptdeclarativeclass_p.h
index d28a371..a0fd6d5 100644
--- a/src/script/bridge/qscriptdeclarativeclass_p.h
+++ b/src/script/bridge/qscriptdeclarativeclass_p.h
@@ -47,16 +47,47 @@ class QScriptContext;
class Q_SCRIPT_EXPORT QScriptDeclarativeClass
{
public:
+#define QT_HAVE_QSCRIPTDECLARATIVECLASS_VALUE
+ class Q_SCRIPT_EXPORT Value
+ {
+ public:
+ Value();
+ Value(const Value &);
+
+ Value(QScriptContext *, int);
+ Value(QScriptContext *, uint);
+ Value(QScriptContext *, bool);
+ Value(QScriptContext *, double);
+ Value(QScriptContext *, float);
+ Value(QScriptContext *, const QString &);
+ Value(QScriptContext *, const QScriptValue &);
+ Value(QScriptEngine *, int);
+ Value(QScriptEngine *, uint);
+ Value(QScriptEngine *, bool);
+ Value(QScriptEngine *, double);
+ Value(QScriptEngine *, float);
+ Value(QScriptEngine *, const QString &);
+ Value(QScriptEngine *, const QScriptValue &);
+ ~Value();
+
+ QScriptValue toScriptValue(QScriptEngine *) const;
+ private:
+ char dummy[8];
+ };
+
typedef void* Identifier;
struct Object { virtual ~Object() {} };
static QScriptValue newObject(QScriptEngine *, QScriptDeclarativeClass *, Object *);
+ static Value newObjectValue(QScriptEngine *, QScriptDeclarativeClass *, Object *);
static QScriptDeclarativeClass *scriptClass(const QScriptValue &);
static Object *object(const QScriptValue &);
static QScriptValue function(const QScriptValue &, const Identifier &);
static QScriptValue property(const QScriptValue &, const Identifier &);
+ static Value functionValue(const QScriptValue &, const Identifier &);
+ static Value propertyValue(const QScriptValue &, const Identifier &);
static QScriptValue scopeChainValue(QScriptContext *, int index);
static QScriptContext *pushCleanContext(QScriptEngine *);
@@ -82,6 +113,9 @@ public:
QScriptEngine *engine() const;
+ bool supportsCall() const;
+ void setSupportsCall(bool);
+
PersistentIdentifier createPersistentIdentifier(const QString &);
PersistentIdentifier createPersistentIdentifier(const Identifier &);
@@ -91,9 +125,10 @@ public:
virtual QScriptClass::QueryFlags queryProperty(Object *, const Identifier &,
QScriptClass::QueryFlags flags);
- virtual QScriptValue property(Object *, const Identifier &);
+ virtual Value property(Object *, const Identifier &);
virtual void setProperty(Object *, const Identifier &name, const QScriptValue &);
virtual QScriptValue::PropertyFlags propertyFlags(Object *, const Identifier &);
+ virtual Value call(Object *, QScriptContext *);
virtual QStringList propertyNames(Object *);
diff --git a/src/script/bridge/qscriptdeclarativeobject.cpp b/src/script/bridge/qscriptdeclarativeobject.cpp
index aecb09a..c6ab6a7 100644
--- a/src/script/bridge/qscriptdeclarativeobject.cpp
+++ b/src/script/bridge/qscriptdeclarativeobject.cpp
@@ -74,9 +74,9 @@ bool DeclarativeObjectDelegate::getOwnPropertySlot(QScriptObject* object,
QScriptClass::QueryFlags flags =
m_class->queryProperty(m_object, identifier, QScriptClass::HandlesReadAccess);
if (flags & QScriptClass::HandlesReadAccess) {
- QScriptValue value = m_class->property(m_object, identifier);
+ QScriptDeclarativeClass::Value val = m_class->property(m_object, identifier);
p->context = 0;
- slot.setValue(engine->scriptValueToJSCValue(value));
+ slot.setValue((const JSC::JSValue &)val);
return true;
}
p->context = 0;
@@ -155,7 +155,36 @@ void DeclarativeObjectDelegate::getOwnPropertyNames(QScriptObject* object, JSC::
JSC::CallType DeclarativeObjectDelegate::getCallData(QScriptObject *object, JSC::CallData &callData)
{
- return QScriptObjectDelegate::getCallData(object, callData);
+ if (!QScriptDeclarativeClassPrivate::get(m_class)->supportsCall)
+ return JSC::CallTypeNone;
+ callData.native.function = call;
+ return JSC::CallTypeHost;
+}
+
+JSC::JSValue DeclarativeObjectDelegate::call(JSC::ExecState *exec, JSC::JSObject *callee,
+ JSC::JSValue thisValue, const JSC::ArgList &args)
+{
+ if (!callee->inherits(&QScriptObject::info))
+ return JSC::throwError(exec, JSC::TypeError, "callee is not a DeclarativeObject object");
+ QScriptObject *obj = static_cast<QScriptObject*>(callee);
+ QScriptObjectDelegate *delegate = obj->delegate();
+ if (!delegate || (delegate->type() != QScriptObjectDelegate::DeclarativeClassObject))
+ return JSC::throwError(exec, JSC::TypeError, "callee is not a DeclarativeObject object");
+
+ QScriptDeclarativeClass *scriptClass = static_cast<DeclarativeObjectDelegate*>(delegate)->m_class;
+ QScriptEnginePrivate *eng_p = scriptEngineFromExec(exec);
+
+ JSC::ExecState *oldFrame = eng_p->currentFrame;
+ eng_p->pushContext(exec, thisValue, args, callee);
+ QScriptContext *ctxt = eng_p->contextForFrame(eng_p->currentFrame);
+
+ QScriptValue scriptObject = eng_p->scriptValueFromJSCValue(obj);
+ QScriptDeclarativeClass::Value result =
+ scriptClass->call(static_cast<DeclarativeObjectDelegate*>(delegate)->m_object, ctxt);
+
+ eng_p->popContext();
+ eng_p->currentFrame = oldFrame;
+ return (JSC::JSValue &)(result);
}
JSC::ConstructType DeclarativeObjectDelegate::getConstructData(QScriptObject* object, JSC::ConstructData &constructData)
diff --git a/src/script/bridge/qscriptdeclarativeobject_p.h b/src/script/bridge/qscriptdeclarativeobject_p.h
index d5bf673..ec8a43e 100644
--- a/src/script/bridge/qscriptdeclarativeobject_p.h
+++ b/src/script/bridge/qscriptdeclarativeobject_p.h
@@ -48,11 +48,12 @@ class QScriptClass;
class QScriptDeclarativeClassPrivate
{
public:
- QScriptDeclarativeClassPrivate() : engine(0), q_ptr(0), context(0) {}
+ QScriptDeclarativeClassPrivate() : engine(0), q_ptr(0), context(0), supportsCall(false) {}
QScriptEngine *engine;
QScriptDeclarativeClass *q_ptr;
QScriptContext *context;
+ bool supportsCall:1;
static QScriptDeclarativeClassPrivate *get(QScriptDeclarativeClass *c) {
return c->d_ptr.data();
@@ -90,6 +91,9 @@ public:
bool includeNonEnumerable = false);
virtual JSC::CallType getCallData(QScriptObject*, JSC::CallData&);
+ static JSC::JSValue JSC_HOST_CALL call(JSC::ExecState*, JSC::JSObject*,
+ JSC::JSValue, const JSC::ArgList&);
+
virtual JSC::ConstructType getConstructData(QScriptObject*, JSC::ConstructData&);
virtual bool hasInstance(QScriptObject*, JSC::ExecState*,
diff --git a/src/scripttools/debugging/qscriptdebuggerconsole.cpp b/src/scripttools/debugging/qscriptdebuggerconsole.cpp
index 7fd80f0..2f7a998 100644
--- a/src/scripttools/debugging/qscriptdebuggerconsole.cpp
+++ b/src/scripttools/debugging/qscriptdebuggerconsole.cpp
@@ -44,16 +44,216 @@
#include "qscriptdebuggerconsolecommandmanager_p.h"
#include "qscriptdebuggerscriptedconsolecommand_p.h"
#include "qscriptmessagehandlerinterface_p.h"
+#include "qscriptbreakpointdata_p.h"
+#include "qscriptdebuggerresponse_p.h"
+#include "qscriptdebuggervalueproperty_p.h"
+#include "qscriptscriptdata_p.h"
#include <QtCore/qdir.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qstring.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qdebug.h>
+#include <QtScript/qscriptcontextinfo.h>
#include <QtScript/qscriptengine.h>
+Q_DECLARE_METATYPE(QScriptDebuggerResponse)
+Q_DECLARE_METATYPE(QScriptBreakpointData)
+Q_DECLARE_METATYPE(QScriptBreakpointMap)
+Q_DECLARE_METATYPE(QScriptScriptData)
+Q_DECLARE_METATYPE(QScriptScriptMap)
+Q_DECLARE_METATYPE(QScriptContextInfo)
+Q_DECLARE_METATYPE(QScriptDebuggerValue)
+Q_DECLARE_METATYPE(QScriptDebuggerValueProperty)
+Q_DECLARE_METATYPE(QScriptDebuggerValuePropertyList)
+Q_DECLARE_METATYPE(QScriptDebuggerConsoleCommand*)
+Q_DECLARE_METATYPE(QScriptDebuggerConsoleCommandList)
+Q_DECLARE_METATYPE(QScriptDebuggerConsoleCommandGroupData)
+Q_DECLARE_METATYPE(QScriptDebuggerConsoleCommandGroupMap)
+
QT_BEGIN_NAMESPACE
+static QScriptValue debuggerResponseToScriptValue(QScriptEngine *eng, const QScriptDebuggerResponse &in)
+{
+ QScriptValue out = eng->newObject();
+ out.setProperty(QString::fromLatin1("result"), qScriptValueFromValue(eng, in.result()));
+ out.setProperty(QString::fromLatin1("error"), QScriptValue(eng, in.error()));
+ out.setProperty(QString::fromLatin1("async"), QScriptValue(eng, in.async()));
+ return out;
+}
+
+static void debuggerResponseFromScriptValue(const QScriptValue &, QScriptDebuggerResponse &)
+{
+ Q_ASSERT(0);
+}
+
+static QScriptValue breakpointDataToScriptValue(QScriptEngine *eng, const QScriptBreakpointData &in)
+{
+ QScriptValue out = eng->newObject();
+ out.setProperty(QString::fromLatin1("scriptId"), QScriptValue(eng, qsreal(in.scriptId())));
+ out.setProperty(QString::fromLatin1("fileName"), QScriptValue(eng, in.fileName()));
+ out.setProperty(QString::fromLatin1("lineNumber"), QScriptValue(eng, in.lineNumber()));
+ out.setProperty(QString::fromLatin1("enabled"), QScriptValue(eng, in.isEnabled()));
+ out.setProperty(QString::fromLatin1("singleShot"), QScriptValue(eng, in.isSingleShot()));
+ out.setProperty(QString::fromLatin1("ignoreCount"), QScriptValue(eng, in.ignoreCount()));
+ out.setProperty(QString::fromLatin1("condition"), QScriptValue(eng, in.condition()));
+ return out;
+}
+
+static void breakpointDataFromScriptValue(const QScriptValue &in, QScriptBreakpointData &out)
+{
+ QScriptValue scriptId = in.property(QString::fromLatin1("scriptId"));
+ if (scriptId.isValid())
+ out.setScriptId((qint64)scriptId.toNumber());
+ out.setFileName(in.property(QString::fromLatin1("fileName")).toString());
+ out.setLineNumber(in.property(QString::fromLatin1("lineNumber")).toInt32());
+ QScriptValue enabled = in.property(QString::fromLatin1("enabled"));
+ if (enabled.isValid())
+ out.setEnabled(enabled.toBoolean());
+ QScriptValue singleShot = in.property(QString::fromLatin1("singleShot"));
+ if (singleShot.isValid())
+ out.setSingleShot(singleShot.toBoolean());
+ out.setIgnoreCount(in.property(QString::fromLatin1("ignoreCount")).toInt32());
+ out.setCondition(in.property(QString::fromLatin1("condition")).toString());
+}
+
+static QScriptValue breakpointMapToScriptValue(QScriptEngine *eng, const QScriptBreakpointMap &in)
+{
+ QScriptValue out = eng->newObject();
+ QScriptBreakpointMap::const_iterator it;
+ for (it = in.constBegin(); it != in.constEnd(); ++it) {
+ out.setProperty(QString::number(it.key()), qScriptValueFromValue(eng, it.value()));
+ }
+ return out;
+}
+
+static void breakpointMapFromScriptValue(const QScriptValue &, QScriptBreakpointMap &)
+{
+ Q_ASSERT(0);
+}
+
+static QScriptValue scriptDataToScriptValue(QScriptEngine *eng, const QScriptScriptData &in)
+{
+ QScriptValue out = eng->newObject();
+ out.setProperty(QString::fromLatin1("contents"), QScriptValue(eng, in.contents()));
+ out.setProperty(QString::fromLatin1("fileName"), QScriptValue(eng, in.fileName()));
+ out.setProperty(QString::fromLatin1("baseLineNumber"), QScriptValue(eng, in.baseLineNumber()));
+ return out;
+}
+
+static void scriptDataFromScriptValue(const QScriptValue &in, QScriptScriptData &out)
+{
+ QString contents = in.property(QString::fromLatin1("contents")).toString();
+ QString fileName = in.property(QString::fromLatin1("fileName")).toString();
+ int baseLineNumber = in.property(QString::fromLatin1("baseLineNumber")).toInt32();
+ QScriptScriptData tmp(contents, fileName, baseLineNumber);
+ out = tmp;
+}
+
+static QScriptValue scriptMapToScriptValue(QScriptEngine *eng, const QScriptScriptMap &in)
+{
+ QScriptValue out = eng->newObject();
+ QScriptScriptMap::const_iterator it;
+ for (it = in.constBegin(); it != in.constEnd(); ++it) {
+ out.setProperty(QString::number(it.key()), qScriptValueFromValue(eng, it.value()));
+ }
+ return out;
+}
+
+static void scriptMapFromScriptValue(const QScriptValue &, QScriptScriptMap &)
+{
+ Q_ASSERT(0);
+}
+
+static QScriptValue consoleCommandToScriptValue(
+ QScriptEngine *eng, QScriptDebuggerConsoleCommand* const &in)
+{
+ if (!in)
+ return eng->undefinedValue();
+ QScriptValue out = eng->newObject();
+ out.setProperty(QString::fromLatin1("name"), QScriptValue(eng, in->name()));
+ out.setProperty(QString::fromLatin1("group"), QScriptValue(eng, in->group()));
+ out.setProperty(QString::fromLatin1("shortDescription"), QScriptValue(eng, in->shortDescription()));
+ out.setProperty(QString::fromLatin1("longDescription"), QScriptValue(eng, in->longDescription()));
+ out.setProperty(QString::fromLatin1("aliases"), qScriptValueFromValue(eng, in->aliases()));
+ out.setProperty(QString::fromLatin1("seeAlso"), qScriptValueFromValue(eng, in->seeAlso()));
+ return out;
+}
+
+static void consoleCommandFromScriptValue(
+ const QScriptValue &, QScriptDebuggerConsoleCommand* &)
+{
+ Q_ASSERT(0);
+}
+
+static QScriptValue consoleCommandGroupDataToScriptValue(
+ QScriptEngine *eng, const QScriptDebuggerConsoleCommandGroupData &in)
+{
+ QScriptValue out = eng->newObject();
+ out.setProperty(QString::fromLatin1("longDescription"), QScriptValue(eng, in.longDescription()));
+ out.setProperty(QString::fromLatin1("shortDescription"), QScriptValue(eng, in.shortDescription()));
+ return out;
+}
+
+static void consoleCommandGroupDataFromScriptValue(
+ const QScriptValue &, QScriptDebuggerConsoleCommandGroupData &)
+{
+ Q_ASSERT(0);
+}
+
+static QScriptValue consoleCommandGroupMapToScriptValue(
+ QScriptEngine *eng, const QScriptDebuggerConsoleCommandGroupMap &in)
+{
+ QScriptValue out = eng->newObject();
+ QScriptDebuggerConsoleCommandGroupMap::const_iterator it;
+ for (it = in.constBegin(); it != in.constEnd(); ++it) {
+ out.setProperty(it.key(), qScriptValueFromValue(eng, it.value()));
+ }
+ return out;
+}
+
+static void consoleCommandGroupMapFromScriptValue(
+ const QScriptValue &, QScriptDebuggerConsoleCommandGroupMap &)
+{
+ Q_ASSERT(0);
+}
+
+static QScriptValue contextInfoToScriptValue(QScriptEngine *eng, const QScriptContextInfo &in)
+{
+ QScriptValue out = eng->newObject();
+ out.setProperty(QString::fromLatin1("scriptId"), QScriptValue(eng, qsreal(in.scriptId())));
+ out.setProperty(QString::fromLatin1("fileName"), QScriptValue(eng, in.fileName()));
+ out.setProperty(QString::fromLatin1("lineNumber"), QScriptValue(eng, in.lineNumber()));
+ out.setProperty(QString::fromLatin1("columnNumber"), QScriptValue(eng, in.columnNumber()));
+ out.setProperty(QString::fromLatin1("functionName"), QScriptValue(eng, in.functionName()));
+ return out;
+}
+
+static void contextInfoFromScriptValue(const QScriptValue &, QScriptContextInfo &)
+{
+ Q_ASSERT(0);
+}
+
+static QScriptValue debuggerScriptValuePropertyToScriptValue(QScriptEngine *eng, const QScriptDebuggerValueProperty &in)
+{
+ QScriptValue out = eng->newObject();
+ out.setProperty(QString::fromLatin1("name"), QScriptValue(eng, in.name()));
+ out.setProperty(QString::fromLatin1("value"), qScriptValueFromValue(eng, in.value()));
+ out.setProperty(QString::fromLatin1("valueAsString"), QScriptValue(eng, in.valueAsString()));
+ out.setProperty(QString::fromLatin1("flags"), QScriptValue(eng, static_cast<int>(in.flags())));
+ return out;
+}
+
+static void debuggerScriptValuePropertyFromScriptValue(const QScriptValue &in, QScriptDebuggerValueProperty &out)
+{
+ QString name = in.property(QString::fromLatin1("name")).toString();
+ QScriptDebuggerValue value = qscriptvalue_cast<QScriptDebuggerValue>(in.property(QString::fromLatin1("value")));
+ QString valueAsString = in.property(QString::fromLatin1("valueAsString")).toString();
+ int flags = in.property(QString::fromLatin1("flags")).toInt32();
+ QScriptDebuggerValueProperty tmp(name, value, valueAsString, QScriptValue::PropertyFlags(flags));
+ out = tmp;
+}
+
/*!
\since 4.5
\class QScriptDebuggerConsole
@@ -76,6 +276,7 @@ public:
QScriptMessageHandlerInterface *messageHandler,
QScriptDebuggerCommandSchedulerInterface *commandScheduler);
+ QScriptEngine *commandEngine;
QScriptDebuggerConsoleCommandManager *commandManager;
QString commandPrefix;
QString input;
@@ -99,11 +300,29 @@ QScriptDebuggerConsolePrivate::QScriptDebuggerConsolePrivate(QScriptDebuggerCons
evaluateAction = 0;
commandPrefix = QLatin1String(".");
commandManager = new QScriptDebuggerConsoleCommandManager();
+
+ commandEngine = new QScriptEngine;
+ qScriptRegisterMetaType<QScriptBreakpointData>(commandEngine, breakpointDataToScriptValue, breakpointDataFromScriptValue);
+ qScriptRegisterMetaType<QScriptBreakpointMap>(commandEngine, breakpointMapToScriptValue, breakpointMapFromScriptValue);
+ qScriptRegisterMetaType<QScriptScriptData>(commandEngine, scriptDataToScriptValue, scriptDataFromScriptValue);
+ qScriptRegisterMetaType<QScriptScriptMap>(commandEngine, scriptMapToScriptValue, scriptMapFromScriptValue);
+ qScriptRegisterMetaType<QScriptContextInfo>(commandEngine, contextInfoToScriptValue, contextInfoFromScriptValue);
+ qScriptRegisterMetaType<QScriptDebuggerValueProperty>(commandEngine, debuggerScriptValuePropertyToScriptValue, debuggerScriptValuePropertyFromScriptValue);
+ qScriptRegisterSequenceMetaType<QScriptDebuggerValuePropertyList>(commandEngine);
+ qScriptRegisterMetaType<QScriptDebuggerResponse>(commandEngine, debuggerResponseToScriptValue, debuggerResponseFromScriptValue);
+ qScriptRegisterMetaType<QScriptDebuggerConsoleCommand*>(commandEngine, consoleCommandToScriptValue, consoleCommandFromScriptValue);
+ qScriptRegisterSequenceMetaType<QScriptDebuggerConsoleCommandList>(commandEngine);
+ qScriptRegisterMetaType<QScriptDebuggerConsoleCommandGroupData>(commandEngine, consoleCommandGroupDataToScriptValue, consoleCommandGroupDataFromScriptValue);
+ qScriptRegisterMetaType<QScriptDebuggerConsoleCommandGroupMap>(commandEngine, consoleCommandGroupMapToScriptValue, consoleCommandGroupMapFromScriptValue);
+// ### can't do this, if it's an object ID the conversion will be incorrect since
+// ### the object ID refers to an object in a different engine!
+// qScriptRegisterMetaType(commandEngine, debuggerScriptValueToScriptValue, debuggerScriptValueFromScriptValue);
}
QScriptDebuggerConsolePrivate::~QScriptDebuggerConsolePrivate()
{
delete commandManager;
+ delete commandEngine;
}
/*!
@@ -126,7 +345,7 @@ void QScriptDebuggerConsolePrivate::loadScriptedCommands(
QString program = stream.readAll();
QScriptDebuggerScriptedConsoleCommand *command;
command = QScriptDebuggerScriptedConsoleCommand::parse(
- program, fileName, messageHandler);
+ program, fileName, commandEngine, messageHandler);
if (!command)
continue;
commandManager->addCommand(command);
diff --git a/src/scripttools/debugging/qscriptdebuggerlocalsmodel.cpp b/src/scripttools/debugging/qscriptdebuggerlocalsmodel.cpp
index 068de42..ec6230b 100644
--- a/src/scripttools/debugging/qscriptdebuggerlocalsmodel.cpp
+++ b/src/scripttools/debugging/qscriptdebuggerlocalsmodel.cpp
@@ -54,6 +54,7 @@
#include <QtCore/qdebug.h>
#include <QtCore/qcoreapplication.h>
+#include <QtCore/qpointer.h>
#include <QtGui/qbrush.h>
#include <QtGui/qfont.h>
@@ -370,6 +371,7 @@ public:
{
if (!m_index.isValid()) {
// nothing to do, the node has been removed
+ finish();
return;
}
QScriptDebuggerCommandSchedulerFrontend frontend(commandScheduler(), this);
@@ -475,7 +477,7 @@ namespace {
class InitModelJob : public QScriptDebuggerCommandSchedulerJob
{
public:
- InitModelJob(QScriptDebuggerLocalsModelPrivate *model,
+ InitModelJob(QScriptDebuggerLocalsModel *model,
int frameIndex,
QScriptDebuggerCommandSchedulerInterface *scheduler)
: QScriptDebuggerCommandSchedulerJob(scheduler),
@@ -484,6 +486,11 @@ public:
void start()
{
+ if (!m_model) {
+ // Model has been deleted.
+ finish();
+ return;
+ }
QScriptDebuggerCommandSchedulerFrontend frontend(commandScheduler(), this);
frontend.scheduleGetScopeChain(m_frameIndex);
}
@@ -491,7 +498,13 @@ public:
void handleResponse(const QScriptDebuggerResponse &response,
int)
{
+ if (!m_model) {
+ // Model has been deleted.
+ finish();
+ return;
+ }
QScriptDebuggerCommandSchedulerFrontend frontend(commandScheduler(), this);
+ QScriptDebuggerLocalsModelPrivate *model_d = QScriptDebuggerLocalsModelPrivate::get(m_model);
switch (m_state) {
case 0: {
QScriptDebuggerValueList scopeChain = response.resultAsScriptValueList();
@@ -500,23 +513,23 @@ public:
QString name = QString::fromLatin1("Scope");
if (i > 0)
name.append(QString::fromLatin1(" (%0)").arg(i));
- QModelIndex index = m_model->addTopLevelObject(name, scopeObject);
+ QModelIndex index = model_d->addTopLevelObject(name, scopeObject);
if (i == 0)
- m_model->emitScopeObjectAvailable(index);
+ model_d->emitScopeObjectAvailable(index);
}
frontend.scheduleGetThisObject(m_frameIndex);
++m_state;
} break;
case 1: {
QScriptDebuggerValue thisObject = response.resultAsScriptValue();
- m_model->addTopLevelObject(QLatin1String("this"), thisObject);
+ model_d->addTopLevelObject(QLatin1String("this"), thisObject);
finish();
} break;
}
}
private:
- QScriptDebuggerLocalsModelPrivate *m_model;
+ QPointer<QScriptDebuggerLocalsModel> m_model;
int m_frameIndex;
int m_state;
};
@@ -527,7 +540,7 @@ void QScriptDebuggerLocalsModel::init(int frameIndex)
{
Q_D(QScriptDebuggerLocalsModel);
d->frameIndex = frameIndex;
- QScriptDebuggerJob *job = new InitModelJob(d, frameIndex, d->commandScheduler);
+ QScriptDebuggerJob *job = new InitModelJob(this, frameIndex, d->commandScheduler);
d->jobScheduler->scheduleJob(job);
}
@@ -536,7 +549,7 @@ namespace {
class SyncModelJob : public QScriptDebuggerCommandSchedulerJob
{
public:
- SyncModelJob(QScriptDebuggerLocalsModelPrivate *model,
+ SyncModelJob(QScriptDebuggerLocalsModel *model,
int frameIndex,
QScriptDebuggerCommandSchedulerInterface *scheduler)
: QScriptDebuggerCommandSchedulerJob(scheduler),
@@ -545,6 +558,11 @@ public:
void start()
{
+ if (!m_model) {
+ // Model has been deleted.
+ finish();
+ return;
+ }
QScriptDebuggerCommandSchedulerFrontend frontend(commandScheduler(), this);
frontend.scheduleGetScopeChain(m_frameIndex);
}
@@ -552,6 +570,11 @@ public:
void handleResponse(const QScriptDebuggerResponse &response,
int)
{
+ if (!m_model) {
+ // Model has been deleted.
+ finish();
+ return;
+ }
QScriptDebuggerCommandSchedulerFrontend frontend(commandScheduler(), this);
switch (m_state) {
case 0: {
@@ -561,18 +584,19 @@ public:
++m_state;
} break;
case 1: {
+ QScriptDebuggerLocalsModelPrivate *model_d = QScriptDebuggerLocalsModelPrivate::get(m_model);
QScriptDebuggerValue thisObject = response.resultAsScriptValue();
m_topLevelObjects.append(thisObject);
- bool equal = (m_topLevelObjects.size() == m_model->invisibleRootNode->children.size());
+ bool equal = (m_topLevelObjects.size() == model_d->invisibleRootNode->children.size());
for (int i = 0; equal && (i < m_topLevelObjects.size()); ++i) {
const QScriptDebuggerValue &object = m_topLevelObjects.at(i);
- equal = (object == m_model->invisibleRootNode->children.at(i)->property.value());
+ equal = (object == model_d->invisibleRootNode->children.at(i)->property.value());
}
if (!equal) {
// the scope chain and/or this-object changed, so invalidate the model.
// we could try to be more clever, i.e. figure out
// exactly which objects were popped/pushed
- m_model->removeTopLevelNodes();
+ model_d->removeTopLevelNodes();
for (int j = 0; j < m_topLevelObjects.size(); ++j) {
const QScriptDebuggerValue &object = m_topLevelObjects.at(j);
QString name;
@@ -583,12 +607,12 @@ public:
if (j > 0)
name.append(QString::fromLatin1(" (%0)").arg(j));
}
- QModelIndex index = m_model->addTopLevelObject(name, object);
+ QModelIndex index = model_d->addTopLevelObject(name, object);
if (j == 0)
- m_model->emitScopeObjectAvailable(index);
+ model_d->emitScopeObjectAvailable(index);
}
} else {
- m_model->syncTopLevelNodes();
+ model_d->syncTopLevelNodes();
}
finish();
} break;
@@ -596,7 +620,7 @@ public:
}
private:
- QScriptDebuggerLocalsModelPrivate *m_model;
+ QPointer<QScriptDebuggerLocalsModel> m_model;
int m_frameIndex;
int m_state;
QScriptDebuggerValueList m_topLevelObjects;
@@ -608,7 +632,7 @@ void QScriptDebuggerLocalsModel::sync(int frameIndex)
{
Q_D(QScriptDebuggerLocalsModel);
d->frameIndex = frameIndex;
- QScriptDebuggerJob *job = new SyncModelJob(d, frameIndex, d->commandScheduler);
+ QScriptDebuggerJob *job = new SyncModelJob(this, frameIndex, d->commandScheduler);
d->jobScheduler->scheduleJob(job);
}
@@ -636,6 +660,7 @@ public:
{
if (!m_index.isValid()) {
// nothing to do, the node has been removed
+ finish();
return;
}
QScriptDebuggerCommandSchedulerFrontend frontend(commandScheduler(), this);
diff --git a/src/scripttools/debugging/qscriptdebuggerlocalswidget.cpp b/src/scripttools/debugging/qscriptdebuggerlocalswidget.cpp
index 516a200..bbced5f 100644
--- a/src/scripttools/debugging/qscriptdebuggerlocalswidget.cpp
+++ b/src/scripttools/debugging/qscriptdebuggerlocalswidget.cpp
@@ -70,6 +70,8 @@ public:
bool hasChildren(const QModelIndex &parent) const
{
+ if (!sourceModel())
+ return false;
QModelIndex sourceParent = mapToSource(parent);
if (parent.isValid() && !sourceParent.isValid())
return false;
@@ -184,7 +186,8 @@ void QScriptDebuggerLocalsWidgetPrivate::_q_insertCompletion(const QString &text
void QScriptDebuggerLocalsWidgetPrivate::_q_expandIndex(const QModelIndex &index)
{
- view->expand(proxy->mapFromSource(index));
+ if (view->model() == index.model())
+ view->expand(proxy->mapFromSource(index));
}
class QScriptDebuggerLocalsItemDelegate
diff --git a/src/scripttools/debugging/qscriptdebuggerscriptedconsolecommand.cpp b/src/scripttools/debugging/qscriptdebuggerscriptedconsolecommand.cpp
index 8d6a579..117c2d6 100644
--- a/src/scripttools/debugging/qscriptdebuggerscriptedconsolecommand.cpp
+++ b/src/scripttools/debugging/qscriptdebuggerscriptedconsolecommand.cpp
@@ -46,8 +46,6 @@
#include "qscriptmessagehandlerinterface_p.h"
#include "qscriptdebuggerconsoleglobalobject_p.h"
#include "qscriptdebuggerresponse_p.h"
-#include "qscriptdebuggervalue_p.h"
-#include "qscriptdebuggervalueproperty_p.h"
#include "qscriptdebuggercommandschedulerinterface_p.h"
#include <QtCore/qstring.h>
@@ -59,202 +57,9 @@
#include <QtCore/qdebug.h>
Q_DECLARE_METATYPE(QScriptDebuggerResponse)
-Q_DECLARE_METATYPE(QScriptBreakpointData)
-Q_DECLARE_METATYPE(QScriptBreakpointMap)
-Q_DECLARE_METATYPE(QScriptScriptData)
-Q_DECLARE_METATYPE(QScriptScriptMap)
-Q_DECLARE_METATYPE(QScriptContextInfo)
-Q_DECLARE_METATYPE(QScriptDebuggerValue)
-Q_DECLARE_METATYPE(QScriptDebuggerValueProperty)
-Q_DECLARE_METATYPE(QScriptDebuggerValuePropertyList)
-Q_DECLARE_METATYPE(QScriptDebuggerConsoleCommand*)
-Q_DECLARE_METATYPE(QScriptDebuggerConsoleCommandList)
-Q_DECLARE_METATYPE(QScriptDebuggerConsoleCommandGroupData)
-Q_DECLARE_METATYPE(QScriptDebuggerConsoleCommandGroupMap)
QT_BEGIN_NAMESPACE
-static QScriptValue debuggerResponseToScriptValue(QScriptEngine *eng, const QScriptDebuggerResponse &in)
-{
- QScriptValue out = eng->newObject();
- out.setProperty(QString::fromLatin1("result"), qScriptValueFromValue(eng, in.result()));
- out.setProperty(QString::fromLatin1("error"), QScriptValue(eng, in.error()));
- out.setProperty(QString::fromLatin1("async"), QScriptValue(eng, in.async()));
- return out;
-}
-
-static void debuggerResponseFromScriptValue(const QScriptValue &, QScriptDebuggerResponse &)
-{
- Q_ASSERT(0);
-}
-
-static QScriptValue breakpointDataToScriptValue(QScriptEngine *eng, const QScriptBreakpointData &in)
-{
- QScriptValue out = eng->newObject();
- out.setProperty(QString::fromLatin1("scriptId"), QScriptValue(eng, qsreal(in.scriptId())));
- out.setProperty(QString::fromLatin1("fileName"), QScriptValue(eng, in.fileName()));
- out.setProperty(QString::fromLatin1("lineNumber"), QScriptValue(eng, in.lineNumber()));
- out.setProperty(QString::fromLatin1("enabled"), QScriptValue(eng, in.isEnabled()));
- out.setProperty(QString::fromLatin1("singleShot"), QScriptValue(eng, in.isSingleShot()));
- out.setProperty(QString::fromLatin1("ignoreCount"), QScriptValue(eng, in.ignoreCount()));
- out.setProperty(QString::fromLatin1("condition"), QScriptValue(eng, in.condition()));
- return out;
-}
-
-static void breakpointDataFromScriptValue(const QScriptValue &in, QScriptBreakpointData &out)
-{
- QScriptValue scriptId = in.property(QString::fromLatin1("scriptId"));
- if (scriptId.isValid())
- out.setScriptId((qint64)scriptId.toNumber());
- out.setFileName(in.property(QString::fromLatin1("fileName")).toString());
- out.setLineNumber(in.property(QString::fromLatin1("lineNumber")).toInt32());
- QScriptValue enabled = in.property(QString::fromLatin1("enabled"));
- if (enabled.isValid())
- out.setEnabled(enabled.toBoolean());
- QScriptValue singleShot = in.property(QString::fromLatin1("singleShot"));
- if (singleShot.isValid())
- out.setSingleShot(singleShot.toBoolean());
- out.setIgnoreCount(in.property(QString::fromLatin1("ignoreCount")).toInt32());
- out.setCondition(in.property(QString::fromLatin1("condition")).toString());
-}
-
-static QScriptValue breakpointMapToScriptValue(QScriptEngine *eng, const QScriptBreakpointMap &in)
-{
- QScriptValue out = eng->newObject();
- QScriptBreakpointMap::const_iterator it;
- for (it = in.constBegin(); it != in.constEnd(); ++it) {
- out.setProperty(QString::number(it.key()), qScriptValueFromValue(eng, it.value()));
- }
- return out;
-}
-
-static void breakpointMapFromScriptValue(const QScriptValue &, QScriptBreakpointMap &)
-{
- Q_ASSERT(0);
-}
-
-static QScriptValue scriptDataToScriptValue(QScriptEngine *eng, const QScriptScriptData &in)
-{
- QScriptValue out = eng->newObject();
- out.setProperty(QString::fromLatin1("contents"), QScriptValue(eng, in.contents()));
- out.setProperty(QString::fromLatin1("fileName"), QScriptValue(eng, in.fileName()));
- out.setProperty(QString::fromLatin1("baseLineNumber"), QScriptValue(eng, in.baseLineNumber()));
- return out;
-}
-
-static void scriptDataFromScriptValue(const QScriptValue &in, QScriptScriptData &out)
-{
- QString contents = in.property(QString::fromLatin1("contents")).toString();
- QString fileName = in.property(QString::fromLatin1("fileName")).toString();
- int baseLineNumber = in.property(QString::fromLatin1("baseLineNumber")).toInt32();
- QScriptScriptData tmp(contents, fileName, baseLineNumber);
- out = tmp;
-}
-
-static QScriptValue scriptMapToScriptValue(QScriptEngine *eng, const QScriptScriptMap &in)
-{
- QScriptValue out = eng->newObject();
- QScriptScriptMap::const_iterator it;
- for (it = in.constBegin(); it != in.constEnd(); ++it) {
- out.setProperty(QString::number(it.key()), qScriptValueFromValue(eng, it.value()));
- }
- return out;
-}
-
-static void scriptMapFromScriptValue(const QScriptValue &, QScriptScriptMap &)
-{
- Q_ASSERT(0);
-}
-
-static QScriptValue consoleCommandToScriptValue(
- QScriptEngine *eng, QScriptDebuggerConsoleCommand* const &in)
-{
- if (!in)
- return eng->undefinedValue();
- QScriptValue out = eng->newObject();
- out.setProperty(QString::fromLatin1("name"), QScriptValue(eng, in->name()));
- out.setProperty(QString::fromLatin1("group"), QScriptValue(eng, in->group()));
- out.setProperty(QString::fromLatin1("shortDescription"), QScriptValue(eng, in->shortDescription()));
- out.setProperty(QString::fromLatin1("longDescription"), QScriptValue(eng, in->longDescription()));
- out.setProperty(QString::fromLatin1("aliases"), qScriptValueFromValue(eng, in->aliases()));
- out.setProperty(QString::fromLatin1("seeAlso"), qScriptValueFromValue(eng, in->seeAlso()));
- return out;
-}
-
-static void consoleCommandFromScriptValue(
- const QScriptValue &, QScriptDebuggerConsoleCommand* &)
-{
- Q_ASSERT(0);
-}
-
-static QScriptValue consoleCommandGroupDataToScriptValue(
- QScriptEngine *eng, const QScriptDebuggerConsoleCommandGroupData &in)
-{
- QScriptValue out = eng->newObject();
- out.setProperty(QString::fromLatin1("longDescription"), QScriptValue(eng, in.longDescription()));
- out.setProperty(QString::fromLatin1("shortDescription"), QScriptValue(eng, in.shortDescription()));
- return out;
-}
-
-static void consoleCommandGroupDataFromScriptValue(
- const QScriptValue &, QScriptDebuggerConsoleCommandGroupData &)
-{
- Q_ASSERT(0);
-}
-
-static QScriptValue consoleCommandGroupMapToScriptValue(
- QScriptEngine *eng, const QScriptDebuggerConsoleCommandGroupMap &in)
-{
- QScriptValue out = eng->newObject();
- QScriptDebuggerConsoleCommandGroupMap::const_iterator it;
- for (it = in.constBegin(); it != in.constEnd(); ++it) {
- out.setProperty(it.key(), qScriptValueFromValue(eng, it.value()));
- }
- return out;
-}
-
-static void consoleCommandGroupMapFromScriptValue(
- const QScriptValue &, QScriptDebuggerConsoleCommandGroupMap &)
-{
- Q_ASSERT(0);
-}
-
-static QScriptValue contextInfoToScriptValue(QScriptEngine *eng, const QScriptContextInfo &in)
-{
- QScriptValue out = eng->newObject();
- out.setProperty(QString::fromLatin1("scriptId"), QScriptValue(eng, qsreal(in.scriptId())));
- out.setProperty(QString::fromLatin1("fileName"), QScriptValue(eng, in.fileName()));
- out.setProperty(QString::fromLatin1("lineNumber"), QScriptValue(eng, in.lineNumber()));
- out.setProperty(QString::fromLatin1("columnNumber"), QScriptValue(eng, in.columnNumber()));
- out.setProperty(QString::fromLatin1("functionName"), QScriptValue(eng, in.functionName()));
- return out;
-}
-
-static void contextInfoFromScriptValue(const QScriptValue &, QScriptContextInfo &)
-{
- Q_ASSERT(0);
-}
-
-static QScriptValue debuggerScriptValuePropertyToScriptValue(QScriptEngine *eng, const QScriptDebuggerValueProperty &in)
-{
- QScriptValue out = eng->newObject();
- out.setProperty(QString::fromLatin1("name"), QScriptValue(eng, in.name()));
- out.setProperty(QString::fromLatin1("value"), qScriptValueFromValue(eng, in.value()));
- out.setProperty(QString::fromLatin1("valueAsString"), QScriptValue(eng, in.valueAsString()));
- out.setProperty(QString::fromLatin1("flags"), QScriptValue(eng, static_cast<int>(in.flags())));
- return out;
-}
-
-static void debuggerScriptValuePropertyFromScriptValue(const QScriptValue &in, QScriptDebuggerValueProperty &out)
-{
- QString name = in.property(QString::fromLatin1("name")).toString();
- QScriptDebuggerValue value = qscriptvalue_cast<QScriptDebuggerValue>(in.property(QString::fromLatin1("value")));
- QString valueAsString = in.property(QString::fromLatin1("valueAsString")).toString();
- int flags = in.property(QString::fromLatin1("flags")).toInt32();
- QScriptDebuggerValueProperty tmp(name, value, valueAsString, QScriptValue::PropertyFlags(flags));
- out = tmp;
-}
-
/*!
\since 4.5
\class QScriptDebuggerScriptedConsoleCommand
@@ -279,19 +84,17 @@ public:
QStringList seeAlso;
QStringList argumentTypes;
QStringList subCommands;
- QScriptEngine *engine;
+ QScriptValue globalObject;
QScriptValue execFunction;
QScriptValue responseFunction;
};
QScriptDebuggerScriptedConsoleCommandPrivate::QScriptDebuggerScriptedConsoleCommandPrivate()
{
- engine = 0;
}
QScriptDebuggerScriptedConsoleCommandPrivate::~QScriptDebuggerScriptedConsoleCommandPrivate()
{
- delete engine;
}
QScriptDebuggerScriptedConsoleCommand::QScriptDebuggerScriptedConsoleCommand(
@@ -299,6 +102,7 @@ QScriptDebuggerScriptedConsoleCommand::QScriptDebuggerScriptedConsoleCommand(
const QString &shortDescription, const QString &longDescription,
const QStringList &aliases, const QStringList &seeAlso,
const QStringList &argumentTypes, const QStringList &subCommands,
+ const QScriptValue &globalObject,
const QScriptValue &execFunction, const QScriptValue &responseFunction)
: QScriptDebuggerConsoleCommand(*new QScriptDebuggerScriptedConsoleCommandPrivate)
{
@@ -311,25 +115,9 @@ QScriptDebuggerScriptedConsoleCommand::QScriptDebuggerScriptedConsoleCommand(
d->seeAlso = seeAlso;
d->argumentTypes = argumentTypes;
d->subCommands = subCommands;
+ d->globalObject = globalObject;
d->execFunction = execFunction;
d->responseFunction = responseFunction;
- d->engine = execFunction.engine();
-
- qScriptRegisterMetaType<QScriptBreakpointData>(d->engine, breakpointDataToScriptValue, breakpointDataFromScriptValue);
- qScriptRegisterMetaType<QScriptBreakpointMap>(d->engine, breakpointMapToScriptValue, breakpointMapFromScriptValue);
- qScriptRegisterMetaType<QScriptScriptData>(d->engine, scriptDataToScriptValue, scriptDataFromScriptValue);
- qScriptRegisterMetaType<QScriptScriptMap>(d->engine, scriptMapToScriptValue, scriptMapFromScriptValue);
- qScriptRegisterMetaType<QScriptContextInfo>(d->engine, contextInfoToScriptValue, contextInfoFromScriptValue);
- qScriptRegisterMetaType<QScriptDebuggerValueProperty>(d->engine, debuggerScriptValuePropertyToScriptValue, debuggerScriptValuePropertyFromScriptValue);
- qScriptRegisterSequenceMetaType<QScriptDebuggerValuePropertyList>(d->engine);
- qScriptRegisterMetaType<QScriptDebuggerResponse>(d->engine, debuggerResponseToScriptValue, debuggerResponseFromScriptValue);
- qScriptRegisterMetaType<QScriptDebuggerConsoleCommand*>(d->engine, consoleCommandToScriptValue, consoleCommandFromScriptValue);
- qScriptRegisterSequenceMetaType<QScriptDebuggerConsoleCommandList>(d->engine);
- qScriptRegisterMetaType<QScriptDebuggerConsoleCommandGroupData>(d->engine, consoleCommandGroupDataToScriptValue, consoleCommandGroupDataFromScriptValue);
- qScriptRegisterMetaType<QScriptDebuggerConsoleCommandGroupMap>(d->engine, consoleCommandGroupMapToScriptValue, consoleCommandGroupMapFromScriptValue);
-// ### can't do this, if it's an object ID the conversion will be incorrect since
-// ### the object ID refers to an object in a different engine!
-// qScriptRegisterMetaType(d->engine, debuggerScriptValueToScriptValue, debuggerScriptValueFromScriptValue);
}
QScriptDebuggerScriptedConsoleCommand::~QScriptDebuggerScriptedConsoleCommand()
@@ -405,7 +193,8 @@ int QScriptDebuggerScriptedConsoleCommandJob::scheduleCommand(
void QScriptDebuggerScriptedConsoleCommandJob::start()
{
Q_D(QScriptDebuggerScriptedConsoleCommandJob);
- QScriptEngine *engine = d->command->engine;
+ QScriptEngine *engine = d->command->globalObject.engine();
+ engine->setGlobalObject(d->command->globalObject);
QScriptValueList args;
for (int i = 0; i < d->arguments.size(); ++i)
args.append(QScriptValue(engine, d->arguments.at(i)));
@@ -435,12 +224,13 @@ void QScriptDebuggerScriptedConsoleCommandJob::handleResponse(
{
Q_D(QScriptDebuggerScriptedConsoleCommandJob);
// ### generalize
- QScriptEngine *engine = d->command->engine;
+ QScriptEngine *engine = d->command->globalObject.engine();
+ engine->setGlobalObject(d->command->globalObject);
QScriptValueList args;
args.append(qScriptValueFromValue(engine, response));
args.append(QScriptValue(engine, commandId));
QScriptDebuggerConsoleGlobalObject *global;
- global = qobject_cast<QScriptDebuggerConsoleGlobalObject*>(engine->globalObject().toQObject());
+ global = qobject_cast<QScriptDebuggerConsoleGlobalObject*>(d->command->globalObject.toQObject());
Q_ASSERT(global != 0);
global->setScheduler(this);
global->setResponseHandler(this);
@@ -551,9 +341,8 @@ QScriptDebuggerConsoleCommandJob *QScriptDebuggerScriptedConsoleCommand::createJ
*/
QScriptDebuggerScriptedConsoleCommand *QScriptDebuggerScriptedConsoleCommand::parse(
const QString &program, const QString &fileName,
- QScriptMessageHandlerInterface *messageHandler)
+ QScriptEngine *engine, QScriptMessageHandlerInterface *messageHandler)
{
- QScriptEngine *engine = new QScriptEngine();
// create a custom global object
QScriptDebuggerConsoleGlobalObject *cppGlobal = new QScriptDebuggerConsoleGlobalObject();
QScriptValue global = engine->newQObject(cppGlobal,
@@ -574,14 +363,12 @@ QScriptDebuggerScriptedConsoleCommand *QScriptDebuggerScriptedConsoleCommand::pa
if (engine->hasUncaughtException()) {
messageHandler->message(QtCriticalMsg, ret.toString(), fileName,
engine->uncaughtExceptionLineNumber());
- delete engine;
return 0;
}
QScriptValue name = global.property(QLatin1String("name"));
if (!name.isString()) {
messageHandler->message(QtCriticalMsg, QLatin1String("command definition lacks a name"), fileName);
- delete engine;
return 0;
}
QString nameStr = name.toString();
@@ -590,7 +377,6 @@ QScriptDebuggerScriptedConsoleCommand *QScriptDebuggerScriptedConsoleCommand::pa
if (!group.isString()) {
messageHandler->message(QtCriticalMsg, QString::fromLatin1("definition of command \"%0\" lacks a group name")
.arg(nameStr), fileName);
- delete engine;
return 0;
}
QString groupStr = group.toString();
@@ -599,7 +385,6 @@ QScriptDebuggerScriptedConsoleCommand *QScriptDebuggerScriptedConsoleCommand::pa
if (!shortDesc.isString()) {
messageHandler->message(QtCriticalMsg, QString::fromLatin1("definition of command \"%0\" lacks shortDescription")
.arg(nameStr), fileName);
- delete engine;
return 0;
}
QString shortDescStr = shortDesc.toString();
@@ -608,7 +393,6 @@ QScriptDebuggerScriptedConsoleCommand *QScriptDebuggerScriptedConsoleCommand::pa
if (!longDesc.isString()) {
messageHandler->message(QtCriticalMsg, QString::fromLatin1("definition of command \"%0\" lacks longDescription")
.arg(nameStr), fileName);
- delete engine;
return 0;
}
QString longDescStr = longDesc.toString();
@@ -629,7 +413,6 @@ QScriptDebuggerScriptedConsoleCommand *QScriptDebuggerScriptedConsoleCommand::pa
if (!execFunction.isFunction()) {
messageHandler->message(QtCriticalMsg, QString::fromLatin1("definition of command \"%0\" lacks execute() function")
.arg(nameStr), fileName);
- delete engine;
return 0;
}
@@ -640,7 +423,7 @@ QScriptDebuggerScriptedConsoleCommand *QScriptDebuggerScriptedConsoleCommand::pa
shortDescStr, longDescStr,
aliases, seeAlso,
argTypes, subCommands,
- execFunction, responseFunction);
+ global, execFunction, responseFunction);
return result;
}
diff --git a/src/scripttools/debugging/qscriptdebuggerscriptedconsolecommand_p.h b/src/scripttools/debugging/qscriptdebuggerscriptedconsolecommand_p.h
index 1536de2..2b2b3f8 100644
--- a/src/scripttools/debugging/qscriptdebuggerscriptedconsolecommand_p.h
+++ b/src/scripttools/debugging/qscriptdebuggerscriptedconsolecommand_p.h
@@ -57,6 +57,7 @@
QT_BEGIN_NAMESPACE
+class QScriptEngine;
class QScriptValue;
class QScriptDebuggerScriptedConsoleCommandPrivate;
@@ -72,6 +73,7 @@ protected:
const QStringList &seeAlso,
const QStringList &argumentTypes,
const QStringList &subCommands,
+ const QScriptValue &globalObject,
const QScriptValue &execFunction,
const QScriptValue &responseFunction);
public:
@@ -79,7 +81,7 @@ public:
static QScriptDebuggerScriptedConsoleCommand *parse(
const QString &program, const QString &fileName,
- QScriptMessageHandlerInterface *messageHandler);
+ QScriptEngine *engine, QScriptMessageHandlerInterface *messageHandler);
QString name() const;
QString group() const;
diff --git a/src/sql/drivers/odbc/qsql_odbc.cpp b/src/sql/drivers/odbc/qsql_odbc.cpp
index 2049a76..18bc743 100644
--- a/src/sql/drivers/odbc/qsql_odbc.cpp
+++ b/src/sql/drivers/odbc/qsql_odbc.cpp
@@ -62,13 +62,6 @@ QT_BEGIN_NAMESPACE
// undefine this to prevent initial check of the ODBC driver
#define ODBC_CHECK_DRIVER
-#if defined(Q_ODBC_VERSION_2)
-//crude hack to get non-unicode capable driver managers to work
-# undef UNICODE
-# define SQLTCHAR SQLCHAR
-# define SQL_C_WCHAR SQL_C_CHAR
-#endif
-
// newer platform SDKs use SQLLEN instead of SQLINTEGER
#if defined(WIN32) && (_MSC_VER < 1300)
# define QSQLLEN SQLINTEGER
@@ -298,13 +291,11 @@ static QVariant::Type qDecodeODBCType(SQLSMALLINT sqltype, const T* p, bool isSi
case SQL_TYPE_TIMESTAMP:
type = QVariant::DateTime;
break;
-#ifndef Q_ODBC_VERSION_2
case SQL_WCHAR:
case SQL_WVARCHAR:
case SQL_WLONGVARCHAR:
type = QVariant::String;
break;
-#endif
case SQL_CHAR:
case SQL_VARCHAR:
case SQL_GUID:
@@ -577,10 +568,8 @@ static QSqlField qMakeFieldInfo(const QODBCPrivate* p, int i )
static int qGetODBCVersion(const QString &connOpts)
{
-#ifndef Q_ODBC_VERSION_2
if (connOpts.contains(QLatin1String("SQL_ATTR_ODBC_VERSION=SQL_OV_ODBC3"), Qt::CaseInsensitive))
return SQL_OV_ODBC3;
-#endif
return SQL_OV_ODBC2;
}
@@ -679,7 +668,6 @@ bool QODBCDriverPrivate::setConnectionOptions(const QString& connOpts)
continue;
}
r = SQLSetConnectAttr(hDbc, SQL_ATTR_TRACE, (SQLPOINTER) v, 0);
-#ifndef Q_ODBC_VERSION_2
} else if (opt.toUpper() == QLatin1String("SQL_ATTR_CONNECTION_POOLING")) {
if (val == QLatin1String("SQL_CP_OFF"))
v = SQL_CP_OFF;
@@ -706,7 +694,6 @@ bool QODBCDriverPrivate::setConnectionOptions(const QString& connOpts)
continue;
}
r = SQLSetConnectAttr(hDbc, SQL_ATTR_CP_MATCH, (SQLPOINTER)v, 0);
-#endif
} else if (opt.toUpper() == QLatin1String("SQL_ATTR_ODBC_VERSION")) {
// Already handled in QODBCDriver::open()
continue;
@@ -1432,7 +1419,6 @@ bool QODBCResult::exec()
*ind == SQL_NULL_DATA ? ind : NULL);
break;
case QVariant::String:
-#ifndef Q_ODBC_VERSION_2
if (d->unicode) {
QString str = val.toString();
str.utf16();
@@ -1469,7 +1455,6 @@ bool QODBCResult::exec()
break;
}
else
-#endif
{
QByteArray str = val.toString().toAscii();
if (*ind != SQL_NULL_DATA)
@@ -1870,11 +1855,6 @@ void QODBCDriver::cleanup()
// as two byte unicode characters
void QODBCDriverPrivate::checkUnicode()
{
-#if defined(Q_ODBC_VERSION_2)
- unicode = false;
- return;
-#endif
-
SQLRETURN r;
SQLUINTEGER fFunc;
diff --git a/src/sql/drivers/odbc/qsql_odbc.h b/src/sql/drivers/odbc/qsql_odbc.h
index 145a902..836dbd6 100644
--- a/src/sql/drivers/odbc/qsql_odbc.h
+++ b/src/sql/drivers/odbc/qsql_odbc.h
@@ -49,13 +49,6 @@
#include <QtCore/qt_windows.h>
#endif
-#if defined (Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_3)
-// assume we use iodbc on MACX
-// comment next line out if you use a
-// unicode compatible manager
-# define Q_ODBC_VERSION_2
-#endif
-
#ifdef QT_PLUGIN
#define Q_EXPORT_SQLDRIVER_ODBC
#else
@@ -75,10 +68,7 @@
# undef _MSC_VER
#endif
-#ifndef Q_ODBC_VERSION_2
#include <sqlucode.h>
-#endif
-
#include <sqlext.h>
QT_BEGIN_HEADER
diff --git a/src/testlib/qbenchmark.cpp b/src/testlib/qbenchmark.cpp
index 4ccbee6..52b5287 100644
--- a/src/testlib/qbenchmark.cpp
+++ b/src/testlib/qbenchmark.cpp
@@ -41,6 +41,7 @@
#include "QtTest/qbenchmark.h"
#include "QtTest/private/qbenchmark_p.h"
+#include "QtTest/private/qbenchmarkmetric_p.h"
#ifdef QT_GUI_LIB
#include <QtGui/qapplication.h>
@@ -138,7 +139,7 @@ void QBenchmarkTestMethodData::endDataRun()
int QBenchmarkTestMethodData::adjustIterationCount(int suggestion)
{
- // Let the -iteration-count option override the measurer.
+ // Let the -iterations option override the measurer.
if (QBenchmarkGlobalData::current->iterationCount != -1) {
iterationCount = QBenchmarkGlobalData::current->iterationCount;
} else {
@@ -148,12 +149,13 @@ int QBenchmarkTestMethodData::adjustIterationCount(int suggestion)
return iterationCount;
}
-void QBenchmarkTestMethodData::setResult(qint64 value)
+void QBenchmarkTestMethodData::setResult(
+ qreal value, QTest::QBenchmarkMetric metric, bool setByMacro)
{
bool accepted = false;
// Always accept the result if the iteration count has been
- // specified on the command line with -iteartion-count.
+ // specified on the command line with -iterations.
if (QBenchmarkGlobalData::current->iterationCount != -1)
accepted = true;
@@ -161,7 +163,7 @@ void QBenchmarkTestMethodData::setResult(qint64 value)
iterationCount = 1;
accepted = true;
}
-
+
// Test the result directly without calling the measurer if the minimum time
// has been specifed on the command line with -minimumvalue.
else if (QBenchmarkGlobalData::current->walltimeMinimum != -1)
@@ -175,8 +177,8 @@ void QBenchmarkTestMethodData::setResult(qint64 value)
else
iterationCount *= 2;
- this->result =
- QBenchmarkResult(QBenchmarkGlobalData::current->context, value, iterationCount);
+ this->result = QBenchmarkResult(
+ QBenchmarkGlobalData::current->context, value, iterationCount, metric, setByMacro);
}
/*!
@@ -208,7 +210,8 @@ QTest::QBenchmarkIterationController::QBenchmarkIterationController()
*/
QTest::QBenchmarkIterationController::~QBenchmarkIterationController()
{
- QBenchmarkTestMethodData::current->setResult(QTest::endBenchmarkMeasurement());
+ const qreal result = QTest::endBenchmarkMeasurement();
+ QBenchmarkTestMethodData::current->setResult(result, QBenchmarkGlobalData::current->measurer->metricType());
}
/*! \internal
@@ -259,28 +262,32 @@ void QTest::beginBenchmarkMeasurement()
/*! \internal
*/
-qint64 QTest::endBenchmarkMeasurement()
+quint64 QTest::endBenchmarkMeasurement()
{
// the clock is ticking before the line below, don't add code here.
return QBenchmarkGlobalData::current->measurer->stop();
}
-/*! \internal
-*/
-void QTest::setResult(qint64 result)
-{
- QBenchmarkTestMethodData::current->setResult(result);
-}
-
-/*! \internal
+/*!
+ Sets the benchmark result for this test function to \a result.
+
+ Use this function if you want to report benchmark results without
+ using the QBENCHMARK macro. Use \a metric to specify how QTestLib
+ should interpret the results.
+
+ The context for the result will be the test function name and any
+ data tag from the _data function. This function can only be called
+ once in each test function, subsequent calls will replace the
+ earlier reported results.
+
+ Note that the -iterations command line argument has no effect
+ on test functions without the QBENCHMARK macro.
+
+ \since 4.7
*/
-void QTest::setResult(const QString &tag, qint64 result)
+void QTest::setBenchmarkResult(qreal result, QTest::QBenchmarkMetric metric)
{
- QBenchmarkContext context = QBenchmarkGlobalData::current->context;
- context.tag = tag;
- QBenchmarkTestMethodData::current->result =
- QBenchmarkResult( context, result,
- QBenchmarkTestMethodData::current->iterationCount);
+ QBenchmarkTestMethodData::current->setResult(result, metric, false);
}
template <typename T>
@@ -298,6 +305,4 @@ Q_TYPENAME T::value_type qAverage(const T &container)
return acc / count;
}
-
QT_END_NAMESPACE
-
diff --git a/src/testlib/qbenchmark.h b/src/testlib/qbenchmark.h
index 0207b5b..38a0e52 100644
--- a/src/testlib/qbenchmark.h
+++ b/src/testlib/qbenchmark.h
@@ -43,6 +43,7 @@
#define QBENCHMARK_H
#include <QtTest/qtest_global.h>
+#include <QtTest/private/qbenchmarkmetric_p.h>
QT_BEGIN_HEADER
@@ -75,6 +76,8 @@ public:
}
+// --- BEGIN public API ---
+
#define QBENCHMARK \
for (QTest::QBenchmarkIterationController __iteration_controller; \
__iteration_controller.isDone() == false; __iteration_controller.next())
@@ -83,6 +86,13 @@ public:
for (QTest::QBenchmarkIterationController __iteration_controller(QTest::QBenchmarkIterationController::RunOnce); \
__iteration_controller.isDone() == false; __iteration_controller.next())
+namespace QTest
+{
+ void Q_TESTLIB_EXPORT setBenchmarkResult(qreal result, QBenchmarkMetric metric);
+}
+
+// --- END public API ---
+
QT_END_NAMESPACE
QT_END_HEADER
diff --git a/src/testlib/qbenchmark_p.h b/src/testlib/qbenchmark_p.h
index 0d6542f..50329e1 100644
--- a/src/testlib/qbenchmark_p.h
+++ b/src/testlib/qbenchmark_p.h
@@ -42,6 +42,8 @@
#ifndef QBENCHMARK_P_H
#define QBENCHMARK_P_H
+#include <stdlib.h>
+
//
// W A R N I N G
// -------------
@@ -68,6 +70,7 @@
#include "QtTest/private/qbenchmarkvalgrind_p.h"
#endif
#include "QtTest/private/qbenchmarkevent_p.h"
+#include "QtTest/private/qbenchmarkmetric_p.h"
QT_BEGIN_NAMESPACE
@@ -92,23 +95,29 @@ class QBenchmarkResult
{
public:
QBenchmarkContext context;
- qint64 value;
+ qreal value;
int iterations;
+ QTest::QBenchmarkMetric metric;
+ bool setByMacro;
bool valid;
QBenchmarkResult()
: value(-1)
, iterations(-1)
+ , setByMacro(true)
, valid(false)
- { }
+ { }
- QBenchmarkResult(const QBenchmarkContext &context, const qint64 value, const int iterations)
+ QBenchmarkResult(
+ const QBenchmarkContext &context, const qreal value, const int iterations,
+ QTest::QBenchmarkMetric metric, bool setByMacro)
: context(context)
, value(value)
, iterations(iterations)
+ , metric(metric)
+ , setByMacro(setByMacro)
, valid(true)
- {
- }
+ { }
bool operator<(const QBenchmarkResult &other) const
{
@@ -167,7 +176,7 @@ public:
bool isBenchmark() const { return result.valid; }
bool resultsAccepted() const { return resultAccepted; }
int adjustIterationCount(int suggestion);
- void setResult(qint64 value);
+ void setResult(qreal value, QTest::QBenchmarkMetric metric, bool setByMacro = true);
QBenchmarkResult result;
bool resultAccepted;
@@ -183,10 +192,7 @@ namespace QTest
void setIterationCount(int count);
Q_TESTLIB_EXPORT void beginBenchmarkMeasurement();
- Q_TESTLIB_EXPORT qint64 endBenchmarkMeasurement();
-
- void setResult(qint64 result);
- void setResult(const QString &tag, qint64 result);
+ Q_TESTLIB_EXPORT quint64 endBenchmarkMeasurement();
}
QT_END_NAMESPACE
diff --git a/src/testlib/qbenchmarkevent.cpp b/src/testlib/qbenchmarkevent.cpp
index 9c67096..39eb1c5 100644
--- a/src/testlib/qbenchmarkevent.cpp
+++ b/src/testlib/qbenchmarkevent.cpp
@@ -41,6 +41,7 @@
#include "QtTest/private/qbenchmarkevent_p.h"
#include "QtTest/private/qbenchmark_p.h"
+#include "QtTest/private/qbenchmarkmetric_p.h"
#include <qdebug.h>
QT_BEGIN_NAMESPACE
@@ -91,14 +92,9 @@ int QBenchmarkEvent::adjustMedianCount(int suggestion)
return 1;
}
-QString QBenchmarkEvent::unitText()
+QTest::QBenchmarkMetric QBenchmarkEvent::metricType()
{
- return QLatin1String("events");
-}
-
-QString QBenchmarkEvent::metricText()
-{
- return QLatin1String("events");
+ return QTest::Events;
}
// This could be done in a much better way, this is just the beginning.
diff --git a/src/testlib/qbenchmarkevent_p.h b/src/testlib/qbenchmarkevent_p.h
index 1a48964..5e13b9f 100644
--- a/src/testlib/qbenchmarkevent_p.h
+++ b/src/testlib/qbenchmarkevent_p.h
@@ -70,8 +70,7 @@ public:
int adjustIterationCount(int suggestion);
int adjustMedianCount(int suggestion);
bool repeatCount() { return 1; }
- QString unitText();
- QString metricText();
+ QTest::QBenchmarkMetric metricType();
static bool eventCountingMechanism(void *message);
static qint64 eventCounter;
};
diff --git a/src/testlib/qbenchmarkmeasurement.cpp b/src/testlib/qbenchmarkmeasurement.cpp
index 836d85f..c03cbff 100644
--- a/src/testlib/qbenchmarkmeasurement.cpp
+++ b/src/testlib/qbenchmarkmeasurement.cpp
@@ -41,6 +41,8 @@
#include "QtTest/private/qbenchmarkmeasurement_p.h"
#include "QtTest/private/qbenchmark_p.h"
+#include "QtTest/private/qbenchmarkmetric_p.h"
+#include "qbenchmark.h"
#include <qdebug.h>
QT_BEGIN_NAMESPACE
@@ -77,14 +79,9 @@ int QBenchmarkTimeMeasurer::adjustMedianCount(int)
return 1;
}
-QString QBenchmarkTimeMeasurer::unitText()
+QTest::QBenchmarkMetric QBenchmarkTimeMeasurer::metricType()
{
- return QLatin1String("msec");
-}
-
-QString QBenchmarkTimeMeasurer::metricText()
-{
- return QLatin1String("walltime");
+ return QTest::WalltimeMilliseconds;
}
#ifdef HAVE_TICK_COUNTER // defined in 3rdparty/cycle_p.h
@@ -126,14 +123,9 @@ bool QBenchmarkTickMeasurer::needsWarmupIteration()
return true;
}
-QString QBenchmarkTickMeasurer::unitText()
-{
- return QLatin1String("ticks");
-}
-
-QString QBenchmarkTickMeasurer::metricText()
+QTest::QBenchmarkMetric QBenchmarkTickMeasurer::metricType()
{
- return QLatin1String("cputicks");
+ return QTest::CPUTicks;
}
#endif
diff --git a/src/testlib/qbenchmarkmeasurement_p.h b/src/testlib/qbenchmarkmeasurement_p.h
index 6f3c034..8ad3613 100644
--- a/src/testlib/qbenchmarkmeasurement_p.h
+++ b/src/testlib/qbenchmarkmeasurement_p.h
@@ -55,6 +55,7 @@
#include <QtCore/qdatetime.h>
#include "3rdparty/cycle_p.h"
+#include "qbenchmark.h"
QT_BEGIN_NAMESPACE
@@ -71,8 +72,7 @@ public:
virtual int adjustMedianCount(int suggestion) = 0;
virtual bool repeatCount() { return 1; }
virtual bool needsWarmupIteration() { return false; }
- virtual QString unitText() = 0;
- virtual QString metricText() = 0;
+ virtual QTest::QBenchmarkMetric metricType() = 0;
};
class QBenchmarkTimeMeasurer : public QBenchmarkMeasurerBase
@@ -84,8 +84,7 @@ public:
bool isMeasurementAccepted(qint64 measurement);
int adjustIterationCount(int sugestion);
int adjustMedianCount(int suggestion);
- QString unitText();
- QString metricText();
+ QTest::QBenchmarkMetric metricType();
private:
QTime time;
};
@@ -102,8 +101,7 @@ public:
int adjustIterationCount(int);
int adjustMedianCount(int suggestion);
bool needsWarmupIteration();
- QString unitText();
- QString metricText();
+ QTest::QBenchmarkMetric metricType();
private:
CycleCounterTicks startTicks;
};
diff --git a/src/testlib/qbenchmarkmetric.cpp b/src/testlib/qbenchmarkmetric.cpp
new file mode 100644
index 0000000..7356134
--- /dev/null
+++ b/src/testlib/qbenchmarkmetric.cpp
@@ -0,0 +1,115 @@
+/****************************************************************************
+**
+** 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 QtTest module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtTest/private/qbenchmarkmetric_p.h>
+
+/*!
+ \enum QTest::QBenchmarkMetric
+ \since 4.7
+
+ This enum lists all the things that can be benchmarked.
+
+ \value FramesPerSecond Frames per second
+ \value BitsPerSecond Bits per second
+ \value BytesPerSecond Bytes per second
+ \value WalltimeMilliseconds Clock time in milliseconds
+ \value CPUTicks CPU time
+ \value InstructionReads Instruction reads
+ \value Events Event count
+
+ \sa QTest::benchmarkMetricName(), QTest::benchmarkMetricUnit()
+
+ */
+
+/*!
+ \relates QTest
+ \since 4.7
+ Returns the enum value \a metric as a character string.
+ */
+const char * QTest::benchmarkMetricName(QBenchmarkMetric metric)
+{
+ switch (metric) {
+ case FramesPerSecond:
+ return "FramesPerSecond";
+ case BitsPerSecond:
+ return "BitsPerSecond";
+ case BytesPerSecond:
+ return "BytesPerSecond";
+ case WalltimeMilliseconds:
+ return "WalltimeMilliseconds";
+ case CPUTicks:
+ return "CPUTicks";
+ case InstructionReads:
+ return "InstructionReads";
+ case Events:
+ return "Events";
+ default:
+ return "";
+ }
+};
+
+/*!
+ \relates QTest
+ \since 4.7
+ Retuns the units of measure for the specified \a metric.
+ */
+const char * QTest::benchmarkMetricUnit(QBenchmarkMetric metric)
+{
+ switch (metric) {
+ case FramesPerSecond:
+ return "fps";
+ case BitsPerSecond:
+ return "bits/s";
+ case BytesPerSecond:
+ return "bytes/s";
+ case WalltimeMilliseconds:
+ return "msecs";
+ case CPUTicks:
+ return "CPU ticks";
+ case InstructionReads:
+ return "instruction reads";
+ case Events:
+ return "events";
+ default:
+ return "";
+ }
+}
+
diff --git a/src/testlib/qbenchmarkmetric.h b/src/testlib/qbenchmarkmetric.h
new file mode 100644
index 0000000..302c1aa
--- /dev/null
+++ b/src/testlib/qbenchmarkmetric.h
@@ -0,0 +1,71 @@
+/****************************************************************************
+**
+** 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 QtTest module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QBENCHMARKMETRIC_H
+#define QBENCHMARKMETRIC_H
+
+#include <QtTest/qtest_global.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Test)
+
+namespace QTest {
+
+enum QBenchmarkMetric {
+ FramesPerSecond,
+ BitsPerSecond,
+ BytesPerSecond,
+ WalltimeMilliseconds,
+ CPUTicks,
+ InstructionReads,
+ Events
+};
+
+}
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QBENCHMARK_H
diff --git a/src/testlib/qbenchmarkmetric_p.h b/src/testlib/qbenchmarkmetric_p.h
new file mode 100644
index 0000000..c919d2e
--- /dev/null
+++ b/src/testlib/qbenchmarkmetric_p.h
@@ -0,0 +1,63 @@
+/****************************************************************************
+**
+** 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 QtTest module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QBENCHMARKMETRIC_P_H
+#define QBENCHMARKMETRIC_P_H
+
+#include <QtTest/qtest_global.h>
+#include <QtTest/qbenchmarkmetric.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Test)
+
+namespace QTest {
+ const char * benchmarkMetricName(QBenchmarkMetric metric);
+ const char * benchmarkMetricUnit(QBenchmarkMetric metric);
+}
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QBENCHMARK_H
diff --git a/src/testlib/qbenchmarkvalgrind.cpp b/src/testlib/qbenchmarkvalgrind.cpp
index 264774e..8c64c0b 100644
--- a/src/testlib/qbenchmarkvalgrind.cpp
+++ b/src/testlib/qbenchmarkvalgrind.cpp
@@ -263,14 +263,9 @@ bool QBenchmarkCallgrindMeasurer::needsWarmupIteration()
return true;
}
-QString QBenchmarkCallgrindMeasurer::unitText()
+QTest::QBenchmarkMetric QBenchmarkCallgrindMeasurer::metricType()
{
- return QLatin1String("instr. loads");
-}
-
-QString QBenchmarkCallgrindMeasurer::metricText()
-{
- return QLatin1String("callgrind");
+ return QTest::InstructionReads;
}
QT_END_NAMESPACE
diff --git a/src/testlib/qbenchmarkvalgrind_p.h b/src/testlib/qbenchmarkvalgrind_p.h
index 754fe3d..7b6893b 100644
--- a/src/testlib/qbenchmarkvalgrind_p.h
+++ b/src/testlib/qbenchmarkvalgrind_p.h
@@ -54,6 +54,7 @@
//
#include "QtTest/private/qbenchmarkmeasurement_p.h"
+#include "QtTest/private/qbenchmarkmetric_p.h"
#include <QtCore/qmap.h>
#include <QtCore/qstring.h>
@@ -84,8 +85,7 @@ public:
int adjustIterationCount(int);
int adjustMedianCount(int);
bool needsWarmupIteration();
- QString unitText();
- QString metricText();
+ QTest::QBenchmarkMetric metricType();
};
QT_END_NAMESPACE
diff --git a/src/testlib/qplaintestlogger.cpp b/src/testlib/qplaintestlogger.cpp
index 0888cfc..46431a8 100644
--- a/src/testlib/qplaintestlogger.cpp
+++ b/src/testlib/qplaintestlogger.cpp
@@ -44,6 +44,7 @@
#include "QtTest/private/qtestlog_p.h"
#include "QtTest/private/qplaintestlogger_p.h"
#include "QtTest/private/qbenchmark_p.h"
+#include "QtTest/private/qbenchmarkmetric_p.h"
#include <stdarg.h>
#include <stdio.h>
@@ -324,7 +325,6 @@ namespace QTest {
QTestResult::currentTestObjectName(),
result.context.slotName.toAscii().data());
-
char bufTag[1024];
bufTag[0] = 0;
QByteArray tag = result.context.tag.toAscii();
@@ -340,32 +340,43 @@ namespace QTest {
char fill[1024];
QTest::qt_snprintf(fill, sizeof(fill), fillFormat, "");
-
- QByteArray unitText = QBenchmarkGlobalData::current->measurer->unitText().toAscii();
+ const char * unitText = QTest::benchmarkMetricUnit(result.metric);
qreal valuePerIteration = qreal(result.value) / qreal(result.iterations);
char resultBuffer[100] = "";
formatResult(resultBuffer, 100, valuePerIteration, countSignificantDigits(result.value));
- QByteArray iterationText = "per iteration";
-
char buf2[1024];
- Q_ASSERT(result.iterations > 0);
QTest::qt_snprintf(
- buf2, sizeof(buf2), "%s %s %s",
+ buf2, sizeof(buf2), "%s %s",
resultBuffer,
- unitText.data(),
+ unitText);
+
+ char buf2_[1024];
+ QByteArray iterationText = " per iteration";
+ Q_ASSERT(result.iterations > 0);
+ QTest::qt_snprintf(
+ buf2_,
+ sizeof(buf2_), "%s",
iterationText.data());
char buf3[1024];
Q_ASSERT(result.iterations > 0);
+ formatResult(resultBuffer, 100, result.value, countSignificantDigits(result.value));
QTest::qt_snprintf(
- buf3, sizeof(buf3), " (total: %s, iterations: %d)\n",
- QByteArray::number(result.value).constData(), // no 64-bit qt_snprintf support
+ buf3, sizeof(buf3), " (total: %s, iterations: %d)",
+ resultBuffer,
result.iterations);
char buf[1024];
- QTest::qt_snprintf(buf, sizeof(buf), "%s%s%s%s%s", buf1, bufTag, fill, buf2, buf3);
+
+ if (result.setByMacro) {
+ QTest::qt_snprintf(
+ buf, sizeof(buf), "%s%s%s%s%s%s\n", buf1, bufTag, fill, buf2, buf2_, buf3);
+ } else {
+ QTest::qt_snprintf(buf, sizeof(buf), "%s%s%s%s\n", buf1, bufTag, fill, buf2);
+ }
+
memcpy(buf, bmtag, strlen(bmtag));
outputMessage(buf);
}
diff --git a/src/testlib/qtestcase.cpp b/src/testlib/qtestcase.cpp
index ecdcca8..40daecb 100644
--- a/src/testlib/qtestcase.cpp
+++ b/src/testlib/qtestcase.cpp
@@ -846,6 +846,9 @@ namespace QTest
static int mouseDelay = -1;
static int eventDelay = -1;
static int keyVerbose = -1;
+#if defined(Q_OS_UNIX) && !defined(Q_OS_SYMBIAN)
+ static bool noCrashHandler = false;
+#endif
void filter_unprintable(char *str)
{
@@ -976,6 +979,9 @@ static void qParseArgs(int argc, char *argv[])
" -keyevent-verbose : Turn on verbose messages for keyboard simulation\n"
" -maxwarnings n : Sets the maximum amount of messages to output.\n"
" 0 means unlimited, default: 2000\n"
+#if defined(Q_OS_UNIX) && !defined(Q_OS_SYMBIAN)
+ " -nocrashhandler : Disables the crash handler\n"
+#endif
"\n"
" Benchmark related options:\n"
#ifdef QTESTLIB_USE_VALGRIND
@@ -1056,6 +1062,10 @@ static void qParseArgs(int argc, char *argv[])
} else {
QTestLog::setMaxWarnings(qToInt(argv[++i]));
}
+#if defined(Q_OS_UNIX) && !defined(Q_OS_SYMBIAN)
+ } else if (strcmp(argv[i], "-nocrashhandler") == 0) {
+ QTest::noCrashHandler = true;
+#endif
} else if (strcmp(argv[i], "-keyevent-verbose") == 0) {
QTest::keyVerbose = 1;
#ifdef QTESTLIB_USE_VALGRIND
@@ -1661,7 +1671,9 @@ int QTest::qExec(QObject *testObject, int argc, char **argv)
#endif
{
#if defined(Q_OS_UNIX) && !defined(Q_OS_SYMBIAN)
- FatalSignalHandler handler;
+ QScopedPointer<FatalSignalHandler> handler;
+ if (!noCrashHandler)
+ handler.reset(new FatalSignalHandler);
#endif
qInvokeTestMethods(testObject);
}
diff --git a/src/testlib/qtestcoreelement.h b/src/testlib/qtestcoreelement.h
index e1ad44a..4738f7d 100644
--- a/src/testlib/qtestcoreelement.h
+++ b/src/testlib/qtestcoreelement.h
@@ -45,6 +45,8 @@
#include <QtTest/qtestcorelist.h>
#include <QtTest/qtestelementattribute.h>
+#include <cstdlib>
+
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
@@ -93,6 +95,9 @@ void QTestCoreElement<ElementType>::addAttribute(const QTest::AttributeIndex att
if (attribute(attributeIndex))
return;
+ // if (attributeIndex == QTest::AI_Metric)
+ // abort();
+
QTestElementAttribute *testAttribute = new QTestElementAttribute;
testAttribute->setPair(attributeIndex, value);
testAttribute->addToList(&listOfAttributes);
diff --git a/src/testlib/qtestlogger.cpp b/src/testlib/qtestlogger.cpp
index c0bc26c..6c76388 100644
--- a/src/testlib/qtestlogger.cpp
+++ b/src/testlib/qtestlogger.cpp
@@ -267,7 +267,9 @@ void QTestLogger::addBenchmarkResult(const QBenchmarkResult &result)
QTestElement *benchmarkElement = new QTestElement(QTest::LET_Benchmark);
// printf("element %i", benchmarkElement->elementType());
- benchmarkElement->addAttribute(QTest::AI_Metric, QBenchmarkGlobalData::current->measurer->metricText().toAscii().data());
+ benchmarkElement->addAttribute(
+ QTest::AI_Metric,
+ QTest::benchmarkMetricName(QBenchmarkTestMethodData::current->result.metric));
benchmarkElement->addAttribute(QTest::AI_Tag, result.context.tag.toAscii().data());
benchmarkElement->addAttribute(QTest::AI_Value, QByteArray::number(result.value).constData());
diff --git a/src/testlib/qxmltestlogger.cpp b/src/testlib/qxmltestlogger.cpp
index 13103f3..2236666 100644
--- a/src/testlib/qxmltestlogger.cpp
+++ b/src/testlib/qxmltestlogger.cpp
@@ -46,6 +46,7 @@
#include "QtTest/private/qxmltestlogger_p.h"
#include "QtTest/private/qtestresult_p.h"
#include "QtTest/private/qbenchmark_p.h"
+#include "QtTest/private/qbenchmarkmetric_p.h"
#include "QtTest/qtestcase.h"
QT_BEGIN_NAMESPACE
@@ -243,7 +244,7 @@ void QXmlTestLogger::addBenchmarkResult(const QBenchmarkResult &result)
QTestCharBuffer quotedTag;
xmlQuote(&quotedMetric,
- QBenchmarkGlobalData::current->measurer->metricText().toAscii().constData());
+ benchmarkMetricUnit(result.metric));
xmlQuote(&quotedTag, result.context.tag.toAscii().constData());
QTest::qt_asprintf(
diff --git a/src/testlib/testlib.pro b/src/testlib/testlib.pro
index f68ff35..a8186d8 100644
--- a/src/testlib/testlib.pro
+++ b/src/testlib/testlib.pro
@@ -47,6 +47,7 @@ SOURCES = qtestcase.cpp \
qbenchmarkmeasurement.cpp \
qbenchmarkvalgrind.cpp \
qbenchmarkevent.cpp \
+ qbenchmarkmetric.cpp \
qtestelement.cpp \
qtestelementattribute.cpp \
qtestbasicstreamer.cpp \
diff --git a/src/tools/moc/generator.cpp b/src/tools/moc/generator.cpp
index 982d95f5..6729c62 100644
--- a/src/tools/moc/generator.cpp
+++ b/src/tools/moc/generator.cpp
@@ -173,7 +173,7 @@ void Generator::generateCode()
int index = 14;
fprintf(out, "static const uint qt_meta_data_%s[] = {\n", qualifiedClassNameIdentifier.constData());
fprintf(out, "\n // content:\n");
- fprintf(out, " %4d, // revision\n", 4);
+ fprintf(out, " %4d, // revision\n", 5);
fprintf(out, " %4d, // classname\n", strreg(cdef->qualified));
fprintf(out, " %4d, %4d, // classinfo\n", cdef->classInfoList.count(), cdef->classInfoList.count() ? index : 0);
index += cdef->classInfoList.count() * 2;
diff --git a/src/xmlpatterns/type/qprimitives_p.h b/src/xmlpatterns/type/qprimitives_p.h
index 1090f7f..c378a66 100644
--- a/src/xmlpatterns/type/qprimitives_p.h
+++ b/src/xmlpatterns/type/qprimitives_p.h
@@ -79,18 +79,6 @@ class QString;
*/
namespace QPatternist
{
-
- /**
- * @internal
- *
- * A method to allow a QHash or QSet with QUrl
- * as key type.
- */
- inline uint qHash(const QUrl &uri)
- {
- return qHash(uri.toString());
- }
-
/**
* @defgroup Patternist_cppWXSTypes C++ Primitives for W3C XML Schema Number Types
*
@@ -208,8 +196,6 @@ namespace QPatternist
QString Q_AUTOTEST_EXPORT escape(const QString &input);
}
-using QPatternist::qHash;
-
QT_END_NAMESPACE
QT_END_HEADER